easemob-websdk 5.1.0 → 5.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/bundle/im-sdk-web.iife.js +1 -1
  2. package/chat-client.d.ts +42 -8
  3. package/chunks/{chat-manager-D_KF5qM1.cjs → chat-manager-BFd2Z4oY.cjs} +1 -1
  4. package/chunks/{chat-manager-DCqgMxLm.js → chat-manager-CId_M_e5.js} +1 -1
  5. package/chunks/common-BvlDAw4a.js +1 -0
  6. package/chunks/common-tHGz9VBk.cjs +1 -0
  7. package/chunks/event-system-B62vbKqG.js +1 -0
  8. package/chunks/{event-system-COBJFEIq.cjs → event-system-TYhmgy4K.cjs} +1 -1
  9. package/chunks/group-user-info-resolver-B-dyr__b.cjs +1 -0
  10. package/chunks/group-user-info-resolver-DMccCqez.js +1 -0
  11. package/chunks/index-BBFJYOM8.js +1 -0
  12. package/chunks/{index-Dvvh1nf6.cjs → index-DJPAjXAp.cjs} +1 -1
  13. package/chunks/index-DtWkVcfb.cjs +1 -0
  14. package/chunks/index-l_BUKi77.js +1 -0
  15. package/chunks/light-BcQg8h2W.cjs +1 -0
  16. package/chunks/light-DImBnNes.js +1 -0
  17. package/chunks/{reflection-proto-codec-CjRraw85.js → reflection-proto-codec-7r8Sei3y.js} +1 -1
  18. package/chunks/{reflection-proto-codec-BerStgkC.cjs → reflection-proto-codec-CwrIKT1L.cjs} +1 -1
  19. package/chunks/{session-list-query-rynxSxtv.js → session-list-query-Cvr6rlme.js} +1 -1
  20. package/chunks/{session-list-query-C4OQMvPf.cjs → session-list-query-Dslj2k3t.cjs} +1 -1
  21. package/chunks/{user-info-DfbCp80h.js → user-info-AlshAvdy.js} +1 -1
  22. package/chunks/{user-info-DsDDTJrw.cjs → user-info-DH3aE1gm.cjs} +1 -1
  23. package/config/timeouts.d.ts +11 -0
  24. package/core/connection/connection-manager.d.ts +18 -1
  25. package/core/connection/login-deadline.d.ts +22 -0
  26. package/core/events/event-hub.d.ts +1 -0
  27. package/core/index.d.ts +8 -1
  28. package/core/message/attachment-downloader.d.ts +1 -1
  29. package/core/session-list-sync/session-list-sync-controller.d.ts +5 -0
  30. package/index.cjs +1 -1
  31. package/index.d.ts +11 -9
  32. package/index.js +2 -2
  33. package/log.d.ts +27 -0
  34. package/managers/chat/index.cjs +1 -1
  35. package/managers/chat/index.js +1 -1
  36. package/managers/chat-thread/index.cjs +1 -1
  37. package/managers/chat-thread/index.js +1 -1
  38. package/managers/chatroom/chatroom.d.ts +1 -1
  39. package/managers/chatroom/index.cjs +1 -1
  40. package/managers/chatroom/index.js +1 -1
  41. package/managers/chatroom-manager.d.ts +6 -1
  42. package/managers/contact/index.cjs +1 -1
  43. package/managers/contact/index.js +1 -1
  44. package/managers/group/index.cjs +1 -1
  45. package/managers/group/index.js +1 -1
  46. package/managers/presence/index.cjs +1 -1
  47. package/managers/presence/index.js +1 -1
  48. package/managers/push/index.cjs +1 -1
  49. package/managers/push/index.d.ts +2 -0
  50. package/managers/push/index.js +1 -1
  51. package/managers/push/native-push-controller.d.ts +62 -0
  52. package/managers/push/native-push-normalizer.d.ts +15 -0
  53. package/managers/push-manager.d.ts +63 -4
  54. package/managers/user-info/index.cjs +1 -1
  55. package/managers/user-info/index.js +1 -1
  56. package/managers/user-info-manager.d.ts +3 -2
  57. package/message/combine-payload-codec.d.ts +2 -1
  58. package/package.json +1 -1
  59. package/platform/index.d.ts +1 -1
  60. package/platform/request/default-request-adapter.d.ts +7 -0
  61. package/platform/socket/default-socket-adapter.d.ts +6 -0
  62. package/platform/types.d.ts +22 -2
  63. package/platform/upload/legacy-multipart-upload.d.ts +14 -0
  64. package/platform/upload/legacy-simple-upload.d.ts +3 -0
  65. package/protocol/msync/codec.d.ts +5 -0
  66. package/rest/client.d.ts +0 -4
  67. package/rest/contact-management.d.ts +1 -0
  68. package/rest/dns-config.d.ts +6 -1
  69. package/rest/error-maps/chatroom.d.ts +6 -0
  70. package/rest/error-maps/common.d.ts +3 -0
  71. package/rest/error-maps/contact.d.ts +8 -3
  72. package/rest/error-maps/push.d.ts +13 -1
  73. package/rest/error-maps/user-info.d.ts +51 -3
  74. package/rest/service-url.d.ts +6 -0
  75. package/types/chat-client.d.ts +16 -9
  76. package/types/chatroom.d.ts +3 -34
  77. package/types/event-system.d.ts +52 -1
  78. package/types/index.d.ts +5 -7
  79. package/types/log.d.ts +19 -0
  80. package/types/manager.d.ts +31 -0
  81. package/types/push.d.ts +77 -0
  82. package/upload/attachment-uploader.d.ts +1 -5
  83. package/upload/multipart-upload.d.ts +4 -14
  84. package/upload/simple-upload.d.ts +4 -3
  85. package/upload/types.d.ts +2 -1
  86. package/utils/error-codes.generated.d.ts +1 -0
  87. package/utils/log-reporter.d.ts +1 -7
  88. package/utils/logger.d.ts +28 -2
  89. package/validators/chat-client.d.ts +22 -50
  90. package/validators/message-create.d.ts +18 -18
  91. package/chunks/common-BIpcR2uQ.cjs +0 -1
  92. package/chunks/common-D_DfwSd3.js +0 -1
  93. package/chunks/event-system-D6IJA0C4.js +0 -1
  94. package/chunks/group-user-info-resolver-Ds35Z1Uf.cjs +0 -1
  95. package/chunks/group-user-info-resolver-lEtRdWli.js +0 -1
  96. package/chunks/index-BmwQgZ3E.js +0 -1
  97. package/chunks/index-BsIqq7LU.cjs +0 -1
  98. package/chunks/index-CFMcR5a_.js +0 -1
  99. package/chunks/light-Dg9A1Xmd.js +0 -1
  100. package/chunks/light-dJjIln5b.cjs +0 -1
@@ -1 +1 @@
1
- var IMSDK=function(e){"use strict";const t="disconnected",r="connecting",s="connected",n="reconnecting",i="reconnectFailed",o="onConnecting",a="onConnected",c="onDisconnected",d="onReconnectFailed",u="onTokenWillExpire",l="onTokenExpired",p="onOfflineMessageSyncStart",h="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",q="onReactionChanged",$="onPinnedMessageChanged",G="onMultiDeviceContact",F="onMultiDeviceConversation",B="onSyncDataStart",j="onSyncDataFinished",z="onPresenceStatusChange",K="onContactInvited",H="onContactDeleted",V="onContactAdded",W="onContactRefuse",J="onContactAgreed",Z="onContactInfoUpdated",Q="onInvitationReceived",Y="onRequestToJoinReceived",X="onRequestToJoinAccepted",ee="onRequestToJoinDeclined",te="onInvitationAccepted",re="onInvitationDeclined",se="onUserRemoved",ne="onGroupDestroyed",ie="onAutoAcceptInvitationFromGroup",oe="onMuteListAdded",ae="onMuteListRemoved",ce="onAllowListAdded",de="onAllowListRemoved",ue="onAllMemberMuteStateChanged",le="onAdminAdded",pe="onAdminRemoved",he="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",qe="__chatroom:onAttributesRemoved",$e="onChatRoomDestroyed",Ge="onMembersJoined",Fe="onMembersExited",Be="onRemovedFromChatRoom",je="onMuteListAdded",ze="onMuteListRemoved",Ke="onAllowListAdded",He="onAllowListRemoved",Ve="onAllMemberMuteStateChanged",We="onAdminAdded",Je="onAdminRemoved",Ze="onOwnerChanged",Qe="onAnnouncementChanged",Ye="onChatRoomInfoChanged",Xe="onAttributesUpdate",et="onAttributesRemoved",rt={START:"STREAM_START",START_COMPLETED:"STREAM_START_COMPLETED",IN_PROGRESS:"STREAM_IN_PROGRESS",COMPLETED:"STREAM_COMPLETED",FULL:"STREAM_FULL",ERROR:"STREAM_ERROR"};function st(e){return"object"==typeof e.stream&&null!==e.stream}const nt=110,it=110,ot=110,at=200,ct=201,dt=202,ut=210,lt=108,pt=213,ht=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,qt=505,$t=506,Gt=507,Ft=508,Bt=509,jt=510,zt=511,Kt=206,Ht=207,Vt=216,Wt=217,Jt=218,Zt=219,Qt=220,Yt=221,Xt=305,er=403,tr=405,rr=406,sr=1200,nr=1299,ir=303,or=110,ar=4,cr=4,dr=500,ur=2,lr=500,pr=2,hr=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,qr=402,$r=301,Gr=1,Fr=4,Br=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=Br,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??pr,t),this.name="NetworkError"}}class Wr extends Hr{constructor(e,t){super(e,t?.code??gt,t),this.name="ConnectionError"}}class Jr extends Hr{constructor(e,t){super(e,t?.code??dt,t),this.name="AuthenticationError"}}class Zr extends Hr{constructor(e,t){super(e,t?.code??ot,t),this.name="ValidationError"}}class Qr extends Hr{constructor(e,t){super(e,t?.code??_t,t),this.name="MessageSendError"}}class Yr extends Hr{constructor(e,t){super(e,t?.code??Mt,t),this.name="MessageReceiveError"}}class Xr extends Hr{constructor(e,t){super(e,t?.code??Ct,t),this.name="StorageError"}}class es extends Hr{constructor(e,t){super(e,t?.code??pr,t),this.name="RestTransportError"}}class ts extends Hr{constructor(e,t){super(e,t?.code??fr,t),this.name="RestBusinessError"}}class rs extends Hr{constructor(e,t){super(e,t?.code??qr,t),this.name="UploadError"}}const ss=0,ns=1,is=2,os=3,as=4,cs=0,ds=1,us=2,ls=3,ps=4,hs=5,ms=6,fs=7,gs=8,ys=0,vs=1,bs=2,Is=3,ws=4,Cs=5,Ss=6,Ts=7,_s=8,Rs=0,As=1,Ms=2,Es=3,Us=4,Ns=0,Os=1,xs=2,Ls=3,Ps=5,Ds=0,qs=1,$s=2,Gs=0,Fs=0,Bs=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,pn=2,hn=3,mn=4,fn=5,gn=6,yn=7,vn=8,bn="Sorry, user register limit",In="Sorry, user register rate limit",wn="Sorry, token expired",Cn="Sorry, token or password does not match login info",Sn="Sorry, user not found",Tn="Sorry, the app month live count limit",_n="Sorry, the app day live count limit",Rn="Sorry, the app online count limit",An={[zs]:dt,[Ks]:dt,[Hs]:nt,[Vs]:it,[Ws]:gt,[Js]:lt,[Zs]:ut,[dn]:ut,[Qs]:gt,[Ys]:Br,[Xs]:Br,[en]:pt,[tn]:ut,[rn]:ht,[sn]:Fr,[nn]:mt,[on]:Br,[an]:Br,[cn]:Mt,[un]:Qt},Mn=new Set([zs,Ks,Hs,Vs,Js,Zs,dn,Ys,Xs,en,tn,rn,sn,nn,on,an,cn,un]),En={[bn]:Fr,[In]:Fr,[wn]:lt,[Cn]:dt,[Sn]:dt,blocked:Et,"group not found":vr,"illegal chatroom tag":nt,"not in group or chatroom":gr,"exceed recall time limit":Dt,"message recall disabled":qt,"group ack not open":qt,"group ack msg permission denied":yr,"the message has expired":$t,"limit send group ack msg":Fr,"not in group or chatroom white list":Gt,nonroster:Yt,"group is disabled":br,"roaming is not open":qt,"Sorry, message does not exist":nt,"Sorry, edit limit reached":Fr,"Sorry, You do not have permission":ut,"Sorry, format is incorrect":nt,"Sorry, edit is not available":Xt,"Sorry, edit fail":zt},Un=[["limit directed users",Fr],["no permission to recall message",ut]],kn={[Tn]:Fr,[_n]:Fr,[Rn]:Fr,"sensitive words":Lt,"blocked by mod_antispam":Lt,"user is mute":Zt,"traffic limit":Bt,"Sorry, data is too large":jt},Nn=(e,t)=>{if("number"!=typeof e)return{code:Br,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?Ft:e===nn?mt:void 0}})(e,t);return{code:r??(An[e]??Br),retryable:!Mn.has(e)}},On={[Fr]:"Message operation exceeded a service limit",[lt]:"Message cannot be sent because the authentication token expired",[nt]:"Message cannot be sent because the request is invalid",[dt]:"Message cannot be sent because authentication failed",[ut]:"Message operation is forbidden",[pt]:"Message cannot be sent because the account is bound to another device",[ht]:"Message cannot be sent because the account is logged in on too many devices",[mt]:"Message cannot be sent because the user is muted in the group or chat room",[Et]:"Message cannot be sent because you are blocked by the recipient",[Zt]:"Message cannot be sent because the user is globally muted",[Qt]:"Message cannot be sent because the current device has changed",[Yt]:"Message cannot be sent because the recipient is not in your contact list",[gt]:"Message cannot be sent because the server is unreachable",[Xt]:"Message editing is not available",[Mt]:"Message processing failed",[Lt]:"Message contains prohibited content",[Pt]:"Message sending traffic limit exceeded",[Dt]:"The message recall time limit has been exceeded",[qt]:"The required messaging service is not enabled",[$t]:"The message has expired",[Gt]:"The user is not in the group or chat room allowlist",[Ft]:"The message was blocked by external logic",[Bt]:"Message sending rate limit exceeded",[jt]:"Message size exceeds the limit",[zt]:"Message editing failed",[gr]:"The user is not in the group or chat room",[yr]:"The user does not have permission to perform this group message operation",[vr]:"The group does not exist",[br]:"The group is disabled",[sr]:"The message was rejected by content moderation",[nr]:"The message was rejected by a third-party service"},xn=3e5,Ln={jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",webp:"image/webp",gif:"image/gif",bmp:"image/bmp",heic:"image/heic",heif:"image/heif",svg:"image/svg+xml",mp4:"video/mp4",mov:"video/quicktime",mp3:"audio/mpeg",m4a:"audio/mp4",wav:"audio/wav",aac:"audio/aac",amr:"audio/amr",pdf:"application/pdf",txt:"text/plain",json:"application/json"},Pn=e=>"undefined"!=typeof Blob&&e instanceof Blob,Dn=e=>{const t=e.replace(/[?#].*$/,"").split(/[\\/]/).filter(Boolean),r=t.length>0?t[t.length-1]:void 0;if(r)return r},qn=e=>{if(!e)return;const t=e.lastIndexOf(".");if(t<0||t===e.length-1)return;const r=e.slice(t+1).toLowerCase();return Ln[r]},$n=(e,t)=>{for(const r of t){const t=e[r];if("string"==typeof t&&t.length>0)return t}},Gn=e=>{const t=e.file,r=e.sourceMeta,s=t.name||(r?$n(r,["name","fileName","filename"]):void 0),n=e.file.type||(r?$n(r,["type","mimeType","filetype"]):void 0),i=e.file.size||(r?((e,t)=>{for(const r of t){const t=e[r];if("number"==typeof t&&Number.isFinite(t))return t}})(r,["size","fileSize","fileLength"]):void 0),o=Fn({fileName:s,fileType:n,fileSize:i,fallbackName:e.fallbackName,fallbackMimeType:e.fallbackMimeType,fallbackSize:e.fallbackSize});return{source:{sourceType:"web-file",file:e.file,name:o.fileName,mimeType:o.fileType,size:o.fileSize},fileName:o.fileName,fileType:o.fileType,fileSize:o.fileSize,webFile:e.file}},Fn=e=>({fileName:e.fileName??e.fallbackName??"file",fileType:e.fileType??e.fallbackMimeType??"application/octet-stream",fileSize:e.fileSize??e.fallbackSize??0}),Bn=e=>{const{file:t,fallbackName:r,fallbackMimeType:s,fallbackSize:n}=e,i=(e=>{if(Pn(e))return e;if("object"!=typeof e||null===e)return;const t=e;for(const r of["file","originFileObj","raw","blob"]){const e=t[r];if(Pn(e))return e}})(t);if(i)return Gn({file:i,fallbackName:r,fallbackMimeType:s,fallbackSize:n,sourceMeta:"object"==typeof t&&null!==t?t:void 0});if((e=>"object"==typeof e&&null!==e&&"path"in e)(t)){const e=Dn(t.path),i=Fn({fileName:t.name??e,fileType:t.type??qn(t.name??e),fileSize:t.size,fallbackName:r,fallbackMimeType:s,fallbackSize:n});return{source:{sourceType:"miniapp-path",path:t.path,name:i.fileName,mimeType:i.fileType,size:i.fileSize},fileName:i.fileName,fileType:i.fileType,fileSize:i.fileSize}}if((e=>"object"==typeof e&&null!==e&&"uri"in e)(t)){const e=Dn(t.uri),i=Fn({fileName:t.name??e,fileType:t.type??qn(t.name??e),fileSize:t.size,fallbackName:r,fallbackMimeType:s,fallbackSize:n});return{source:{sourceType:"rn-uri",uri:t.uri,name:i.fileName,mimeType:i.fileType,size:i.fileSize},fileName:i.fileName,fileType:i.fileType,fileSize:i.fileSize}}const o=Fn({fallbackName:r,fallbackMimeType:s,fallbackSize:n});return{source:{sourceType:"web-file",name:o.fileName,mimeType:o.fileType,size:o.fileSize},fileName:o.fileName,fileType:o.fileType,fileSize:o.fileSize}},jn=5242880,zn=5242880,Kn="CHAT",Hn="GROUP",Vn="ROOM",Wn="original",Jn="large",Zn=e=>/^https?:\/\//i.test(e),Qn=e=>{const t=e.split("#");if(2!==t.length||!t[0]||!t[1])throw new rs("Invalid appKey for upload",{code:Pr,details:{appKey:e}});return{orgName:t[0],appName:t[1]}},Yn=e=>"singleChat"===e?Kn:"groupChat"===e?Hn:Vn,Xn=(e,t)=>ti(e,{size:t}),ei=e=>{try{return decodeURIComponent(e)}catch{return e}},ti=(e,t)=>{const[r="",s]=e.split("#",2),[n,i=""]=r.split("?",2),o=i.split("&").filter(Boolean);return Object.entries(t).forEach(([e,t])=>{const r=encodeURIComponent(e),s=o.filter(t=>{const[s=""]=t.split("=",2);return s!==r&&ei(s)!==e});o.length=0,o.push(...s),void 0!==t&&o.push(`${r}=${encodeURIComponent(String(t))}`)}),`${n}${o.length>0?`?${o.join("&")}`:""}${s?`#${s}`:""}`},ri=(e,t)=>{if(!e)return"";const r={};return e.includes("em-redirect")||(r["em-redirect"]="true"),t&&!e.includes("share-secret=")&&(r["share-secret"]=t),0===Object.keys(r).length?e:ti(e,r)},si=e=>{const t=(r=e.messageType,s=e.imageType,"image"!==r?"attachment":s===Wn?"image-origin":"image-big");var r,s;const n=(e=>"image-origin"===e?204800:1048576)(t),i=e.fileSize>n;return{shouldPrecheck:i,thresholdType:t,thresholdBytes:n,actualBytes:e.fileSize,reason:i?"threshold-exceeded":"below-threshold"}},ni=(e,t)=>{if(!e)return{};if(!1===t?.deriveVariants)return{originalImageUrl:e};const r=(e=>{const[t="",r]=e.split("#",2),[s,n=""]=t.split("?",2),i=n.split("&").filter(Boolean).filter(e=>{const[t="",r=""]=e.split("=",2),s=ei(t),n=ei(r);return"size"!==s||!["big","large","thumbnail","small"].includes(n)}).join("&");return`${s}${i?`?${i}`:""}${r?`#${r}`:""}`})(e);return{originalImageUrl:r,bigImageUrl:Xn(r,"large"),thumbnailUrl:Xn(r,"small")}},ii=e=>e===Wn?"origin":"large",oi=e=>2===e?Jn:Wn,ai=e=>{const t=e.response.entities?.[0];if(!t?.uuid)throw new rs("Upload response missing uuid",{code:qr,details:{response:e.response}});const r=t["share-secret"],s=t["file-metadata"]??{},n="number"==typeof s["content-length"]?s["content-length"]:e.fallbackSize,i="string"==typeof s["content-type"]?s["content-type"]:e.fileType,o=`${e.restBaseUrl}/${e.orgName}/${e.appName}/chatfiles/${t.uuid}`;if("image"===e.messageType){const t=(e.imageType??Jn)===Wn;return{...ni(o,{deriveVariants:!e.useCustomAttachmentUpload}),isOriginalImage:t,secret:r,fileLength:n,filetype:i,filename:e.fileName,width:e.width,height:e.height}}const a="video"===e.messageType?`${o}?vframe=true`:void 0;return{url:o,secret:r,fileLength:n,filetype:i,filename:e.fileName,thumbnailUrl:a}},ci=e=>new Promise(t=>{setTimeout(t,e)});const di=new class{constructor(e){this.state="disabled",this.timerId=null,this.reporting=!1,this.context={},this.buffer=[],this.bufferBytes=0,this.reportIntervalMs=this.normalizeReportInterval(e?.reportIntervalMs),this.reportTimeoutMs=e?.reportTimeoutMs??15e3,this.chunkDelayMs=e?.chunkDelayMs??3e3,this.maxChunkBytes=e?.maxChunkBytes??2097152,this.maxBufferBytes=e?.maxBufferBytes??3145728}setEnabled(e){this.setState(e?"enabled":"disabled")}setState(e){this.state=e,"enabled"!==e?(this.stop(),this.clearBuffer()):this.start()}updateContext(e){this.context={...this.context,...e}}updateReportInterval(e){this.reportIntervalMs=this.normalizeReportInterval(e),"enabled"===this.state&&this.start()}append(e){if("disabled"===this.state)return;const t=this.formatEntry(e);this.pushBuffer(t)}async reportNow(){await this.reportLogs()}stop(){this.timerId&&(clearInterval(this.timerId),this.timerId=null)}clearBuffer(){this.buffer=[],this.bufferBytes=0}start(){this.stop(),this.timerId=setInterval(()=>{this.reportLogs()},this.reportIntervalMs)}normalizeReportInterval(e){const t=void 0!==e&&Number.isFinite(e)&&e>0?e:3e5;return Math.max(t,6e4)}canReport(){return Boolean(this.context.restBaseUrl&&this.context.appKey&&this.context.userId&&this.context.token&&this.context.requestAdapter)}formatEntry(e){const t=e.args.length>0?e.args.map(e=>(e=>{if("string"==typeof e)return e;try{return JSON.stringify(e)}catch{return String(e)}})(e)).join(" "):"",r=t?`${e.message} ${t}`:e.message;return`${e.timestamp} [${e.level}] ${r}`}pushBuffer(e){const t=e.length;if(!(t>=this.maxBufferBytes)){for(;this.bufferBytes+t>this.maxBufferBytes&&this.buffer.length>0;){const e=this.buffer.shift();e&&(this.bufferBytes-=e.length)}this.buffer.push(e),this.bufferBytes+=t}}consumeBuffer(){if(0===this.buffer.length)return[];const e=`${this.buffer.join("\n")}\n`;this.clearBuffer();const t=[];let r=e;for(;r.length>this.maxChunkBytes;)t.push(r.slice(0,this.maxChunkBytes)),r=r.slice(this.maxChunkBytes);return r.length>0&&t.push(r),t}requeueChunk(e){this.pushBuffer(e)}async reportLogs(){if("enabled"===this.state&&!this.reporting&&0!==this.buffer.length){this.reporting=!0;try{const e=this.consumeBuffer();if(0===e.length)return;if(!this.canReport())return void e.forEach(e=>this.requeueChunk(e));for(const t of e){await this.reportChunk(t)||this.requeueChunk(t),await ci(this.chunkDelayMs)}}finally{this.reporting=!1}}}async reportChunk(e){if(!this.canReport())return!1;const{restBaseUrl:t,appKey:r,userId:s,token:n,resource:i,requestAdapter:o}=this.context;if(!(t&&r&&s&&n&&o))return!1;let a="",c="";try{const e=Qn(r);a=e.orgName,c=e.appName}catch{return!1}const d=`${t}/${a}/${c}/sdk/users/${s}/client/logs`,u={resource:i??"webim",logContent:e};try{const e=await o.request({url:d,method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json",Accept:"application/json"},body:u,responseType:"json",timeoutMs:this.reportTimeoutMs});if(e.status<200||e.status>=300)return!1;const t="string"==typeof e.data?(e=>{try{return JSON.parse(e)}catch{return}})(e.data):e.data;return!t||!t.status||"ok"===t.status}catch{return!1}}},ui="[MASKED]",li=new Set(["token","password","authorization","appkey","userid","deviceid","accesstoken","refreshtoken","secret","authtoken","sessionid","clientresource"]),pi=e=>!!e&&li.has((e=>e.toLowerCase())(e)),hi=(e,t,r)=>{const s=r??new WeakSet;if("string"==typeof e)return((e,t)=>pi(t)?ui:e)(e,t);if("number"==typeof e||"boolean"==typeof e||null==e)return e;if("bigint"==typeof e||"symbol"==typeof e)return e.toString();if("function"==typeof e)return`[Function ${e.name||"anonymous"}]`;if(e instanceof Error)return{name:(n=e).name,message:n.message};var n;if(e instanceof Date)return e.toISOString();if(Array.isArray(e))return e.map(e=>hi(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))pi(r)?t[r]=ui:t[r]=hi(n,r,s);return t}return Object.prototype.toString.call(e)}return"[Unsupported]"},mi="undefined"!=typeof document,fi={DEBUG:0,WARN:1,ERROR:2};class gi{constructor(e="WARN"){this.level=e}setLevel(e){this.level=e}shouldLog(e){return fi[e]>=fi[this.level]}emit(e,t,r){const s=(e=>{const t=new WeakSet;return e.map(e=>hi(e,void 0,t))})(r),n=((e,t,r)=>({timestamp:(new Date).toISOString(),level:e,message:t,args:r}))(e,t,s);di.append(n);const i=new Date,o=`[Chat][${e}][${`${String(i.getHours()).padStart(2,"0")}:${String(i.getMinutes()).padStart(2,"0")}:${String(i.getSeconds()).padStart(2,"0")}.${String(i.getMilliseconds()).padStart(3,"0")}`}]`;mi?console.log(`%c${o}`,"color: rgb(0, 157, 255); font-weight: bold",t,...s):console.log(o,t,...s)}debug(e,...t){this.shouldLog("DEBUG")&&this.emit("DEBUG",e,t)}warn(e,...t){this.shouldLog("WARN")&&this.emit("WARN",e,t)}error(e,...t){this.shouldLog("ERROR")&&this.emit("ERROR",e,t)}}let yi=new gi;function vi(e){di.setState(e)}function bi(e){di.updateContext(e)}async function Ii(){await di.reportNow()}function wi(){di.stop()}const Ci=(e,...t)=>yi.debug(e,...t),Si=(e,...t)=>yi.warn(e,...t),Ti=(e,...t)=>yi.error(e,...t),_i=e=>{if("function"==typeof TextEncoder)return(new TextEncoder).encode(e);const t=[];for(let r=0;r<e.length;r+=1){let s=e.charCodeAt(r);if(s>=55296&&s<=56319&&r+1<e.length){const t=e.charCodeAt(r+1);t>=56320&&t<=57343&&(s=65536+(s-55296<<10)+(t-56320),r+=1)}s<=127?t.push(s):s<=2047?t.push(192|s>>6,128|63&s):s<=65535?t.push(224|s>>12,128|s>>6&63,128|63&s):t.push(240|s>>18,128|s>>12&63,128|s>>6&63,128|63&s)}return new Uint8Array(t)},Ri=e=>{if("function"==typeof TextDecoder)return(new TextDecoder).decode(e);let t="";for(let r=0;r<e.length;r+=1){const s=e[r]??0;if(s<128){t+=String.fromCharCode(s);continue}if(s>=192&&s<224){const n=e[r+1]??0;t+=String.fromCharCode((31&s)<<6|63&n),r+=1;continue}if(s>=224&&s<240){const n=e[r+1]??0,i=e[r+2]??0;t+=String.fromCharCode((15&s)<<12|(63&n)<<6|63&i),r+=2;continue}const n=((7&s)<<18|(63&(e[r+1]??0))<<12|(63&(e[r+2]??0))<<6|63&(e[r+3]??0))-65536;t+=String.fromCharCode(55296+(n>>10),56320+(1023&n)),r+=3}return t};class Ai{constructor(){this.lastEventKey=null}normalize(e,u){const l=(e=>{switch(e){case r:case n:return o;case s:return a;case t:return c;case i:return d;default:return null}})(e);if(!l)return null;const p=((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===p?null:(this.lastEventKey=p,{eventName:l,payload:u})}reset(){this.lastEventKey=null}}const Mi={WEB:"web",WECHAT_MINIAPP:"wechat-miniapp",QQ_MINIAPP:"qq-miniapp",TOUTIAO_MINIAPP:"toutiao-miniapp",BAIDU_MINIAPP:"baidu-miniapp",ALIPAY_MINIAPP:"alipay-miniapp",DINGTALK_MINIAPP:"dingtalk-miniapp",LARK_MINIAPP:"lark-miniapp",KUAISHOU_MINIAPP:"kuaishou-miniapp",JD_MINIAPP:"jd-miniapp",MINIAPP_360:"360-miniapp",HARMONY_MINIAPP:"harmony-miniapp",QUICKAPP:"quickapp",UNIAPP:"uniapp",REACT_NATIVE:"react-native",ELECTRON_RENDERER:"electron-renderer",ELECTRON_MAIN:"electron-main",UNKNOWN:"unknown"},Ei="init",Ui="request",ki="upload",Ni="socket",Oi="proto",xi="runtime",Li="PLATFORM_INIT_FAILED",Pi="PLATFORM_MISSING_CAPABILITY",Di="PLATFORM_REQUEST_FAILED",qi="PLATFORM_UPLOAD_FAILED",$i="PLATFORM_SOCKET_FAILED",Gi="PLATFORM_PROTO_FAILED",Fi=(e,t)=>{const r=new Error(e);return r.name="PlatformAdapterError",r.code=t.code,r.stage=t.stage,r.retryable=t.retryable,t.details&&(r.details=Kr(t.details)),r},Bi=0,ji=1,zi=2,Ki=3,Hi=["__uniConfig","skipWaiting","registration","navigator","process","window","document","localStorage","fetch","WebSocket","XMLHttpRequest","FormData","TextEncoder","TextDecoder","crypto"],Vi=e=>{if(e)return e;return((e,t)=>{if(!e)return t;if(0===Object.keys(t).length)return e;const r={},s=e;for(const n of Hi)try{const e=s[n];void 0!==e&&(r[n]=e)}catch{}for(const n of Object.keys(t))r[n]=t[n];return r})("undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:"undefined"!=typeof global?global:void 0,{..."undefined"!=typeof wx?{wx:wx}:{},..."undefined"!=typeof qq?{qq:qq}:{},..."undefined"!=typeof tt?{tt:tt}:{},..."undefined"!=typeof swan?{swan:swan}:{},..."undefined"!=typeof my?{my:my}:{},..."undefined"!=typeof dd?{dd:dd}:{},..."undefined"!=typeof jd?{jd:jd}:{},..."undefined"!=typeof ks?{ks:ks}:{},..."undefined"!=typeof uni?{uni:uni}:{}})},Wi={web:Mi.WEB,"mp-weixin":Mi.WECHAT_MINIAPP,"mp-alipay":Mi.ALIPAY_MINIAPP,"mp-baidu":Mi.BAIDU_MINIAPP,"mp-toutiao":Mi.TOUTIAO_MINIAPP,"mp-lark":Mi.LARK_MINIAPP,"mp-qq":Mi.QQ_MINIAPP,"mp-kuaishou":Mi.KUAISHOU_MINIAPP,"mp-jd":Mi.JD_MINIAPP,"mp-360":Mi.MINIAPP_360,"mp-harmony":Mi.HARMONY_MINIAPP,"quickapp-webview":Mi.QUICKAPP,"quickapp-webview-union":Mi.QUICKAPP,"quickapp-webview-huawei":Mi.QUICKAPP},Ji=(e,t)=>{if("object"!=typeof e&&"function"!=typeof e||null===e)return!1;return"function"==typeof e[t]},Zi=e=>(e=>Ji(e,"canIUse")&&Ji(e,"getSystemInfo"))(e)||(e=>Ji(e,"request")&&Ji(e,"connectSocket"))(e),Qi=e=>Ji(e,"request")&&Ji(e,"connectSocket")&&Ji(e,"uploadFile"),Yi=(e,t)=>t===Mi.WECHAT_MINIAPP?e.wx:t===Mi.QQ_MINIAPP?e.qq:t===Mi.TOUTIAO_MINIAPP?e.tt:t===Mi.BAIDU_MINIAPP?e.swan:t===Mi.ALIPAY_MINIAPP?e.my:t===Mi.DINGTALK_MINIAPP?e.dd:t===Mi.JD_MINIAPP?e.jd:t===Mi.KUAISHOU_MINIAPP?e.ks:t===Mi.UNIAPP?e.uni:void 0,Xi=e=>{const t=e?.miniGlobal;return Zi(t)?t:e},eo=e=>{const t=Xi(e);return Qi(t)?t:void 0},to=e=>void 0!==e.window&&void 0!==e.document,ro=e=>!(void 0!==e.window||void 0!==e.document)&&"function"==typeof e.fetch&&("function"==typeof e.skipWaiting||void 0!==e.registration),so=e=>{const t=e.uni;if(void 0!==e.__uniConfig)return!0;if(Zi(t))return!0;try{if(!Ji(t,"getSystemInfoSync"))return!1;const e=t.getSystemInfoSync();return"object"==typeof e&&null!==e&&"string"==typeof e.uniPlatform}catch{return!1}},no=e=>Qi(e.wx)?Mi.WECHAT_MINIAPP:Qi(e.my)?Mi.ALIPAY_MINIAPP:Qi(e.dd)?Mi.DINGTALK_MINIAPP:Qi(e.swan)?Mi.BAIDU_MINIAPP:Qi(e.tt)?Mi.TOUTIAO_MINIAPP:Qi(e.qq)?Mi.QQ_MINIAPP:Qi(e.jd)?Mi.JD_MINIAPP:Qi(e.ks)?Mi.KUAISHOU_MINIAPP:void 0,io=e=>void 0!==no(e),oo=e=>{const t=no(e);if(t)return t;try{const t=e.uni?.getSystemInfoSync?.(),r=t?.uniPlatform;if("string"==typeof r)return Wi[r]??Mi.UNIAPP}catch{return Mi.UNIAPP}return to(e)?Mi.WEB:Mi.UNIAPP},ao=(e,t)=>{const r=eo(Yi(e,t));if(r)return r;const s=eo(e.uni);return s||(e.uni??e)},co=(e,t)=>{const r=e??Vi();if(t){const e=t===Mi.UNIAPP||so(r),s=e?oo(r):t;return{platform:t,hostPlatform:s,framework:e?"uniapp":to(r)?"web":"native",global:e?ao(r,s):Xi(Yi(r,t))??r}}if(so(r)){const e=oo(r);return{platform:Mi.UNIAPP,hostPlatform:e,framework:"uniapp",global:ao(r,e)}}return Zi(r.swan)?{platform:Mi.BAIDU_MINIAPP,hostPlatform:Mi.BAIDU_MINIAPP,framework:"native",global:Xi(r.swan)??r.swan}:Zi(r.tt)?{platform:Mi.TOUTIAO_MINIAPP,hostPlatform:Mi.TOUTIAO_MINIAPP,framework:"native",global:Xi(r.tt)??r.tt}:Zi(r.dd)?{platform:Mi.DINGTALK_MINIAPP,hostPlatform:Mi.DINGTALK_MINIAPP,framework:"native",global:Xi(r.dd)??r.dd}:Zi(r.my)?{platform:Mi.ALIPAY_MINIAPP,hostPlatform:Mi.ALIPAY_MINIAPP,framework:"native",global:Xi(r.my)??r.my}:Zi(r.wx)?{platform:Mi.WECHAT_MINIAPP,hostPlatform:Mi.WECHAT_MINIAPP,framework:"native",global:Xi(r.wx)??r.wx}:Zi(r.qq)?{platform:Mi.QQ_MINIAPP,hostPlatform:Mi.QQ_MINIAPP,framework:"native",global:Xi(r.qq)??r.qq}:Zi(r.jd)?{platform:Mi.JD_MINIAPP,hostPlatform:Mi.JD_MINIAPP,framework:"native",global:Xi(r.jd)??r.jd}:Zi(r.ks)?{platform:Mi.KUAISHOU_MINIAPP,hostPlatform:Mi.KUAISHOU_MINIAPP,framework:"native",global:Xi(r.ks)??r.ks}:(e=>"ReactNative"===e.navigator?.product)(r)?{platform:Mi.REACT_NATIVE,hostPlatform:Mi.REACT_NATIVE,framework:"react-native",global:r}:(e=>"string"==typeof e.process?.versions?.electron)(r)?{platform:to(r)?Mi.ELECTRON_RENDERER:Mi.ELECTRON_MAIN,hostPlatform:to(r)?Mi.ELECTRON_RENDERER:Mi.ELECTRON_MAIN,framework:"electron",global:r}:ro(r)||to(r)?{platform:Mi.WEB,hostPlatform:Mi.WEB,framework:ro(r)?"worker":"web",global:r}:{platform:Mi.UNKNOWN,hostPlatform:Mi.UNKNOWN,framework:"native",global:r}},uo=e=>e===Mi.WECHAT_MINIAPP||e===Mi.QQ_MINIAPP||e===Mi.TOUTIAO_MINIAPP||e===Mi.BAIDU_MINIAPP||e===Mi.ALIPAY_MINIAPP||e===Mi.DINGTALK_MINIAPP||e===Mi.LARK_MINIAPP||e===Mi.KUAISHOU_MINIAPP||e===Mi.JD_MINIAPP||e===Mi.MINIAPP_360||e===Mi.HARMONY_MINIAPP||e===Mi.QUICKAPP||e===Mi.UNIAPP,lo=["request","upload","socket","proto"],po=(e,t=lo)=>{const r=((e,t=lo)=>t.filter(t=>!e[t]))(e,t);if(0!==r.length)throw Fi("Platform missing required capabilities.",{code:Pi,stage:Ei,retryable:!1,details:{required:[...t],missing:r}})};var ho=null;try{ho=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch{}function mo(e,t,r){this.low=0|e,this.high=0|t,this.unsigned=!!r}function fo(e){return!0===(e&&e.__isLong__)}function go(e){var t=Math.clz32(e&-e);return e?31-t:t}mo.prototype.__isLong__,Object.defineProperty(mo.prototype,"__isLong__",{value:!0}),mo.isLong=fo;var yo={},vo={};function bo(e,t){var r,s,n;return t?(n=0<=(e>>>=0)&&e<256)&&(s=vo[e])?s:(r=wo(e,0,!0),n&&(vo[e]=r),r):(n=-128<=(e|=0)&&e<128)&&(s=yo[e])?s:(r=wo(e,e<0?-1:0,!1),n&&(yo[e]=r),r)}function Io(e,t){if(isNaN(e))return t?Uo:Eo;if(t){if(e<0)return Uo;if(e>=Ro)return Lo}else{if(e<=-Ao)return Po;if(e+1>=Ao)return xo}return e<0?Io(-e,t).neg():wo(e%_o|0,e/_o|0,t)}function wo(e,t,r){return new mo(e,t,r)}mo.fromInt=bo,mo.fromNumber=Io,mo.fromBits=wo;var Co=Math.pow;function So(e,t,r){if(0===e.length)throw Error("empty string");if("number"==typeof t?(r=t,t=!1):t=!!t,"NaN"===e||"Infinity"===e||"+Infinity"===e||"-Infinity"===e)return t?Uo:Eo;if((r=r||10)<2||36<r)throw RangeError("radix");var s;if((s=e.indexOf("-"))>0)throw Error("interior hyphen");if(0===s)return So(e.substring(1),t,r).neg();for(var n=Io(Co(r,8)),i=Eo,o=0;o<e.length;o+=8){var a=Math.min(8,e.length-o),c=parseInt(e.substring(o,o+a),r);if(a<8){var d=Io(Co(r,a));i=i.mul(d).add(Io(c))}else i=(i=i.mul(n)).add(Io(c))}return i.unsigned=t,i}function To(e,t){return"number"==typeof e?Io(e,t):"string"==typeof e?So(e,t):wo(e.low,e.high,"boolean"==typeof t?t:e.unsigned)}mo.fromString=So,mo.fromValue=To;var _o=4294967296,Ro=_o*_o,Ao=Ro/2,Mo=bo(1<<24),Eo=bo(0);mo.ZERO=Eo;var Uo=bo(0,!0);mo.UZERO=Uo;var ko=bo(1);mo.ONE=ko;var No=bo(1,!0);mo.UONE=No;var Oo=bo(-1);mo.NEG_ONE=Oo;var xo=wo(-1,2147483647,!1);mo.MAX_VALUE=xo;var Lo=wo(-1,-1,!0);mo.MAX_UNSIGNED_VALUE=Lo;var Po=wo(0,-2147483648,!1);mo.MIN_VALUE=Po;var Do=mo.prototype;Do.toInt=function(){return this.unsigned?this.low>>>0:this.low},Do.toNumber=function(){return this.unsigned?(this.high>>>0)*_o+(this.low>>>0):this.high*_o+(this.low>>>0)},Do.toString=function(e){if((e=e||10)<2||36<e)throw RangeError("radix");if(this.isZero())return"0";if(this.isNegative()){if(this.eq(Po)){var t=Io(e),r=this.div(t),s=r.mul(t).sub(this);return r.toString(e)+s.toInt().toString(e)}return"-"+this.neg().toString(e)}for(var n=Io(Co(e,6),this.unsigned),i=this,o="";;){var a=i.div(n),c=(i.sub(a.mul(n)).toInt()>>>0).toString(e);if((i=a).isZero())return c+o;for(;c.length<6;)c="0"+c;o=""+c+o}},Do.getHighBits=function(){return this.high},Do.getHighBitsUnsigned=function(){return this.high>>>0},Do.getLowBits=function(){return this.low},Do.getLowBitsUnsigned=function(){return this.low>>>0},Do.getNumBitsAbs=function(){if(this.isNegative())return this.eq(Po)?64:this.neg().getNumBitsAbs();for(var e=0!=this.high?this.high:this.low,t=31;t>0&&!(e&1<<t);t--);return 0!=this.high?t+33:t+1},Do.isSafeInteger=function(){var e=this.high>>21;return!e||!this.unsigned&&(-1===e&&!(0===this.low&&-2097152===this.high))},Do.isZero=function(){return 0===this.high&&0===this.low},Do.eqz=Do.isZero,Do.isNegative=function(){return!this.unsigned&&this.high<0},Do.isPositive=function(){return this.unsigned||this.high>=0},Do.isOdd=function(){return!(1&~this.low)},Do.isEven=function(){return!(1&this.low)},Do.equals=function(e){return fo(e)||(e=To(e)),(this.unsigned===e.unsigned||this.high>>>31!=1||e.high>>>31!=1)&&(this.high===e.high&&this.low===e.low)},Do.eq=Do.equals,Do.notEquals=function(e){return!this.eq(e)},Do.neq=Do.notEquals,Do.ne=Do.notEquals,Do.lessThan=function(e){return this.comp(e)<0},Do.lt=Do.lessThan,Do.lessThanOrEqual=function(e){return this.comp(e)<=0},Do.lte=Do.lessThanOrEqual,Do.le=Do.lessThanOrEqual,Do.greaterThan=function(e){return this.comp(e)>0},Do.gt=Do.greaterThan,Do.greaterThanOrEqual=function(e){return this.comp(e)>=0},Do.gte=Do.greaterThanOrEqual,Do.ge=Do.greaterThanOrEqual,Do.compare=function(e){if(fo(e)||(e=To(e)),this.eq(e))return 0;var t=this.isNegative(),r=e.isNegative();return t&&!r?-1:!t&&r?1:this.unsigned?e.high>>>0>this.high>>>0||e.high===this.high&&e.low>>>0>this.low>>>0?-1:1:this.sub(e).isNegative()?-1:1},Do.comp=Do.compare,Do.negate=function(){return!this.unsigned&&this.eq(Po)?Po:this.not().add(ko)},Do.neg=Do.negate,Do.add=function(e){fo(e)||(e=To(e));var t=this.high>>>16,r=65535&this.high,s=this.low>>>16,n=65535&this.low,i=e.high>>>16,o=65535&e.high,a=e.low>>>16,c=0,d=0,u=0,l=0;return u+=(l+=n+(65535&e.low))>>>16,d+=(u+=s+a)>>>16,c+=(d+=r+o)>>>16,c+=t+i,wo((u&=65535)<<16|(l&=65535),(c&=65535)<<16|(d&=65535),this.unsigned)},Do.subtract=function(e){return fo(e)||(e=To(e)),this.add(e.neg())},Do.sub=Do.subtract,Do.multiply=function(e){if(this.isZero())return this;if(fo(e)||(e=To(e)),ho)return wo(ho.mul(this.low,this.high,e.low,e.high),ho.get_high(),this.unsigned);if(e.isZero())return this.unsigned?Uo:Eo;if(this.eq(Po))return e.isOdd()?Po:Eo;if(e.eq(Po))return this.isOdd()?Po:Eo;if(this.isNegative())return e.isNegative()?this.neg().mul(e.neg()):this.neg().mul(e).neg();if(e.isNegative())return this.mul(e.neg()).neg();if(this.lt(Mo)&&e.lt(Mo))return Io(this.toNumber()*e.toNumber(),this.unsigned);var t=this.high>>>16,r=65535&this.high,s=this.low>>>16,n=65535&this.low,i=e.high>>>16,o=65535&e.high,a=e.low>>>16,c=65535&e.low,d=0,u=0,l=0,p=0;return l+=(p+=n*c)>>>16,u+=(l+=s*c)>>>16,l&=65535,u+=(l+=n*a)>>>16,d+=(u+=r*c)>>>16,u&=65535,d+=(u+=s*a)>>>16,u&=65535,d+=(u+=n*o)>>>16,d+=t*c+r*a+s*o+n*i,wo((l&=65535)<<16|(p&=65535),(d&=65535)<<16|(u&=65535),this.unsigned)},Do.mul=Do.multiply,Do.divide=function(e){if(fo(e)||(e=To(e)),e.isZero())throw Error("division by zero");var t,r,s;if(ho)return this.unsigned||-2147483648!==this.high||-1!==e.low||-1!==e.high?wo((this.unsigned?ho.div_u:ho.div_s)(this.low,this.high,e.low,e.high),ho.get_high(),this.unsigned):this;if(this.isZero())return this.unsigned?Uo:Eo;if(this.unsigned){if(e.unsigned||(e=e.toUnsigned()),e.gt(this))return Uo;if(e.gt(this.shru(1)))return No;s=Uo}else{if(this.eq(Po))return e.eq(ko)||e.eq(Oo)?Po:e.eq(Po)?ko:(t=this.shr(1).div(e).shl(1)).eq(Eo)?e.isNegative()?ko:Oo:(r=this.sub(e.mul(t)),s=t.add(r.div(e)));if(e.eq(Po))return this.unsigned?Uo:Eo;if(this.isNegative())return e.isNegative()?this.neg().div(e.neg()):this.neg().div(e).neg();if(e.isNegative())return this.div(e.neg()).neg();s=Eo}for(r=this;r.gte(e);){t=Math.max(1,Math.floor(r.toNumber()/e.toNumber()));for(var n=Math.ceil(Math.log(t)/Math.LN2),i=n<=48?1:Co(2,n-48),o=Io(t),a=o.mul(e);a.isNegative()||a.gt(r);)a=(o=Io(t-=i,this.unsigned)).mul(e);o.isZero()&&(o=ko),s=s.add(o),r=r.sub(a)}return s},Do.div=Do.divide,Do.modulo=function(e){return fo(e)||(e=To(e)),ho?wo((this.unsigned?ho.rem_u:ho.rem_s)(this.low,this.high,e.low,e.high),ho.get_high(),this.unsigned):this.sub(this.div(e).mul(e))},Do.mod=Do.modulo,Do.rem=Do.modulo,Do.not=function(){return wo(~this.low,~this.high,this.unsigned)},Do.countLeadingZeros=function(){return this.high?Math.clz32(this.high):Math.clz32(this.low)+32},Do.clz=Do.countLeadingZeros,Do.countTrailingZeros=function(){return this.low?go(this.low):go(this.high)+32},Do.ctz=Do.countTrailingZeros,Do.and=function(e){return fo(e)||(e=To(e)),wo(this.low&e.low,this.high&e.high,this.unsigned)},Do.or=function(e){return fo(e)||(e=To(e)),wo(this.low|e.low,this.high|e.high,this.unsigned)},Do.xor=function(e){return fo(e)||(e=To(e)),wo(this.low^e.low,this.high^e.high,this.unsigned)},Do.shiftLeft=function(e){return fo(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?wo(this.low<<e,this.high<<e|this.low>>>32-e,this.unsigned):wo(0,this.low<<e-32,this.unsigned)},Do.shl=Do.shiftLeft,Do.shiftRight=function(e){return fo(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?wo(this.low>>>e|this.high<<32-e,this.high>>e,this.unsigned):wo(this.high>>e-32,this.high>=0?0:-1,this.unsigned)},Do.shr=Do.shiftRight,Do.shiftRightUnsigned=function(e){return fo(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?wo(this.low>>>e|this.high<<32-e,this.high>>>e,this.unsigned):wo(32===e?this.high:this.high>>>e-32,0,this.unsigned)},Do.shru=Do.shiftRightUnsigned,Do.shr_u=Do.shiftRightUnsigned,Do.rotateLeft=function(e){var t;return fo(e)&&(e=e.toInt()),0==(e&=63)?this:32===e?wo(this.high,this.low,this.unsigned):e<32?(t=32-e,wo(this.low<<e|this.high>>>t,this.high<<e|this.low>>>t,this.unsigned)):(t=32-(e-=32),wo(this.high<<e|this.low>>>t,this.low<<e|this.high>>>t,this.unsigned))},Do.rotl=Do.rotateLeft,Do.rotateRight=function(e){var t;return fo(e)&&(e=e.toInt()),0==(e&=63)?this:32===e?wo(this.high,this.low,this.unsigned):e<32?(t=32-e,wo(this.high<<t|this.low>>>e,this.low<<t|this.high>>>e,this.unsigned)):(t=32-(e-=32),wo(this.low<<t|this.high>>>e,this.high<<t|this.low>>>e,this.unsigned))},Do.rotr=Do.rotateRight,Do.toSigned=function(){return this.unsigned?wo(this.low,this.high,!1):this},Do.toUnsigned=function(){return this.unsigned?this:wo(this.low,this.high,!0)},Do.toBytes=function(e){return e?this.toBytesLE():this.toBytesBE()},Do.toBytesLE=function(){var e=this.high,t=this.low;return[255&t,t>>>8&255,t>>>16&255,t>>>24,255&e,e>>>8&255,e>>>16&255,e>>>24]},Do.toBytesBE=function(){var e=this.high,t=this.low;return[e>>>24,e>>>16&255,e>>>8&255,255&e,t>>>24,t>>>16&255,t>>>8&255,255&t]},mo.fromBytes=function(e,t,r){return r?mo.fromBytesLE(e,t):mo.fromBytesBE(e,t)},mo.fromBytesLE=function(e,t){return new mo(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24,t)},mo.fromBytesBE=function(e,t){return new mo(e[4]<<24|e[5]<<16|e[6]<<8|e[7],e[0]<<24|e[1]<<16|e[2]<<8|e[3],t)},"function"==typeof BigInt&&(mo.fromBigInt=function(e,t){return wo(Number(BigInt.asIntN(32,e)),Number(BigInt.asIntN(32,e>>BigInt(32))),t)},mo.fromValue=function(e,t){return"bigint"==typeof e?mo.fromBigInt(e,t):To(e,t)},Do.toBigInt=function(){var e=BigInt(this.low>>>0);return BigInt(this.unsigned?this.high>>>0:this.high)<<BigInt(32)|e});var qo,$o,Go="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},Fo={exports:{}},Bo={},jo={};function zo(){if($o)return qo;return $o=1,qo=function(e,t){var r=new Array(arguments.length-1),s=0,n=2,i=!0;for(;n<arguments.length;)r[s++]=arguments[n++];return new Promise(function(n,o){r[s]=function(e){if(i)if(i=!1,e)o(e);else{for(var t=new Array(arguments.length-1),r=0;r<t.length;)t[r++]=arguments[r];n.apply(null,t)}};try{e.apply(t||null,r)}catch(a){i&&(i=!1,o(a))}})},qo}var Ko,Ho,Vo,Wo,Jo,Zo,Qo,Yo={};function Xo(){return Qo?Zo:(Qo=1,Zo=function(){return null})}var ea,ta,ra,sa,na,ia,oa,aa,ca,da,ua,la,pa,ha,ma={};function fa(){return ia||(ia=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=zo(),r.base64=(Ko||(Ko=1,function(e){var t=e;t.length=function(e){var t=e.length;if(!t)return 0;for(var r=0;--t%4>1&&"="===e.charAt(t);)++r;return Math.ceil(3*e.length)/4-r};for(var r=new Array(64),s=new Array(123),n=0;n<64;)s[r[n]=n<26?n+65:n<52?n+71:n<62?n-4:n-59|43]=n++;t.encode=function(e,t,s){for(var n,i=null,o=[],a=0,c=0;t<s;){var d=e[t++];switch(c){case 0:o[a++]=r[d>>2],n=(3&d)<<4,c=1;break;case 1:o[a++]=r[n|d>>4],n=(15&d)<<2,c=2;break;case 2:o[a++]=r[n|d>>6],o[a++]=r[63&d],c=0}a>8191&&((i||(i=[])).push(String.fromCharCode.apply(String,o)),a=0)}return c&&(o[a++]=r[n],o[a++]=61,1===c&&(o[a++]=61)),i?(a&&i.push(String.fromCharCode.apply(String,o.slice(0,a))),i.join("")):String.fromCharCode.apply(String,o.slice(0,a))};var i="invalid encoding";t.decode=function(e,t,r){for(var n,o=r,a=0,c=0;c<e.length;){var d=e.charCodeAt(c++);if(61===d&&a>1)break;if(void 0===(d=s[d]))throw Error(i);switch(a){case 0:n=d,a=1;break;case 1:t[r++]=n<<2|(48&d)>>4,n=d,a=2;break;case 2:t[r++]=(15&n)<<4|(60&d)>>2,n=d,a=3;break;case 3:t[r++]=(3&n)<<6|d,a=0}}if(1===a)throw Error(i);return r-o},t.test=function(e){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e)}}(Yo)),Yo),r.EventEmitter=function(){if(Vo)return Ho;function e(){this._listeners={}}return Vo=1,Ho=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},Ho}(),r.float=function(){if(Jo)return Wo;function e(e){return"undefined"!=typeof Float32Array?function(){var t=new Float32Array([-0]),r=new Uint8Array(t.buffer),s=128===r[3];function n(e,s,n){t[0]=e,s[n]=r[0],s[n+1]=r[1],s[n+2]=r[2],s[n+3]=r[3]}function i(e,s,n){t[0]=e,s[n]=r[3],s[n+1]=r[2],s[n+2]=r[1],s[n+3]=r[0]}function o(e,s){return r[0]=e[s],r[1]=e[s+1],r[2]=e[s+2],r[3]=e[s+3],t[0]}function a(e,s){return r[3]=e[s],r[2]=e[s+1],r[1]=e[s+2],r[0]=e[s+3],t[0]}e.writeFloatLE=s?n:i,e.writeFloatBE=s?i:n,e.readFloatLE=s?o:a,e.readFloatBE=s?a:o}():function(){function i(e,t,r,s){var n=t<0?1:0;if(n&&(t=-t),0===t)e(1/t>0?0:2147483648,r,s);else if(isNaN(t))e(2143289344,r,s);else if(t>34028234663852886e22)e((n<<31|2139095040)>>>0,r,s);else if(t<11754943508222875e-54)e((n<<31|Math.round(t/1401298464324817e-60))>>>0,r,s);else{var i=Math.floor(Math.log(t)/Math.LN2);e((n<<31|i+127<<23|8388607&Math.round(t*Math.pow(2,-i)*8388608))>>>0,r,s)}}function o(e,t,r){var s=e(t,r),n=2*(s>>31)+1,i=s>>>23&255,o=8388607&s;return 255===i?o?NaN:n*(1/0):0===i?1401298464324817e-60*n*o:n*Math.pow(2,i-150)*(o+8388608)}e.writeFloatLE=i.bind(null,t),e.writeFloatBE=i.bind(null,r),e.readFloatLE=o.bind(null,s),e.readFloatBE=o.bind(null,n)}(),"undefined"!=typeof Float64Array?function(){var t=new Float64Array([-0]),r=new Uint8Array(t.buffer),s=128===r[7];function n(e,s,n){t[0]=e,s[n]=r[0],s[n+1]=r[1],s[n+2]=r[2],s[n+3]=r[3],s[n+4]=r[4],s[n+5]=r[5],s[n+6]=r[6],s[n+7]=r[7]}function i(e,s,n){t[0]=e,s[n]=r[7],s[n+1]=r[6],s[n+2]=r[5],s[n+3]=r[4],s[n+4]=r[3],s[n+5]=r[2],s[n+6]=r[1],s[n+7]=r[0]}function o(e,s){return r[0]=e[s],r[1]=e[s+1],r[2]=e[s+2],r[3]=e[s+3],r[4]=e[s+4],r[5]=e[s+5],r[6]=e[s+6],r[7]=e[s+7],t[0]}function a(e,s){return r[7]=e[s],r[6]=e[s+1],r[5]=e[s+2],r[4]=e[s+3],r[3]=e[s+4],r[2]=e[s+5],r[1]=e[s+6],r[0]=e[s+7],t[0]}e.writeDoubleLE=s?n:i,e.writeDoubleBE=s?i:n,e.readDoubleLE=s?o:a,e.readDoubleBE=s?a:o}():function(){function i(e,t,r,s,n,i){var o=s<0?1:0;if(o&&(s=-s),0===s)e(0,n,i+t),e(1/s>0?0:2147483648,n,i+r);else if(isNaN(s))e(0,n,i+t),e(2146959360,n,i+r);else if(s>17976931348623157e292)e(0,n,i+t),e((o<<31|2146435072)>>>0,n,i+r);else{var a;if(s<22250738585072014e-324)e((a=s/5e-324)>>>0,n,i+t),e((o<<31|a/4294967296)>>>0,n,i+r);else{var c=Math.floor(Math.log(s)/Math.LN2);1024===c&&(c=1023),e(4503599627370496*(a=s*Math.pow(2,-c))>>>0,n,i+t),e((o<<31|c+1023<<20|1048576*a&1048575)>>>0,n,i+r)}}}function o(e,t,r,s,n){var i=e(s,n+t),o=e(s,n+r),a=2*(o>>31)+1,c=o>>>20&2047,d=4294967296*(1048575&o)+i;return 2047===c?d?NaN:a*(1/0):0===c?5e-324*a*d:a*Math.pow(2,c-1075)*(d+4503599627370496)}e.writeDoubleLE=i.bind(null,t,0,4),e.writeDoubleBE=i.bind(null,r,4,0),e.readDoubleLE=o.bind(null,s,0,4),e.readDoubleBE=o.bind(null,n,4,0)}(),e}function t(e,t,r){t[r]=255&e,t[r+1]=e>>>8&255,t[r+2]=e>>>16&255,t[r+3]=e>>>24}function r(e,t,r){t[r]=e>>>24,t[r+1]=e>>>16&255,t[r+2]=e>>>8&255,t[r+3]=255&e}function s(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0}function n(e,t){return(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0}return Jo=1,Wo=e(e)}(),r.inquire=Xo(),r.utf8=(ea||(ea=1,(t=ma).length=function(e){for(var t=0,r=0,s=0;s<e.length;++s)(r=e.charCodeAt(s))<128?t+=1:r<2048?t+=2:55296==(64512&r)&&56320==(64512&e.charCodeAt(s+1))?(++s,t+=4):t+=3;return t},t.read=function(e,t,r){if(r-t<1)return"";for(var s,n=null,i=[],o=0;t<r;)(s=e[t++])<128?i[o++]=s:s>191&&s<224?i[o++]=(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,i[o++]=55296+(s>>10),i[o++]=56320+(1023&s)):i[o++]=(15&s)<<12|(63&e[t++])<<6|63&e[t++],o>8191&&((n||(n=[])).push(String.fromCharCode.apply(String,i)),o=0);return n?(o&&n.push(String.fromCharCode.apply(String,i.slice(0,o))),n.join("")):String.fromCharCode.apply(String,i.slice(0,o))},t.write=function(e,t,r){for(var s,n,i=r,o=0;o<e.length;++o)(s=e.charCodeAt(o))<128?t[r++]=s:s<2048?(t[r++]=s>>6|192,t[r++]=63&s|128):55296==(64512&s)&&56320==(64512&(n=e.charCodeAt(o+1)))?(s=65536+((1023&s)<<10)+(1023&n),++o,t[r++]=s>>18|240,t[r++]=s>>12&63|128,t[r++]=s>>6&63|128,t[r++]=63&s|128):(t[r++]=s>>12|224,t[r++]=s>>6&63|128,t[r++]=63&s|128);return r-i}),ma),r.pool=ra?ta:(ra=1,ta=function(e,t,r){var s=r||8192,n=s>>>1,i=null,o=s;return function(r){if(r<1||r>n)return e(r);o+r>s&&(i=e(s),o=0);var a=t.call(i,o,o+=r);return 7&o&&(o=1+(7|o)),a}}),r.LongBits=function(){if(na)return sa;na=1,sa=t;var e=fa();function t(e,t){this.lo=e>>>0,this.hi=t>>>0}var r=t.zero=new t(0,0);r.toNumber=function(){return 0},r.zzEncode=r.zzDecode=function(){return this},r.length=function(){return 1};var s=t.zeroHash="\0\0\0\0\0\0\0\0";t.fromNumber=function(e){if(0===e)return r;var s=e<0;s&&(e=-e);var n=e>>>0,i=(e-n)/4294967296>>>0;return s&&(i=~i>>>0,n=~n>>>0,++n>4294967295&&(n=0,++i>4294967295&&(i=0))),new t(n,i)},t.from=function(s){if("number"==typeof s)return t.fromNumber(s);if(e.isString(s)){if(!e.Long)return t.fromNumber(parseInt(s,10));s=e.Long.fromString(s)}return s.low||s.high?new t(s.low>>>0,s.high>>>0):r},t.prototype.toNumber=function(e){if(!e&&this.hi>>>31){var t=1+~this.lo>>>0,r=~this.hi>>>0;return t||(r=r+1>>>0),-(t+4294967296*r)}return this.lo+4294967296*this.hi},t.prototype.toLong=function(t){return e.Long?new e.Long(0|this.lo,0|this.hi,Boolean(t)):{low:0|this.lo,high:0|this.hi,unsigned:Boolean(t)}};var n=String.prototype.charCodeAt;return t.fromHash=function(e){return e===s?r:new t((n.call(e,0)|n.call(e,1)<<8|n.call(e,2)<<16|n.call(e,3)<<24)>>>0,(n.call(e,4)|n.call(e,5)<<8|n.call(e,6)<<16|n.call(e,7)<<24)>>>0)},t.prototype.toHash=function(){return String.fromCharCode(255&this.lo,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,255&this.hi,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)},t.prototype.zzEncode=function(){var e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this},t.prototype.zzDecode=function(){var e=-(1&this.lo);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this},t.prototype.length=function(){var e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,r=this.hi>>>24;return 0===r?0===t?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:r<128?9:10},sa}(),r.isNode=Boolean(void 0!==Go&&Go&&Go.process&&Go.process.versions&&Go.process.versions.node),r.global=r.isNode&&Go||"undefined"!=typeof window&&window||"undefined"!=typeof self&&self||jo,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}}(jo)),jo}function ga(){if(aa)return oa;aa=1,oa=c;var e,t=fa(),r=t.LongBits,s=t.base64,n=t.utf8;function i(e,t,r){this.fn=e,this.len=t,this.next=void 0,this.val=r}function o(){}function a(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}function c(){this.len=0,this.head=new i(o,0,0),this.tail=this.head,this.states=null}var d=function(){return t.Buffer?function(){return(c.create=function(){return new e})()}:function(){return new c}};function u(e,t,r){t[r]=255&e}function l(e,t){this.len=e,this.next=void 0,this.val=t}function p(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 h(e,t,r){t[r]=255&e,t[r+1]=e>>>8&255,t[r+2]=e>>>16&255,t[r+3]=e>>>24}c.create=d(),c.alloc=function(e){return new t.Array(e)},t.Array!==Array&&(c.alloc=t.pool(c.alloc,t.Array.prototype.subarray)),c.prototype._push=function(e,t,r){return this.tail=this.tail.next=new i(e,t,r),this.len+=t,this},l.prototype=Object.create(i.prototype),l.prototype.fn=function(e,t,r){for(;e>127;)t[r++]=127&e|128,e>>>=7;t[r]=e},c.prototype.uint32=function(e){return this.len+=(this.tail=this.tail.next=new l((e>>>=0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this},c.prototype.int32=function(e){return e<0?this._push(p,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(p,t.length(),t)},c.prototype.int64=c.prototype.uint64,c.prototype.sint64=function(e){var t=r.from(e).zzEncode();return this._push(p,t.length(),t)},c.prototype.bool=function(e){return this._push(u,1,e?1:0)},c.prototype.fixed32=function(e){return this._push(h,4,e>>>0)},c.prototype.sfixed32=c.prototype.fixed32,c.prototype.fixed64=function(e){var t=r.from(e);return this._push(h,4,t.lo)._push(h,4,t.hi)},c.prototype.sfixed64=c.prototype.fixed64,c.prototype.float=function(e){return this._push(t.float.writeFloatLE,4,e)},c.prototype.double=function(e){return this._push(t.float.writeDoubleLE,8,e)};var m=t.Array.prototype.set?function(e,t,r){t.set(e,r)}:function(e,t,r){for(var s=0;s<e.length;++s)t[r+s]=e[s]};return c.prototype.bytes=function(e){var r=e.length>>>0;if(!r)return this._push(u,1,0);if(t.isString(e)){var n=c.alloc(r=s.length(e));s.decode(e,n,0),e=n}return this.uint32(r)._push(m,r,e)},c.prototype.string=function(e){var t=n.length(e);return t?this.uint32(t)._push(n.write,t,e):this._push(u,1,0)},c.prototype.fork=function(){return this.states=new a(this),this.head=this.tail=new i(o,0,0),this.len=0,this},c.prototype.reset=function(){return this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new i(o,0,0),this.len=0),this},c.prototype.ldelim=function(){var e=this.head,t=this.tail,r=this.len;return this.reset().uint32(r),r&&(this.tail.next=e.next,this.tail=t,this.len+=r),this},c.prototype.finish=function(){for(var e=this.head.next,t=this.constructor.alloc(this.len),r=0;e;)e.fn(e.val,t,r),r+=e.len,e=e.next;return t},c._configure=function(t){e=t,c.create=d(),e._configure()},oa}function ya(){if(la)return ua;la=1,ua=i;var e,t=fa(),r=t.LongBits,s=t.utf8;function n(e,t){return RangeError("index out of range: "+e.pos+" + "+(t||1)+" > "+e.len)}function i(e){this.buf=e,this.pos=0,this.len=e.length}var o="undefined"!=typeof Uint8Array?function(e){if(e instanceof Uint8Array||Array.isArray(e))return new i(e);throw Error("illegal buffer")}:function(e){if(Array.isArray(e))return new i(e);throw Error("illegal buffer")},a=function(){return t.Buffer?function(r){return(i.create=function(r){return t.Buffer.isBuffer(r)?new e(r):o(r)})(r)}:o};function c(){var e=new r(0,0),t=0;if(!(this.len-this.pos>4)){for(;t<3;++t){if(this.pos>=this.len)throw n(this);if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(127&this.buf[this.pos++])<<7*t)>>>0,e}for(;t<4;++t)if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(127&this.buf[this.pos])<<28)>>>0,e.hi=(e.hi|(127&this.buf[this.pos])>>4)>>>0,this.buf[this.pos++]<128)return e;if(t=0,this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw n(this);if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}function d(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}function u(){if(this.pos+8>this.len)throw n(this,8);return new r(d(this.buf,this.pos+=4),d(this.buf,this.pos+=4))}return i.create=a(),i.prototype._slice=t.Array.prototype.subarray||t.Array.prototype.slice,i.prototype.uint32=function(){var e=4294967295;return function(){if(e=(127&this.buf[this.pos])>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<7)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<14)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<21)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(15&this.buf[this.pos])<<28)>>>0,this.buf[this.pos++]<128)return e;if((this.pos+=5)>this.len)throw this.pos=this.len,n(this,10);return e}}(),i.prototype.int32=function(){return 0|this.uint32()},i.prototype.sint32=function(){var e=this.uint32();return e>>>1^-(1&e)},i.prototype.bool=function(){return 0!==this.uint32()},i.prototype.fixed32=function(){if(this.pos+4>this.len)throw n(this,4);return d(this.buf,this.pos+=4)},i.prototype.sfixed32=function(){if(this.pos+4>this.len)throw n(this,4);return 0|d(this.buf,this.pos+=4)},i.prototype.float=function(){if(this.pos+4>this.len)throw n(this,4);var e=t.float.readFloatLE(this.buf,this.pos);return this.pos+=4,e},i.prototype.double=function(){if(this.pos+8>this.len)throw n(this,4);var e=t.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,e},i.prototype.bytes=function(){var e=this.uint32(),r=this.pos,s=this.pos+e;if(s>this.len)throw n(this,e);if(this.pos+=e,Array.isArray(this.buf))return this.buf.slice(r,s);if(r===s){var i=t.Buffer;return i?i.alloc(0):new this.buf.constructor(0)}return this._slice.call(this.buf,r,s)},i.prototype.string=function(){var e=this.bytes();return s.read(e,0,e.length)},i.prototype.skip=function(e){if("number"==typeof e){if(this.pos+e>this.len)throw n(this,e);this.pos+=e}else do{if(this.pos>=this.len)throw n(this)}while(128&this.buf[this.pos++]);return this},i.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},i._configure=function(r){e=r,i.create=a(),e._configure();var s=t.Long?"toLong":"toNumber";t.merge(i.prototype,{int64:function(){return c.call(this)[s](!1)},uint64:function(){return c.call(this)[s](!0)},sint64:function(){return c.call(this).zzDecode()[s](!1)},fixed64:function(){return u.call(this)[s](!0)},sfixed64:function(){return u.call(this)[s](!1)}})},ua}var va,ba,Ia,wa,Ca,Sa,Ta={};function _a(){return Ia||(Ia=1,Ta.Service=function(){if(ba)return va;ba=1,va=t;var e=fa();function t(t,r,s){if("function"!=typeof t)throw TypeError("rpcImpl must be a function");e.EventEmitter.call(this),this.rpcImpl=t,this.requestDelimited=Boolean(r),this.responseDelimited=Boolean(s)}return(t.prototype=Object.create(e.EventEmitter.prototype)).constructor=t,t.prototype.rpcCall=function t(r,s,n,i,o){if(!i)throw TypeError("request must be specified");var a=this;if(!o)return e.asPromise(t,a,r,s,n,i);if(a.rpcImpl)try{return a.rpcImpl(r,s[a.requestDelimited?"encodeDelimited":"encode"](i).finish(),function(e,t){if(e)return a.emit("error",e,r),o(e);if(null!==t){if(!(t instanceof n))try{t=n[a.responseDelimited?"decodeDelimited":"decode"](t)}catch(s){return a.emit("error",s,r),o(s)}return a.emit("data",t,r),o(null,t)}a.end(!0)})}catch(c){return a.emit("error",c,r),void setTimeout(function(){o(c)},0)}else setTimeout(function(){o(Error("already ended"))},0)},t.prototype.end=function(e){return this.rpcImpl&&(e||this.rpcImpl(null,null,null),this.rpcImpl=null,this.emit("end").off()),this},va}()),Ta}function Ra(){return Ca?wa:(Ca=1,wa={})}function Aa(){return Sa||(Sa=1,function(e){var t=e;function r(){t.util._configure(),t.Writer._configure(t.BufferWriter),t.Reader._configure(t.BufferReader)}t.build="minimal",t.Writer=ga(),t.BufferWriter=function(){if(da)return ca;da=1,ca=r;var e=ga();(r.prototype=Object.create(e.prototype)).constructor=r;var t=fa();function r(){e.call(this)}function s(e,r,s){e.length<40?t.utf8.write(e,r,s):r.utf8Write?r.utf8Write(e,s):r.write(e,s)}return r._configure=function(){r.alloc=t._Buffer_allocUnsafe,r.writeBytesBuffer=t.Buffer&&t.Buffer.prototype instanceof Uint8Array&&"set"===t.Buffer.prototype.set.name?function(e,t,r){t.set(e,r)}:function(e,t,r){if(e.copy)e.copy(t,r,0,e.length);else for(var s=0;s<e.length;)t[r++]=e[s++]}},r.prototype.bytes=function(e){t.isString(e)&&(e=t._Buffer_from(e,"base64"));var s=e.length>>>0;return this.uint32(s),s&&this._push(r.writeBytesBuffer,s,e),this},r.prototype.string=function(e){var r=t.Buffer.byteLength(e);return this.uint32(r),r&&this._push(s,r,e),this},r._configure(),ca}(),t.Reader=ya(),t.BufferReader=function(){if(ha)return pa;ha=1,pa=r;var e=ya();(r.prototype=Object.create(e.prototype)).constructor=r;var t=fa();function r(t){e.call(this,t)}return r._configure=function(){t.Buffer&&(r.prototype._slice=t.Buffer.prototype.slice)},r.prototype.string=function(){var e=this.uint32();return this.buf.utf8Slice?this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+e,this.len)):this.buf.toString("utf-8",this.pos,this.pos=Math.min(this.pos+e,this.len))},r._configure(),pa}(),t.util=fa(),t.rpc=_a(),t.roots=Ra(),t.configure=r,r()}(Bo)),Bo}var Ma,Ea,Ua,ka,Na={},Oa={exports:{}};var xa,La,Pa,Da,qa,$a,Ga,Fa,Ba,ja,za,Ka,Ha,Va,Wa,Ja={};function Za(){if(Pa)return La;Pa=1,La=c;var e=xc();((c.prototype=Object.create(e.prototype)).constructor=c).className="Namespace";var t,r,s,n=Nc(),i=Uc(),o=Oc();function a(e,t){if(e&&e.length){for(var r={},s=0;s<e.length;++s)r[e[s].name]=e[s].toJSON(t);return r}}function c(t,r){e.call(this,t,r),this.nested=void 0,this._nestedArray=null,this._lookupCache={},this._needsRecursiveFeatureResolution=!0,this._needsRecursiveResolve=!0}function d(e){e._nestedArray=null,e._lookupCache={};for(var t=e;t=t.parent;)t._lookupCache={};return e}return c.fromJSON=function(e,t){return new c(e,t.options).addJSON(t.nested)},c.arrayToJSON=a,c.isReservedId=function(e,t){if(e)for(var r=0;r<e.length;++r)if("string"!=typeof e[r]&&e[r][0]<=t&&e[r][1]>t)return!0;return!1},c.isReservedName=function(e,t){if(e)for(var r=0;r<e.length;++r)if(e[r]===t)return!0;return!1},Object.defineProperty(c.prototype,"nestedArray",{get:function(){return this._nestedArray||(this._nestedArray=i.toArray(this.nested))}}),c.prototype.toJSON=function(e){return i.toObject(["options",this.options,"nested",a(this.nestedArray,e)])},c.prototype.addJSON=function(e){if(e)for(var i,o=Object.keys(e),a=0;a<o.length;++a)i=e[o[a]],this.add((void 0!==i.fields?t.fromJSON:void 0!==i.values?s.fromJSON:void 0!==i.methods?r.fromJSON:void 0!==i.id?n.fromJSON:c.fromJSON)(o[a],i));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 o||e instanceof s||e instanceof r||e instanceof c))throw TypeError("object must be a valid nested object");if(this.nested){var i=this.get(e.name);if(i){if(!(i instanceof c&&e instanceof c)||i instanceof t||i instanceof r)throw Error("duplicate name '"+e.name+"' in "+this);for(var a=i.nestedArray,u=0;u<a.length;++u)e.add(a[u]);this.remove(i),this.nested||(this.nested={}),e.setOptions(i.options,!0)}}else this.nested={};this.nested[e.name]=e,this instanceof t||this instanceof r||this instanceof s||this instanceof n||e._edition||(e._edition=e._defaultEdition),this._needsRecursiveFeatureResolution=!0,this._needsRecursiveResolve=!0;for(var l=this;l=l.parent;)l._needsRecursiveFeatureResolution=!0,l._needsRecursiveResolve=!0;return e.onAdd(this),d(this)},c.prototype.remove=function(t){if(!(t instanceof e))throw TypeError("object must be a ReflectionObject");if(t.parent!==this)throw Error(t+" is not a member of "+this);return delete this.nested[t.name],Object.keys(this.nested).length||(this.nested=void 0),t.onRemove(this),d(this)},c.prototype.define=function(e,t){if(i.isString(e))e=e.split(".");else if(!Array.isArray(e))throw TypeError("illegal path");if(e&&e.length&&""===e[0])throw Error("path must be relative");for(var r=this;e.length>0;){var s=e.shift();if(r.nested&&r.nested[s]){if(!((r=r.nested[s])instanceof c))throw Error("path conflicts with non-namespace objects")}else r.add(r=new c(s))}return t&&r.addJSON(t),r},c.prototype.resolveAll=function(){if(!this._needsRecursiveResolve)return this;this._resolveFeaturesRecursive(this._edition);var e=this.nestedArray,t=0;for(this.resolve();t<e.length;)e[t]instanceof c?e[t++].resolveAll():e[t++].resolve();return this._needsRecursiveResolve=!1,this},c.prototype._resolveFeaturesRecursive=function(t){return this._needsRecursiveFeatureResolution?(this._needsRecursiveFeatureResolution=!1,t=this._edition||t,e.prototype._resolveFeaturesRecursive.call(this,t),this.nestedArray.forEach(e=>{e._resolveFeaturesRecursive(t)}),this):this},c.prototype.lookup=function(e,t,r){if("boolean"==typeof t?(r=t,t=void 0):t&&!Array.isArray(t)&&(t=[t]),i.isString(e)&&e.length){if("."===e)return this.root;e=e.split(".")}else if(!e.length)return this;var s=e.join(".");if(""===e[0])return this.root.lookup(e.slice(1),t);var n=this.root._fullyQualifiedObjects&&this.root._fullyQualifiedObjects["."+s];if(n&&(!t||t.indexOf(n.constructor)>-1))return n;if((n=this._lookupImpl(e,s))&&(!t||t.indexOf(n.constructor)>-1))return n;if(r)return null;for(var o=this;o.parent;){if((n=o.parent._lookupImpl(e,s))&&(!t||t.indexOf(n.constructor)>-1))return n;o=o.parent}return null},c.prototype._lookupImpl=function(e,t){if(Object.prototype.hasOwnProperty.call(this._lookupCache,t))return this._lookupCache[t];var r=this.get(e[0]),s=null;if(r)1===e.length?s=r:r instanceof c&&(e=e.slice(1),s=r._lookupImpl(e,e.join(".")));else for(var n=0;n<this.nestedArray.length;++n)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,i){t=e,r=n,s=i},La}function Qa(){if(qa)return Da;qa=1,Da=s;var e=Nc();((s.prototype=Object.create(e.prototype)).constructor=s).className="MapField";var t=kc(),r=Uc();function s(t,s,n,i,o,a){if(e.call(this,t,s,i,void 0,void 0,o,a),!r.isString(n))throw TypeError("keyType must be a string");this.keyType=n,this.resolvedKeyType=null,this.map=!0}return s.fromJSON=function(e,t){return new s(e,t.id,t.keyType,t.type,t.options,t.comment)},s.prototype.toJSON=function(e){var t=!!e&&Boolean(e.keepComments);return r.toObject(["keyType",this.keyType,"type",this.type,"id",this.id,"extend",this.extend,"options",this.options,"comment",t?this.comment:void 0])},s.prototype.resolve=function(){if(this.resolved)return this;if(void 0===t.mapKey[this.keyType])throw Error("invalid key type: "+this.keyType);return e.prototype.resolve.call(this)},s.d=function(e,t,n){return"function"==typeof n?n=r.decorateType(n).name:n&&"object"==typeof n&&(n=r.decorateEnum(n).name),function(i,o){r.decorateType(i.constructor).add(new s(o,e,t,n))}},Da}function Ya(){if(Ga)return $a;Ga=1,$a=r;var e=xc();((r.prototype=Object.create(e.prototype)).constructor=r).className="Method";var t=Uc();function r(r,s,n,i,o,a,c,d,u){if(t.isObject(o)?(c=o,o=a=void 0):t.isObject(a)&&(c=a,a=void 0),void 0!==s&&!t.isString(s))throw TypeError("type must be a string");if(!t.isString(n))throw TypeError("requestType must be a string");if(!t.isString(i))throw TypeError("responseType must be a string");e.call(this,r,c),this.type=s||"rpc",this.requestType=n,this.requestStream=!!o||void 0,this.responseType=i,this.responseStream=!!a||void 0,this.resolvedRequestType=null,this.resolvedResponseType=null,this.comment=d,this.parsedOptions=u}return r.fromJSON=function(e,t){return new r(e,t.type,t.requestType,t.responseType,t.requestStream,t.responseStream,t.options,t.comment,t.parsedOptions)},r.prototype.toJSON=function(e){var r=!!e&&Boolean(e.keepComments);return t.toObject(["type","rpc"!==this.type&&this.type||void 0,"requestType",this.requestType,"requestStream",this.requestStream,"responseType",this.responseType,"responseStream",this.responseStream,"options",this.options,"comment",r?this.comment:void 0,"parsedOptions",this.parsedOptions])},r.prototype.resolve=function(){return this.resolved?this:(this.resolvedRequestType=this.parent.lookupType(this.requestType),this.resolvedResponseType=this.parent.lookupType(this.responseType),e.prototype.resolve.call(this))},$a}function Xa(){if(Ba)return Fa;Ba=1,Fa=n;var e=Za();((n.prototype=Object.create(e.prototype)).constructor=n).className="Service";var t=Ya(),r=Uc(),s=_a();function n(t,r){e.call(this,t,r),this.methods={},this._methodsArray=null}function i(e){return e._methodsArray=null,e}return n.fromJSON=function(e,r){var s=new n(e,r.options);if(r.methods)for(var i=Object.keys(r.methods),o=0;o<i.length;++o)s.add(t.fromJSON(i[o],r.methods[i[o]]));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,i(this)):e.prototype.add.call(this,r)},n.prototype.remove=function(r){if(r instanceof t){if(this.methods[r.name]!==r)throw Error(r+" is not a member of "+this);return delete this.methods[r.name],r.parent=null,i(this)}return e.prototype.remove.call(this,r)},n.prototype.create=function(e,t,n){for(var i,o=new s.Service(e,t,n),a=0;a<this.methodsArray.length;++a){var c=r.lcFirst((i=this._methodsArray[a]).resolve().name).replace(/[^$\w_]/g,"");o[c]=r.codegen(["r","c"],r.isReserved(c)?c+"_":c)("return this.rpcCall(m,q,s,r,c)")({m:i,q:i.resolvedRequestType.ctor,s:i.resolvedResponseType.ctor})}return o},Fa}function ec(){if(za)return ja;za=1,ja=t;var e=fa();function t(e){if(e)for(var t=Object.keys(e),r=0;r<t.length;++r)this[t[r]]=e[t[r]]}return t.create=function(e){return this.$type.create(e)},t.encode=function(e,t){return this.$type.encode(e,t)},t.encodeDelimited=function(e,t){return this.$type.encodeDelimited(e,t)},t.decode=function(e){return this.$type.decode(e)},t.decodeDelimited=function(e){return this.$type.decodeDelimited(e)},t.verify=function(e){return this.$type.verify(e)},t.fromObject=function(e){return this.$type.fromObject(e)},t.toObject=function(e,t){return this.$type.toObject(e,t)},t.prototype.toJSON=function(){return this.$type.toObject(this,e.toJSONOptions)},ja}function tc(){if(Ha)return Ka;Ha=1,Ka=function(n){for(var i=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){"),o=0;o<n.fieldsArray.length;++o){var a=n._fieldsArray[o].resolve(),c=a.resolvedType instanceof e?"int32":a.type,d="m"+r.safeProp(a.name);i("case %i: {",a.id),a.map?(i("if(%s===util.emptyObject)",d)("%s={}",d)("var c2 = r.uint32()+r.pos"),void 0!==t.defaults[a.keyType]?i("k=%j",t.defaults[a.keyType]):i("k=null"),void 0!==t.defaults[c]?i("value=%j",t.defaults[c]):i("value=null"),i("while(r.pos<c2){")("var tag2=r.uint32()")("switch(tag2>>>3){")("case 1: k=r.%s(); break",a.keyType)("case 2:"),void 0===t.basic[c]?i("value=types[%i].decode(r,r.uint32())",o):i("value=r.%s()",c),i("break")("default:")("r.skipType(tag2&7)")("break")("}")("}"),void 0!==t.long[a.keyType]?i('%s[typeof k==="object"?util.longToHash(k):k]=value',d):i("%s[k]=value",d)):a.repeated?(i("if(!(%s&&%s.length))",d,d)("%s=[]",d),void 0!==t.packed[c]&&i("if((t&7)===2){")("var c2=r.uint32()+r.pos")("while(r.pos<c2)")("%s.push(r.%s())",d,c)("}else"),void 0===t.basic[c]?i(a.delimited?"%s.push(types[%i].decode(r,undefined,((t&~7)|4)))":"%s.push(types[%i].decode(r,r.uint32()))",d,o):i("%s.push(r.%s())",d,c)):void 0===t.basic[c]?i(a.delimited?"%s=types[%i].decode(r,undefined,((t&~7)|4))":"%s=types[%i].decode(r,r.uint32())",d,o):i("%s=r.%s()",d,c),i("break")("}")}for(i("default:")("r.skipType(t&7)")("break")("}")("}"),o=0;o<n._fieldsArray.length;++o){var u=n._fieldsArray[o];u.required&&i("if(!m.hasOwnProperty(%j))",u.name)("throw util.ProtocolError(%j,{instance:m})",s(u))}return i("return m")};var e=Lc(),t=kc(),r=Uc();function s(e){return"missing required '"+e.name+"'"}return Ka}function rc(){if(Wa)return Va;Wa=1,Va=function(e){var i=t.codegen(["m"],e.name+"$verify")('if(typeof m!=="object"||m===null)')("return%j","object expected"),o=e.oneofsArray,a={};o.length&&i("var p={}");for(var c=0;c<e.fieldsArray.length;++c){var d=e._fieldsArray[c].resolve(),u="m"+t.safeProp(d.name);if(d.optional&&i("if(%s!=null&&m.hasOwnProperty(%j)){",u,d.name),d.map)i("if(!util.isObject(%s))",u)("return%j",r(d,"object"))("var k=Object.keys(%s)",u)("for(var i=0;i<k.length;++i){"),n(i,d,"k[i]"),s(i,d,c,u+"[k[i]]")("}");else if(d.repeated)i("if(!Array.isArray(%s))",u)("return%j",r(d,"array"))("for(var i=0;i<%s.length;++i){",u),s(i,d,c,u+"[i]")("}");else{if(d.partOf){var l=t.safeProp(d.partOf.name);1===a[d.partOf.name]&&i("if(p%s===1)",l)("return%j",d.partOf.name+": multiple values"),a[d.partOf.name]=1,i("p%s=1",l)}s(i,d,c,u)}d.optional&&i("}")}return i("return null")};var e=Lc(),t=Uc();function r(e,t){return e.name+": "+t+(e.repeated&&"array"!==t?"[]":e.map&&"object"!==t?"{k:"+e.keyType+"}":"")+" expected"}function s(t,s,n,i){if(s.resolvedType)if(s.resolvedType instanceof e){t("switch(%s){",i)("default:")("return%j",r(s,"enum value"));for(var o=Object.keys(s.resolvedType.values),a=0;a<o.length;++a)t("case %i:",s.resolvedType.values[o[a]]);t("break")("}")}else t("{")("var e=types[%i].verify(%s);",n,i)("if(e)")("return%j+e",s.name+".")("}");else switch(s.type){case"int32":case"uint32":case"sint32":case"fixed32":case"sfixed32":t("if(!util.isInteger(%s))",i)("return%j",r(s,"integer"));break;case"int64":case"uint64":case"sint64":case"fixed64":case"sfixed64":t("if(!util.isInteger(%s)&&!(%s&&util.isInteger(%s.low)&&util.isInteger(%s.high)))",i,i,i,i)("return%j",r(s,"integer|Long"));break;case"float":case"double":t('if(typeof %s!=="number")',i)("return%j",r(s,"number"));break;case"bool":t('if(typeof %s!=="boolean")',i)("return%j",r(s,"boolean"));break;case"string":t("if(!util.isString(%s))",i)("return%j",r(s,"string"));break;case"bytes":t('if(!(%s&&typeof %s.length==="number"||util.isString(%s)))',i,i,i)("return%j",r(s,"buffer"))}return t}function n(e,t,s){switch(t.keyType){case"int32":case"uint32":case"sint32":case"fixed32":case"sfixed32":e("if(!util.key32Re.test(%s))",s)("return%j",r(t,"integer key"));break;case"int64":case"uint64":case"sint64":case"fixed64":case"sfixed64":e("if(!util.key64Re.test(%s))",s)("return%j",r(t,"integer|Long key"));break;case"bool":e("if(!util.key2Re.test(%s))",s)("return%j",r(t,"boolean key"))}return e}return Va}var sc,nc={};function ic(){return sc||(sc=1,function(e){var t=e,r=Lc(),s=Uc();function n(e,t,s,n){var i=!1;if(t.resolvedType)if(t.resolvedType instanceof r){e("switch(d%s){",n);for(var o=t.resolvedType.values,a=Object.keys(o),c=0;c<a.length;++c)o[a[c]]!==t.typeDefault||i||(e("default:")('if(typeof(d%s)==="number"){m%s=d%s;break}',n,n,n),t.repeated||e("break"),i=!0),e("case%j:",a[c])("case %i:",o[a[c]])("m%s=%j",n,o[a[c]])("break");e("}")}else e('if(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 i(e,t,s,n){if(t.resolvedType)t.resolvedType instanceof r?e("d%s=o.enums===String?(types[%i].values[m%s]===undefined?m%s:types[%i].values[m%s]):m%s",n,s,n,n,s,n,n):e("d%s=types[%i].toObject(m%s,o)",n,s,n);else{var i=!1;switch(t.type){case"double":case"float":e("d%s=o.json&&!isFinite(m%s)?String(m%s):m%s",n,n,n,n);break;case"uint64":i=!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,i?"true":"",n);break;case"bytes":e("d%s=o.bytes===String?util.base64.encode(m%s,0,m%s.length):o.bytes===Array?Array.prototype.slice.call(m%s):m%s",n,n,n,n,n);break;default:e("d%s=m%s",n,n)}}return e}t.fromObject=function(e){var t=e.fieldsArray,i=s.codegen(["d"],e.name+"$fromObject")("if(d instanceof this.ctor)")("return d");if(!t.length)return i("return new this.ctor");i("var m=new this.ctor");for(var o=0;o<t.length;++o){var a=t[o].resolve(),c=s.safeProp(a.name);a.map?(i("if(d%s){",c)('if(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(i,a,o,c+"[ks[i]]")("}")("}")):a.repeated?(i("if(d%s){",c)("if(!Array.isArray(d%s))",c)("throw TypeError(%j)",a.fullName+": array expected")("m%s=[]",c)("for(var i=0;i<d%s.length;++i){",c),n(i,a,o,c+"[i]")("}")("}")):(a.resolvedType instanceof r||i("if(d%s!=null){",c),n(i,a,o,c),a.resolvedType instanceof r||i("}"))}return i("return m")},t.toObject=function(e){var t=e.fieldsArray.slice().sort(s.compareFieldsById);if(!t.length)return s.codegen()("return {}");for(var n=s.codegen(["m","o"],e.name+"$toObject")("if(!o)")("o={}")("var d={}"),o=[],a=[],c=[],d=0;d<t.length;++d)t[d].partOf||(t[d].resolve().repeated?o:t[d].map?a:c).push(t[d]);if(o.length){for(n("if(o.arrays||o.defaults){"),d=0;d<o.length;++d)n("d%s=[]",s.safeProp(o[d].name));n("}")}if(a.length){for(n("if(o.objects||o.defaults){"),d=0;d<a.length;++d)n("d%s={}",s.safeProp(a[d].name));n("}")}if(c.length){for(n("if(o.defaults){"),d=0;d<c.length;++d){var u=c[d],l=s.safeProp(u.name);if(u.resolvedType instanceof r)n("d%s=o.enums===String?%j:%j",l,u.resolvedType.valuesById[u.typeDefault],u.typeDefault);else if(u.long)n("if(util.Long){")("var n=new util.Long(%i,%i,%j)",u.typeDefault.low,u.typeDefault.high,u.typeDefault.unsigned)("d%s=o.longs===String?n.toString():o.longs===Number?n.toNumber():n",l)("}else")("d%s=o.longs===String?%j:%i",l,u.typeDefault.toString(),u.typeDefault.toNumber());else if(u.bytes){var p="["+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,p)("if(o.bytes!==Array)d%s=util.newBuffer(d%s)",l,l)("}")}else n("d%s=%j",l,u.typeDefault)}n("}")}var h=!1;for(d=0;d<t.length;++d){u=t[d];var m=e._fieldsArray.indexOf(u);l=s.safeProp(u.name);u.map?(h||(h=!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){"),i(n,u,m,l+"[ks2[j]]")("}")):u.repeated?(n("if(m%s&&m%s.length){",l,l)("d%s=[]",l)("for(var j=0;j<m%s.length;++j){",l),i(n,u,m,l+"[j]")("}")):(n("if(m%s!=null&&m.hasOwnProperty(%j)){",l,u.name),i(n,u,m,l),u.partOf&&n("if(o.oneofs)")("d%s=%j",s.safeProp(u.partOf.name),u.name)),n("}")}return n("return d")}}(nc)),nc}var oc,ac,cc,dc,uc,lc,pc,hc,mc,fc,gc,yc,vc,bc,Ic,wc,Cc,Sc,Tc,_c,Rc={};function Ac(){return oc||(oc=1,e=Rc,t=ec(),e[".google.protobuf.Any"]={fromObject:function(e){if(e&&e["@type"]){var t=e["@type"].substring(e["@type"].lastIndexOf("/")+1),r=this.lookup(t);if(r){var s="."===e["@type"].charAt(0)?e["@type"].slice(1):e["@type"];return-1===s.indexOf("/")&&(s="/"+s),this.create({type_url:s,value:r.encode(r.fromObject(e)).finish()})}}return this.fromObject(e)},toObject:function(e,r){var s="",n="";if(r&&r.json&&e.type_url&&e.value){n=e.type_url.substring(e.type_url.lastIndexOf("/")+1),s=e.type_url.substring(0,e.type_url.lastIndexOf("/")+1);var i=this.lookup(n);i&&(e=i.decode(e.value))}if(!(e instanceof this.ctor)&&e instanceof t){var o=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),o["@type"]=n,o}return this.toObject(e,r)}}),Rc;var e,t}function Mc(){if(cc)return ac;cc=1,ac=f;var e=Za();((f.prototype=Object.create(e.prototype)).constructor=f).className="Type";var t=Lc(),r=Oc(),s=Nc(),n=Qa(),i=Xa(),o=ec(),a=ya(),c=ga(),d=Uc(),u=Pc(),l=tc(),p=rc(),h=ic(),m=Ac();function f(t,r){e.call(this,t,r),this.fields={},this.oneofs=void 0,this.extensions=void 0,this.reserved=void 0,this.group=void 0,this._fieldsById=null,this._fieldsArray=null,this._oneofsArray=null,this._ctor=null}function g(e){return e._fieldsById=e._fieldsArray=e._oneofsArray=null,delete e.encode,delete e.decode,delete e.verify,e}return Object.defineProperties(f.prototype,{fieldsById:{get:function(){if(this._fieldsById)return this._fieldsById;this._fieldsById={};for(var e=Object.keys(this.fields),t=0;t<e.length;++t){var r=this.fields[e[t]],s=r.id;if(this._fieldsById[s])throw Error("duplicate id "+s+" in "+this);this._fieldsById[s]=r}return this._fieldsById}},fieldsArray:{get:function(){return this._fieldsArray||(this._fieldsArray=d.toArray(this.fields))}},oneofsArray:{get:function(){return this._oneofsArray||(this._oneofsArray=d.toArray(this.oneofs))}},ctor:{get:function(){return this._ctor||(this.ctor=f.generateConstructor(this)())},set:function(e){var t=e.prototype;t instanceof o||((e.prototype=new o).constructor=e,d.merge(e.prototype,t)),e.$type=e.prototype.$type=this,d.merge(e,o,!0),this._ctor=e;for(var r=0;r<this.fieldsArray.length;++r)this._fieldsArray[r].resolve();var s={};for(r=0;r<this.oneofsArray.length;++r)s[this._oneofsArray[r].resolve().name]={get:d.oneOfGetter(this._oneofsArray[r].oneof),set:d.oneOfSetter(this._oneofsArray[r].oneof)};r&&Object.defineProperties(e.prototype,s)}}}),f.generateConstructor=function(e){for(var t,r=d.codegen(["p"],e.name),s=0;s<e.fieldsArray.length;++s)(t=e._fieldsArray[s]).map?r("this%s={}",d.safeProp(t.name)):t.repeated&&r("this%s=[]",d.safeProp(t.name));return r("if(p)for(var ks=Object.keys(p),i=0;i<ks.length;++i)if(p[ks[i]]!=null)")("this[ks[i]]=p[ks[i]]")},f.fromJSON=function(o,a){var c=new f(o,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?i.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=p(this)({types:t,util:d}),this.fromObject=h.fromObject(this)({types:t,util:d}),this.toObject=h.toObject(this)({types:t,util:d});var s=m[e];if(s){var n=Object.create(this);n.fromObject=this.fromObject,this.fromObject=s.fromObject.bind(n),n.toObject=this.toObject,this.toObject=s.toObject.bind(n)}return this},f.prototype.encode=function(e,t){return this.setup().encode(e,t)},f.prototype.encodeDelimited=function(e,t){return this.encode(e,t&&t.len?t.fork():t).ldelim()},f.prototype.decode=function(e,t){return this.setup().decode(e,t)},f.prototype.decodeDelimited=function(e){return e instanceof a||(e=a.create(e)),this.decode(e,e.uint32())},f.prototype.verify=function(e){return this.setup().verify(e)},f.prototype.fromObject=function(e){return this.setup().fromObject(e)},f.prototype.toObject=function(e,t){return this.setup().toObject(e,t)},f.d=function(e){return function(t){d.decorateType(t,e)}},ac}function Ec(){if(uc)return dc;uc=1,dc=c;var e=Za();((c.prototype=Object.create(e.prototype)).constructor=c).className="Root";var t,r,s,n=Nc(),i=Lc(),o=Oc(),a=Uc();function c(t){e.call(this,"",t),this.deferred=[],this.files=[],this._edition="proto2",this._fullyQualifiedObjects={}}function d(){}c.fromJSON=function(e,t){return t||(t=new c),e.options&&t.setOptions(e.options),t.addJSON(e.nested).resolveAll()},c.prototype.resolvePath=a.path.resolve,c.prototype.fetch=a.fetch,c.prototype.load=function e(t,n,i){"function"==typeof n&&(i=n,n=void 0);var o=this;if(!i)return a.asPromise(e,o,t,n);var c=i===d;function u(e,t){if(i){if(c)throw e;t&&t.resolveAll();var r=i;i=null,r(e,t)}}function l(e){var t=e.lastIndexOf("google/protobuf/");if(t>-1){var r=e.substring(t);if(r in s)return r}return null}function p(e,t){try{if(a.isString(t)&&"{"===t.charAt(0)&&(t=JSON.parse(t)),a.isString(t)){r.filename=e;var s,i=r(t,o,n),d=0;if(i.imports)for(;d<i.imports.length;++d)(s=l(i.imports[d])||o.resolvePath(e,i.imports[d]))&&h(s);if(i.weakImports)for(d=0;d<i.weakImports.length;++d)(s=l(i.weakImports[d])||o.resolvePath(e,i.weakImports[d]))&&h(s,!0)}else o.setOptions(t.options).addJSON(t.nested)}catch(p){u(p)}c||m||u(null,o)}function h(e,t){if(e=l(e)||e,!(o.files.indexOf(e)>-1))if(o.files.push(e),e in s)c?p(e,s[e]):(++m,setTimeout(function(){--m,p(e,s[e])}));else if(c){var r;try{r=a.fs.readFileSync(e).toString("utf8")}catch(n){return void(t||u(n))}p(e,r)}else++m,o.fetch(e,function(r,s){--m,i&&(r?t?m||u(null,o):u(r):p(e,s))})}var m=0;a.isString(t)&&(t=[t]);for(var f,g=0;g<t.length;++g)(f=o.resolvePath("",t[g]))&&h(f);return c?(o.resolveAll(),o):(m||u(null,o),o)},c.prototype.loadSync=function(e,t){if(!a.isNode)throw Error("not supported");return this.load(e,t,d)},c.prototype.resolveAll=function(){if(!this._needsRecursiveResolve)return this;if(this.deferred.length)throw Error("unresolvable extensions: "+this.deferred.map(function(e){return"'extend "+e.extend+"' in "+e.parent.fullName}).join(", "));return e.prototype.resolveAll.call(this)};var u=/^[A-Z]/;function l(e,t){var r=t.parent.lookup(t.extend);if(r){var s=new n(t.fullName,t.id,t.type,t.rule,void 0,t.options);return r.get(s.name)||(s.declaringField=t,t.extensionField=s,r.add(s)),!0}return!1}return c.prototype._handleAdd=function(e){if(e instanceof n)void 0===e.extend||e.extensionField||l(0,e)||this.deferred.push(e);else if(e instanceof i)u.test(e.name)&&(e.parent[e.name]=e.values);else if(!(e instanceof o)){if(e instanceof t)for(var r=0;r<this.deferred.length;)l(0,this.deferred[r])?this.deferred.splice(r,1):++r;for(var s=0;s<e.nestedArray.length;++s)this._handleAdd(e._nestedArray[s]);u.test(e.name)&&(e.parent[e.name]=e)}(e instanceof t||e instanceof i||e instanceof n)&&(this._fullyQualifiedObjects[e.fullName]=e)},c.prototype._handleRemove=function(t){if(t instanceof n){if(void 0!==t.extend)if(t.extensionField)t.extensionField.parent.remove(t.extensionField),t.extensionField=null;else{var r=this.deferred.indexOf(t);r>-1&&this.deferred.splice(r,1)}}else if(t instanceof i)u.test(t.name)&&delete t.parent[t.name];else if(t instanceof e){for(var s=0;s<t.nestedArray.length;++s)this._handleRemove(t._nestedArray[s]);u.test(t.name)&&delete t.parent[t.name]}delete this._fullyQualifiedObjects[t.fullName]},c._configure=function(e,n,i){t=e,r=n,s=i},dc}function Uc(){if(lc)return Oa.exports;lc=1;var e,t,r,s,n,i=Oa.exports=fa(),o=Ra();i.codegen=function(){if(Ea)return Ma;function e(t,r){"string"==typeof t&&(r=t,t=void 0);var s=[];function n(t){if("string"!=typeof t){var r=i();if(e.verbose&&console.log("codegen: "+r),r="return "+r,t){for(var o=Object.keys(t),a=new Array(o.length+1),c=new Array(o.length),d=0;d<o.length;)a[d]=o[d],c[d]=t[o[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 i(e){return"function "+(e||r||"")+"("+(t&&t.join(",")||"")+"){\n "+s.join("\n ")+"\n}"}return n.toString=i,n}return Ea=1,Ma=e,e.verbose=!1,Ma}(),i.fetch=function(){if(ka)return Ua;ka=1,Ua=r;var e=zo(),t=Xo()("fs");function r(s,n,i){return"function"==typeof n?(i=n,n={}):n||(n={}),i?!n.xhr&&t&&t.readFile?t.readFile(s,function(e,t){return e&&"undefined"!=typeof XMLHttpRequest?r.xhr(s,n,i):e?i(e):i(null,n.binary?t:t.toString("utf8"))}):r.xhr(s,n,i):e(r,this,s,n)}return r.xhr=function(e,t,r){var s=new XMLHttpRequest;s.onreadystatechange=function(){if(4===s.readyState){if(0!==s.status&&200!==s.status)return r(Error("status "+s.status));if(t.binary){var e=s.response;if(!e){e=[];for(var n=0;n<s.responseText.length;++n)e.push(255&s.responseText.charCodeAt(n))}return r(null,"undefined"!=typeof Uint8Array?new Uint8Array(e):e)}return r(null,s.responseText)}},t.binary&&("overrideMimeType"in s&&s.overrideMimeType("text/plain; charset=x-user-defined"),s.responseType="arraybuffer"),s.open("GET",e),s.send()},Ua}(),i.path=(xa||(xa=1,s=(r=Ja).isAbsolute=function(e){return/^(?:\/|\w+:)/.test(e)},n=r.normalize=function(e){var t=(e=e.replace(/\\/g,"/").replace(/\/{2,}/g,"/")).split("/"),r=s(e),n="";r&&(n=t.shift()+"/");for(var i=0;i<t.length;)".."===t[i]?i>0&&".."!==t[i-1]?t.splice(--i,2):r?t.splice(i,1):++i:"."===t[i]?t.splice(i,1):++i;return n+t.join("/")},r.resolve=function(e,t,r){return r||(t=n(t)),s(t)?t:(r||(e=n(e)),(e=e.replace(/(?:\/|^)[^/]+$/,"")).length?n(e+"/"+t):t)}),Ja),i.fs=i.inquire("fs"),i.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[]},i.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;i.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)},i.safeProp=function(e){return!/^[$\w_]+$/.test(e)||i.isReserved(e)?'["'+e.replace(a,"\\\\").replace(c,'\\"')+'"]':"."+e},i.ucFirst=function(e){return e.charAt(0).toUpperCase()+e.substring(1)};var d=/_([a-z])/g;i.camelCase=function(e){return e.substring(0,1)+e.substring(1).replace(d,function(e,t){return t.toUpperCase()})},i.compareFieldsById=function(e,t){return e.id-t.id},i.decorateType=function(t,r){if(t.$type)return r&&t.$type.name!==r&&(i.decorateRoot.remove(t.$type),t.$type.name=r,i.decorateRoot.add(t.$type)),t.$type;e||(e=Mc());var s=new e(r||t.name);return i.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 i.decorateEnum=function(e){if(e.$type)return e.$type;t||(t=Lc());var r=new t("Enum"+u++,e);return i.decorateRoot.add(r),Object.defineProperty(e,"$type",{value:r,enumerable:!1}),r},i.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 i=r.shift();if("__proto__"===i||"prototype"===i)return t;if(r.length>0)t[i]=e(t[i]||{},r,n);else{var o=t[i];if(o&&s)return t;o&&(n=[].concat(o).concat(n)),t[i]=n}return t}(e,t=t.split("."),r)},Object.defineProperty(i,"decorateRoot",{get:function(){return o.decorated||(o.decorated=new(Ec()))}}),Oa.exports}function kc(){return pc||(pc=1,function(e){var t=e,r=Uc(),s=["double","float","int32","uint32","sint32","fixed32","sfixed32","int64","uint64","sint64","fixed64","sfixed64","bool","string","bytes"];function n(e,t){var r=0,n={};for(t|=0;r<e.length;)n[s[r+t]]=e[r++];return n}t.basic=n([1,5,0,0,0,5,5,0,0,0,1,1,0,2,2]),t.defaults=n([0,0,0,0,0,0,0,0,0,0,0,0,!1,"",r.emptyArray,null]),t.long=n([0,0,0,1,1],7),t.mapKey=n([0,0,0,5,5,0,0,0,1,1,0,2],2),t.packed=n([1,5,0,0,0,5,5,0,0,0,1,1,0])}(Na)),Na}function Nc(){if(mc)return hc;mc=1,hc=o;var e=xc();((o.prototype=Object.create(e.prototype)).constructor=o).className="Field";var t,r=Lc(),s=kc(),n=Uc(),i=/^required|optional|repeated$/;function o(t,r,o,a,c,d,u){if(n.isObject(a)?(u=c,d=a,a=c=void 0):n.isObject(c)&&(u=d,d=c,c=void 0),e.call(this,t,d),!n.isInteger(r)||r<0)throw TypeError("id must be a non-negative integer");if(!n.isString(o))throw TypeError("type must be a string");if(void 0!==a&&!i.test(a=a.toString().toLowerCase()))throw TypeError("rule must be a string rule");if(void 0!==c&&!n.isString(c))throw TypeError("extend must be a string");"proto3_optional"===a&&(a="optional"),this.rule=a&&"optional"!==a?a:void 0,this.type=o,this.id=r,this.extend=c||void 0,this.repeated="repeated"===a,this.map=!1,this.message=null,this.partOf=null,this.typeDefault=null,this.defaultValue=null,this.long=!!n.Long&&void 0!==s.long[o],this.bytes="bytes"===o,this.resolvedType=null,this.extensionField=null,this.declaringField=null,this.comment=u}return o.fromJSON=function(e,t){var r=new o(e,t.id,t.type,t.rule,t.extend,t.options,t.comment);return t.edition&&(r._edition=t.edition),r._defaultEdition="proto3",r},Object.defineProperty(o.prototype,"required",{get:function(){return"LEGACY_REQUIRED"===this._features.field_presence}}),Object.defineProperty(o.prototype,"optional",{get:function(){return!this.required}}),Object.defineProperty(o.prototype,"delimited",{get:function(){return this.resolvedType instanceof t&&"DELIMITED"===this._features.message_encoding}}),Object.defineProperty(o.prototype,"packed",{get:function(){return"PACKED"===this._features.repeated_field_encoding}}),Object.defineProperty(o.prototype,"hasPresence",{get:function(){return!this.repeated&&!this.map&&(this.partOf||this.declaringField||this.extensionField||"IMPLICIT"!==this._features.field_presence)}}),o.prototype.setOption=function(t,r,s){return e.prototype.setOption.call(this,t,r,s)},o.prototype.toJSON=function(e){var t=!!e&&Boolean(e.keepComments);return n.toObject(["edition",this._editionToJSON(),"rule","optional"!==this.rule&&this.rule||void 0,"type",this.type,"id",this.id,"extend",this.extend,"options",this.options,"comment",t?this.comment:void 0])},o.prototype.resolve=function(){if(this.resolved)return this;if(void 0===(this.typeDefault=s.defaults[this.type])?(this.resolvedType=(this.declaringField?this.declaringField.parent:this.parent).lookupTypeOrEnum(this.type),this.resolvedType instanceof t?this.typeDefault=null:this.typeDefault=this.resolvedType.values[Object.keys(this.resolvedType.values)[0]]):this.options&&this.options.proto3_optional&&(this.typeDefault=null),this.options&&null!=this.options.default&&(this.typeDefault=this.options.default,this.resolvedType instanceof r&&"string"==typeof this.typeDefault&&(this.typeDefault=this.resolvedType.values[this.typeDefault])),this.options&&(void 0===this.options.packed||!this.resolvedType||this.resolvedType instanceof r||delete this.options.packed,Object.keys(this.options).length||(this.options=void 0)),this.long)this.typeDefault=n.Long.fromNumber(this.typeDefault,"u"===this.type.charAt(0)),Object.freeze&&Object.freeze(this.typeDefault);else if(this.bytes&&"string"==typeof this.typeDefault){var i;n.base64.test(this.typeDefault)?n.base64.decode(this.typeDefault,i=n.newBuffer(n.base64.length(this.typeDefault)),0):n.utf8.write(this.typeDefault,i=n.newBuffer(n.utf8.length(this.typeDefault)),0),this.typeDefault=i}return this.map?this.defaultValue=n.emptyObject:this.repeated?this.defaultValue=n.emptyArray:this.defaultValue=this.typeDefault,this.parent instanceof t&&(this.parent.ctor.prototype[this.name]=this.defaultValue),e.prototype.resolve.call(this)},o.prototype._inferLegacyProtoFeatures=function(e){if("proto2"!==e&&"proto3"!==e)return{};var r={};if("required"===this.rule&&(r.field_presence="LEGACY_REQUIRED"),this.parent&&void 0===s.defaults[this.type]){var n=this.parent.get(this.type.split(".").pop());n&&n instanceof t&&n.group&&(r.message_encoding="DELIMITED")}return!0===this.getOption("packed")?r.repeated_field_encoding="PACKED":!1===this.getOption("packed")&&(r.repeated_field_encoding="EXPANDED"),r},o.prototype._resolveFeatures=function(t){return e.prototype._resolveFeatures.call(this,this._edition||t)},o.d=function(e,t,r,s){return"function"==typeof t?t=n.decorateType(t).name:t&&"object"==typeof t&&(t=n.decorateEnum(t).name),function(i,a){n.decorateType(i.constructor).add(new o(a,e,t,r,{default:s}))}},o._configure=function(e){t=e},hc}function Oc(){if(gc)return fc;gc=1,fc=s;var e=xc();((s.prototype=Object.create(e.prototype)).constructor=s).className="OneOf";var t=Nc(),r=Uc();function s(t,r,s,n){if(Array.isArray(r)||(s=r,r=void 0),e.call(this,t,s),void 0!==r&&!Array.isArray(r))throw TypeError("fieldNames must be an Array");this.oneof=r||[],this.fieldsArray=[],this.comment=n}function n(e){if(e.parent)for(var t=0;t<e.fieldsArray.length;++t)e.fieldsArray[t].parent||e.parent.add(e.fieldsArray[t])}return s.fromJSON=function(e,t){return new s(e,t.oneof,t.options,t.comment)},s.prototype.toJSON=function(e){var t=!!e&&Boolean(e.keepComments);return r.toObject(["options",this.options,"oneof",this.oneof,"comment",t?this.comment:void 0])},s.prototype.add=function(e){if(!(e instanceof t))throw TypeError("field must be a Field");return e.parent&&e.parent!==this.parent&&e.parent.remove(e),this.oneof.push(e.name),this.fieldsArray.push(e),e.partOf=this,n(this),this},s.prototype.remove=function(e){if(!(e instanceof t))throw TypeError("field must be a Field");var r=this.fieldsArray.indexOf(e);if(r<0)throw Error(e+" is not a member of "+this);return this.fieldsArray.splice(r,1),(r=this.oneof.indexOf(e.name))>-1&&this.oneof.splice(r,1),e.partOf=null,this},s.prototype.onAdd=function(t){e.prototype.onAdd.call(this,t);for(var r=0;r<this.oneof.length;++r){var s=t.get(this.oneof[r]);s&&!s.partOf&&(s.partOf=this,this.fieldsArray.push(s))}n(this)},s.prototype.onRemove=function(t){for(var r,s=0;s<this.fieldsArray.length;++s)(r=this.fieldsArray[s]).parent&&r.parent.remove(r);e.prototype.onRemove.call(this,t)},Object.defineProperty(s.prototype,"isProto3Optional",{get:function(){if(null==this.fieldsArray||1!==this.fieldsArray.length)return!1;var e=this.fieldsArray[0];return null!=e.options&&!0===e.options.proto3_optional}}),s.d=function(){for(var e=new Array(arguments.length),t=0;t<arguments.length;)e[t]=arguments[t++];return function(t,n){r.decorateType(t.constructor).add(new s(n,e)),Object.defineProperty(t,n,{get:r.oneOfGetter(e),set:r.oneOfSetter(e)})}},fc}function xc(){if(vc)return yc;vc=1,yc=o,o.className="ReflectionObject";const e=Oc();var t,r=Uc(),s={enum_type:"OPEN",field_presence:"EXPLICIT",json_format:"ALLOW",message_encoding:"LENGTH_PREFIXED",repeated_field_encoding:"PACKED",utf8_validation:"VERIFY"},n={enum_type:"CLOSED",field_presence:"EXPLICIT",json_format:"LEGACY_BEST_EFFORT",message_encoding:"LENGTH_PREFIXED",repeated_field_encoding:"EXPANDED",utf8_validation:"NONE"},i={enum_type:"OPEN",field_presence:"IMPLICIT",json_format:"ALLOW",message_encoding:"LENGTH_PREFIXED",repeated_field_encoding:"PACKED",utf8_validation:"VERIFY"};function o(e,t){if(!r.isString(e))throw TypeError("name must be a string");if(t&&!r.isObject(t))throw TypeError("options must be an object");this.options=t,this.parsedOptions=null,this.name=e,this._edition=null,this._defaultEdition="proto2",this._features={},this._featuresResolved=!1,this.parent=null,this.resolved=!1,this.comment=null,this.filename=null}return Object.defineProperties(o.prototype,{root:{get:function(){for(var e=this;null!==e.parent;)e=e.parent;return e}},fullName:{get:function(){for(var e=[this.name],t=this.parent;t;)e.unshift(t.name),t=t.parent;return e.join(".")}}}),o.prototype.toJSON=function(){throw Error()},o.prototype.onAdd=function(e){this.parent&&this.parent!==e&&this.parent.remove(this),this.parent=e,this.resolved=!1;var r=e.root;r instanceof t&&r._handleAdd(this)},o.prototype.onRemove=function(e){var r=e.root;r instanceof t&&r._handleRemove(this),this.parent=null,this.resolved=!1},o.prototype.resolve=function(){return this.resolved||this.root instanceof t&&(this.resolved=!0),this},o.prototype._resolveFeaturesRecursive=function(e){return this._resolveFeatures(this._edition||e)},o.prototype._resolveFeatures=function(t){if(!this._featuresResolved){var r={};if(!t)throw new Error("Unknown edition for "+this.fullName);var o=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({},i);else{if("2023"!==t)throw new Error("Unknown edition: "+t);r=Object.assign({},s)}return this._features=Object.assign(r,o||{}),void(this._featuresResolved=!0)}if(this.partOf instanceof e){var a=Object.assign({},this.partOf._features);this._features=Object.assign(a,o||{})}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,o||{})}this.extensionField&&(this.extensionField._features=this._features),this._featuresResolved=!0}},o.prototype._inferLegacyProtoFeatures=function(){return{}},o.prototype.getOption=function(e){if(this.options)return this.options[e]},o.prototype.setOption=function(e,t,s){return this.options||(this.options={}),/^features\./.test(e)?r.setProperty(this.options,e,t,s):s&&void 0!==this.options[e]||(this.getOption(e)!==t&&(this.resolved=!1),this.options[e]=t),this},o.prototype.setParsedOption=function(e,t,s){this.parsedOptions||(this.parsedOptions=[]);var n=this.parsedOptions;if(s){var i=n.find(function(t){return Object.prototype.hasOwnProperty.call(t,e)});if(i){var o=i[e];r.setProperty(o,s,t)}else(i={})[e]=r.setProperty({},s,t),n.push(i)}else{var a={};a[e]=t,n.push(a)}return this},o.prototype.setOptions=function(e,t){if(e)for(var r=Object.keys(e),s=0;s<r.length;++s)this.setOption(r[s],e[r[s]],t);return this},o.prototype.toString=function(){var e=this.constructor.className,t=this.fullName;return t.length?e+" "+t:e},o.prototype._editionToJSON=function(){if(this._edition&&"proto3"!==this._edition)return this._edition},o._configure=function(e){t=e},yc}function Lc(){if(Ic)return bc;Ic=1,bc=s;var e=xc();((s.prototype=Object.create(e.prototype)).constructor=s).className="Enum";var t=Za(),r=Uc();function s(t,r,s,n,i,o){if(e.call(this,t,s),r&&"object"!=typeof r)throw TypeError("values must be an object");if(this.valuesById={},this.values=Object.create(this.valuesById),this.comment=n,this.comments=i||{},this.valuesOptions=o,this._valuesFeatures={},this.reserved=void 0,r)for(var a=Object.keys(r),c=0;c<a.length;++c)"number"==typeof r[a[c]]&&(this.valuesById[this.values[a[c]]=r[a[c]]]=a[c])}return s.prototype._resolveFeatures=function(t){return t=this._edition||t,e.prototype._resolveFeatures.call(this,t),Object.keys(this.values).forEach(e=>{var t=Object.assign({},this._features);this._valuesFeatures[e]=Object.assign(t,this.valuesOptions&&this.valuesOptions[e]&&this.valuesOptions[e].features)}),this},s.fromJSON=function(e,t){var r=new s(e,t.values,t.options,t.comment,t.comments);return r.reserved=t.reserved,t.edition&&(r._edition=t.edition),r._defaultEdition="proto3",r},s.prototype.toJSON=function(e){var t=!!e&&Boolean(e.keepComments);return r.toObject(["edition",this._editionToJSON(),"options",this.options,"valuesOptions",this.valuesOptions,"values",this.values,"reserved",this.reserved&&this.reserved.length?this.reserved:void 0,"comment",t?this.comment:void 0,"comments",t?this.comments:void 0])},s.prototype.add=function(e,t,s,n){if(!r.isString(e))throw TypeError("name must be a string");if(!r.isInteger(t))throw TypeError("id must be an integer");if(void 0!==this.values[e])throw Error("duplicate name '"+e+"' in "+this);if(this.isReservedId(t))throw Error("id "+t+" is reserved in "+this);if(this.isReservedName(e))throw Error("name '"+e+"' is reserved in "+this);if(void 0!==this.valuesById[t]){if(!this.options||!this.options.allow_alias)throw Error("duplicate id "+t+" in "+this);this.values[e]=t}else this.valuesById[this.values[e]=t]=e;return n&&(void 0===this.valuesOptions&&(this.valuesOptions={}),this.valuesOptions[e]=n||null),this.comments[e]=s||null,this},s.prototype.remove=function(e){if(!r.isString(e))throw TypeError("name must be a string");var t=this.values[e];if(null==t)throw Error("name '"+e+"' does not exist in "+this);return delete this.valuesById[t],delete this.values[e],delete this.comments[e],this.valuesOptions&&delete this.valuesOptions[e],this},s.prototype.isReservedId=function(e){return t.isReservedId(this.reserved,e)},s.prototype.isReservedName=function(e){return t.isReservedName(this.reserved,e)},bc}function Pc(){if(Cc)return wc;Cc=1,wc=function(n){for(var i,o=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,p=t.basic[l];i="m"+r.safeProp(d.name),d.map?(o("if(%s!=null&&Object.hasOwnProperty.call(m,%j)){",i,d.name)("for(var ks=Object.keys(%s),i=0;i<ks.length;++i){",i)("w.uint32(%i).fork().uint32(%i).%s(ks[i])",(d.id<<3|2)>>>0,8|t.mapKey[d.keyType],d.keyType),void 0===p?o("types[%i].encode(%s[ks[i]],w.uint32(18).fork()).ldelim().ldelim()",u,i):o(".uint32(%i).%s(%s[ks[i]]).ldelim()",16|p,l,i),o("}")("}")):d.repeated?(o("if(%s!=null&&%s.length){",i,i),d.packed&&void 0!==t.packed[l]?o("w.uint32(%i).fork()",(d.id<<3|2)>>>0)("for(var i=0;i<%s.length;++i)",i)("w.%s(%s[i])",l,i)("w.ldelim()"):(o("for(var i=0;i<%s.length;++i)",i),void 0===p?s(o,d,u,i+"[i]"):o("w.uint32(%i).%s(%s[i])",(d.id<<3|p)>>>0,l,i)),o("}")):(d.optional&&o("if(%s!=null&&Object.hasOwnProperty.call(m,%j))",i,d.name),void 0===p?s(o,d,u,i):o("w.uint32(%i).%s(%s)",(d.id<<3|p)>>>0,l,i))}return o("return w")};var e=Lc(),t=kc(),r=Uc();function s(e,t,r,s){return t.delimited?e("types[%i].encode(%s,w.uint32(%i)).uint32(%i)",r,s,(t.id<<3|3)>>>0,(t.id<<3|4)>>>0):e("types[%i].encode(%s,w.uint32(%i).fork()).ldelim()",r,s,(t.id<<3|2)>>>0)}return wc}var Dc=_c?Tc:(_c=1,Tc=function(){if(Sc)return Fo.exports;Sc=1;var e=Fo.exports=Aa();return e.build="light",e.load=function(t,r,s){return"function"==typeof r?(s=r,r=new e.Root):r||(r=new e.Root),r.load(t,s)},e.loadSync=function(t,r){return r||(r=new e.Root),r.loadSync(t)},e.encoder=Pc(),e.decoder=tc(),e.verifier=rc(),e.converter=ic(),e.ReflectionObject=xc(),e.Namespace=Za(),e.Root=Ec(),e.Enum=Lc(),e.Type=Mc(),e.Field=Nc(),e.OneOf=Oc(),e.MapField=Qa(),e.Service=Xa(),e.Method=Ya(),e.Message=ec(),e.wrappers=Ac(),e.types=kc(),e.util=Uc(),e.ReflectionObject._configure(e.Root),e.Namespace._configure(e.Type,e.Service,e.Enum),e.Root._configure(e.Type),e.Field._configure(e.Type),Fo.exports}());const qc={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}}}}}}}}}},$c=e=>{if(!e||0===e.trim().length)throw Fi("Proto type name is required.",{code:Gi,stage:Oi,retryable:!1,details:{typeName:e}})};class Gc{constructor(){this.codecMap=new Map}register(e,t){$c(e),this.codecMap.set(e,t)}registerType(e,t){this.register(e,{encode:r=>{const s=((e,t)=>{if("object"==typeof e&&null!==e)return e;throw Fi("Proto payload must be an object.",{code:Gi,stage:Oi,retryable:!1,details:{typeName:t,payloadType:typeof e}})})(r,e),n=t.fromObject(s);return t.encode(n).finish()},decode:e=>{const r=t.decode(e);return t.toObject(r,{longs:String,enums:Number,defaults:!1})}})}get(e){return $c(e),this.codecMap.get(e)}getOrThrow(e){const t=this.get(e);if(t)return t;throw Fi("Proto codec not found.",{code:Gi,stage:Oi,retryable:!1,details:{typeName:e}})}}const Fc=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),Bc=e=>{class t extends Dc.Message{constructor(e){super(),((e,t)=>{if(t)for(const r of Object.keys(t)){const s=t[r];null!=s&&(e[r]=s)}})(this,e)}}const r=t;return r.$type=e,r.prototype.$type=e,r},jc=e=>mo.isLong(e),zc=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&"number"==typeof e.byteLength,Kc=e=>Object.prototype.hasOwnProperty.call(Dc.types.packed,e),Hc=e=>{const t=e.resolve();return t.resolvedType instanceof Dc.Enum||Kc(t.type)},Vc=(e,t)=>t in e?e[t]:void 0,Wc=e=>{const t=e.resolve();return t.resolvedType instanceof Dc.Enum?0:(r=t.type,Object.prototype.hasOwnProperty.call(Dc.types.basic,r)?Dc.types.basic[t.type]:2);var r},Jc=(e,t)=>jc(e)||"number"==typeof e||"string"==typeof e?e:Fc(e)&&"number"==typeof e.low&&"number"==typeof e.high?new mo(e.low,e.high,t):t?mo.UZERO:mo.ZERO,Zc=(e,t,r)=>{switch(t){case"double":return e.double(Number(r));case"float":return e.float(Number(r));case"int32":return e.int32(Number(r));case"uint32":return e.uint32(Number(r));case"sint32":return e.sint32(Number(r));case"fixed32":return e.fixed32(Number(r));case"sfixed32":return e.sfixed32(Number(r));case"int64":return e.int64(Jc(r,!1));case"uint64":return e.uint64(Jc(r,!0));case"sint64":return e.sint64(Jc(r,!1));case"fixed64":return e.fixed64(Jc(r,!0));case"sfixed64":return e.sfixed64(Jc(r,!1));case"bool":return e.bool(Boolean(r));case"string":return e.string(String(r));case"bytes":return e.bytes((e=>"string"==typeof e?e:zc(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):Array.isArray(e)?Uint8Array.from(e.filter(e=>"number"==typeof e)):new Uint8Array)(r));default:throw new TypeError(`Unsupported protobuf field type: ${t}`)}},Qc=(e,t,r)=>{if(t<0||e.pos+t>r)throw RangeError(`index out of range: ${e.pos} + ${t} > ${r}`)},Yc=(e,t)=>{const r=e.uint32();return Qc(e,r,t),r},Xc=(e,t,r)=>{const s=e.len;e.len=r;try{switch(t){case 0:return void e.skip();case 1:return Qc(e,8,r),void e.skip(8);case 2:{const t=Yc(e,r);return void e.skip(t)}case 5:return Qc(e,4,r),void e.skip(4);default:throw new Error(`Unsupported protobuf wire type: ${String(t)}`)}}finally{e.len=s}},ed=(e,t,r)=>{const s=t.resolve(),n=s.resolvedType;if(n instanceof Dc.Type){const t=e.fork();return rd(n,Fc(r)?r:{},t),t.ldelim(),e}return n instanceof Dc.Enum?(e.int32("number"==typeof r?r:Number(r)),e):Zc(e,s.type,r)},td=(e,t,r)=>{if(0===r.length)return e;const s=t.resolve();if(Kc(s.type)&&t.packed){e.uint32(t.id<<3|2).fork();for(const s of r)ed(e,t,s);return e.ldelim(),e}const n=Wc(t);for(const i of r)e.uint32(t.id<<3|n),ed(e,t,i);return e},rd=(e,t,r=Dc.Writer.create())=>{const s=e.fieldsArray.slice().sort(Dc.util.compareFieldsById);for(const n of s){const e=Vc(t,n.name);null!=e&&(n.repeated?td(r,n,Array.isArray(e)?e:[]):(r.uint32(n.id<<3|Wc(n)),ed(r,n,e)))}return r},sd=(e,t,r,s)=>{const n=t.resolve(),i=n.resolvedType;return i instanceof Dc.Type?2!==r?void Xc(e,r,s):nd(i,e,Yc(e,s)):i instanceof Dc.Enum?e.int32():((e,t)=>{switch(t){case"double":return e.double();case"float":return e.float();case"int32":return e.int32();case"uint32":return e.uint32();case"sint32":return e.sint32();case"fixed32":return e.fixed32();case"sfixed32":return e.sfixed32();case"int64":return e.int64();case"uint64":return e.uint64();case"sint64":return e.sint64();case"fixed64":return e.fixed64();case"sfixed64":return e.sfixed64();case"bool":return e.bool();case"string":return e.string();case"bytes":return e.bytes();default:throw new TypeError(`Unsupported protobuf field type: ${t}`)}})(e,n.type)},nd=(e,t,r)=>{const s=t instanceof Dc.Reader?t:Dc.Reader.create(t),n=void 0===r?s.len:s.pos+r,i=(e=>{const t={};for(const r of e.fieldsArray)r.repeated&&(t[r.name]=[]);return t})(e),o=e.fieldsById;for(;s.pos<n;){const t=s.pos,r=s.uint32(),c=o[r>>>3],d=7&r;try{if(!c){Xc(s,d,n);continue}if(c.repeated){const e=Array.isArray(i[c.name])?i[c.name]:[];if(Hc(c)&&2===d){const t=Yc(s,n)+s.pos;for(;s.pos<t;)e.push(sd(s,c,0,t))}else{const t=sd(s,c,d,n);void 0!==t&&e.push(t)}i[c.name]=e;continue}const e=sd(s,c,d,n);void 0!==e&&(i[c.name]=e)}catch(a){if(a instanceof RangeError){const i=c?`${c.name}#${c.id}`:`unknown#${r>>>3}`;throw new RangeError(`${a.message}; protobufType=${e.fullName}; field=${i}; tag=${r}; wireType=${d}; tagPosition=${t}; readerPosition=${s.pos}; messageEnd=${n}`)}throw a}}return i},id=(e,t)=>t?.longs===String?e.toString():t?.longs===Number?e.toNumber():e,od=(e,t)=>{const r=e.resolve();if(r.resolvedType instanceof Dc.Type)return null;if(r.resolvedType instanceof Dc.Enum){if(t?.enums===String){return r.resolvedType.valuesById[r.typeDefault]??r.typeDefault}return r.typeDefault}return"bytes"===r.type?t?.bytes===String?"":t?.bytes===Array?[]:new Uint8Array:r.long&&jc(r.typeDefault)?id(r.typeDefault,t):r.typeDefault},ad=(e,t,r)=>{const s=e.resolve();if(void 0!==t)return s.resolvedType instanceof Dc.Type?Fc(t)?cd(s.resolvedType,t,r):t:s.resolvedType instanceof Dc.Enum?r?.enums===String&&"number"==typeof t?s.resolvedType.valuesById[t]??t:t:s.long&&jc(t)?id(t,r):"bytes"===s.type&&zc(t)?((e,t)=>t?.bytes===String?Dc.util.base64.encode(e,0,e.length):t?.bytes===Array?Array.prototype.slice.call(e):e)(t,r):t},cd=(e,t,r)=>{const s={};for(const n of e.fieldsArray.slice().sort(Dc.util.compareFieldsById)){const e=Vc(t,n.name);n.repeated?Array.isArray(e)?s[n.name]=e.map(e=>ad(n,e,r)):(r?.arrays||r?.defaults)&&(s[n.name]=[]):null==e?r?.defaults&&(s[n.name]=od(n,r)):s[n.name]=ad(n,e,r)}return s},ud=e=>{const t=e;t.__reflectionCodecInstalled||(t.__reflectionCodecInstalled=!0,e.encode=(t,r)=>rd(e,Fc(t)?t:{},r),e.decode=(t,r)=>nd(e,t,r),e.fromObject=e=>Fc(e)?e:{},e.toObject=(t,r)=>cd(e,Fc(t)?t:{},r),e.create=e=>e?{...e}:{},e.verify=()=>null)},ld=e=>{ud(e);for(const t of e.nestedArray)if(t instanceof Dc.Type)ld(t);else if(t instanceof Dc.Namespace)for(const e of t.nestedArray)e instanceof Dc.Type&&ld(e)},pd=e=>{for(const t of e.nestedArray)t instanceof Dc.Type?ld(t):t instanceof Dc.Namespace&&pd(t)},hd=()=>{const e=Dc.Type;e.__reflectionRuntimeInstalled||(e.generateConstructor=e=>()=>Bc(e),Dc.Type.prototype.setup=function(){return ud(this),this},Dc.Type.prototype.create=function(e){return e?{...e}:{}},Dc.Type.prototype.encode=function(e,t){return rd(this,Fc(e)?e:{},t)},Dc.Type.prototype.decode=function(e,t){return nd(this,e,t)},Dc.Type.prototype.fromObject=function(e){return Fc(e)?e:{}},Dc.Type.prototype.toObject=function(e,t){return cd(this,Fc(e)?e:{},t)},Dc.Type.prototype.verify=function(){return null},e.__reflectionRuntimeInstalled=!0)};let md=!1,fd=null,gd=null,yd=null;const vd=e=>e.startsWith(".")?e.slice(1):e,bd=e=>e instanceof Dc.Namespace,Id=e=>e instanceof Dc.Type,wd=e=>{for(const t of e.nestedArray)Id(t)?ld(t):bd(t)&&wd(t)},Cd=()=>{md||(Dc.util.Long=mo,Dc.configure(),md=!0),hd();const e=Dc.Root.fromJSON(qc);return wd(e),e},Sd=(e,t)=>{const r=e.nestedArray;for(const s of r){if(Id(s)){const e=vd(s.fullName);ld(s),t.registerType(e,s);continue}bd(s)&&Sd(s,t)}},Td=(e,t,r)=>{const s=t instanceof Error?t.message:String(t);return Fi(`Static proto ${r} failed.`,{code:Gi,stage:Oi,retryable:!1,details:{typeName:e,operation:r,cause:s}})},_d=()=>fd||(fd=Cd(),fd),Rd=()=>{if(yd)return yd;const e=(()=>{if(gd)return gd;const e=new Gc,t=_d();return Sd(t,e),gd=e,e})();return yd={encode(t,r){try{return e.getOrThrow(vd(t)).encode(r)}catch(s){throw Td(t,s,"encode")}},decode(t,r){try{return e.getOrThrow(vd(t)).decode(r)}catch(s){throw Td(t,s,"decode")}}},yd},Ad=e=>{const t={};if("function"==typeof e.forEach)return e.forEach((e,r)=>{t[r]=e}),t;const r=e.get?.("content-type");return r&&(t["content-type"]=r),t},Md=e=>{const t=e?.fetchImpl;if("function"==typeof t)return{async request(r){const s=r.method??"GET",n={...r.headers??{}},i=new AbortController,o=r.timeoutMs??e?.timeoutMs??15e3,a=setTimeout(()=>{i.abort()},o),c=((e,t,r)=>{if(e.body instanceof Uint8Array)return new Uint8Array(e.body).buffer;if("string"==typeof e.body)return e.body;if(e.body&&"GET"!==r)return Object.keys(t).some(e=>"content-type"===e.toLowerCase())||(t["Content-Type"]="application/json"),JSON.stringify(e.body)})(r,n,s);try{const e=await t(r.url,{method:s,headers:n,body:c,signal:r.signal??i.signal});let o;if("arraybuffer"===r.responseType)o=await e.arrayBuffer();else if("text"===r.responseType)o=await e.text();else{const t=e.headers.get("content-type")??"",r=await e.text();o=t.includes("application/json")&&r?JSON.parse(r):r}return{status:e.status,headers:Ad(e.headers),data:o}}catch(d){throw Fi("Request adapter execution failed.",{code:Di,stage:Ui,retryable:!0,details:{url:r.url,method:s,cause:d instanceof Error?d.message:String(d)}})}finally{clearTimeout(a)}}}},Ed=e=>"function"==typeof e.addEventListener&&"function"==typeof e.removeEventListener,Ud=e=>"function"==typeof e.on&&"function"==typeof e.off,kd=(e,t,r)=>{if(Ed(e))return e.addEventListener(t,r),()=>{e.removeEventListener(t,r)};if(Ud(e)){const s=e;return s.on(t,r),()=>{s.off(t,r)}}throw Fi("Socket event listener API is unsupported.",{code:$i,stage:Ni,retryable:!1,details:{event:t}})},Nd=(e,t,r)=>{if(Ed(e)){const s=(...n)=>{e.removeEventListener(t,s),r(...n)};return e.addEventListener(t,s),()=>{e.removeEventListener(t,s)}}if(Ud(e)){const s=e;if("function"==typeof s.once)return s.once?.(t,r),()=>{s.off(t,r)};let n=()=>{};return n=kd(e,t,(...e)=>{n(),r(...e)}),n}throw Fi("Socket one-time listener API is unsupported.",{code:$i,stage:Ni,retryable:!1,details:{event:t}})},Od=e=>{return"string"==typeof e||(t=e,"[object ArrayBuffer]"===Object.prototype.toString.call(t))||"undefined"!=typeof Blob&&e instanceof Blob?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength).slice().buffer:e&&"object"==typeof e&&"data"in e?Od(e.data):null;var t},xd=e=>{const t=new Set,r=new Set,s=new Set,n=new Set;return kd(e,"open",()=>{t.forEach(e=>{e()})}),kd(e,"message",(...e)=>{const t=Od(e[0]);null!==t&&r.forEach(e=>{e(t)})}),kd(e,"error",(...e)=>{const t=e[0];s.forEach(e=>{e(t)})}),kd(e,"close",(...e)=>{const t=(e=>{const[t,r]=e;if(t&&"object"==typeof t){const e=t;return{code:"number"==typeof e.code?e.code:void 0,reason:"string"==typeof e.reason?e.reason:void 0}}return{code:"number"==typeof t?t:void 0,reason:"string"==typeof r?r:ArrayBuffer.isView(r)?(new TextDecoder).decode(new Uint8Array(r.buffer,r.byteOffset,r.byteLength)):void 0}})(e);n.forEach(e=>{e(t)})}),{get readyState(){return e.readyState},send(t){if(e.readyState!==ji)throw Fi("Socket is not open.",{code:$i,stage:Ni,retryable:!0,details:{readyState:e.readyState}});return e.send(t),Promise.resolve()},close(t,r){e.close(t,r)},onOpen:e=>(t.add(e),()=>{t.delete(e)}),onMessage:e=>(r.add(e),()=>{r.delete(e)}),onError:e=>(s.add(e),()=>{s.delete(e)}),onClose:e=>(n.add(e),()=>{n.delete(e)})}},Ld=e=>{const t=e?.webSocketCtor;if(void 0!==t)return{connect:e=>new Promise((r,s)=>{let n;try{n=new t(e.url,e.protocols);try{n.binaryType="arraybuffer"}catch{}}catch(l){return void s(Fi("Socket creation failed.",{code:$i,stage:Ni,retryable:!0,details:{cause:l instanceof Error?l.message:String(l)}}))}let i,o=()=>{},a=()=>{},c=!1;const d=()=>{void 0!==i&&(clearTimeout(i),i=void 0)},u=()=>{c||(c=!0,o(),a(),d(),n.close(),s(Fi("Socket connection timed out.",{code:$i,stage:Ni,retryable:!0,details:{url:e.url,reason:"timeout"}})))};o=Nd(n,"open",()=>{c||(c=!0,o(),a(),d(),r(xd(n)))}),a=Nd(n,"error",e=>{if(c)return;c=!0,o(),a(),d();const t=e&&"object"==typeof e&&"type"in e?String(e.type):void 0;s(Fi("Socket connection failed before open.",{code:$i,stage:Ni,retryable:!0,details:{eventType:t}}))}),"number"==typeof e.timeoutMs&&e.timeoutMs>0&&(i=setTimeout(u,e.timeoutMs))})}},Pd=(e,t)=>{throw Fi("Upload adapter execution failed.",{code:qi,stage:ki,retryable:"abort"!==e,details:{reason:e,url:t.url}})},Dd=e=>{const t=new FormData;return Object.entries(e.fields??{}).forEach(([e,r])=>{t.append(e,r)}),((e,t)=>{if("web-file"!==t.source.sourceType)throw Fi("Web upload adapter only supports web-file source.",{code:qi,stage:ki,retryable:!1,details:{sourceType:t.source.sourceType}});const r=t.source.file;if(!r)throw Fi("Upload source file is required for web-file uploads.",{code:qi,stage:ki,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},qd=(e,t,r)=>new Promise((s,n)=>{const i=e(),o=r.timeoutMs??t?.timeoutMs??3e4;((e,t)=>{e.upload&&t.onProgress&&e.upload.addEventListener("progress",e=>{if(!e.lengthComputable)return void t.onProgress?.({loaded:e.loaded});const r=e.total>0?e.loaded/e.total*100:void 0;t.onProgress?.({loaded:e.loaded,total:e.total,percent:r})})})(i,r),i.addEventListener("abort",()=>{try{Pd("abort",r)}catch(e){n(e instanceof Error?e:new Error(String(e)))}}),i.addEventListener("timeout",()=>{try{Pd("timeout",r)}catch(e){n(e instanceof Error?e:new Error(String(e)))}}),i.addEventListener("error",()=>{try{Pd("network",r)}catch(e){n(e instanceof Error?e:new Error(String(e)))}}),i.addEventListener("load",()=>{s({status:i.status,body:i.responseText})});try{const e=Dd(r);i.timeout=o,i.open("POST",r.url),((e,t)=>{Object.entries(t??{}).forEach(([t,r])=>{e.setRequestHeader(t,r)})})(i,r.headers),i.send(e)}catch(a){n(Fi("Upload adapter execution failed.",{code:qi,stage:ki,retryable:!1,details:{url:r.url,reason:"invalid-config",cause:a instanceof Error?a.message:String(a)}}))}}),$d=(e,t)=>e?"timeout":"abort",Gd=e=>{const t=Boolean(e&&"xhrFactory"in e)?e?.xhrFactory:"undefined"!=typeof XMLHttpRequest?()=>new XMLHttpRequest:void 0,r=e?.fetchImpl;if("function"==typeof t||"function"==typeof r)return{upload(s){if("function"==typeof t)return qd(t,e,s);if("function"==typeof r)return(async(e,t,r)=>{const s=r.timeoutMs??t?.timeoutMs??3e4;let n=!1;const i="undefined"!=typeof AbortController?new AbortController:void 0,o=i&&Number.isFinite(s)?setTimeout(()=>{n=!0,i.abort()},s):void 0,a=((e,t)=>e??t?.signal)(r.signal,i);try{const t=Dd(r),s=await e(r.url,{method:"POST",headers:r.headers,body:t,signal:a}),n=await s.text(),i=r.source.size;return"number"==typeof i&&r.onProgress?.({loaded:i,total:i,percent:i>0?100:void 0}),{status:s.status,body:n}}catch(c){const e=c instanceof Error&&"AbortError"===c.name;throw Fi("Upload adapter execution failed.",{code:qi,stage:ki,retryable:!e,details:{reason:e?$d(n):"network",url:r.url,cause:c instanceof Error?c.message:String(c)}})}finally{o&&clearTimeout(o)}})(r,e,s);throw Fi("Upload adapter execution failed.",{code:qi,stage:ki,retryable:!1,details:{reason:"missing-upload-runtime",url:s.url}})}}},Fd=(e,t)=>{const r=new e;return Object.entries(t.fields??{}).forEach(([e,t])=>{r.append(e,t)}),r.append("file",(e=>{const t=e.source;if("rn-uri"!==t.sourceType||!t.uri)throw Fi("React Native upload adapter only supports rn-uri source.",{code:qi,stage:ki,retryable:!1,details:{sourceType:t.sourceType}});return{uri:t.uri,name:t.name??"upload.bin",type:t.mimeType??"application/octet-stream"}})(t)),r},Bd=e=>{const t=e?.fetchImpl,r=e?.formDataCtor;if("function"==typeof t&&"function"==typeof r)return{async upload(s){const n=s.timeoutMs??e?.timeoutMs??3e4,i="function"==typeof AbortController?new AbortController:void 0;let o=!1;const a=i&&Number.isFinite(n)?setTimeout(()=>{o=!0,i.abort()},n):void 0;try{const e=Fd(r,s),n=await t(s.url,{method:"POST",headers:s.headers,body:e,signal:s.signal??i?.signal}),o=await n.text(),a=s.source.size;return"number"==typeof a&&s.onProgress?.({loaded:a,total:a,percent:a>0?100:void 0}),{status:n.status,body:o}}catch(c){if((e=>{if("object"!=typeof e||null===e)return!1;const t=e;return t.code===qi&&t.stage===ki})(c))throw c;const e=c instanceof Error&&"AbortError"===c.name;throw Fi("React Native upload adapter execution failed.",{code:qi,stage:ki,retryable:!e||o,details:{url:s.url,reason:e?o?"timeout":"abort":"network",cause:c instanceof Error?c.message:String(c)}})}finally{void 0!==a&&clearTimeout(a)}}}},zd=(e,t)=>e+t&4294967295,Kd=(e,t,r,s,n,i)=>{return zd((o=zd(zd(t,e),zd(s,i)))<<(a=n)|o>>>32-a,r);var o,a},Hd=(e,t,r,s,n,i,o)=>Kd(t&r|~t&s,e,t,n,i,o),Vd=(e,t,r,s,n,i,o)=>Kd(t&s|r&~s,e,t,n,i,o),Wd=(e,t,r,s,n,i,o)=>Kd(t^r^s,e,t,n,i,o),Jd=(e,t,r,s,n,i,o)=>Kd(r^(t|~s),e,t,n,i,o),Zd=(e,t)=>{let[r,s,n,i]=e;r=Hd(r,s,n,i,t[0]??0,7,-680876936),i=Hd(i,r,s,n,t[1]??0,12,-389564586),n=Hd(n,i,r,s,t[2]??0,17,606105819),s=Hd(s,n,i,r,t[3]??0,22,-1044525330),r=Hd(r,s,n,i,t[4]??0,7,-176418897),i=Hd(i,r,s,n,t[5]??0,12,1200080426),n=Hd(n,i,r,s,t[6]??0,17,-1473231341),s=Hd(s,n,i,r,t[7]??0,22,-45705983),r=Hd(r,s,n,i,t[8]??0,7,1770035416),i=Hd(i,r,s,n,t[9]??0,12,-1958414417),n=Hd(n,i,r,s,t[10]??0,17,-42063),s=Hd(s,n,i,r,t[11]??0,22,-1990404162),r=Hd(r,s,n,i,t[12]??0,7,1804603682),i=Hd(i,r,s,n,t[13]??0,12,-40341101),n=Hd(n,i,r,s,t[14]??0,17,-1502002290),s=Hd(s,n,i,r,t[15]??0,22,1236535329),r=Vd(r,s,n,i,t[1]??0,5,-165796510),i=Vd(i,r,s,n,t[6]??0,9,-1069501632),n=Vd(n,i,r,s,t[11]??0,14,643717713),s=Vd(s,n,i,r,t[0]??0,20,-373897302),r=Vd(r,s,n,i,t[5]??0,5,-701558691),i=Vd(i,r,s,n,t[10]??0,9,38016083),n=Vd(n,i,r,s,t[15]??0,14,-660478335),s=Vd(s,n,i,r,t[4]??0,20,-405537848),r=Vd(r,s,n,i,t[9]??0,5,568446438),i=Vd(i,r,s,n,t[14]??0,9,-1019803690),n=Vd(n,i,r,s,t[3]??0,14,-187363961),s=Vd(s,n,i,r,t[8]??0,20,1163531501),r=Vd(r,s,n,i,t[13]??0,5,-1444681467),i=Vd(i,r,s,n,t[2]??0,9,-51403784),n=Vd(n,i,r,s,t[7]??0,14,1735328473),s=Vd(s,n,i,r,t[12]??0,20,-1926607734),r=Wd(r,s,n,i,t[5]??0,4,-378558),i=Wd(i,r,s,n,t[8]??0,11,-2022574463),n=Wd(n,i,r,s,t[11]??0,16,1839030562),s=Wd(s,n,i,r,t[14]??0,23,-35309556),r=Wd(r,s,n,i,t[1]??0,4,-1530992060),i=Wd(i,r,s,n,t[4]??0,11,1272893353),n=Wd(n,i,r,s,t[7]??0,16,-155497632),s=Wd(s,n,i,r,t[10]??0,23,-1094730640),r=Wd(r,s,n,i,t[13]??0,4,681279174),i=Wd(i,r,s,n,t[0]??0,11,-358537222),n=Wd(n,i,r,s,t[3]??0,16,-722521979),s=Wd(s,n,i,r,t[6]??0,23,76029189),r=Wd(r,s,n,i,t[9]??0,4,-640364487),i=Wd(i,r,s,n,t[12]??0,11,-421815835),n=Wd(n,i,r,s,t[15]??0,16,530742520),s=Wd(s,n,i,r,t[2]??0,23,-995338651),r=Jd(r,s,n,i,t[0]??0,6,-198630844),i=Jd(i,r,s,n,t[7]??0,10,1126891415),n=Jd(n,i,r,s,t[14]??0,15,-1416354905),s=Jd(s,n,i,r,t[5]??0,21,-57434055),r=Jd(r,s,n,i,t[12]??0,6,1700485571),i=Jd(i,r,s,n,t[3]??0,10,-1894986606),n=Jd(n,i,r,s,t[10]??0,15,-1051523),s=Jd(s,n,i,r,t[1]??0,21,-2054922799),r=Jd(r,s,n,i,t[8]??0,6,1873313359),i=Jd(i,r,s,n,t[15]??0,10,-30611744),n=Jd(n,i,r,s,t[6]??0,15,-1560198380),s=Jd(s,n,i,r,t[13]??0,21,1309151649),r=Jd(r,s,n,i,t[4]??0,6,-145523070),i=Jd(i,r,s,n,t[11]??0,10,-1120210379),n=Jd(n,i,r,s,t[2]??0,15,718787259),s=Jd(s,n,i,r,t[9]??0,21,-343485551),e[0]=zd(r,e[0]),e[1]=zd(s,e[1]),e[2]=zd(n,e[2]),e[3]=zd(i,e[3])},Qd=(e,t)=>{const r=new Array(16).fill(0);for(let s=0;s<16;s+=1){const n=t+4*s;r[s]=(e[n]??0)|(e[n+1]??0)<<8|(e[n+2]??0)<<16|(e[n+3]??0)<<24}return r},Yd=e=>{let t="";for(let r=0;r<4;r+=1){t+=(e>>8*r&255).toString(16).padStart(2,"0")}return t},Xd=e=>{const t=[1732584193,-271733879,-1732584194,271733878];let r=0;for(;r+64<=e.length;r+=64)Zd(t,Qd(e,r));const s=new Array(16).fill(0);let n=0;for(;r<e.length;r+=1){const t=n>>2;s[t]=(s[t]??0)|(e[r]??0)<<n%4*8,n+=1}const i=n>>2;s[i]=(s[i]??0)|128<<n%4*8,n>55&&(Zd(t,s),s.fill(0));const o=8*e.length;return s[14]=4294967295&o,s[15]=Math.floor(o/4294967296),Zd(t,s),t.map(Yd).join("")},eu=async e=>{if("function"==typeof createImageBitmap){const t=await createImageBitmap(e);return{image:t,width:t.width,height:t.height,cleanup:()=>{t.close()}}}if("undefined"==typeof Image||"undefined"==typeof URL)throw Fi("Image decode capability is missing for current platform",{code:Pi,stage:xi,retryable:!1,details:{reason:"image decode unavailable"}});const t=URL.createObjectURL(e);return new Promise((e,r)=>{const s=new Image;s.onload=()=>{e({image:s,width:s.naturalWidth||s.width,height:s.naturalHeight||s.height,cleanup:()=>{URL.revokeObjectURL(t)}})},s.onerror=()=>{URL.revokeObjectURL(t),r(Fi("Image decode failed",{code:qi,stage:xi,retryable:!1,details:{reason:"image load error"}}))},s.src=t})},tu=e=>{if(!(e=>"web-file"===e.sourceType&&"undefined"!=typeof Blob&&e.file instanceof Blob)(e))throw Fi("Web image processor only supports web file source",{code:Pi,stage:xi,retryable:!1,details:{sourceType:e.sourceType}});return e.file},ru=()=>({async getImageInfo(e){const t=tu(e),r=await eu(t);try{return{width:r.width,height:r.height,mimeType:e.mimeType,fileSize:e.size,isGif:"image/gif"===e.mimeType}}finally{r.cleanup()}},async generateBigImage(e,t){const r=tu(e),s=await eu(r);try{const r=((e,t,r)=>{const s=Math.min(e,t);if(s<=r)return{width:e,height:t};const n=r/s;return{width:Math.max(1,Math.round(e*n)),height:Math.max(1,Math.round(t*n))}})(s.width,s.height,t.maxShortEdge),i=((e,t)=>{if("undefined"!=typeof OffscreenCanvas)return new OffscreenCanvas(e,t);if("undefined"!=typeof document){const r=document.createElement("canvas");return r.width=e,r.height=t,r}throw Fi("Canvas capability is missing for current platform",{code:Pi,stage:xi,retryable:!1,details:{reason:"canvas unavailable"}})})(r.width,r.height),o=i.getContext("2d");if(!o)throw Fi("Canvas 2d context is missing",{code:Pi,stage:xi,retryable:!1});o.drawImage(s.image,0,0,r.width,r.height);const a="image/png"===(n=e.mimeType)||"image/webp"===n?n:"image/jpeg",c=await(async(e,t,r)=>{if("convertToBlob"in e&&"function"==typeof e.convertToBlob)return e.convertToBlob({type:t,quality:r});if("toBlob"in e&&"function"==typeof e.toBlob)return new Promise((s,n)=>{e.toBlob(e=>{e?s(e):n(Fi("Image encode failed",{code:qi,stage:xi,retryable:!1,details:{reason:"canvas toBlob returned null"}}))},t,r)});throw Fi("Canvas encode capability is missing for current platform",{code:Pi,stage:xi,retryable:!1,details:{reason:"canvas encode unavailable"}})})(i,a,t.quality),d=(e=>e.name??"image")(e),u="undefined"!=typeof File?new File([c],d,{type:a,lastModified:Date.now()}):void 0;return{source:{sourceType:"web-file",file:u??c,name:d,mimeType:a,size:u?.size??c.size},width:r.width,height:r.height,fileName:d,fileType:a,fileSize:u?.size??c.size,webFile:u}}finally{s.cleanup()}var n},async computeMd5(e){const t=tu(e),r=await(async e=>{if("function"==typeof e.arrayBuffer)return e.arrayBuffer();if("undefined"==typeof FileReader)throw Fi("Binary read capability is missing for current platform",{code:Pi,stage:xi,retryable:!1,details:{reason:"blob.arrayBuffer unavailable"}});return new Promise((t,r)=>{const s=new FileReader;s.onerror=()=>{r(Fi("Binary read failed",{code:qi,stage:xi,retryable:!1}))},s.onload=()=>{s.result instanceof ArrayBuffer?t(s.result):r(Fi("Binary read returned invalid result",{code:qi,stage:xi,retryable:!1}))},s.readAsArrayBuffer(e)})})(t);return Xd(new Uint8Array(r))}}),su=e=>{if(e instanceof Error)return e.message;if("object"==typeof e&&null!==e&&"errMsg"in e){const t=e.errMsg;if("string"==typeof t)return t}return String(e)},nu=e=>{if(!(e=>"miniapp-path"===e.sourceType&&"string"==typeof e.path&&e.path.length>0)(e))throw Fi("Miniapp image processor only supports miniapp path source",{code:Pi,stage:xi,retryable:!1,details:{sourceType:e.sourceType}});return e.path},iu=e=>{const t=e.getFileSystemManager?.();if(t)return t;throw Fi("Miniapp file system capability is missing",{code:Pi,stage:xi,retryable:!1,details:{capability:"getFileSystemManager"}})},ou=e=>{if(!e)return;const t=e.toLowerCase();return t.startsWith("image/")?t:`image/${t}`},au=async(e,t)=>new Promise((r,s)=>{e.getImageInfo({src:t,success:e=>{r(e)},fail:e=>{s(e instanceof Error?e:new Error(su(e)))}})}).catch(e=>{throw Fi("Miniapp image info read failed",{code:qi,stage:xi,retryable:!1,details:{src:t,cause:su(e)}})}),cu=(e,t)=>"string"==typeof t.path&&t.path.length>0?t.path:e,du=async(e,t)=>{if(!(e=>/^https?:\/\/tmp\//i.test(e))(t))return t;const r=await au(e,t);return cu(t,r)},uu=e=>({async getImageInfo(t){const r=nu(t),s=await au(e,r),n=ou(s.type)??t.mimeType;return{width:s.width,height:s.height,mimeType:n,fileSize:t.size,isGif:"image/gif"===n}},async generateBigImage(t,r){const s=nu(t);if("function"!=typeof e.compressImage)throw Fi("Miniapp image compress capability is missing",{code:Pi,stage:xi,retryable:!1,details:{capability:"compressImage"}});const n=await au(e,s),i=cu(s,n),o=((e,t,r)=>{const s=Math.min(e,t);if(s<=r)return{width:e,height:t};const n=r/s;return{width:Math.max(1,Math.round(e*n)),height:Math.max(1,Math.round(t*n))}})(n.width,n.height,r.maxShortEdge),a=await new Promise((t,s)=>{e.compressImage?.({src:i,quality:Math.max(0,Math.min(100,Math.round(100*r.quality))),compressedWidth:o.width,compressedHeight:o.height,success:e=>{e.tempFilePath?t(e.tempFilePath):s(new Error("compressImage missing tempFilePath"))},fail:e=>{s(e instanceof Error?e:new Error(su(e)))}})}).catch(e=>{throw Fi("Miniapp image compress failed",{code:qi,stage:xi,retryable:!1,details:{src:i,cause:su(e)}})}),c=await du(e,a),d=await au(e,c),u=ou(d.type)??t.mimeType,l=await(async(e,t,r)=>{const s=iu(e);return s.getFileInfo?new Promise((e,r)=>{s.getFileInfo?.({filePath:t,success:t=>{e(t.size)},fail:e=>{r(e instanceof Error?e:new Error(su(e)))}})}).catch(e=>{throw Fi("Miniapp file info read failed",{code:qi,stage:xi,retryable:!1,details:{filePath:t,cause:su(e)}})}):r})(e,c,t.size);return{source:{sourceType:"miniapp-path",path:c,name:t.name,mimeType:u,size:l},width:d.width,height:d.height,fileName:t.name,fileType:u,fileSize:l}},async computeMd5(t){const r=nu(t),s=await du(e,r),n=await(async(e,t)=>{const r=iu(e),s=await new Promise((e,s)=>{r.readFile({filePath:t,success:t=>{e(t.data)},fail:e=>{s(e instanceof Error?e:new Error(su(e)))}})}).catch(e=>{throw Fi("Miniapp file read failed",{code:qi,stage:xi,retryable:!1,details:{filePath:t,cause:su(e)}})});return s instanceof ArrayBuffer?new Uint8Array(s):"function"==typeof TextEncoder?(new TextEncoder).encode(s):Uint8Array.from(Array.from(s).map(e=>255&e.charCodeAt(0)))})(e,s);return Xd(n)}}),lu=new Set(["quotaexceedederror","ns_error_dom_quota_reached"]),pu=[/\bquota\b/i,/\bexceed(?:ed)?\s+storage\s+max(?:imum)?\s+size\b/i,/\b(?:storage\s+)?max(?:imum)?\s+size\b.*\bexceed(?:ed)?\b/i,/\bstorage\b.*\blimit\b.*\b(?:exceed(?:ed)?|reach(?:ed)?)\b/i],hu=(e,t)=>{if("object"!=typeof e||null===e)return null;const r=e[t];return"string"==typeof r?r:null},mu=e=>{if(!e)return!1;const t=hu(e,"name");if(t&&lu.has(t.toLowerCase()))return!0;return["string"==typeof e?e:null,hu(e,"message"),hu(e,"errMsg")].some(e=>null!==e&&pu.some(t=>t.test(e)))},fu=e=>{if(e instanceof Error)return e;const t=hu(e,"message")??hu(e,"errMsg")??"Storage quota exceeded";return Object.assign(new Error(t),{name:"QuotaExceededError",cause:e})},gu="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",yu=e=>Array.from(e,e=>e.toString(16).padStart(2,"0")).join(""),vu=e=>e===Mi.ALIPAY_MINIAPP||e===Mi.DINGTALK_MINIAPP,bu=e=>{const t=e.replace(/\s/g,"").replace(/-/g,"+").replace(/_/g,"/"),r=t.endsWith("==")?2:t.endsWith("=")?1:0,s=Math.max(0,Math.floor(3*t.length/4)-r),n=new Uint8Array(s);let i=0;for(let o=0;o<t.length;o+=4){const e=gu.indexOf(t[o]??""),r=gu.indexOf(t[o+1]??""),a=t[o+2]??"=",c=t[o+3]??"=",d="="===a?0:gu.indexOf(a),u="="===c?0:gu.indexOf(c);if(e<0||r<0||d<0||u<0)return new ArrayBuffer(0);const l=e<<18|r<<12|d<<6|u;for(const t of[16,8,0])i<s&&(n[i]=l>>t&255,i+=1)}return n.buffer},Iu=e=>"[object ArrayBuffer]"===Object.prototype.toString.call(e),wu=e=>{const t=new Uint8Array(e.byteLength);return t.set(e),t},Cu=(e,t=0)=>{if(t>3||"object"!=typeof e||null===e||Array.isArray(e))return e;if(Iu(e)||ArrayBuffer.isView(e))return e;const r=e;return"data"in r&&r.data!==e?Cu(r.data,t+1):e},Su=(e,t=0)=>{if(t>3||null==e)return;if(e instanceof Uint8Array)return wu(e);if(Iu(e))try{return wu(new Uint8Array(e))}catch{return}if(ArrayBuffer.isView(e))return wu(new Uint8Array(e.buffer,e.byteOffset,e.byteLength));if(Array.isArray(e))return e.every(e=>Number.isInteger(e)&&e>=0&&e<=255)?Uint8Array.from(e):void 0;if("object"!=typeof e)return;const r=e;if("data"in r&&r.data!==e){const e=Su(r.data,t+1);if(e)return e}if("buffer"in r&&r.buffer!==e){const e=Su(r.buffer,t+1);if(!e)return;const s="number"==typeof r.byteOffset&&Number.isInteger(r.byteOffset)?r.byteOffset:0,n="number"==typeof r.byteLength&&Number.isInteger(r.byteLength)?r.byteLength:e.byteLength-s;if(s<0||n<0||s+n>e.byteLength)return;return e.slice(s,s+n)}},Tu=(e,t)=>{if("string"==typeof e)return e;const r=e instanceof Uint8Array?e:new Uint8Array(e);if(vu(t)){const s=(e=>{let t="";for(let r=0;r<e.length;r+=3){const s=e[r]??0,n=e[r+1],i=e[r+2],o=s<<16|(n??0)<<8|(i??0);t+=gu[o>>18&63],t+=gu[o>>12&63],t+=void 0===n?"=":gu[o>>6&63],t+=void 0===i?"=":gu[63&o]}return t})(r);return Si("Mini program socket frame encoded as Base64",{operation:"platform.socket.frame.encode-base64",hostPlatform:t,sourceType:e instanceof Uint8Array?"uint8array":"arraybuffer",sourceBytes:r.byteLength,encodedCharacters:s.length,sourcePrefixHex:yu(r.subarray(0,8))}),s}const s=new ArrayBuffer(r.byteLength);return new Uint8Array(s).set(r),s},_u=(e,t)=>"string"!=typeof e&&vu(t),Ru=(e,t)=>{const r=Cu(e.data);if("string"==typeof r){if(!vu(t))return r;const s=bu(r),n=new Uint8Array(s);return Si("Mini program socket Base64 frame decoded",{operation:"platform.socket.frame.decode-base64",hostPlatform:t,sourceType:r===e.data?"string":"wrapped-string",sourceCharacters:r.length,decodedBytes:s.byteLength,decodedPrefixHex:yu(n.subarray(0,8)),decodedSuffixHex:yu(n.subarray(Math.max(0,n.length-8)))}),s}const s=Su(r);if(!s){const s="object"==typeof e.data&&null!==e.data?e.data:void 0;return void Si("Mini program socket frame shape is unsupported",{operation:"platform.socket.frame.unsupported-shape",hostPlatform:t,sourceType:typeof r,sourceTag:Object.prototype.toString.call(e.data),sourceKeys:s?Object.keys(s).slice(0,10):[],isBuffer:e.isBuffer})}if(!vu(t))return s.buffer;const n=(e=>{let t="";for(const s of e){if(9!==s&&10!==s&&13!==s&&32!==s&&!(s>=48&&s<=57||s>=65&&s<=90||s>=97&&s<=122||43===s||45===s||47===s||61===s||95===s))return;t+=String.fromCharCode(s)}const r=t.replace(/\s/g,"");if(0!==r.length&&r.length%4!=1&&/^[A-Za-z0-9+/_-]+={0,2}$/.test(r))return r})(s);if(!n)return Si("Mini program socket binary frame preserved",{operation:"platform.socket.frame.preserve-binary",hostPlatform:t,sourceType:Object.prototype.toString.call(r),sourceBytes:s.byteLength,sourcePrefixHex:yu(s.subarray(0,8))}),s.buffer;const i=bu(n),o=new Uint8Array(i);return Si("Mini program socket Base64 buffer decoded",{operation:"platform.socket.frame.decode-base64-buffer",hostPlatform:t,sourceType:Object.prototype.toString.call(r),sourceBytes:s.byteLength,decodedBytes:i.byteLength,decodedPrefixHex:yu(o.subarray(0,8)),decodedSuffixHex:yu(o.subarray(Math.max(0,o.length-8)))}),i},Au=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),Mu=(e,t)=>("object"==typeof e||"function"==typeof e)&&null!==e&&"function"==typeof e[t],Eu=e=>e instanceof Error?e.message:Au(e)&&"string"==typeof e.errMsg?e.errMsg:Au(e)&&"string"==typeof e.errorMessage?e.errorMessage:String(e),Uu=e=>e?{...e}:{},ku=e=>"number"==typeof e&&Number.isInteger(e)&&e>=100&&e<=599,Nu=e=>ku(e.statusCode)?e.statusCode:ku(e.status)?e.status:void 0,Ou=e=>{if(!Au(e))return{};const t={};return Object.entries(e).forEach(([e,r])=>{"string"==typeof r&&(t[e]=r)}),t},xu=e=>({...Ou(e.headers),...Ou(e.header)}),Lu=(e,t)=>{if(!e)return()=>{};if(e.aborted)return t(),()=>{};const r=()=>{t()};return e.addEventListener("abort",r,{once:!0}),()=>{e.removeEventListener("abort",r)}},Pu=e=>{try{e.close()}catch{}},Du=(e,t)=>new Promise((r,s)=>{let n=!1,i=()=>{};const o=(e,r,o)=>{n||(n=!0,i(),s(Fi(e,{code:Di,stage:Ui,retryable:o,details:{url:t.url,method:"GET",cause:Eu(r)}})))},a=e.downloadFile?.({url:t.url,header:Uu(t.headers),timeout:t.timeoutMs??15e3,success:s=>{const a=s.tempFilePath??s.apFilePath;a?((e,t)=>new Promise((r,s)=>{const n=e.getFileSystemManager?.();n?n.readFile({filePath:t,success:e=>{const t=Su(e.data);t?r(t.buffer):s(new Error("downloaded file response is not binary"))},fail:s}):s(new Error("getFileSystemManager returned no file system manager"))}))(e,a).then(e=>{n||(n=!0,i(),Si("Mini program binary response read from downloaded file",{operation:"platform.request.arraybuffer.download-file",url:t.url,filePathType:s.apFilePath?"apFilePath":"tempFilePath",status:s.statusCode??200,bytes:e.byteLength}),r({status:s.statusCode??200,headers:s.header??{},data:e}))}).catch(e=>{o("Mini program downloaded file read failed.",e,!1)}):o("Mini program download did not return a file path.",s,!1)},fail:e=>{o("Mini program file download failed.",e,!0)}});i=Lu(t.signal,()=>{a?.abort(),o("Mini program file download aborted.","abort",!1)})}),qu=e=>({request:t=>"arraybuffer"!==t.responseType||void 0!==t.method&&"GET"!==t.method||!(e=>"function"==typeof e.downloadFile&&"function"==typeof e.getFileSystemManager)(e)?new Promise((r,s)=>{let n=()=>{};const i=e.request({url:t.url,method:t.method??"GET",header:Uu(t.headers),data:t.body,timeout:t.timeoutMs??15e3,responseType:"arraybuffer"===t.responseType?"arraybuffer":"text",success:e=>{n();const i=Nu(e);void 0!==i?r({status:i,headers:xu(e),data:e.data}):s(Fi("Mini program request response status is invalid.",{code:Di,stage:Ui,retryable:!1,details:{url:t.url,method:t.method??"GET",statusCode:e.statusCode,status:e.status}}))},fail:e=>{n(),s(Fi("Mini program request failed.",{code:Di,stage:Ui,retryable:!0,details:{url:t.url,method:t.method??"GET",cause:Eu(e)}}))}});n=Lu(t.signal,()=>{i.abort(),s(Fi("Mini program request aborted.",{code:Di,stage:Ui,retryable:!1,details:{url:t.url,method:t.method??"GET",reason:"abort"}}))})}):Du(e,t)}),$u=(e,t)=>({connect:r=>new Promise((s,n)=>{let i,o,a=!1;const c=()=>{void 0!==o&&(clearTimeout(o),o=void 0)},d=(e,t,s)=>{a||(a=!0,c(),i&&Pu(i),n(Fi(t,{code:$i,stage:Ni,retryable:s,details:{url:r.url,cause:Eu(e)}})))},u=e=>{if(!(Mu(r=e,"send")&&Mu(r,"close")&&Mu(r,"onOpen")&&Mu(r,"onMessage")&&Mu(r,"onError")&&Mu(r,"onClose")))return void d(new Error("returnedType="+typeof e),"Mini program connectSocket did not return a SocketTask.",!1);var r;const n=e;if(a)return void Pu(n);i=n;const o=()=>{n.offOpen?.(u),n.offError?.(l)},u=()=>{a?Pu(n):(a=!0,c(),o(),s(((e,t,r=Bi)=>{const s=new Set,n=new Set,i=new Set,o=new Set;let a=r;return e.onOpen(()=>{a=ji,s.forEach(e=>{e()})}),e.onMessage(e=>{const r=Ru(e,t);void 0!==r&&n.forEach(e=>{e(r)})}),e.onError(e=>{i.forEach(t=>{t(e)})}),e.onClose(e=>{a=Ki,o.forEach(t=>{t({code:e.code,reason:e.reason})})}),{get readyState(){return a},send(r){if(a!==ji)throw Fi("Mini program socket is not open.",{code:$i,stage:Ni,retryable:!0,details:{readyState:a}});return new Promise((s,n)=>{e.send({data:Tu(r,t),..._u(r,t)?{isBuffer:!0}:{},success:s,fail:e=>{n(Fi("Mini program socket send failed.",{code:$i,stage:Ni,retryable:!0,details:{cause:Eu(e)}}))}})})},close(t,r){a=zi,e.close({code:t,reason:r})},onOpen:e=>(s.add(e),()=>{s.delete(e)}),onMessage:e=>(n.add(e),()=>{n.delete(e)}),onError:e=>(i.add(e),()=>{i.delete(e)}),onClose:e=>(o.add(e),()=>{o.delete(e)})}})(n,t,ji)))},l=e=>{o(),d(e.errMsg??"socket error","Mini program socket connection failed before open.",!0)};n.onOpen(u),n.onError(l)};let l;"number"==typeof r.timeoutMs&&r.timeoutMs>0&&(o=setTimeout(()=>{d("timeout","Mini program socket connection timed out.",!0)},r.timeoutMs));try{l=e.connectSocket({url:r.url,...t===Mi.ALIPAY_MINIAPP?{multiple:!0}:{},protocols:Array.isArray(r.protocols)?[...r.protocols]:"string"==typeof r.protocols?[r.protocols]:void 0,fail:e=>{d(e,"Mini program socket connect failed.",!0)}})}catch(h){return void d(h,"Mini program socket creation failed.",!0)}var p;"object"!=typeof(p=l)||null===p||"function"!=typeof p.then?u(l):Promise.resolve(l).then(e=>u(e),e=>d(e,"Mini program socket connect failed.",!0))})}),Gu=e=>({upload:t=>new Promise((r,s)=>{const n=(e=>{if("miniapp-path"!==e.sourceType||!e.path)throw Fi("Mini program upload only supports miniapp-path source.",{code:qi,stage:ki,retryable:!1,details:{sourceType:e.sourceType}});return e})(t.source);let i=()=>{};const o=e.uploadFile({url:t.url,filePath:n.path,name:"file",header:Uu(t.headers),formData:t.fields,timeout:t.timeoutMs??3e4,success:e=>{i();const o=Nu(e);void 0!==o?r({status:o,body:e.data}):s(Fi("Mini program upload response status is invalid.",{code:qi,stage:ki,retryable:!1,details:{url:t.url,path:n.path,statusCode:e.statusCode,status:e.status}}))},fail:e=>{i(),s(Fi("Mini program upload failed.",{code:qi,stage:ki,retryable:!0,details:{url:t.url,path:n.path,cause:Eu(e)}}))}});o.onProgressUpdate?.(e=>{t.onProgress?.({loaded:e.totalBytesSent,total:e.totalBytesExpectedToSend,percent:e.progress})}),i=Lu(t.signal,()=>{o.abort(),s(Fi("Mini program upload aborted.",{code:qi,stage:ki,retryable:!1,details:{url:t.url,path:n.path,reason:"abort"}}))})})}),Fu=(e,t)=>{const r=(e=>e===Mi.ALIPAY_MINIAPP||e===Mi.DINGTALK_MINIAPP)(t);return{async getItem(t){if(Mu(e,"getStorageSync"))try{const s=(e=>Au(e)&&"data"in e?e.data:e)(e.getStorageSync(r?{key:t}:t));return"string"==typeof s&&s.length>0?s:null}catch{return null}return Mu(e,"getStorage")?new Promise(r=>{e.getStorage({key:t,success:e=>{r("string"==typeof e.data&&e.data.length>0?e.data:null)},fail:()=>{r(null)}})}):null},async setItem(t,s){if(Mu(e,"setStorageSync"))try{r?e.setStorageSync({key:t,data:s}):e.setStorageSync(t,s)}catch(n){if(mu(n))throw fu(n)}else if(Mu(e,"setStorage"))return new Promise((r,i)=>{try{e.setStorage({key:t,data:s,success:r,fail:e=>{mu(e)?i(fu(e)):r()}})}catch(n){if(mu(n))return void i(fu(n));r()}})},async removeItem(t){if(Mu(e,"removeStorageSync"))try{e.removeStorageSync(r?{key:t}:t)}catch{}else if(Mu(e,"removeStorage"))return new Promise(r=>{try{e.removeStorage({key:t,success:r,fail:()=>{r()}})}catch{r()}})}}},Bu=(e,t)=>({getPlatform:()=>t,getNetworkType:()=>Mu(e,"getNetworkType")?new Promise(t=>{e.getNetworkType?.({success:e=>{t(e.networkType??"unknown")},fail:()=>{t("unknown")}})}):Promise.resolve("unknown"),onNetworkChange(t){const r=e=>{t(e.isConnected)};return Mu(e,"onNetworkStatusChange")&&e.onNetworkStatusChange(r),Mu(e,"getNetworkType")&&e.getNetworkType({success:e=>{t("none"!==e.networkType)}}),()=>{Mu(e,"offNetworkStatusChange")&&e.offNetworkStatusChange(r)}},onAppVisibilityChange(t){const r=()=>{t(!0)},s=()=>{t(!1)};return Mu(e,"onAppShow")&&e.onAppShow(r),Mu(e,"onAppHide")&&e.onAppHide(s),t(!0),()=>{Mu(e,"offAppShow")&&e.offAppShow(r),Mu(e,"offAppHide")&&e.offAppHide(s)}}}),ju=(e,t=Mi.WECHAT_MINIAPP,r=t)=>{const s=(e=>{if(Mu(e,"request")&&Mu(e,"connectSocket")&&Mu(e,"uploadFile"))return e;throw Fi("Mini program platform capability is missing.",{code:Pi,stage:Ei,retryable:!1,details:{capability:"request/connectSocket/uploadFile"}})})(e),n="function"==typeof s.getImageInfo?uu(s):void 0;return{request:qu(s),socket:$u(s,r),upload:Gu(s),runtime:Bu(s,t),storage:Fu(s,r),imageProcessor:n}},zu=[Mi.WEB,Mi.ELECTRON_RENDERER,Mi.REACT_NATIVE],Ku=(e,t)=>{if("object"!=typeof e&&"function"!=typeof e||null===e)return!1;return"function"==typeof e[t]},Hu=e=>zu.includes(e),Vu=(e,t)=>e!==Mi.UNIAPP?Hu(e):!io(t)&&!Ju(t)&&to(t),Wu=e=>Ku(e,"getImageInfo")&&Ku(e,"getFileSystemManager"),Ju=e=>!io(e)&&"app"===(e=>{try{const t=e.uni?.getSystemInfoSync?.(),r=t?.uniPlatform;return"string"==typeof r?r:void 0}catch{return}})(e),Zu=(e,t)=>{if(Hu(e)&&e!==Mi.REACT_NATIVE)return ru();if(uo(e)&&Wu(t))return uu(t);if(e===Mi.UNIAPP&&"object"==typeof t&&null!==t){const e=t;if(to(e))return ru();if(Wu(e.uni))return uu(e.uni);if(Wu(e.wx))return uu(e.wx)}},Qu=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())}},Yu=(e,t,r,s)=>{if(e===Mi.UNIAPP&&Ju(r)&&void 0!==r.uni&&Zi(r.uni))return{...ju(r.uni,e,t),proto:Rd()};if(((e,t)=>!Vu(e,t)&&uo(e))(e,r)&&Zi(s))return{...ju(s,e,t),proto:Rd()};const n=r.XMLHttpRequest,i=Vu(e,r),o=i?Md({fetchImpl:r.fetch}):void 0,a=i?Ld({webSocketCtor:r.WebSocket}):void 0,c=e===Mi.REACT_NATIVE?Bd({fetchImpl:r.fetch,formDataCtor:r.FormData}):i?Gd({xhrFactory:"function"==typeof n?()=>new n:void 0,fetchImpl:r.fetch}):void 0,d=i&&e!==Mi.REACT_NATIVE?(u={platform:e,windowRef:r.window,documentRef:r.document,navigatorRef:r.navigator},{getPlatform:()=>u.platform,getNetworkType:()=>!1===u.navigatorRef?.onLine?Promise.resolve("none"):Promise.resolve(u.navigatorRef?.connection?.type??u.navigatorRef?.connection?.effectiveType??"unknown"),onNetworkChange(e){const t=u.windowRef;if(!t)return()=>{};const r=()=>{e(!0)},s=()=>{e(!1)};return t.addEventListener("online",r),t.addEventListener("offline",s),"boolean"==typeof u.navigatorRef?.onLine&&e(u.navigatorRef.onLine),()=>{t.removeEventListener("online",r),t.removeEventListener("offline",s)}},onAppVisibilityChange(e){const t=u.documentRef;if(!t)return()=>{};const r=()=>{e((e=>"hidden"!==e?.visibilityState)(t))};return t.addEventListener("visibilitychange",r),r(),()=>{t.removeEventListener("visibilitychange",r)}}}):(e=>({getPlatform:()=>e,onNetworkChange:e=>()=>{},onAppVisibilityChange:e=>()=>{}}))(e);var u;return{request:o,upload:c,socket:a,runtime:d,proto:Rd(),storage:Qu(r),imageProcessor:i&&e!==Mi.REACT_NATIVE?ru():Zu(e,s)}},Xu=(e,t)=>{if(void 0!==e)return e;throw Fi("Platform adapter initialization failed.",{code:Li,stage:Ei,retryable:!1,details:{capability:t}})},el=e=>{const t=Vi(e?.runtimeInput),r=co(t,e?.prefer),s=r.platform,n=Yu(s,r.hostPlatform,t,r.global),i=((e,t)=>e?"function"==typeof e?e(t):e:{})(e?.overrides,n),o={...n,...i},a=(e=>({request:void 0!==e.request,upload:void 0!==e.upload,socket:void 0!==e.socket,runtime:void 0!==e.runtime,proto:void 0!==e.proto,storage:void 0!==e.storage,imageProcessor:void 0!==e.imageProcessor}))(o);po(a);return{platform:s,platformId:s,capability:a,request:Xu(o.request,"request"),upload:Xu(o.upload,"upload"),socket:Xu(o.socket,"socket"),runtime:Xu(o.runtime,"runtime"),proto:Xu(o.proto,"proto"),storage:Xu(o.storage,"storage"),imageProcessor:o.imageProcessor}},tl=e=>{if(e instanceof rs)return e;if((e=>"object"==typeof e&&null!==e)(e)){const t=e.details;if(e.code===Pi){const r=t?.capability;if(e.stage===xi&&"string"==typeof r&&r.includes("FileSystem")){const r=e instanceof Error?e.message:"Upload failed";return new rs(r,{code:qr,details:t})}return new rs("Upload capability is missing for current platform",{code:Lr,details:t})}if(e.stage===ki)return(e=>{const t=e?.reason;return!("string"!=typeof t||!t.toLowerCase().includes("abort"))})(t)?new rs("Upload canceled",{code:Gr,details:t}):(e=>{const t=e?.reason;return!("string"!=typeof t||!t.toLowerCase().includes("timeout"))})(t)?new rs("Upload timeout",{code:$r,details:t}):new rs("Upload failed",{code:qr,details:t})}const t=e instanceof Error?e.message:"Upload failed";return new rs(t,{code:qr,details:{cause:e}})},rl={maxAttempts:10,initialDelay:1e3,maxDelay:6e4,backoffMultiplier:2,randomSource:Math.random};class sl{constructor(e={}){this.attemptCount=0,this.config={...rl,...e}}getRetryDelay(){const e=Math.max(this.attemptCount-1,0),t=this.config.initialDelay*Math.pow(this.config.backoffMultiplier,e),r=Math.min(t,this.config.maxDelay);return r/2+r/2*Math.min(1,Math.max(0,this.config.randomSource()))}recordAttempt(){this.attemptCount++}reset(){this.attemptCount=0}shouldRetry(){return this.attemptCount<this.config.maxAttempts}getAttemptCount(){return this.attemptCount}async waitForRetry(){const e=this.getRetryDelay();return Ci(`Waiting ${e}ms before retry (attempt ${this.attemptCount})`),new Promise(t=>setTimeout(t,e))}}const nl={interval:3e4,timeout:6e4},il="function"==typeof TextDecoder?new TextDecoder:null;class ol{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(!ol.isRecord(r))return;"pong"===ol.readString(r.type)&&(this.markAlive(),Ci("Pong received"))},this.config={...nl,...e}}start(e,t,r){this.heartbeatTimer&&this.stop(),this.attachWebSocket(e),this.onTimeoutCallback=t||null,this.sendPing=r??null,this.lastPongTime=Date.now(),this.heartbeatTimer=setInterval(()=>{this.sendPingInternal()},this.config.interval),Ci("Heartbeat started",{interval:this.config.interval})}stop(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null),this.timeoutTimer&&(clearTimeout(this.timeoutTimer),this.timeoutTimer=null),this.messageDisposer?.(),this.messageDisposer=null,this.websocket=null,this.sendPing=null,this.resolveProbe(!1),Ci("Heartbeat stopped")}sendPingInternal(){if(this.websocket&&this.websocket.readyState===ji)try{if(this.sendPing)this.sendPing();else{const e=JSON.stringify({type:"ping",timestamp:Date.now()});Promise.resolve(this.websocket.send(e)).catch(e=>{Ti("Failed to send ping:",e),this.resolveProbe(!1)})}this.resetTimeout(),Ci("Ping sent")}catch(e){Ti("Failed to send ping:",e),this.resolveProbe(!1)}else this.resolveProbe(!1)}extractMessageText(e){if("string"==typeof e)return e;if(e instanceof ArrayBuffer){const t=new Uint8Array(e);return(e=>{for(const t of e)if(32!==t&&9!==t&&10!==t&&13!==t)return 123===t;return!1})(t)?il?.decode(t)??Ri(t):null}return null}parseJson(e){try{return JSON.parse(e)}catch{return null}}static isRecord(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}static readString(e){return"string"==typeof e?e:void 0}resetTimeout(){this.timeoutTimer&&clearTimeout(this.timeoutTimer),this.timeoutTimer=setTimeout(()=>{Si("Heartbeat timeout"),this.onTimeoutCallback&&this.onTimeoutCallback()},this.config.timeout)}markAlive(){this.lastPongTime=Date.now(),this.resetTimeout(),this.resolveProbe(!0)}getLastPongTime(){return this.lastPongTime}async probeOnce(e,t){try{if(e.readyState!==ji)return!1;this.attachWebSocket(e);const r=t??this.config.timeout;return await new Promise(e=>{const t=setTimeout(()=>{this.removeProbeResolver(e),e(!1)},r);this.probeResolvers.push(r=>{clearTimeout(t),e(r)}),this.sendPingInternal()})}catch(r){return Si("Heartbeat probe failed",r),!1}}attachWebSocket(e){this.websocket!==e&&(this.messageDisposer?.(),this.websocket=e,this.messageDisposer=e.onMessage(e=>{this.handlePong(e)}))}resolveProbe(e){if(0===this.probeResolvers.length)return;const t=[...this.probeResolvers];this.probeResolvers=[];for(const r of t)r(e)}removeProbeResolver(e){this.probeResolvers=this.probeResolvers.filter(t=>t!==e)}}let al=null;function cl(){return al||(al=_d()),al}const dl="websdk2:device-info",ul="webim",ll="web",pl=e=>{const t=Date.now(),r=e.deviceId,s=e.customOSPlatform,n=void 0!==s?e.customDeviceName:void 0,i=Vi().localStorage,o=()=>{if(!i)return null;try{const t=i.getItem(dl);if(!t)return null;const r=JSON.parse(t);if("object"==typeof(e=r)&&null!==e&&!Array.isArray(e)&&"string"==typeof r.deviceId&&"string"==typeof r.deviceName&&"string"==typeof r.deviceUuid)return{deviceId:r.deviceId,deviceName:r.deviceName,deviceUuid:r.deviceUuid}}catch{return null}var e;return null},a=e=>{if(i)try{i.setItem(dl,JSON.stringify(e))}catch{}},c=e=>void 0===s?e:{deviceId:`custom${s}_${e.deviceUuid}`,deviceName:n??r,deviceUuid:e.deviceUuid};if(e.useFixedDeviceId){const e=o();if(e)return c(e);if(r===ul){const e=`${ll}_${t}`,s=c({deviceId:`${r}_${e}`,deviceName:r,deviceUuid:e});return a(s),s}if(void 0!==s){const e=c({deviceId:`webim_${ll}_${r}`,deviceName:r,deviceUuid:`${ll}_${t}`});return a(e),e}const n={deviceId:`webim_${ll}_${r}`,deviceName:`webim_${ll}_${r}`,deviceUuid:`webim_${ll}_${r}`};return a(n),n}if(r===ul){const e=`random_${ll}_${t}`;return c({deviceId:`${r}_${e}`,deviceName:r,deviceUuid:e})}if(void 0!==s){return c({deviceId:`webim_${ll}_${r}`,deviceName:r,deviceUuid:`random_${ll}_${t}`})}return{deviceId:`webim_${ll}_${r}`,deviceName:`webim_${ll}_${r}`,deviceUuid:`webim_${ll}_${r}`}},hl=e=>({appKey:e.appKey,name:e.name,domain:e.domain,clientResource:e.clientResource}),ml=e=>{if("string"==typeof e)return e;if("number"==typeof e)return Number.isFinite(e)?`${e}`:"";if("bigint"==typeof e)return e.toString();if(e&&"object"==typeof e&&"low"in e&&"high"in e&&"number"==typeof e.low&&"number"==typeof e.high){const t=e;return new mo(t.low,t.high,Boolean(t.unsigned)).toString()}return e&&"function"==typeof e.toString?e.toString():""},fl=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:pn,varintValue:s}):t.push({key:r,type:gn,doubleValue:s});else t.push({key:r,type:ln,varintValue:s?1:0});return t},gl=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!==pn&&s!==hn&&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},yl=()=>`${Date.now()}${Math.floor(1e6*Math.random()).toString().padStart(6,"0")}`,vl="X-Request-Id",bl=new Set(["mute"]),Il={name:"name",title:"name",description:"description",max_users:"maxMembers",custom:"ext"},wl=e=>{if("string"!=typeof e)return;const t=e.trim();return t.length>0?t:void 0},Cl=e=>{if(!e)return null;try{const t=JSON.parse(e);return!t||"object"!=typeof t||Array.isArray(t)?null:t}catch{return null}},Sl=(e,t)=>{const r=e?.map(e=>wl(e)).filter(e=>"string"==typeof e)??[];return r.length>0?r:t?[t]:[]},Tl=(e,t)=>{const r=Number(e);if(!Number.isNaN(r)&&Number.isFinite(r)&&r>0)return r;const s=Cl(t);if(!s)return;const n=s.muteExpire??s.mute_expire??s.expire??s.expired??s.expireAt??s.expiredAt,i=Number(n);return Number.isFinite(i)&&i>0?i:void 0},_l=e=>{const t=Cl(e);if(!t)return;const r={};for(const[s,n]of Object.entries(t)){const e=Il[s];if(!e)continue;let t=n;if(bl.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},Rl=e=>{const t=Cl(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:wl(t.operator)??wl(t.username)}},Al=(e,t)=>({eventName:e,payload:t}),Ml=e=>{const t={chatRoomId:e.chatRoomId,chatRoomName:e.chatRoomName},r=wl(e.from?.name),s=(n=e.to,wl(n?.[0]?.name));var n;switch(e.operation){case 1:return Al($e,t);case 10:return Al(Be,{...t,reason:e.reason,reasonCode:Number.isFinite(Number(e.reason))?Number(e.reason):0,participantId:s??r});case 17:return Al(Ge,{...t,memberIds:Sl(e.members,r),ext:e.ext??e.eventExt});case 18:return Al(Fe,{...t,memberIds:Sl(e.members,r)});case 20:return Al(Ze,{...t,oldOwnerId:r,newOwnerId:s});case 21:return Al(We,{...t,adminId:s??r});case 22:return Al(Je,{...t,adminId:s??r});case 23:{const r=(e=>{const t=Cl(e),r=t?.user_mute_time;if(!r||"object"!=typeof r||Array.isArray(r))return null;const s={};for(const[n,i]of Object.entries(r)){const e=Number(i);n&&Number.isFinite(e)&&(s[n]=e)}return Object.keys(s).length>0?s:null})(e.ext??e.eventExt),n=r?Object.keys(r):Sl(e.members,s),i=46388736e5;return Al(je,{...t,userIds:n,muteMembers:r??Object.fromEntries(n.map(e=>[e,i])),muteExpire:Tl(e.reason,e.eventExt)??i})}case 24:return Al(ze,{...t,userIds:Sl(e.members,s)});case 25:return Al(Qe,{...t,announcement:e.reason??""});case 26:return Al(Qe,{...t,announcement:""});case 29:return Al(Ke,{...t,userIds:Sl(e.members,s)});case 30:return Al(He,{...t,userIds:Sl(e.members,s)});case 31:return Al(Ve,{...t,isMuted:!0});case 32:return Al(Ve,{...t,isMuted:!1});case 14:return Al(Ye,{...t,shouldFetchChatRoomDetail:!0,chatRoomPatch:_l(e.eventExt)});case 43:{const s=Rl(e.eventExt);return Al(Xe,{...t,attributes:s.attributes,from:s.from??r})}case 44:{const s=Rl(e.eventExt);return Al(et,{...t,keyList:s.keyList,from:s.from??r})}default:return null}},El=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),Ul=(e,t)=>{if(!e)return t;try{return JSON.parse(e)}catch{return t}},kl=["nickname","avatarUrl","mail","phone","gender","sign","birth","ext"],Nl=e=>({userId:e.userId,nickname:e.nickname,avatarUrl:e.avatarUrl,sign:e.sign,ext:e.ext}),Ol=e=>({userId:e}),xl=(e,t,r)=>{const s={userId:r};for(const n of kl){const r=t?.[n]??e?.[n];void 0!==r&&(s[n]=r)}return s},Ll=async(e,t)=>{const r=(e=>{const t=[],r=new Set;for(const s of e){const e=s.trim();e&&!r.has(e)&&(r.add(e),t.push(e))}return t})(e),s=new Map;if(0===r.length)return s;const n=t.cacheManager?.getUserInfoSummaries(r,!1)??[];for(const o of n)s.set(o.userId,Nl(o));const i=r.filter(e=>!s.has(e));if(i.length>0&&t.fetchUserInfos){const e=await t.fetchUserInfos({userIds:i});for(const t of e)s.set(t.userId,t)}for(const o of r)s.has(o)||s.set(o,Ol(o));return s},Pl=e=>El(e)?e:null,Dl=e=>{if("string"==typeof e)return e},ql=e=>{const t=Dl(e)?.trim();return t||void 0},$l=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}},Gl=e=>{if("boolean"==typeof e)return e;if("string"==typeof e){if("true"===e)return!0;if("false"===e)return!1}},Fl=e=>{const t=Pl(e);return t&&Array.isArray(t.data)?t.data:t&&Array.isArray(t.entities)?t.entities:Array.isArray(e)?e:[]},Bl=e=>{const t=Pl(e);return t?Pl(t.data)?t.data:t:null},jl=(e,t)=>{const r=Pl(e),s=r&&Pl(r.params),n=s?.[t];if(Array.isArray(n)&&0!==n.length)return $l(n[0])},zl=(e,t)=>{const r=(e=>{const t=Pl(e);return t?$l(t.count):void 0})(e);if(void 0!==r&&void 0!==t)return r>=t},Kl=e=>ql(e.groupId)??ql(e.groupid)??ql(e.id)??"",Hl=e=>Dl(e.name)??Dl(e.groupname)??Dl(e.groupName)??"",Vl=e=>{const t=Fl(e),r=Pl(t[0])??Bl(e)??{},s=(e=>{const t=Pl(e);if(!t)return null;const r=Kl(t);return r?{groupId:r,name:Hl(t),description:Dl(t.description),memberCount:$l(t.memberCount)??$l(t.affiliations_count),public:Gl(t.public),joinApprovalRequired:Gl(t.joinApprovalRequired)??Gl(t.approval)??Gl(t.membersonly)??Gl(t.members_only),allowInvites:Gl(t.allowInvites)??Gl(t.allowinvites)??Gl(t.allow_user_invites),maxMembers:$l(t.maxMembers)??$l(t.maxusers),role:ql(t.role)??ql(t.permission),disabled:Gl(t.disabled)}:null})(r)??{groupId:Kl(r),name:Hl(r)},n=ql(r.owner)??ql(r.admin)??ql(r.member),i=(Array.isArray(r.affiliations)?r.affiliations:[]).map(e=>Pl(e)).filter(e=>null!==e).map(e=>$l(e.joined_time)).find(e=>void 0!==e);return{...s,owner:n?Ol(n):void 0,inviteNeedConfirm:Gl(r.inviteNeedConfirm)??Gl(r.invite_need_confirm),muteAllMembers:Gl(r.mute),ext:Dl(r.ext)??Dl(r.custom),createdAt:$l(r.createdAt)??$l(r.created),joinedAt:i,avatarUrl:Dl(r.avatar),messageBlocked:Gl(r.messageBlocked)??Gl(r.isMessageBlocked)??Gl(r.shieldgroup)}},Wl=e=>Ol(e),Jl=e=>Fl(e).map(e=>ql(e)).filter(e=>Boolean(e)).map(e=>Wl(e)),Zl=e=>{const t=Pl(e);if(!t)return null;const r=ql(t.fileId)??ql(t.file_id);if(!r)return null;const s=Dl(t.fileName)??Dl(t.file_name)??r,n=ql(t.fileOwner)??ql(t.file_owner);return{fileId:r,fileName:s,fileOwner:n?Wl(n):void 0,fileSize:$l(t.fileSize)??$l(t.file_size),createdAt:$l(t.createdAt)??$l(t.created)}},Ql=new Set(["public","members_only","allow_user_invites","invite_need_confirm"]),Yl={name:"name",title:"name",description:"description",public:"public",members_only:"joinApprovalRequired",allow_user_invites:"allowInvites",max_users:"maxMembers",invite_need_confirm:"inviteNeedConfirm",custom:"ext"},Xl=e=>{if("string"!=typeof e)return;const t=e.trim();return t.length>0?t:void 0},ep=e=>{if(!e)return null;try{const t=JSON.parse(e);return!t||"object"!=typeof t||Array.isArray(t)?null:t}catch{return null}},tp=(e,t)=>{const r=e?.map(e=>Xl(e)).filter(e=>"string"==typeof e)??[];return r.length>0?r:t?[t]:[]},rp=(e,t)=>{const r=Number(e);if(!Number.isNaN(r)&&Number.isFinite(r)&&r>0)return r;const s=ep(t);if(!s)return;const n=s.muteExpire??s.mute_expire??s.expire??s.expired??s.expireAt??s.expiredAt,i=Number(n);return Number.isFinite(i)&&i>0?i:void 0},sp=e=>{const t=ep(e);if(!t)return;const r={};for(const[s,n]of Object.entries(t)){const e=Yl[s];if(!e)continue;let t=n;if(Ql.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},np=(e,t)=>{const r=ep(t)??ep(e);return Zl(r??void 0)??void 0},ip=(e,t)=>{const r=ep(t)??ep(e);return Xl(r?.fileId)??Xl(r?.file_id)??Xl(e)??""},op=(e,t)=>({eventName:e,payload:t}),ap=e=>{const t={groupId:e.groupId,groupName:e.groupName},r=Xl(e.from?.name),s=(n=e.to,Xl(n?.[0]?.name));var n;switch(e.operation){case 4:return op(Y,{...t,applicantId:r,reason:e.reason});case 5:return op(X,{...t,accepterId:r});case 6:return op(ee,{...t,declinerId:r,applicantId:s,reason:e.reason});case 7:return op(Q,{...t,inviterId:r,reason:e.reason});case 8:return op(te,{...t,inviteeId:r,reason:e.reason});case 9:return op(re,{...t,inviteeId:r,reason:e.reason});case 10:return op(se,t);case 1:return op(ne,t);case 19:return op(ie,{...t,inviterId:r,reason:e.reason});case 23:{const r=(e=>{const t=ep(e),r=t?.user_mute_time;if(!r||"object"!=typeof r||Array.isArray(r))return null;const s={};for(const[n,i]of Object.entries(r)){const e=Xl(n),t=Number(i);e&&Number.isFinite(t)&&t>0&&(s[e]=t)}return Object.keys(s).length>0?s:null})(e.ext),n=r?Object.keys(r):tp(e.members,s);return op(oe,{...t,userIds:n,muteExpire:n.map(e=>r?.[e]).find(e=>void 0!==e)??rp(e.reason,e.eventExt)})}case 24:return op(ae,{...t,userIds:tp(e.members,s)});case 29:return op(ce,{...t,userIds:tp(e.members,s)});case 30:return op(de,{...t,userIds:tp(e.members,s)});case 31:return op(ue,{...t,isMuted:!0});case 32:return op(ue,{...t,isMuted:!1});case 21:return op(le,{...t,administratorId:s??r});case 22:return op(pe,{...t,administratorId:s??r});case 20:return op(he,{...t,oldOwnerId:r,newOwnerId:s});case 17:{const s=tp(e.members,r);return op(me,{...t,memberIds:s})}case 18:{const s=tp(e.members,r);return op(fe,{...t,memberIds:s})}case 25:return op(ge,{...t,announcement:e.reason??""});case 26:return op(ge,{...t,announcement:""});case 27:return op(ye,{...t,sharedFile:np(e.reason,e.eventExt)});case 28:return op(ve,{...t,fileId:ip(e.reason,e.eventExt)});case 14:return op(be,{...t,shouldFetchGroupDetail:!0,groupPatch:sp(e.eventExt)});case 41:return op(Ie,{...t,shouldFetchGroupDetail:!0,isDisabled:!0});case 42:return op(Ie,{...t,shouldFetchGroupDetail:!0,isDisabled:!1});case 45:{const s=(e=>{const t=ep(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:Xl(t.username),attribute:s}})(e.eventExt);return op(we,{...t,userId:s.userId,attribute:s.attribute,from:r,source:e.source??"direct"})}default:return null}},cp=new WeakMap,dp=(e,t)=>{cp.set(e,t)},up=e=>cp.get(e)??null,lp=(e,t)=>{const r=up(e);r&&dp(t,r)},pp=new WeakMap,hp=e=>pp.get(e),mp=new WeakMap,fp=e=>mp.get(e),gp=(e,t)=>{const r=mp.get(e);r&&mp.set(t,r)},yp="singleChat",vp="groupChat",bp=e=>{if("string"!=typeof e)return;const t=e.trim();return t.length>0?t:void 0},Ip=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}},wp=e=>{if(!Array.isArray(e))return;const t=e.map(e=>bp(e)).filter(e=>"string"==typeof e);return t.length>0?t:void 0},Cp=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),Sp=(...e)=>{for(const t of e){const e=bp(t);if(e)return e}},Tp=(e,t)=>Boolean(e&&t&&e===t),_p=(e,t,r)=>Boolean(e&&e===r.userId&&t&&r.clientResource&&t!==r.clientResource),Rp=(e,t,r)=>{const s=wp(e);if(s&&s.length>0)return s;const n=(t??[]).map(e=>bp(e.name)).filter(e=>"string"==typeof e);if(n.length>0)return n;const i=bp(r?.name);return i?[i]:[]},Ap=e=>{const t=Ip(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}}},Mp=(e,t)=>{const r=Sp(e.to?.[0]?.clientResource);if(1!==e.to?.length||bp(e.to[0]?.name)!==t.userId||!_p(t.userId,r,t))return null;const s=(n=e.from,bp(n?.name)??"");var n;if(!s)return Si("Discarded MultiDevice contact event without target user",{operation:e.operation}),null;const i=(e=>{switch(e){case 3:return"CONTACT_REMOVE";case 4:case 8:return"CONTACT_ACCEPT";case 5:case 9:return"CONTACT_DECLINE";case 6:return"CONTACT_BAN";case 7:return"CONTACT_ALLOW";default:return Si("Discarded unknown MultiDevice contact operation",{operation:e}),"UNKNOWN"}})(e.operation);return"UNKNOWN"===i?null:{category:"contact",operation:i,targetUserId:s,rosterVersion:e.rosterVersion,ext:e.ext,deviceId:r,timestamp:e.timestamp,raw:e.raw}},Ep=(e,t)=>{if(!e.groupId)return Si("Discarded MultiDevice group event without groupId",{operation:e.operation}),null;const r=Sp(e.from?.clientResource,e.raw?.resource,e.raw?.clientResource);if(!_p(bp(e.from?.name),r,t))return null;const s=(e=>{switch(e){case 0:return"GROUP_CREATE";case 1:return"GROUP_DESTROY";case 2:return"GROUP_JOIN";case 3:return"GROUP_LEAVE";case 4:return"GROUP_APPLY";case 5:return"GROUP_APPLY_ACCEPT";case 6:return"GROUP_APPLY_DECLINE";case 7:return"GROUP_INVITE";case 8:return"GROUP_INVITE_ACCEPT";case 9:return"GROUP_INVITE_DECLINE";case 10:return"GROUP_KICK";case 12:return"GROUP_BAN";case 13:return"GROUP_ALLOW";case 15:return"GROUP_BLOCK";case 16:return"GROUP_UNBLOCK";case 20:return"GROUP_ASSIGN_OWNER";case 21:return"GROUP_ADD_ADMIN";case 22:return"GROUP_REMOVE_ADMIN";case 23:return"GROUP_ADD_MUTE";case 24:return"GROUP_REMOVE_MUTE";case 29:return"GROUP_ADD_USER_WHITE_LIST";case 30:return"GROUP_REMOVE_USER_WHITE_LIST";case 31:return"GROUP_ALL_BAN";case 32:return"GROUP_REMOVE_ALL_BAN";case 45:return"GROUP_MEMBER_METADATA_CHANGED";case 14:return"GROUP_UPDATED";default:return Si("Discarded unknown MultiDevice group operation",{operation:e}),"UNKNOWN"}})(e.operation);if("UNKNOWN"===s)return null;const n=Rp(e.members,e.to,e.from);return{category:"group",operation:s,groupId:e.groupId,userIds:n.length>0?n:void 0,operatorId:bp(e.from?.name),groupName:e.groupName,deviceId:r,timestamp:e.timestamp,raw:e.raw}},Up=(e,t)=>{if(!e.threadId)return Si("Discarded MultiDevice thread event without threadId",{operation:e.operation}),null;const r=Sp(e.from?.clientResource,e.raw?.resource,e.raw?.clientResource);if(!_p(bp(e.from?.name),r,t))return null;const s=(e=>{switch(e){case 33:return"THREAD_CREATE";case 35:return"THREAD_JOIN";case 38:return"THREAD_UPDATE";case 36:return"THREAD_LEAVE";case 34:return"THREAD_DESTROY";case 37:return"THREAD_KICK";default:return Si("Discarded unknown MultiDevice thread operation",{operation:e}),"UNKNOWN"}})(e.operation);if("UNKNOWN"===s)return null;const n=Rp(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:bp(e.from?.name),threadName:e.threadName,deviceId:r,timestamp:e.timestamp,raw:e.raw}},kp=(e,t)=>{if("pin"===e.operation||"pin_delete"===e.operation)return null;const r=Sp(e.res,e.raw?.resource,e.raw?.clientResource);if(Tp(r,t.clientResource))return Ci("Discarded same-device MultiDevice conversation echo",{operation:e.operation,conversationId:e.id}),null;const s="chat"===(n=e.type)||"singleChat"===n?yp:vp;var n;const i=bp(e.id)??(s===yp?bp(e.from):void 0);if(!i)return Si("Discarded MultiDevice conversation event without conversationId",{operation:e.operation}),null;const o=(e=>{switch(e){case"del":return"CONVERSATION_DELETED";case"top":return"CONVERSATION_PINNED";case"not_top":return"CONVERSATION_UNPINNED";case"mark":case"mark_delete":return"CONVERSATION_MARK";case"setSilentModeForConversation":case"removeSilentModeForConversation":return"CONVERSATION_MUTE_INFO_CHANGED";default:return Si("Discarded unknown MultiDevice conversation operation",{operation:e}),"UNKNOWN"}})(e.operation);return"UNKNOWN"===o?null:{category:"conversation",operation:o,conversationId:i,conversationType:s,mark:"mark"===e.operation||"mark_delete"===e.operation?Ap(e.ext):void 0,operatorId:bp(e.from),deviceId:r,timestamp:Ip(e.ts),raw:e.raw}},Np=(e,t)=>{const r=Sp(e.resource,e.raw?.resource,e.raw?.clientResource);if(Tp(r,t.clientResource))return Ci("Discarded same-device MultiDevice roaming delete echo",{conversationId:e.to}),null;const s=bp(e.to);if(!s)return Si("Discarded MultiDevice roaming delete event without conversationId",{}),null;const n=bp(e.lastMsgId),i=wp(e.msgIdList)??(n?[n]:void 0),o=Ip(e.deleteTime);if(!i&&void 0===o)return Si("Discarded MultiDevice roaming delete event without messageIds or beforeTimestamp",{conversationId:s}),null;const a=(e=>e&&"deleteRoaming"!==e&&"MESSAGE_REMOVED"!==e?(Si("Discarded unknown MultiDevice message-removed operation",{operation:e}),"UNKNOWN"):"MESSAGE_REMOVED")(e.messageRoamingType);return"UNKNOWN"===a?null:{category:"messageRemoved",operation:a,conversationId:s,conversationType:"groupchat"===e.chatType||"groupChat"===e.chatType?vp:yp,messageIds:i,beforeTimestamp:o,deviceId:r,raw:e.raw}},Op=e=>{switch(e){case"contact":return"onMultiDeviceContact";case"group":return"onMultiDeviceGroup";case"thread":return"onMultiDeviceThread";case"conversation":return"onMultiDeviceConversation";case"messageRemoved":return"onMultiDeviceMessageRemoved"}},xp=2147483647,Lp=e=>{const t=Number(e);if(!Number.isFinite(t)||t<=0)return;const r=Math.floor(t);return r<=0||r>xp?void 0:r},Pp=e=>{if("number"!=typeof e||!Number.isFinite(e)||e<=0)return;const t=e>xp?Math.floor(e/1e3):Math.floor(e);return Lp(t)};var Dp=4096,qp=65547,$p=15,Gp=2113929216,Fp=65536,Bp=65536,jp=10485760,zp={MANUAL:0,AUTO_IMMEDIATE:1,AUTO_THRESHOLD:2},Kp={SUCCESS:0,FAILED:-1,NOT_INITIALIZED:-2,INITIALIZED_FAILED:-3,COMPRESS_FAILED:-4,DECOMPRESS_FAILED:-5,PARAM_ERROR:-6,BUFFER_RESIZE_FAILED:-7};function Hp(e){if(!(e>0))return Bp;if(e<=Bp)return Bp;if(e>1073741823)return e;for(var t=Bp;t<e;)t*=2;return t}var Vp={byU16:0,byU32:1},Wp=0,Jp=1,Zp=2,Qp=0,Yp=1;function Xp(e,t){return e[t]|e[t+1]<<8}function eh(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0}function th(e,t,r){e[t]=255&r,e[t+1]=r>>>8&255}var rh="fast";function sh(e){return 2654435761*(e>>>0)>>>20&4095}function nh(e){return 2654435761*(e>>>0)>>>19&8191}function ih(e,t,r){if("fast"===rh){var s=eh(e,t);return r===Vp.byU16?nh(s):sh(s)}throw new Error("Unsupported hash strategy: "+rh)}function oh(e,t,r,s,n){r[t]=e-n}function ah(e,t,r,s,n){oh(t,ih(e,t,s),r,0,n)}function ch(e,t,r,s){return t[e]+s}function dh(e,t,r,s,n){return ch(ih(e,t,s),r,0,n)}function uh(e,t,r,s){for(var n=t;t<s-3;){if(eh(e,t)!==eh(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 lh(e,t,r,s,n,i,o,a,c,d){var u,l,p,h=e.hashTable,m=s,f=m-e.dictSize,g=e.dictionary,y=e.dictionaryStart,v=y+e.dictSize,b=e.dictSize>0?v-s:0,I=s,w=s+n,C=w-12,S=w-5,T=0,_=i>0?i:r.length,R=0;if(n>Gp)return 0;switch(c){case Wp:default:u=s,l=s;break;case Jp:u=s-e.currentOffset,l=s-e.dictSize;break;case Zp:u=s-e.currentOffset,l=s}if(a===Vp.byU16&&n>=qp)return 0;if(n<13)return mh(t,r,I,w,T,_,o);ah(t,m,h,a,u),p=ih(t,++m,a);e:for(;;){var A,M,E=m,U=1,k=64;do{var N=p;if(m=E,E+=U,U=k++>>>6,E>C)return mh(t,r,I,w,T,_,o);A=ch(N,h,0,u),c===Zp&&(A<s?(R=b,l=y):(R=0,l=s)),p=ih(t,E,a),oh(m,N,h,0,u)}while(d===Yp&&A<f||a!==Vp.byU16&&A+65535<m||!ph(t,g,m,A,R,c,s));for(;m>I&&A+R>l;){var O=A+R-1;if(t[m-1]!==(c===Zp&&A<s?g[O-y+e.dictionaryStart]:t[O]))break;m--,A--}var x=m-I;if(M=T++,o&&T+x+8+Math.floor(x/255)>_)return 0;if(x>=$p){var L=x-$p;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(th(r,T,m-A),T+=2,c===Zp&&A<s){var q=m+(v-(A+R));if(q>S&&(q=S),(m+=4+(D=hh(t,g,m+4,A+R+4-y+e.dictionaryStart,q,v-y)))===q&&q<S){var $=uh(t,m,s,S);D+=$,m+=$}}else m+=4+(D=uh(t,m+4,A+4,S));if(o&&T+6+(D>>>8)>_)return 0;if(D>=15){for(r[M]+=15,D-=15;D>=510;)r[T++]=255,r[T++]=255,D-=510;D>=255&&(D-=255,r[T++]=255),r[T++]=D}else r[M]+=D;if(I=m,m>C)break e;if(ah(t,m-2,h,a,u),A=dh(t,m,h,a,u),c===Zp&&(A<s?(R=b,l=y):(R=0,l=s)),ah(t,m,h,a,u),!((d!==Yp||A>=f)&&A+65535>=m&&ph(t,g,m,A,R,c,s)))break t;r[M=T++]=0}p=ih(t,++m,a)}return mh(t,r,I,w,T,_,o)}function ph(e,t,r,s,n,i,o){var a,c=eh(e,r);i===Zp&&s+n<o?a=eh(t,s+n):a=eh(e,s+n);return c===a}function hh(e,t,r,s,n,i,o){for(var a=r;s<i&&r<n&&t[s]===e[r];)s++,r++;return r-a}function mh(e,t,r,s,n,i,o){var a=s-r;if(o&&n+a+1+Math.floor((a+255-$p)/255)>i)return 0;if(a>=$p){for(t[n++]=240,a-=$p;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 fh(e,t,r,s){var n,i=0;if(s&&t.ip>=r)return-1;do{if(i+=n=e[t.ip++],t.ip>r)return-1;if(i>2147483647)return-1}while(255===n);return i}function gh(e,t,r,s,n,i,o,a,c,d,u,l,p){if(null==e)return-1;if(i<0)return-1;var h=r,m=r+s,f=n,g=n+i,y=u-p,v=l+p,b=p<65536;if(0===i)return 1===s&&0===e[h]?0:-1;if(0===s)return-1;for(;;){var I,w,C,S;if(h>=m)return-(h-r)-1;if((w=(I=e[h++])>>>4)===$p){var T=fh(e,A={ip:h},m-$p,!0);if(h=A.ip,-1===T)return-(h-r)-1;if(f+(w+=T)<f)return-(h-r)-1;if(h+w<h)return-(h-r)-1}if(C=f+w,o&&(C>g-12||h+w>m-8)||!o&&C>g-8){if(!o&&C!==g)return-(h-r)-1;if(o&&(h+w!==m||C>g))return-(h-r)-1;if(w>=16&&t.set&&e.subarray)t.set(e.subarray(h,h+w),f);else for(var _=0;_<w;_++)t[f+_]=e[h+_];h+=w,f+=w;break}if(w>=16&&t.set&&e.subarray)t.set(e.subarray(h,h+w),f);else for(_=0;_<w;_++)t[f+_]=e[h+_];if(f=C,(h+=w)+2>m)return-(h-r)-1;var R=Xp(e,h);if(h+=2,S=C-R,b&&S+p<u)return-(h-r)-1;if(0===R)return-(h-r)-1;if(15===(w=15&I)){var A;T=fh(e,A={ip:h},m-5+1,!1);if(h=A.ip,-1===T)return-(h-r)-1;if(f+(w+=T)<f)return-(h-r)-1}if(w+=4,d===Zp&&S<u){if(f+w>g-5)return-(h-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-(h-r)-1;if(C=f+w,f-S<8)for(t[f]=t[S],t[f+1]=t[S+1],t[f+2]=t[S+2],t[f+3]=t[S+3],f+=4,S+=4;f<C;)t[f++]=t[S++];else for(;f<C;)t[f++]=t[S++]}}return o?f-n:h-r}function yh(){return{hashTable:new Uint32Array(Dp),currentOffset:0,initCheck:0,dictionary:null,dictionaryStart:0,dictSize:0,bufferStart:null}}function vh(e){e.hashTable.fill(0),e.currentOffset=0,e.initCheck=0,e.dictionary=null,e.dictionaryStart=0,e.dictSize=0,e.bufferStart=null}function bh(e,t,r,s,n,i,o,a){s=s||0;var c=e.dictionaryStart+e.dictSize,d=s;if(e.initCheck)return 0;e.dictSize>0&&d>c&&(d=c),function(e){if(e.currentOffset>2147483648){for(var t=e.currentOffset-65536,r=e.dictionaryStart+e.dictSize,s=0;s<e.hashTable.length;s++)e.hashTable[s]<t?e.hashTable[s]=0:e.hashTable[s]-=t;e.currentOffset=65536,e.dictSize>65536&&(e.dictSize=65536),e.dictionaryStart=r-e.dictSize}}(e);var u,l=s+n;e.dictionary&&l>e.dictionaryStart&&l<c&&(e.dictSize=c-l,e.dictSize>65536&&(e.dictSize=65536),e.dictSize<4&&(e.dictSize=0),e.dictionaryStart=c-e.dictSize);var p=e.dictSize<65536&&e.dictSize<e.currentOffset?Yp:Qp;return e.dictionary&&c===s?(u=lh(e,t,r,s,n,o||0,a||!1,Vp.byU32,Jp,p),e.dictSize+=n,e.currentOffset+=n,u):(u=lh(e,t,r,s,n,o||0,a||!1,Vp.byU32,Zp,p),e.dictionary=t,e.dictionaryStart=s,e.dictSize=n,e.currentOffset+=n,u)}function Ih(e,t,r,s){var n=e.dictionaryStart+e.dictSize;s>65536&&(s=65536),s>e.dictSize&&(s=e.dictSize);var i=n-s;if(t.set&&e.dictionary.subarray)t.set(e.dictionary.subarray(i,i+s),r);else for(var o=0;o<s;o++)t[r+o]=e.dictionary[i+o];return e.dictionary=t,e.dictionaryStart=r,e.dictSize=s,s}function wh(){return{externalDict:null,extDictStart:0,extDictSize:0,prefixEnd:0,prefixSize:0}}function Ch(e,t,r,s){return e.prefixSize=s,e.prefixEnd=r+s,e.externalDict=null,e.extDictStart=0,e.extDictSize=0,1}function Sh(e,t,r,s,n,i,o){var a;if(e.prefixEnd===i){if((a=gh(t,r,s,n,i,o,!0,0,0,Zp,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=gh(t,r,s,n,i,o,!0,0,0,Zp,i,e.extDictStart,e.extDictSize))<=0)return a;e.prefixSize=a,e.prefixEnd=i+a}return a}function Th(e){var t=(e=e||{}).minWorkArea||Bp,r=e.maxWorkArea||jp,s=e.shrinkThreshold||t;t<Bp&&(t=Bp),r<t&&(r=t),s<t&&(s=t),s>r&&(s=r),this.minBufferSize=Fp+t,this.maxBufferSize=Fp+r,this.shrinkThreshold=Fp+s,this.ringBufferSize=this.minBufferSize,this.shrinkMode=void 0!==e.shrinkMode?e.shrinkMode:zp.MANUAL,this.ringBuffer=new Uint8Array(this.ringBufferSize),this.offset=0,this.stream=yh()}function _h(e){var t=(e=e||{}).minWorkArea||Bp,r=e.maxWorkArea||jp,s=e.shrinkThreshold||t;t<Bp&&(t=Bp),r<t&&(r=t),s<t&&(s=t),s>r&&(s=r),this.minBufferSize=Fp+t,this.maxBufferSize=Fp+r,this.shrinkThreshold=Fp+s,this.ringBufferSize=this.minBufferSize,this.shrinkMode=void 0!==e.shrinkMode?e.shrinkMode:zp.MANUAL,this.ringBuffer=new Uint8Array(this.ringBufferSize),this.offset=0,this.streamDecode={externalDict:null,extDictStart:0,extDictSize:0,prefixEnd:0,prefixSize:0}}Th.prototype._resizeBuffer=function(e){var t=new Uint8Array(e),r=0;if(this.offset>0){var s=this.offset<Fp?this.offset:Fp,n=this.offset>Fp?this.offset-Fp:0;t.set(this.ringBuffer.subarray(n,n+s),0),Ih(this.stream,t,0,s),r=s}return this.ringBuffer=t,this.ringBufferSize=e,this.offset=r,!0},Th.prototype.compress=function(e,t){var r=e.length;if(r<=0)return Kp.PARAM_ERROR;if(r>this.maxBufferSize-Fp)return Kp.PARAM_ERROR;if(r>this.ringBufferSize-Fp){var s=Hp(r),n=Fp+s;if(n>this.maxBufferSize&&(n=this.maxBufferSize),!this._resizeBuffer(n))return Kp.BUFFER_RESIZE_FAILED}this.offset+r>this.ringBufferSize&&(Ih(this.stream,this.ringBuffer,0,Fp),this.offset=Fp);var i=this.offset;this.ringBuffer.set(e,i);var o=bh(this.stream,this.ringBuffer,t,i,r,0,t.length,!0);return o<=0?Kp.COMPRESS_FAILED:(this.offset+=r,this._tryAutoShrink(),o)},Th.prototype.reset=function(){this.offset=0,vh(this.stream)},Th.prototype.shrink=function(){this.ringBufferSize>this.minBufferSize&&this._resizeBuffer(this.minBufferSize)},Th.prototype._tryAutoShrink=function(){this.shrinkMode!==zp.MANUAL&&(this.ringBufferSize<=this.minBufferSize||(this.shrinkMode===zp.AUTO_IMMEDIATE||this.shrinkMode===zp.AUTO_THRESHOLD&&this.ringBufferSize>this.shrinkThreshold)&&this.shrink())},Th.prototype.getWorkArea=function(){return this.ringBufferSize-Fp},Th.prototype.getRingBufferSize=function(){return this.ringBufferSize},Th.prototype.getBaseBufferSize=function(){return this.minBufferSize},Th.prototype.getMaxBufferSize=function(){return this.maxBufferSize},Th.prototype.getCurrentOffset=function(){return this.offset},Th.prototype.getShrinkMode=function(){return this.shrinkMode},Th.prototype.setShrinkMode=function(e){this.shrinkMode=e},Th.prototype.getShrinkThreshold=function(){return this.shrinkThreshold},Th.prototype.setShrinkThreshold=function(e){var t=this.minBufferSize-Fp,r=this.maxBufferSize-Fp;if(e<t||e>r)return Kp.PARAM_ERROR;this.shrinkThreshold=Fp+e},_h.prototype._resizeBuffer=function(e){var t=new Uint8Array(e),r=0;if(this.offset>0){var s=this.offset<Fp?this.offset:Fp,n=this.offset>Fp?this.offset-Fp:0;t.set(this.ringBuffer.subarray(n,n+s),0),r=s,Ch(this.streamDecode,0,0,s)}return this.ringBuffer=t,this.ringBufferSize=e,this.offset=r,!0},_h.prototype.decompress=function(e,t,r){var s=e.length;if(s<=0||r<=0)return Kp.PARAM_ERROR;if(r>this.maxBufferSize-Fp)return Kp.PARAM_ERROR;if(r>this.ringBufferSize-Fp){var n=Hp(r),i=Fp+n;if(i>this.maxBufferSize&&(i=this.maxBufferSize),!this._resizeBuffer(i))return Kp.BUFFER_RESIZE_FAILED}if(this.offset+r>this.ringBufferSize){var o=this.offset-Fp;o>0&&this.ringBuffer.set(this.ringBuffer.subarray(o,o+Fp),0),Ch(this.streamDecode,this.ringBuffer,0,Fp),this.offset=Fp}var a=Sh(this.streamDecode,e,this.ringBuffer,0,s,this.offset,r);return a<=0?Kp.DECOMPRESS_FAILED:(t.set(this.ringBuffer.subarray(this.offset,this.offset+a),0),this.offset+=a,this._tryAutoShrink(),a)},_h.prototype.reset=function(){this.offset=0,this.streamDecode={externalDict:null,extDictStart:0,extDictSize:0,prefixEnd:0,prefixSize:0}},_h.prototype.shrink=function(){this.ringBufferSize>this.minBufferSize&&this._resizeBuffer(this.minBufferSize)},_h.prototype._tryAutoShrink=function(){this.shrinkMode!==zp.MANUAL&&(this.ringBufferSize<=this.minBufferSize||(this.shrinkMode===zp.AUTO_IMMEDIATE||this.shrinkMode===zp.AUTO_THRESHOLD&&this.ringBufferSize>this.shrinkThreshold)&&this.shrink())},_h.prototype.getWorkArea=function(){return this.ringBufferSize-Fp},_h.prototype.getRingBufferSize=function(){return this.ringBufferSize},_h.prototype.getBaseBufferSize=function(){return this.minBufferSize},_h.prototype.getMaxBufferSize=function(){return this.maxBufferSize},_h.prototype.getCurrentOffset=function(){return this.offset},_h.prototype.getShrinkMode=function(){return this.shrinkMode},_h.prototype.setShrinkMode=function(e){this.shrinkMode=e},_h.prototype.getShrinkThreshold=function(){return this.shrinkThreshold},_h.prototype.setShrinkThreshold=function(e){var t=this.minBufferSize-Fp,r=this.maxBufferSize-Fp;if(e<t||e>r)return Kp.PARAM_ERROR;this.shrinkThreshold=Fp+e};const Rh={LZ4_MAX_INPUT_SIZE:Gp,BLOCK_MAX_SIZE:65536,DICT_SIZE:Fp,DEFAULT_WORK_AREA:Bp,DEFAULT_MAX_WORK:jp,SHRINK_MODE:zp,LZ4_ERROR:Kp,alignToPowerOf2:Hp,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".');rh=e},getHashStrategy:function(){return rh},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>Gp)return 0;if(0===s)return t.length>n?(t[n]=0,1):0;var i=s<qp?Vp.byU16:Vp.byU32;return lh({hashTable:new Uint32Array(i===Vp.byU16?8192:Dp),currentOffset:0,dictSize:0,dictionary:null,dictionaryStart:0},e,t,r,s,0,!1,i,Wp,Qp)},compressLimited:function(e,t,r,s,n,i){if(null==e)return 0;if(null==t)return 0;if(r=r||0,s=void 0===s?e.length:s,n=n||0,r<0||n<0)return 0;if(s<0||i<0)return 0;if(r+s>e.length)return 0;if(s>Gp)return 0;if(i<1)return 0;if(0===s)return t[n]=0,1;var o=s<qp?Vp.byU16:Vp.byU32;return lh({hashTable:new Uint32Array(o===Vp.byU16?8192:Dp),currentOffset:0,dictSize:0,dictionary:null,dictionaryStart:0},e,t,r,s,i,!0,o,Wp,Qp)},compressBound:function(e){return e<0||e>Gp?0:e+Math.floor(e/255)+16},decompressSafe:function(e,t,r,s,n,i){return null==e||null==t?-1:(n=n||0,(r=r||0)<0||n<0||s<0||i<0||r+s>e.length||n+i>t.length?-1:gh(e,t,r,s,n,i,!0,0,0,Wp,n,null,0))},decompressFast:function(e,t,r,s,n){return gh(e,t,r=r||0,0,s=s||0,n,!1,0,0,Jp,s-65536,0,65536)},createStream:yh,resetStream:vh,loadDict:function(e,t,r,s){if(e.initCheck&&vh(e),s<4)return e.dictionary=null,e.dictSize=0,0;s>65536&&(r=r+s-65536,s=65536);var n=r-e.currentOffset;e.dictionary=t,e.dictionaryStart=r,e.dictSize=s,e.currentOffset+=s;for(var i=r,o=r+s;i<=o-4;)ah(t,i,e.hashTable,Vp.byU32,n),i+=3;return s},compressContinue:bh,saveDict:Ih,createStreamDecode:wh,setStreamDecode:Ch,decompressSafeContinue:Sh,RingBufferEncoder:Th,RingBufferDecoder:_h,_hashU16:nh,_hashU32:sh,_TABLE_TYPE:Vp},Ah=268435455,Mh=new Uint32Array(256);let Eh=!1;function Uh(e){!function(){if(!Eh){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;Mh[e]=t>>>0}Eh=!0}}();let t=4294967295;for(let r=0;r<e.length;r+=1){const s=e[r]??0;t=t>>>8^(Mh[255&(t^255&s)]??0)}return(4294967295^t)>>>0}var kh=(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))(kh||{});const Nh=268435455;class Oh{constructor(){this.mode=-1,this.enableUplinkCompression=!1,this.enableDownlinkCompression=!1;const e={minWorkArea:Rh.DEFAULT_WORK_AREA,maxWorkArea:Rh.DEFAULT_MAX_WORK,shrinkMode:Rh.SHRINK_MODE.MANUAL};this.encoder=new Rh.RingBufferEncoder(e),this.decoder=new Rh.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>Nh)throw new Error(`Data size exceeds maximum allowed: ${t.length}`);const r=Rh.compressBound(t.length),s=new Uint8Array(r),n=this.encoder.compress(t,s);if(n<0)throw new Error(`LZ4 compression failed with error code: ${n}`);const i=s.subarray(0,n),o=function(e){if(e<0)throw new Error("encodeLength: Length must be non-negative");if(e>Ah)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=Uh(t),c=new Uint8Array(o.length+4+n);let d=0;c.set(o,d),d+=o.length;return new DataView(c.buffer).setUint32(d,a,!1),d+=4,c.set(i,d),c}decompress(e){const t=e instanceof ArrayBuffer?new Uint8Array(e):e;if(!t||0===t.length)return new Uint8Array(0);if(t.length<5)throw new Error("Compressed data is too short: must contain at least length and CRC32");const r={offset:0},s=function(e,t){if(t.offset>=e.length)throw new Error("decodeLength: No data to decode: offset beyond data length");let r=0,s=0;for(;t.offset<e.length;){const n=e[t.offset]??0;if(t.offset+=1,r|=(127&n)<<s,!(128&n))return r>>>0;if(s+=7,s>=28)throw new Error("decodeLength: Invalid length encoding: exceeds 4 bytes")}throw new Error("decodeLength: Incomplete length encoding: missing terminator byte")}(t,r);if(s>Nh)throw new Error(`Original size exceeds maximum allowed: ${s}`);if(t.length<r.offset+4)throw new Error("Compressed data is too short: missing CRC32 checksum");const n=new DataView(t.buffer,t.byteOffset+r.offset,4).getUint32(0,!1);r.offset+=4;const i=t.subarray(r.offset),o=new Uint8Array(s),a=this.decoder.decompress(i,o,s);if(a<0||a!==s)throw new Error(`LZ4 decompression failed: expected ${s}, got ${a}`);const c=Uh(o);if(c!==n)throw new Error(`CRC32 checksum mismatch: expected ${n}, got ${c}`);return o}reset(){this.encoder.reset(),this.decoder.reset()}}const xh=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),Lh=(e,t)=>rd(e,t).finish();class Ph{constructor(e){this.compressor=null,this.compressionFailureCount=0,this.maxCompressionFailures=1,this.context=(e=>{const t=pl({useFixedDeviceId:e.useFixedDeviceId??!0,deviceId:e.deviceId??"webim",customDeviceName:e.customDeviceName,customOSPlatform:e.customOSPlatform}),r=`${Date.now()}:`;return{appKey:e.appKey,userId:e.userId,token:e.token,domain:e.domain??"easemob.com",version:e.version??"4.11.0",uiKitVersion:e.uiKitVersion,osType:void 0!==e.customOSPlatform?5:e.osType??16,deviceId:t.deviceId,deviceName:t.deviceName,deviceUuid:t.deviceUuid,clientResource:t.deviceId,customOSPlatform:e.customOSPlatform,loginExtensionInfo:e.loginExtensionInfo,encryptType:[Gs],compressType:[Fs],sessionId:r,serviceId:e.serviceId}})(e),this.useReplacedMessageContents=e.useReplacedMessageContents??!1,this.useCustomAttachmentUpload=e.useCustomAttachmentUpload??!1}updateToken(e){this.context.token=e}updateResource(e){e&&(this.context.clientResource=e)}getContext(){return{...this.context}}encodeProvision(){const e=cl(),t=e.lookupType("easemob.pb.Provision"),r=e.lookupType("easemob.pb.MSync"),s={osType:this.context.osType,version:this.context.uiKitVersion??this.context.version,compressType:[Fs],encryptType:[Gs],protocolCompressType:this.getRequestedCompressTypes(),deviceUuid:this.context.deviceUuid,deviceName:this.context.deviceName,resource:this.context.deviceId,actionVersion:"v6.0",authToken:`{"token":"$t$${this.context.token}"}`,sessionId:this.context.sessionId,...this.context.serviceId?{serviceId:this.context.serviceId}:{},...void 0!==this.context.customOSPlatform?{osCustomValue:this.context.customOSPlatform}:{},...this.context.loginExtensionInfo?{reason:this.context.loginExtensionInfo}:{}},n=Lh(t,s),i={version:0,guid:hl({appKey:this.context.appKey,name:this.context.userId,domain:this.context.domain,clientResource:this.context.clientResource}),auth:`$t$${this.context.token}`,command:os,deviceId:0,encryptType:[Gs],payload:n,traceId:yl()};return Lh(r,i)}encodeHeartbeat(){const e=cl(),t=e.lookupType("easemob.pb.CommUnreadUL"),r=e.lookupType("easemob.pb.MSync"),s=Lh(t,{}),n={version:0,encryptType:[Gs],command:ns,payload:s,traceId:yl()};return Lh(r,n)}encodeStatisticRebuild(){const e=cl(),t=e.lookupType("easemob.pb.StatisticsBody"),r=e.lookupType("easemob.pb.Meta"),s=e.lookupType("easemob.pb.CommSyncUL"),n=e.lookupType("easemob.pb.MSync"),i=Lh(t,{operation:0}),o=r.decode(new Uint8Array);o.id=Date.now(),o.ns=Ns,o.payload=i;const a=s.decode(new Uint8Array);a.meta=o;const c=Lh(s,a);return Lh(n,{version:0,encryptType:[Gs],command:ss,payload:c,traceId:yl()})}decodeProvision(e){const t=cl().lookupType("easemob.pb.Provision").decode(e),r=t.status??{},s="number"==typeof r.errorCode?r.errorCode:zs,n="string"==typeof r.reason?r.reason:void 0,i="string"==typeof t.resource?t.resource:void 0,o="string"==typeof t.authToken?t.authToken:void 0,a=Array.isArray(t.protocolCompressType)?t.protocolCompressType:void 0,c="number"==typeof t.protocolCompressDirection?t.protocolCompressDirection:void 0;return this.configureCompression(a,c),{ok:s===js,statusCode:s,reason:n,resource:i,authToken:o,protocolCompressType:a,protocolCompressDirection:c}}decodeLogout(e){const t=cl().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=cl().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=cl().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=cl(),r=t.lookupType("easemob.pb.CommSyncDL"),s=t.lookupType("easemob.pb.MessageBody"),n=r.decode(e);Ci("decodeSync commSyncDl",{hasMetas:Array.isArray(n.metas)});const i=Array.isArray(n.metas)?n.metas:[],o=this.decodeAck(n);o?.ok&&(o.chatRoomInfo=this.decodeChatRoomJoinInfo(i));const a=ml(n.metaId),c=ml(n.nextKey),d=n.queue??void 0,u="boolean"==typeof n.isLast?n.isLast:void 0,l=[],p=[];if(a&&"0"!==a){const e=this.useReplacedMessageContents?this.decodeReplacedMessage(i,s):void 0;for(const t of i){const e=this.decodeNotifyMeta(t);e.length>0&&p.push(...e)}return{ack:o,messages:l,notifies:p.length>0?p:void 0,metaId:a,queue:d,nextKey:c,isLast:u,replacedMessage:e}}for(const h of i){const e=this.decodeChatMeta(h,s);e&&l.push(e);const t=this.decodeChatActionMeta(h,s);t&&p.push(t);const r=this.decodeNotifyMeta(h);r.length>0&&p.push(...r)}return{ack:o,messages:l,notifies:p.length>0?p:void 0,metaId:a,queue:d,nextKey:c,isLast:u}}decodeReplacedMessage(e,t){for(const r of e){const e=this.decodeChatMeta(r,t);if(e)return e}}decodeChatMeta(e,t){if(!e||"object"!=typeof e)return null;const r=e,s=r.payload;let n=null;if(s instanceof Uint8Array?n=s:s instanceof ArrayBuffer?n=new Uint8Array(s):ArrayBuffer.isView(s)&&(n=new Uint8Array(s.buffer,s.byteOffset,s.byteLength)),!n)return null;if(("number"==typeof r.ns?r.ns:void 0)!==Os)return null;try{const e=t.decode(n);if(!e||"object"!=typeof e)return null;const s=e;return this.decodeMessage(r,s)}catch{return null}}decodeChatActionMeta(e,t){if(!e||"object"!=typeof e)return null;const r=e,s=r.payload;let n=null;if(s instanceof Uint8Array?n=s:s instanceof ArrayBuffer?n=new Uint8Array(s):ArrayBuffer.isView(s)&&(n=new Uint8Array(s.buffer,s.byteOffset,s.byteLength)),!n)return null;if(("number"==typeof r.ns?r.ns:void 0)!==Os)return null;try{const e=t.decode(n);if(!e||"object"!=typeof e)return null;const s=e,i="number"==typeof s.type?s.type:cs;if(i!==ps&&i!==ms&&i!==fs&&i!==gs&&i!==hs)return null;const o=this.readJid(r.to),a=Number(ml(r.timestamp))||Date.now(),c=this.resolveActionConversationType(o.domain,s.meta,s),{senderId:d,receiverId:u}=this.resolveIncomingMessageParties(r,s,c),l=this.resolveActionConversationId(d,u,c);if(i===fs)return!0===s.clearAllUnreadMessageCount?{type:"multiDevice",eventName:"onMultiDeviceConversation",data:{category:"conversation",operation:"ALL_CONVERSATIONS_UNREAD_MESSAGE_COUNT_CLEARED",timestamp:a}}:l?{type:"multiDevice",eventName:"onMultiDeviceConversation",data:{category:"conversation",operation:"CONVERSATION_UNREAD_MESSAGE_COUNT_CLEARED",conversationId:l,conversationType:"groupChat"===c?"groupChat":"singleChat",timestamp:a}}:null;if(i===ps){Ci("Received READ_ACK MessageBody",s);const e=(Array.isArray(s.ackMessageIds)?s.ackMessageIds:[]).map(e=>ml(e)).filter(e=>Boolean(e)),t=ml(s.ackMessageId);if(0===e.length&&t&&e.push(t),0===e.length||!l)return null;const r=gl(Array.isArray(s.ext)?s.ext.filter(xh):void 0),n=xh(r.group_ack_count)?r.group_ack_count:{},i=e.flatMap(e=>{const t=n[e];return"number"==typeof t&&Number.isInteger(t)&&t>=0?[{messageId:e,count:t}]:[]});return{type:"message_receipts",data:{messageIds:e,conversationId:l,conversationType:"groupChat"===c?"groupChat":"singleChat",timestamp:a,..."groupChat"===c?{receiptDetails:i}:{}}}}if(i===hs){const e=ml(s.ackMessageId);return e&&l?{type:"message_delivered",data:{messageId:e,from:d,to:u,conversationId:l,conversationType:"singleChat"}}:null}if(i===ms){const e=ml(s.ackMessageId);return e&&l?{type:"message_recalled",data:{messageId:e,conversationId:l,conversationType:c,timestamp:a}}:null}const p=ml(s.editMessageId),h=(Array.isArray(s.contents)?s.contents:[])[0],m=h?this.decodeContent(h):null;if(!p||!l||!m)return null;const f=this.resolveModifiedInfo(s.meta);return{type:"message_updated",data:{messageId:p,conversationId:l,conversationType:c,timestamp:a,message:{type:m.type,body:m.body,ext:gl(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=cl(),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(!xh(n)||!Array.isArray(n.group_ack))return[];const i=this.readMetaTimestamp(e)??Date.now(),o=new Map;for(const e of n.group_ack){if(!xh(e))continue;const t="string"==typeof e.groupId&&e.groupId.length>0?e.groupId:"";for(const[r,s]of Object.entries(e)){if("groupId"===r)continue;const e="number"==typeof s?s:"string"==typeof s&&s.trim().length>0?Number(s):Number.NaN;!r||!Number.isInteger(e)||e<0||o.set(r,{conversationId:t,count:e})}}return Ci("Decoded MSync statistic group read receipts",{receiptDetails:Array.from(o,([e,{conversationId:t,count:r}])=>({messageId:e,conversationId:t,count:r}))}),Array.from(o,([e,{conversationId:t,count:r}])=>({type:"message_receipts",data:{messageIds:[e],conversationId:t,conversationType:"groupChat",timestamp:i,receiptDetails:[{messageId:e,count:r}]}}))}catch{return[]}}decodeStatisticMeta(e){if(!e||"object"!=typeof e)return null;const t=e;if(t.ns!==Ns)return null;const r=t.payload;let s=null;if(r instanceof Uint8Array?s=r:r instanceof ArrayBuffer?s=new Uint8Array(r):ArrayBuffer.isView(r)&&(s=new Uint8Array(r.buffer,r.byteOffset,r.byteLength)),!s)return null;try{const e=cl(),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=cl(),s=r.lookupType("easemob.pb.RosterBody").decode(t),n="number"==typeof s.operation?s.operation:-1,i=this.readRosterJid(s.from),o=this.readRosterJidList(s.to),a="string"==typeof s.reason?s.reason:"",c="string"==typeof s.rosterVer&&s.rosterVer.trim().length>0?s.rosterVer:void 0,d=i.name??"",u=o[0]?.name??"";if(!d&&!u)return[];const l=Mp({operation:n,from:i,to:o,rosterVersion:c,ext:a,timestamp:this.readMetaTimestamp(e),raw:s},this.msyncCodecContext());if(l)return[this.createMultiDeviceNotify(l)];const p=this.mapRosterOperationToEvent(n,{from:d,to:u,message:a,rosterVersion:c});return p?[{type:"contact",eventName:p.eventName,data:p.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=cl(),s=r.lookupType("easemob.pb.MUCBody").decode(t),n="number"==typeof s.operation?s.operation:-1,i=!0===s.isChatroom,o=!0===s.isThread,a=this.readJid(s.from),c=Array.isArray(s.to)?s.to.map(e=>this.readJid(e)):[],d=s.eventInfo&&"object"==typeof s.eventInfo?s.eventInfo:void 0,u=Array.isArray(s.members)?s.members.filter(e=>"string"==typeof e):[],l=a.name===this.context.userId&&a.clientResource&&a.clientResource!==this.context.clientResource?"multiDevice":"direct";if(o){const t=Up({operation:n,threadId:this.readJid(s.mucId).name??"",threadName:"string"==typeof s.mucName?s.mucName:void 0,parentId:this.readJid(s.mucParentId).name??void 0,from:a,to:c,members:u,timestamp:this.readMetaTimestamp(e),raw:s},this.msyncCodecContext());if(t)return[this.createMultiDeviceNotify(t)];const r=37===n&&c.some(e=>e.name===this.context.userId),i=this.readJid(s.mucId).name??"",o=this.readJid(s.mucParentId).name??"";return r&&i&&o?[{type:"thread",eventName:"onChatThreadChange",data:{eventName:"onChatThreadChange",payload:{id:i,name:"string"==typeof s.mucName?s.mucName:void 0,muc_parent_id:o,timestamp:this.readMetaTimestamp(e),from:a.name,userIds:[this.context.userId],operation:"kick"}}}]:[]}if(!i){const t=Ep({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 p=i?Ml({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}):ap({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 p?[{type:i?"chatroom":"group",eventName:i?"onChatRoomNotify":"onGroupNotify",data:p}]:[]}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&&pp.set(e,t)})(r,t.rosterVersion),e){case 2:return{eventName:"onContactInvited",payload:r};case 3:return{eventName:"onContactDeleted",payload:r};case 4:return{eventName:"onContactAdded",payload:r};case 5:case 9:return{eventName:"onContactRefuse",payload:r};case 8:return{eventName:"onContactAgreed",payload:r};default:return null}}decodeNotifyPayload(e){try{let t="";for(let i=0;i<e.length;i+=1){const r=e[i];if(void 0===r)return[];t+=`%${r.toString(16)}`}const r=decodeURIComponent(t),s=JSON.parse(r);Ci("Decoded MSync notify payload",{payload:s});const n="string"==typeof s.type?s.type:"";if(!n)return[];if("thread"===n){return[{type:n,eventName:"onChatThreadChange",data:{eventName:"onChatThreadChange",payload:xh(s.data)?s.data:s}}]}if("conv"===n){const e=xh(s.data)?s.data:s,t=[],r="string"==typeof e.op?e.op:"";if("pin"===r||"pin_delete"===r)return[{type:n,eventName:"onPinnedMessageChanged",data:e}];const i=kp({operation:r,id:"string"==typeof e.id?e.id:"",type:"string"==typeof e.type?e.type:void 0,from:"string"==typeof e.from?e.from:void 0,res:"string"==typeof e.res?e.res:void 0,ts:e.ts,ext:"string"==typeof e.ext?e.ext:void 0,raw:e},this.msyncCodecContext());return i&&t.push(this.createMultiDeviceNotify(i)),t}if("roaming_delete"===n){const e=xh(s.data)?s.data:s,t=Np({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(!Cp(s))continue;const e=Sp(s.operator_resource,s.resource,s.clientResource);if(Tp(e,t.clientResource))continue;const n=bp(s.group)??bp(s.user);if(!n||!Cp(s.data))continue;const i=bp(s.group)?vp:yp,o=s.data;r.push({category:"conversation",operation:"CONVERSATION_MUTE_INFO_CHANGED",conversationId:n,conversationType:i,remindType:bp(o.type),silentMode:o,deviceId:e,raw:s})}return r})(xh(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(ml(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:Op(e.category),data:e}}decodeNotice(e){const t=cl().lookupType("easemob.pb.CommNotice").decode(e);return{queue:t.queue&&"object"==typeof t.queue?t.queue:void 0}}decodeUnread(e){const t=cl().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=cl(),r=t.lookupType("easemob.pb.CommSyncUL"),s=t.lookupType("easemob.pb.MSync"),n=Lh(r,{queue:e}),i={version:0,encryptType:[Gs],command:ss,payload:n,traceId:yl()};return Lh(s,i)}encodeLastSession(e,t){const r=cl(),s=r.lookupType("easemob.pb.CommSyncUL"),n=r.lookupType("easemob.pb.MSync"),i=Lh(s,{queue:e,key:t}),o={version:0,encryptType:[Gs],command:ss,payload:i,traceId:yl()};return Lh(n,o)}encodeChatMessage(e,t){const r=cl(),s=r.lookupType("easemob.pb.MessageBody"),n=r.lookupType("easemob.pb.CommSyncUL"),i=r.lookupType("easemob.pb.MSync"),o=this.buildContent(e),a=this.resolveMessageProfileVersionFields(e),c=this.buildMessageMeta(e),d=this.resolveOutboundMessageTarget(e.conversationId,e.conversationType),u={type:this.resolveChatType(e),from:{name:this.context.userId},to:{name:d.name},contents:[o],ext:fl(e.ext??{}),...c?{meta:c}:{},...a,...e.needReadReceipt?{msgConfig:{allowGroupAck:!0}}:{}},l=Lh(s,u),p="singleChat"===e.conversationType?this.context.domain:"conference.easemob.com",h=this.resolveDirectedUsers(e),m=this.resolveMetaExt(e),f={id:t,to:hl({appKey:this.context.appKey,name:d.name,domain:p,clientResource:d.clientResource}),ns:Os,payload:l,routetype:this.resolveRouteType(e),directedUsers:h,ext:m,...void 0!==e.webhookEnv?{env:e.webhookEnv}:{}},g=Lh(n,{meta:f}),y={version:0,encryptType:[Gs],command:ss,payload:g,traceId:yl()};return Lh(i,y)}encodeActionMessage(e,t){const r=cl(),s=r.lookupType("easemob.pb.MessageBody"),n=r.lookupType("easemob.pb.CommSyncUL"),i=r.lookupType("easemob.pb.MSync"),o=r.lookupEnum("easemob.pb.MessageBody.EditScope"),a=this.resolveOutboundMessageTarget(e.conversationId,e.conversationType),c=e.body&&e.messageType?[this.buildContent({msgServerId:e.messageId??"",msgLocalId:t,from:this.context.userId,to:e.conversationId,sender:{userId:this.context.userId},conversationId:e.conversationId,conversationType:e.conversationType,type:e.messageType,sendStatus:"sending",ext:e.ext??{},timestamp:Date.now(),body:e.body})]:[],d={type:this.resolveActionMessageType(e),from:{name:this.context.userId},to:{name:a.name},contents:c,ext:fl(e.ext??{})};"recall"!==e.kind&&"deliveryAck"!==e.kind||(d.ackMessageId=e.messageId),"sendMessageReadReceipts"===e.kind&&(d.ackMessageIds=e.messageIds,"groupChat"===e.conversationType&&(d.msgConfig={allowGroupAck:!0})),"clearConversationUnreadMessageCount"===e.kind&&(d.sendToPeer=e.sendToPeer??!1),"clearAllConversationUnreadMessageCount"===e.kind&&(d.sendToPeer=e.sendToPeer??!1,d.clearAllUnreadMessageCount=e.clearAllUnreadMessageCount??!0),"update"===e.kind&&(d.editMessageId=e.messageId,d.editScope=e.ext&&Object.keys(e.ext).length>0?o.values.BODY_AND_EXT:o.values.BODY);const u=Lh(s,d);if("clearAllConversationUnreadMessageCount"===e.kind){const e=s.decode(u),r=s.fields.clearAllUnreadMessageCount;Ci("Clear-all unread MessageBody wire encoded",{operation:"msync.action.clear-all-unread.wire",protocolId:t,messageType:d.type,fieldId:r?.id,requestedValue:d.clearAllUnreadMessageCount,decodedHasField:Object.prototype.hasOwnProperty.call(e,"clearAllUnreadMessageCount"),decodedValue:e.clearAllUnreadMessageCount,messageBodyBytes:u.byteLength,wireTailHex:Array.from(u.slice(-16),e=>e.toString(16).padStart(2,"0")).join(" ")})}const l={id:t,to:hl({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:[]},p=Lh(n,{meta:l}),h={version:0,encryptType:[Gs],command:ss,payload:p,traceId:yl()};return Lh(i,h)}encodeChatRoomOperation(e,t){const r=cl(),s=r.lookupType("easemob.pb.MUCBody"),n=r.lookupType("easemob.pb.CommSyncUL"),i=r.lookupType("easemob.pb.MSync"),o={mucId:hl({appKey:this.context.appKey,name:e.chatRoomId,domain:"conference.easemob.com"}),operation:"join"===e.operation?2:3,from:{name:this.context.userId},isChatroom:!0};"join"===e.operation&&(void 0!==e.ext&&(o.ext=e.ext),void 0!==e.leaveOtherRooms&&(o.leaveOtherRooms=e.leaveOtherRooms));const a=Lh(s,o),c={id:t,from:hl({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=Lh(n,{meta:c}),u={version:0,encryptType:[Gs],command:ss,payload:d,traceId:yl()};return Lh(i,u)}decodeServerMessageMeta(e){const t=cl(),r=t.lookupType("easemob.pb.Meta"),s=t.lookupType("easemob.pb.MessageBody");try{const t=r.decode(e);return this.decodeChatMeta(t,s)}catch{return null}}async normalizeIncoming(e){if(e instanceof Uint8Array)return e;if(t=e,"[object ArrayBuffer]"===Object.prototype.toString.call(t))return new Uint8Array(e);var t;if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);if((e=>"undefined"!=typeof Blob&&e instanceof Blob||"object"==typeof e&&null!==e&&"function"==typeof e.arrayBuffer)(e)){const t=await e.arrayBuffer();return new Uint8Array(t)}return"string"==typeof e?_i(e):e&&"object"==typeof e&&"data"in e?this.normalizeIncoming(e.data):new Uint8Array}decompressIncoming(e){if(!this.compressor||!this.compressor.enableDownlinkCompression)return e;try{return this.compressor.decompress(e)}catch{return this.compressionFailureCount+=1,null}}prepareOutgoing(e){if(!this.compressor||!this.compressor.enableUplinkCompression)return e;try{return this.compressor.compress(e)}catch{throw this.compressionFailureCount+=1,new Error("compress outgoing message failed")}}resetCompressionNegotiation(){this.compressor?.reset(),this.disableCompression()}toProtocolId(e){return(e=>{if(/^\d+$/.test(e))return e;const t=mo.fromString("1099511628211",!0);let r=mo.fromString("1469598103934665603",!0);for(let s=0;s<e.length;s+=1)r=r.xor(mo.fromInt(e.charCodeAt(s),!0)).multiply(t).toUnsigned();return r.isZero()?"1":r.toString()})(e)}decodeChatRoomJoinInfo(e){const t=cl().lookupType("easemob.pb.MUCBody");for(const s of e){if(!xh(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(!xh(e)||!xh(e.status))continue;const r=e.status.chatroomInfo;if("string"!=typeof r||""===r)continue;const s=JSON.parse(r);if(!xh(s))continue;const i=s[this.context.userId];if(!xh(i))continue;const o=i;return{..."boolean"==typeof o.is_all_mute?{isAllMembersMuted:o.is_all_mute}:{},..."number"==typeof o.create_timestamp?{createTimestamp:o.create_timestamp}:{},..."boolean"==typeof o.is_in_white_list?{isInAllowlist:o.is_in_white_list}:{},..."number"==typeof o.member_count?{memberCount:o.member_count}:{},muteExpireTimestamp:"number"==typeof o.mute_duration&&0!==o.mute_duration?o.mute_duration:-1}}catch(r){Ti("Failed to decode chat room info from ACK",r)}}}decodeAck(e){const t=ml(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:ml(e.serverId),ok:s===js,statusCode:s,reason:n}}decodeMessage(e,t){const r="number"==typeof t.type?t.type:ds;if(!this.isPublicMessageType(r))return null;const s=(Array.isArray(t.contents)?t.contents:[])[0];if(!s)return null;const n=this.resolveConversationType(r),{senderUserId:i,senderId:o,receiverId:a}=this.resolveIncomingMessageParties(e,t,n),c=o===this.context.userId?"SEND":"RECEIVE",d="singleChat"===n?"SEND"===c?a:o:a,u=this.decodeContent(s);if(!u)return null;const l=gl(t.ext),p=gl(e.ext),h=Number(ml(e.timestamp))||Date.now(),m=ml(e.id),f=this.resolveBroadcast(p),g=this.resolvePriority(p),y=this.resolveMessageMetaPayload(t.meta,e.meta),v=this.resolveContentReplaced(y),b=this.resolveReactions(y),I=this.resolveModifiedInfo(y),w=this.resolveChatThreadMessageContext(y),C=this.resolveChatThreadOverview(y),S=this.resolveProfileVersionTime(t.userInfoUpdateTime),T=this.resolveProfileVersionTime(t.namecardUpdateTime),_={msgServerId:m,msgLocalId:"",from:o,to:a,sender:{userId:i},conversationId:d,conversationType:n,type:u.type,sendStatus:"sent",ext:l,timestamp:h,body:u.body,direct:c,isOnline:this.resolveMessageIsOnline(r,p)};dp(_,{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=up(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 Lp(ml(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(ml(r.streamSeq));if(!Number.isFinite(s))return;const n="number"==typeof r.streamStatus?r.streamStatus:Ms,i="number"==typeof r.streamError?r.streamError:0,o="number"==typeof r.streamFinishReason?r.streamFinishReason:void 0,a=this.resolveContentText(t),c=a;return{customType:"string"==typeof r.streamType?r.streamType:void 0,seq:s,status:this.mapStreamStatus(n,i),errorType:i,finishReason:o,deltaText:a,fullText:c}}mapStreamStatus(e,t){return t>0?rt.ERROR:e===Rs?rt.START:e===As?rt.START_COMPLETED:e===Es?rt.COMPLETED:e===Us?rt.FULL:rt.IN_PROGRESS}resolveContentText(e){return e&&"string"==typeof e.text?e.text:e&&"string"==typeof e.customEvent?e.customEvent:""}buildContent(e){if("text"===e.type){const t=e.body;return{type:ys,text:t.content}}if("cmd"===e.type){const t=e.body;return{type:Ss,action:t.action}}if("custom"===e.type){const t=e.body;return{type:Ts,customEvent:t.event,customExts:fl(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:fp(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=gl(e.customExts);return{type:"custom",body:{event:"string"==typeof e.customEvent?e.customEvent:"",params:t}}}if(t===Is)return{type:"location",body:{latitude:"number"==typeof e.latitude?e.latitude:0,longitude:"number"==typeof e.longitude?e.longitude:0,address:"string"==typeof e.address?e.address:void 0,buildingName:"string"==typeof e.buildingName?e.buildingName:void 0}};if(t===vs){const t=e.size??{},r="number"==typeof t.width?t.width:0,s="number"==typeof t.height?t.height:0,n=oi(e.imageType)===Wn,i="string"==typeof e.remotePath?e.remotePath:"",o=ni(i,{deriveVariants:!this.useCustomAttachmentUpload}),a="string"==typeof e.thumbnailRemotePath&&e.thumbnailRemotePath.length>0?e.thumbnailRemotePath:void 0;return{type:"image",body:{localUrl:"",filename:"string"==typeof e.displayName?e.displayName:"image",filetype:"application/octet-stream",width:r,height:s,isGif:1===e.subType,isOriginalImage:n,originalImageUrl:o.originalImageUrl,bigImageUrl:o.bigImageUrl,secret:"string"==typeof e.secretKey?e.secretKey:void 0,fileLength:"number"==typeof e.fileLength?e.fileLength:void 0,thumbnailUrl:a??o.thumbnailUrl}}}if(t===bs){const t=e.size??{},r="number"==typeof t.width?t.width:void 0,s="number"==typeof t.height?t.height:void 0,n="string"==typeof e.thumbnailRemotePath?e.thumbnailRemotePath:void 0;return{type:"video",body:{url:"string"==typeof e.remotePath?e.remotePath:"",filename:"string"==typeof e.displayName?e.displayName:"video",filetype:"application/octet-stream",duration:"number"==typeof e.duration?e.duration:0,width:r,height:s,secret:"string"==typeof e.secretKey?e.secretKey:void 0,fileLength:"number"==typeof e.fileLength?e.fileLength:void 0,thumbnailUrl:n}}}if(t===ws){return{type:"voice",body:{url:"string"==typeof e.remotePath?e.remotePath:"",filename:"string"==typeof e.displayName?e.displayName:"voice",filetype:"application/octet-stream",duration:"number"==typeof e.duration?e.duration:0,secret:"string"==typeof e.secretKey?e.secretKey:void 0,fileLength:"number"==typeof e.fileLength?e.fileLength:void 0}}}if(t===Cs){return{type:"file",body:{url:"string"==typeof e.remotePath?e.remotePath:"",filename:"string"==typeof e.displayName?e.displayName:"file",filetype:"application/octet-stream",secret:"string"==typeof e.secretKey?e.secretKey:void 0,fileLength:"number"==typeof e.fileLength?e.fileLength:void 0}}}return null}resolveChatType(e){switch(e.conversationType){case"groupChat":return us;case"chatRoom":return ls;default:return ds}}resolveActionConversationType(e,t,r){const s=this.resolveConversationTypeFromMeta(t);if(s)return s;const n=r?.msgConfig&&"object"==typeof r.msgConfig?r.msgConfig:null;return!0===n?.allowGroupAck||"conference.easemob.com"===e?"groupChat":"singleChat"}resolveConversationTypeFromMeta(e){if("string"!=typeof e||0===e.length)return null;try{const t=JSON.parse(e),r=t.edit_msg&&"object"==typeof t.edit_msg?t.edit_msg:void 0,s=("string"==typeof t.chat_type?t.chat_type:void 0)??("string"==typeof t.chatType?t.chatType:void 0)??("string"==typeof t.type?t.type:void 0)??("string"==typeof r?.chat_type?r.chat_type:void 0);if("chat:user"===s||"singleChat"===s)return"singleChat";if("chat:group"===s||"groupChat"===s)return"groupChat";if("chat:room"===s||"chatRoom"===s)return"chatRoom"}catch{}return null}resolveActionConversationId(e,t,r){return"singleChat"===r?e===this.context.userId?t:e:t}resolveOutboundMessageTarget(e,t){if("singleChat"!==t)return{name:e};const r=`${this.context.userId}/`;if(!e.startsWith(r))return{name:e};const s=e.slice(r.length);return s?{name:this.context.userId,clientResource:s}:{name:e}}resolveIncomingMessageParties(e,t,r){const s=this.readJid(e.from),n=this.readJid(e.to),i=this.readJid(t.from),o=this.readJid(t.to),a=i.name??s.name??"",c=o.name??n.name??"";if(!("singleChat"===r&&a===this.context.userId&&c===this.context.userId))return{senderUserId:a,senderId:a,receiverId:c};return{senderUserId:a,senderId:s.clientResource&&s.clientResource!==this.context.clientResource?`${a}/${s.clientResource}`:a,receiverId:n.clientResource?`${c}/${n.clientResource}`:c}}resolveActionMessageType(e){switch(e.kind){case"clearConversationUnreadMessageCount":case"clearAllConversationUnreadMessageCount":return fs;case"sendMessageReadReceipts":return ps;case"deliveryAck":return hs;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?fl({chatroom_msg_tag:this.mapPriorityToTag(e.priority)}):[]}resolveRouteType(e){return this.resolveDirectedUsers(e).length>0?$s:this.resolveDeliverOnlineOnly(e)?qs:Ds}resolveBroadcast(e){if(!Object.prototype.hasOwnProperty.call(e,"is_broadcast"))return;const t=e.is_broadcast;return"boolean"==typeof t?t:"number"==typeof t?0!==t:"string"==typeof t?"1"===t||"true"===t.toLowerCase():Boolean(t)}resolvePriority(e){if(!Object.prototype.hasOwnProperty.call(e,"chatroom_msg_tag"))return;const t=Number(e.chatroom_msg_tag);return 0===t?"high":2===t?"low":"normal"}resolveContentReplaced(e){const t=this.parseMetaPayload(e);if(t&&Object.prototype.hasOwnProperty.call(t,"callback_replace"))return Boolean(t.callback_replace)}resolveMessageMetaPayload(e,t){const r=this.parseMetaPayload(e),s=this.parseMetaPayload(t);return r&&s?{...s,...r}:r??s??e??t}resolvePeerRead(e,t,r){if("singleChat"!==t||"SEND"!==r)return;const s=this.parseMetaPayload(e);return"boolean"==typeof s?.isRead?s.isRead:void 0}resolveGroupReadCount(e,t){if("groupChat"!==t)return;const r=this.parseMetaPayload(e),s=r?.group_read_ack;return"number"==typeof s&&Number.isInteger(s)&&s>=0?s:void 0}resolveModifiedInfo(e){const t=this.parseMetaPayload(e),r=t?.edit_msg;if(!xh(r))return;const s="string"==typeof r.operator?r.operator:"",n=this.toFiniteNumber(r.count),i=this.toFiniteNumber(r.edit_time);return s&&void 0!==n&&void 0!==i?{operatorId:s,operationCount:n,operationTime:i}:void 0}resolveChatThreadMessageContext(e){const t=this.parseMetaPayload(e),r=t?.thread;if(!xh(r)||0===Object.keys(r).length)return;const s=this.readString(r.msg_parent_id??r.messageId),n=this.readString(r.muc_parent_id??r.parentId);if(!s||!n)return;const i=this.readString(r.thread_name??r.chatThreadName);return{messageId:s,parentId:n,...i?{chatThreadName:i}:{}}}resolveChatThreadOverview(e){const t=this.parseMetaPayload(e),r=t?.thread_overview??t?.threadOverview;if(!xh(r)||0===Object.keys(r).length)return;const s=this.readString(r.id??r.thread_id??r.chatThreadId),n=this.readString(r.muc_parent_id??r.parentId);if(!s||!n)return;const i=this.readString(r.name),o=this.resolveChatThreadOverviewLastMessage(r.last_message??r.lastMessage,s);return{chatThreadId:s,parentId:n,...i?{name:i}:{},...void 0!==o?{lastMessage:o}:{},...this.numberField("createdAt",r.create_timestamp??r.createdAt),...this.numberField("updatedAt",r.update_timestamp??r.updatedAt),...this.numberField("messageCount",r.message_count??r.messageCount)}}resolveChatThreadOverviewLastMessage(e,t){if(!xh(e)||0===Object.keys(e).length)return null;const r=this.readString(e.msgId??e.msg_id??e.id);if(!r)return null;const s=this.toFiniteNumber(e.timestamp)??0,n=this.resolveThreadLastMessagePayload(e),i=this.readString(n?.from)??this.readString(e.from)??"",o=this.readString(n?.to)??this.readString(e.to)??t,a=Array.isArray(n?.bodies)?n.bodies:[],c=xh(a[0])?a[0]:null,d=this.readString(c?.type)??this.readString(e.type),u=this.mapThreadMessageType(d),l=this.normalizeThreadLastMessageBody(u,c,e),p=t,h=i===this.context.userId?"SEND":"RECEIVE";return{msgServerId:r,msgLocalId:"",from:i,to:o,sender:{userId:i},conversationId:p,conversationType:"groupChat",type:u,sendStatus:"sent",ext:xh(n?.ext)?n.ext:{},timestamp:s,body:l,direct:h}}resolveThreadLastMessagePayload(e){const t=e.payload;if(xh(t))return t;if("string"==typeof t){const e=this.parseMetaPayload(t);if(e)return e}return null}mapThreadMessageType(e){switch(e){case"txt":default:return"text";case"img":return"image";case"loc":return"location";case"audio":return"voice";case"video":return"video";case"file":return"file";case"cmd":return"cmd";case"custom":return"custom";case"combine":return"combine";case"text":case"image":case"voice":case"location":return e}}normalizeThreadLastMessageBody(e,t,r){if(!t){return{content:this.readString(r.msg??r.content??r.text)??""}}switch(e){case"text":default:return{content:this.readString(t.msg??t.content??t.text)??""};case"image":{const e=this.readString(t.url)??"",r=ni(e,{deriveVariants:!this.useCustomAttachmentUpload});return{localUrl:"",filename:this.readString(t.filename)??"image",filetype:this.readString(t.filetype)??"application/octet-stream",width:this.toFiniteNumber(t.width)??0,height:this.toFiniteNumber(t.height)??0,isGif:!0===t.isGif,isOriginalImage:!1,originalImageUrl:r.originalImageUrl,bigImageUrl:r.bigImageUrl,thumbnailUrl:this.readString(t.thumb)??r.thumbnailUrl,secret:this.readString(t.secret),fileLength:this.toFiniteNumber(t.file_length??t.fileLength)}}case"voice":return{url:this.readString(t.url)??"",filename:this.readString(t.filename)??"voice",filetype:this.readString(t.filetype)??"application/octet-stream",duration:this.toFiniteNumber(t.duration??t.length)??0,secret:this.readString(t.secret),fileLength:this.toFiniteNumber(t.file_length??t.fileLength)};case"video":return{url:this.readString(t.url)??"",filename:this.readString(t.filename)??"video",filetype:this.readString(t.filetype)??"application/octet-stream",duration:this.toFiniteNumber(t.duration??t.length)??0,width:this.toFiniteNumber(t.width),height:this.toFiniteNumber(t.height),thumbnailUrl:this.readString(t.thumb),secret:this.readString(t.secret),fileLength:this.toFiniteNumber(t.file_length??t.fileLength)};case"file":return{url:this.readString(t.url)??"",filename:this.readString(t.filename)??"file",filetype:this.readString(t.filetype)??"application/octet-stream",secret:this.readString(t.secret),fileLength:this.toFiniteNumber(t.file_length??t.fileLength)};case"location":return{latitude:this.toFiniteNumber(t.lat??t.latitude)??0,longitude:this.toFiniteNumber(t.lng??t.longitude)??0,address:this.readString(t.addr??t.address),buildingName:this.readString(t.buildingName)};case"cmd":return{action:this.readString(t.action)??""};case"custom":return{event:this.readString(t.event??t.customEvent)??"",params:xh(t.params??t.customExts)?t.params??t.customExts:{}};case"combine":return{title:this.readString(t.title)??"",summary:this.readString(t.summary)??"",filename:this.readString(t.filename)??"combine",filetype:"application/octet-stream",url:this.readString(t.url),secret:this.readString(t.secret),fileLength:this.toFiniteNumber(t.file_length??t.fileLength),combineLevel:this.toFiniteNumber(t.combineLevel)??0}}}readString(e){return"string"==typeof e&&e.length>0?e:void 0}numberField(e,t){const r=this.toFiniteNumber(t);return void 0===r?{}:{[e]:r}}parseMetaPayload(e){const t=this.normalizeMetaPayload(e);if(t){if(0===t.length)return null;try{const e=JSON.parse(Ri(t));return xh(e)?e:null}catch{return null}}if(xh(e))return e;if("string"==typeof e)try{const t=JSON.parse(e);return xh(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(xh).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?[]:[Bs]}configureCompression(e,t){if(!e||!e.includes(Bs))return void this.disableCompression();this.compressor||(this.compressor=new Oh);const r=this.resolveCompressionMode(t);this.compressor.mode=r,this.compressor.enableUplinkCompression=r===kh.UPLINK_ONLY||r===kh.BIDIRECTIONAL,this.compressor.enableDownlinkCompression=r===kh.DOWNLINK_ONLY||r===kh.BIDIRECTIONAL}resolveCompressionMode(e){return 0===e?kh.UPLINK_ONLY:1===e?kh.DOWNLINK_ONLY:2===e?kh.BIDIRECTIONAL:kh.NONE}disableCompression(){this.compressor&&(this.compressor.mode=kh.NONE,this.compressor.enableUplinkCompression=!1,this.compressor.enableDownlinkCompression=!1)}}const Dh=1e3,qh="direct";class $h{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 Gh{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 Fh={none:0,disconnected:0,ethernet:1,lan:1,wifi:2,"slow-2g":7,"2g":7,"3g":7,"4g":7,"5g":7,cellular:7},Bh=()=>{const e=Vi(),t=e.crypto?.randomUUID;return("function"==typeof t?t.call(e.crypto):void 0)??`${Date.now()}_${Math.random().toString(36).slice(2)}`};class jh{constructor(e){this.currentState="disabled",this.networkType=-1,this.now=e.now??Date.now,this.randomId=e.randomId??Bh;const t=new Gh({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 $h({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:Fh[e.trim().toLowerCase()]??-1)(e)}applyDnsSwitch(e){if(this.session){if("true"===e)return this.currentState="enabled",void this.queue.enable();this.currentState="disabled",this.queue.clear()}else this.currentState="disabled"}startOperation(e){const t=this.session?.sessionId;if(!t||"disabled"===this.currentState)return this.createNoopOperation();const r=`opr_${this.randomId()}`,s=this.now();let n=!1,i=!1,o=`req_${this.randomId()}`,a=0,c="";const d=()=>!n&&!i&&this.session?.sessionId===t,u=(t,s,n,i,o)=>{d()&&(a=o.success?0:o.code,c=o.success?"":o.description??"",this.enqueue(9675,{uid:e.uid??this.session?.uid,operationId:r,requestid:s,operationName:e.operationName,operationType:e.operationType,requestName:t.requestName??e.operationName,subrequestid:String(n),requestMethod:t.method??"",requestUrl:t.url??"",requestElapse:Math.max(0,this.now()-i),code:o.code,codeDesc:o.description??"",isLastApi:0,isSuccess:o.success?1:0,accessChannel:this.session?.accessChannel??qh,msgId:e.msgId,messageType:e.messageType,resultCount:o.resultCount}))},l=(e,t,r,s)=>{const n=this.now();let i=!1;return{retry:()=>(s.next+=1,l(e,t,s.next,s)),finish:s=>{i||(i=!0,u(e,t,r,n,s))}}};return{startRequest:(e={})=>(o=`req_${this.randomId()}`,l(e,o,1,{next:1})),finish:t=>{d()&&(n=!0,this.enqueue(9675,{uid:e.uid??this.session?.uid,operationId:r,requestid:o,operationName:e.operationName,operationType:e.operationType,requestName:"",subrequestid:"0",requestMethod:"",requestUrl:"",requestElapse:Math.max(0,this.now()-s),code:t.success?0:t.code??a,codeDesc:t.success?"":t.description??c,isLastApi:1,isSuccess:t.success?1:0,accessChannel:this.session?.accessChannel??qh,msgId:e.msgId,messageType:e.messageType,resultCount:t.resultCount}))},discard:()=>{i=!0}}}reset(){this.currentState="disabled",this.session=void 0,this.queue.clear()}enqueue(e,t){const r=this.session;if(!r||"disabled"===this.currentState)return;const s={lts:this.now(),net:this.networkType,appkey:r.appKey,sdkServiceId:r.serviceId,sdkProduct:0,uikitVersion:r.uikitVersion??"",...t},n={eventId:e,body:Object.fromEntries(Object.entries(s).filter(([,e])=>void 0!==e))};this.queue.enqueue({appKey:r.appKey,wire:n})}createNoopOperation(){const e={retry:()=>e,finish:()=>{}};return{startRequest:()=>e,finish:()=>{},discard:()=>{}}}}let zh;const Kh=e=>{zh?.updateSession(e)},Hh=e=>{zh?.applyDnsSwitch(e)},Vh=e=>{zh?.updateNetworkType(e)},Wh=e=>{if("disabled"!==zh?.state)return zh?.startOperation(e)},Jh=()=>{zh?.reset(),zh=void 0};class Zh{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 Ph({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 sl({maxAttempts:this.config.autoReconnectNumMax,initialDelay:1e3,maxDelay:6e4,backoffMultiplier:2}),this.heartbeatManager=new ol({interval:this.config.heartBeatWait,timeout:6e4}),this.connectionEventNormalizer=new Ai,this.socketAdapter=this.resolveSocketAdapter(e),this.isOnline="undefined"==typeof navigator||navigator.onLine,this.eventHub.addEventHandler(this.internalHandlerId,{[m]:e=>{this.handleSendTimeout(e)}})}getConnectionStatus(){return this.connection.status}getWebSocket(){return this.websocket}getMsyncCodec(){return this.msyncCodec}getClientResource(){return this.msyncCodec.getContext().clientResource}setMessageReceiver(e){this.messageReceiver=e}renewToken(e,t){const r=Date.now();if(t<=r)throw new Wr("Token is expired",{code:lt,details:{stage:"token"}});return this.config.token=e,this.connection.token=e,this.msyncCodec.updateToken(e),this.setupTokenLifecycle(e,t,r),Si("Connection token renewed",{userId:this.config.userId,expireAt:t}),{token:e,expireAt:t}}handleOnline(){Si("Network online event received",this.getReconnectDiagnostic()),this.isOnline=!0;const e=this.offlineRecoverPending?S:C;this.offlineRecoverPending=!1,this.resumeReconnect(e)}handleOffline(){Si("Network offline event received",this.getReconnectDiagnostic()),this.isOnline=!1,this.offlineRecoverPending=!0,this.reconnectPaused=!0,this.clearReconnectTimer(),this.stopHeartbeat(),this.closeWebSocket(E,!0),Si("Network offline state applied",this.getReconnectDiagnostic())}async handleForeground(){if(!this.isLoggedIn)return;if(!this.isOnline)return;if(this.reconnectInProgress)return void Si("Foreground recovery skipped",{guard:"reconnect-in-progress",...this.getReconnectDiagnostic()});const e=this.websocket;try{if(!(await this.checkHeartbeatOnce())){if(this.reconnectInProgress||this.websocket!==e)return;this.closeWebSocket(T,!0,!0),this.resumeReconnect(T)}}catch(t){if(Si("Foreground heartbeat check failed",t),this.reconnectInProgress||this.websocket!==e)return;this.closeWebSocket(T,!0,!0),this.resumeReconnect(T)}}resumeReconnect(e){this.isLoggedIn&&(this.reconnectInProgress?Si("Reconnect recovery skipped",{guard:"reconnect-in-progress",reason:e,...this.getReconnectDiagnostic()}):this.connection.status===s&&this.websocket||(this.reconnectPaused=!1,this.resetReconnectState(),Si("Reconnect recovery requested",{reason:e,...this.getReconnectDiagnostic()}),this.triggerReconnect(e)))}handleSendTimeout(e){this.isLoggedIn&&this.isOnline&&(this.reconnectPaused||e.reason===_&&Si("Message send timeout received without reconnect",e))}resetReconnectState(){this.reconnectAttempts=0,this.connection.reconnectAttempts=0,this.connectionRetry.reset()}getReconnectDiagnostic(){return{status:this.connection.status,isOnline:this.isOnline,isLoggedIn:this.isLoggedIn,isLoginPhase:this.isLoginPhase,reconnectInProgress:this.reconnectInProgress,reconnectPaused:this.reconnectPaused,offlineRecoverPending:this.offlineRecoverPending,reconnectAttempts:this.reconnectAttempts,hasWebSocket:null!==this.websocket,hasReconnectTimer:null!==this.reconnectTimerId}}normalizeServerUrls(e){const t=(e.serverUrls??[]).filter(e=>"string"==typeof e&&e.length>0);return t.length>0?[...t]:[e.serverUrl]}pickNextServerUrl(){if(0===this.serverUrls.length)return this.config.serverUrl;const e=this.serverUrlIndex%this.serverUrls.length,t=this.serverUrls[e]??this.config.serverUrl;return this.serverUrlIndex=(e+1)%this.serverUrls.length,this.config.serverUrl=t,this.connection.serverUrl=t,t}resolveEffectiveMaxAttempts(){return this.isLoginPhase&&0===this.config.autoReconnectNumMax?1:this.config.autoReconnectNumMax}isNonRetryableError(e){if(!(e instanceof Wr))return!1;const t=e.details;if(!t||"object"!=typeof t)return!1;return!1===t.retryable}isServerNormalClosePayload(e){if(e.length>64)return!1;let t;try{t=JSON.parse(Ri(e))}catch{return!1}return!(!Array.isArray(t)||t.length<2)&&(3e3===t[0]&&"normal closed"===t[1])}clearReconnectTimer(){this.reconnectTimerId&&(clearTimeout(this.reconnectTimerId),this.reconnectTimerId=null)}async waitForReconnectDelay(){const e=this.connectionRetry.getRetryDelay();Si("Reconnect retry scheduled",{delayMs:Math.round(e),...this.getReconnectDiagnostic()}),this.clearReconnectTimer(),await new Promise(t=>{this.reconnectTimerId=setTimeout(()=>{this.reconnectTimerId=null,t()},e)})}buildConnectionEventPayload(e,t){const r=this.connection.error instanceof Wr?this.connection.error:void 0;return{state:e,reason:t,attempt:this.reconnectAttempts,maxAttempts:this.resolveEffectiveMaxAttempts(),isLoginPhase:this.isLoginPhase,isOnline:this.isOnline,errorCode:r?.code,errorMessage:r?.message,timestamp:Date.now()}}dispatchConnectionEvent(e,r){if(e===t&&!this.hasEverConnected)return;if(e===i&&!this.isLoggedIn)return;if(this.isLoginPhase&&(e===t||e===i))return;const s=this.buildConnectionEventPayload(e,r),n=this.connectionEventNormalizer.normalize(e,s);n&&this.eventHub.dispatch(n.eventName,n.payload)}updateStatus(e,t,r,n=!1){const i=this.connection.status!==e;(i||n)&&(i&&(this.connection.status=e,this.connection.lastConnectedAt=e===s?Date.now():void 0),r&&this.dispatchConnectionEvent(e,t),Ci("Connection status updated",{status:e,reason:t,attempt:this.reconnectAttempts,forceEmit:n}))}clampTimerDelay(e){return e<=0?0:Math.min(e,2**31-1)}clearTokenTimers(){this.tokenWillExpireTimerId&&(clearTimeout(this.tokenWillExpireTimerId),this.tokenWillExpireTimerId=null),this.tokenExpiredTimerId&&(clearTimeout(this.tokenExpiredTimerId),this.tokenExpiredTimerId=null)}setupTokenLifecycle(e,t,r=Date.now()){this.clearTokenTimers();const s=Math.max(t-r,0),n=r+Math.floor(.8*s);this.tokenLifecycle={token:e,issuedAt:r,expireAt:t,willExpireAt:n,willExpireEmitted:!1,expiredEmitted:!1},this.tokenWillExpireTimerId=setTimeout(()=>{this.emitTokenWillExpire()},this.clampTimerDelay(n-Date.now())),this.tokenExpiredTimerId=setTimeout(()=>{this.handleTokenExpiredDisconnect("timer")},this.clampTimerDelay(t-Date.now()))}setupTokenLifecycleFromProvision(e){if(e&&!this.tokenWillExpireTimerId&&!this.tokenExpiredTimerId)try{const t=JSON.parse(e);if(!t||"object"!=typeof t)return void Si("Provision auth token has invalid payload");const r=Number(t.expires_in);if(!Number.isFinite(r))return void Si("Provision auth token has invalid expires_in");this.setupTokenLifecycle(this.connection.token??this.config.token,r)}catch(t){Si("Failed to parse provision auth token expiration",t)}}emitTokenWillExpire(){this.tokenLifecycle&&!this.tokenLifecycle.willExpireEmitted&&(this.tokenLifecycle.willExpireEmitted=!0,Si("Token will expire"),this.eventHub.dispatch(u,void 0))}emitTokenExpired(){this.tokenLifecycle||(this.tokenLifecycle={token:this.connection.token??"",issuedAt:Date.now(),expireAt:Date.now(),willExpireAt:Date.now(),willExpireEmitted:!0,expiredEmitted:!1});const e=this.tokenLifecycle;e.expiredEmitted||(e.expiredEmitted=!0,Si("Token expired"),this.eventHub.dispatch(l,void 0))}isTokenExpiredConnectionError(e){return e instanceof Wr&&e.code===lt}handleTokenExpiredDisconnect(e){Si("Connection closing because token expired",{source:e}),this.connection.error=new Wr("Token expired",{code:lt,details:{stage:"token",source:e,retryable:!1}}),this.emitTokenExpired(),this.clearTokenTimers(),this.clearReconnectTimer(),this.resetProvisionHandlers(),this.stopHeartbeat(),this.reconnectPaused=!0,this.reconnectInProgress=!1,this.offlineRecoverPending=!1,this.isLoginPhase=!1,this.isLoggedIn=!1,this.closeWebSocket(U,!0,!0),this.updateStatus(t,U,!0)}startHeartbeat(e){this.heartbeatManager.start(e,()=>{this.triggerReconnect(T)},()=>{this.sendHeartbeatPing()})}stopHeartbeat(){this.heartbeatManager.stop()}async checkHeartbeatOnce(){return!!this.websocket&&this.heartbeatManager.probeOnce(this.websocket,6e4)}sendHeartbeatPing(){const e=this.msyncCodec.encodeHeartbeat();this.sendMsyncPayload(e)}async connect(){if(!this.reconnectInProgress)if(this.connection.status!==s&&this.connection.status!==r){this.isLoginPhase=!0,this.reconnectPaused=!1,this.resetReconnectState(),this.connectionEventNormalizer.reset();try{await this.connectWithRetry(I,!0),this.isLoggedIn=!0}catch(e){throw this.isLoggedIn=!1,e}finally{this.isLoginPhase=!1}}else Si("Connection already established or connecting")}async connectWithRetry(e,o){if(Si("Reconnect flow requested",{reason:e,throwOnFailure:o,...this.getReconnectDiagnostic()}),this.reconnectInProgress)return void Si("Reconnect flow skipped",{guard:"reconnect-in-progress",reason:e,...this.getReconnectDiagnostic()});if(this.connection.status===s&&this.websocket)return;if(this.reconnectPaused)return void Si("Reconnect flow skipped",{guard:"reconnect-paused",reason:e,...this.getReconnectDiagnostic()});if(!this.isLoginPhase&&0===this.config.autoReconnectNumMax)return;if(!this.isOnline&&!this.isLoginPhase)return;this.reconnectInProgress=!0;let a=null,c=null;const d=this.resolveEffectiveMaxAttempts();this.connectionRetry.reset(),Si("Reconnect flow started",{reason:e,throwOnFailure:o,maxAttempts:d,...this.getReconnectDiagnostic()});try{for(;this.connectionRetry.getAttemptCount()<d;){this.connectionRetry.recordAttempt(),this.reconnectAttempts=this.connectionRetry.getAttemptCount(),this.connection.reconnectAttempts=this.reconnectAttempts;const t=this.isLoginPhase?r:n;Si("Reconnect attempt started",{attempt:this.reconnectAttempts,maxAttempts:d,reason:e,nextStatus:t,...this.getReconnectDiagnostic()}),this.updateStatus(t,e,!0,!0),this.prepareForConnectAttempt();try{return await this.connectOnce(),void this.handleConnectSuccess(e)}catch(u){if(a=u,Si("Connection attempt failed",{attempt:this.reconnectAttempts,reason:e,error:a}),!this.isLoginPhase&&this.isTokenExpiredConnectionError(a))return void this.handleTokenExpiredDisconnect("server");if(this.isNonRetryableError(a)){c=a;break}}if(this.connectionRetry.getAttemptCount()>=d)break;if(this.reconnectPaused||!this.isOnline&&!this.isLoginPhase){Si("Reconnect retry loop interrupted",{reason:e,attempt:this.reconnectAttempts,maxAttempts:d,...this.getReconnectDiagnostic()});break}await this.waitForReconnectDelay()}if(c){if(this.connection.error=c,o)throw this.updateStatus(t,A,!1),c;return this.reconnectPaused=!0,void this.updateStatus(t,A,!0)}if(o)throw this.updateStatus(t,A,!1),a??new Wr("Connection failed",{code:gt,details:{stage:"ws"}});this.reconnectPaused=!0,Si("Reconnect attempts exhausted",{reason:e,attempt:this.reconnectAttempts,maxAttempts:d,lastError:a,...this.getReconnectDiagnostic()}),this.updateStatus(i,M,!0)}finally{this.reconnectInProgress=!1,Si("Reconnect flow finished",{reason:e,...this.getReconnectDiagnostic()})}}async connectOnce(){await this.createWebSocketConnection()}prepareForConnectAttempt(){this.clearReconnectTimer(),this.stopHeartbeat(),this.resetProvisionHandlers(),this.resetSyncState(),this.websocket&&this.closeWebSocket(w,!1,!1),this.msyncCodec.resetCompressionNegotiation()}handleConnectSuccess(e){this.updateStatus(s,e,!0),this.hasEverConnected=!0,this.connection.error=void 0,this.resetReconnectState(),this.offlineRecoverPending=!1,this.reconnectPaused=!1,this.sendPostProvisionInitialSync(),this.websocket&&this.startHeartbeat(this.websocket),Si("Connection established successfully")}sendPostProvisionInitialSync(){this.sendMsyncPayload(this.msyncCodec.encodeHeartbeat()),this.sendMsyncPayload(this.msyncCodec.encodeStatisticRebuild())}async triggerReconnect(e){Si("Reconnect trigger received",{reason:e,...this.getReconnectDiagnostic()}),this.isLoggedIn?this.reconnectInProgress?Si("Reconnect trigger skipped",{guard:"reconnect-in-progress",reason:e,...this.getReconnectDiagnostic()}):this.reconnectPaused?Si("Reconnect trigger skipped",{guard:"reconnect-paused",reason:e,...this.getReconnectDiagnostic()}):(this.connection.status===s&&this.websocket&&this.closeWebSocket(e,!0,!0),await this.connectWithRetry(e,!1)):Si("Reconnect trigger skipped",{guard:"not-logged-in",reason:e,...this.getReconnectDiagnostic()})}handleDisconnection(e){Si("Connection disconnection handled",{reason:e,...this.getReconnectDiagnostic()}),this.stopHeartbeat(),this.updateStatus(t,e,!0),e!==U&&this.isLoggedIn&&this.isOnline&&(this.reconnectPaused||this.triggerReconnect(e))}closeWebSocket(e,r,s=!0){this.websocket?(this.suppressNextCloseEvent=!0,this.websocket.close(),this.websocket=null,this.stopHeartbeat(),s&&this.updateStatus(t,e,r)):s&&this.updateStatus(t,e,r)}createWebSocketConnection(){return new Promise((e,t)=>{const r=this.pickNextServerUrl();Ci("WebSocket connecting",{url:r}),this.clearSocketListeners();let s=!1;const n=setTimeout(()=>{s=!0,Si("WebSocket connection attempt timed out",{url:r,connectTimeout:this.config.connectTimeout,...this.getReconnectDiagnostic()}),t(new Wr("Connection timeout",{code:ft,details:{stage:"ws"}}))},this.config.connectTimeout);this.socketAdapter.connect({url:r,timeoutMs:this.config.connectTimeout}).then(i=>{if(clearTimeout(n),s||this.reconnectPaused)return Si("WebSocket connection result discarded",{url:r,cancelled:s,reconnectPaused:this.reconnectPaused,note:"outer connection promise remains pending",...this.getReconnectDiagnostic()}),void i.close();this.websocket=i,this.socketGeneration+=1,this.inboundMessageQueue=Promise.resolve(),this.attachSocketListeners(i,this.socketGeneration),this.startProvision().then(()=>{if(this.resetProvisionHandlers(),s||this.reconnectPaused)return Si("Provision result discarded",{url:r,cancelled:s,reconnectPaused:this.reconnectPaused,note:"outer connection promise remains pending",...this.getReconnectDiagnostic()}),void this.closeWebSocket(A,!1,!1);e()}).catch(e=>{this.resetProvisionHandlers(),this.closeWebSocket(A,!1,!1),t(e instanceof Error?e:new Error(String(e)))})}).catch(e=>{if(clearTimeout(n),s)return;const r=e instanceof Wr?e:new Wr("Failed to create WebSocket",{code:gt,details:{stage:"ws",cause:e instanceof Error?e.message:String(e)}});this.handleConnectionError(r,A),t(r)})}).catch(e=>{if(e instanceof Wr)throw e;const t=new Wr("Failed to create WebSocket",{code:gt,details:{stage:"ws",cause:e instanceof Error?e.message:String(e)}});throw this.handleConnectionError(t,A),t})}handleWebSocketClose(e){this.suppressNextCloseEvent?this.suppressNextCloseEvent=!1:(Si("WebSocket closed",{code:e.code,reason:e.reason}),this.provisionReject&&this.rejectProvisionAfterQueuedMessages(),this.websocket=null,this.clearSocketListeners(),this.stopHeartbeat(),this.handleDisconnection(R))}async rejectProvisionAfterQueuedMessages(){try{await this.inboundMessageQueue}catch{}this.provisionReject&&(this.provisionReject(new Wr("Provision interrupted",{code:It,details:{stage:"provision"}})),this.resetProvisionHandlers())}handleConnectionError(e,t){if(Ti("Connection error:",e),this.connection.error=e,this.provisionTimeoutId&&(clearTimeout(this.provisionTimeoutId),this.provisionTimeoutId=null),this.resetProvisionHandlers(),this.websocket){this.suppressNextCloseEvent=!0;const e=this.websocket;this.clearSocketListeners(),e.close(),this.websocket=null}this.stopHeartbeat(),this.handleDisconnection(t)}handleTerminalConnectionError(e,r){if(Si("Terminal connection error received",{code:e.code,message:e.message,details:e.details}),this.connection.error=e,this.reconnectPaused=!0,this.reconnectInProgress=!1,this.offlineRecoverPending=!1,this.resetProvisionHandlers(),this.clearReconnectTimer(),this.websocket){this.suppressNextCloseEvent=!0;const e=this.websocket;this.clearSocketListeners(),e.close(),this.websocket=null}this.stopHeartbeat(),this.updateStatus(t,r,!0,!0)}async handleWebSocketMessage(e,t){try{if(t!==this.socketGeneration)return;Ci("WebSocket message received",{dataType:typeof e});const s=await this.msyncCodec.normalizeIncoming(e);if(t!==this.socketGeneration)return;if(Ci("handleWebSocketMessage data",{length:s.length}),!s.length)return;const n=this.msyncCodec.decompressIncoming(s);if(!n){const e=null!==this.provisionReject;return Ti("Failed to decompress mSync payload, closing connection",{stage:e?"provision":"connected"}),void(e?(this.rejectPendingProvision(new Wr("Failed to decompress Provision payload",{code:gt,details:{stage:"provision",cause:"decompression-failed",retryable:!0}})),this.closeWebSocket(A,!1,!1)):this.websocket?.close())}if(this.isServerNormalClosePayload(n))return void Ci("Ignore server normal close payload",{length:n.length});let i=null;try{i=this.msyncCodec.decodeMsync(n)}catch(r){const e=r instanceof Error?r:new Error("Failed to decode mSync payload");if(e instanceof RangeError)return void Si("Discard invalid mSync payload",{length:n.length,message:e.message,prefixHex:Array.from(n.subarray(0,16),e=>e.toString(16).padStart(2,"0")).join(""),suffixHex:Array.from(n.subarray(Math.max(0,n.length-16)),e=>e.toString(16).padStart(2,"0")).join("")});throw Si("Invalid mSync payload signature",{length:n.length,prefixHex:Array.from(n.subarray(0,8),e=>e.toString(16).padStart(2,"0")).join("")}),e}switch(this.heartbeatManager.markAlive(),Ci("handleWebSocketMessage decoded",{command:i.command}),i.command){case os:this.handleProvisionMessage(i.payload);break;case as:this.handleLogoutMessage(i.payload);break;case is:this.handleNoticeMessage(i.payload);break;case ns:this.handleUnreadMessage(i.payload);break;case ss:this.handleSyncMessage(i.payload)}}catch(r){const e=r instanceof Error?r:new Error("Failed to handle mSync payload");Ti("Failed to handle mSync payload",e),this.handleConnectionError(e,A)}}startProvision(){this.provisionPromise=new Promise((e,t)=>{this.provisionResolve=e,this.provisionReject=t}),this.provisionTimeoutId&&clearTimeout(this.provisionTimeoutId),this.provisionTimeoutId=setTimeout(()=>{this.rejectPendingProvision(new Wr("Provision timeout",{code:vt,details:{stage:"provision",retryable:!0}}))},1e4);try{const e=this.msyncCodec.encodeProvision();Ci("startProvision provision",{length:e.length}),this.sendMsyncPayload(e)}catch{this.provisionReject?.(new Wr("Provision send failed",{code:gt,details:{stage:"provision"}})),this.resetProvisionHandlers()}return this.provisionPromise}handleProvisionMessage(e){const t=this.msyncCodec.decodeProvision(e);if(this.provisionTimeoutId&&(clearTimeout(this.provisionTimeoutId),this.provisionTimeoutId=null),t.ok)this.msyncCodec.updateResource(t.resource),this.setupTokenLifecycleFromProvision(t.authToken),this.provisionResolve?.();else{Si("Provision rejected",{statusCode:t.statusCode,reason:t.reason});const e=Nn(t.statusCode,t.reason),r=e.code===Br?bt:e.code;this.provisionReject?.(new Wr("Provision rejected",{code:r,details:{stage:"provision",reason:t.reason,statusCode:t.statusCode,retryable:e.retryable}}))}}handleNoticeMessage(e){const{queue:t}=this.msyncCodec.decodeNotice(e),r=t?this.getQueueId(t):null,s=!!t&&this.isSelfQueue(t),n=!!t&&this.isQueueInList(t);t&&r&&(s||n||(this.queues.push(t),1===this.queues.length&&this.sendBackqueue(t)))}handleUnreadMessage(e){const{queues:t}=this.msyncCodec.decodeUnread(e),r=t.filter(e=>this.getQueueId(e));if(r.length){r.length!==t.length&&Si("Unread queues without usable identity were ignored",{ignoredCount:t.length-r.length}),this.startOfflineMessageSync(r);for(const e of r)this.isQueueInList(e)||this.queues.push(e);if(this.queues.length>0&&!this.currentQueue){const e=this.queues[0];e&&this.sendBackqueue(e)}}}handleSyncMessage(e){const t=this.resolveStatisticDisconnectError(this.msyncCodec.decodeSyncStatisticOperations(e));if(t)return void this.handleTerminalConnectionError(t,A);if(!this.messageReceiver)return;const r=this.messageReceiver.handleSyncPayload(e);if(Ci("handleSyncMessage result",{result:r}),!r)return;(void 0!==r.queue||void 0!==r.nextKey||void 0!==r.isLast)&&this.handleSyncQueueState(r)}handleSyncQueueState(e){Ci("[QueueSync] handleSyncQueueState",{isLast:e.isLast,nextKey:e.nextKey,queueName:e.queue?this.getQueueName(e.queue):null,queueId:e.queue?this.getQueueId(e.queue):null,queuesLength:this.queues.length});const t=this.resolveSyncQueueState(e);if(!t)return e.queue&&e.isLast?(this.queues=this.queues.filter(e=>null!==this.getQueueId(e)),void this.sendNextQueue()):e.queue&&e.nextKey?void this.sendLastSession(e.queue,e.nextKey):void 0;const{queue:r,queueId:s}=t;if(this.offlineMessageSyncing&&this.offlineMessageQueueNames.has(s)){const t=this.offlineMessageQueueCounts.get(s)??0;this.offlineMessageQueueCounts.set(s,t+e.messages.length),this.offlineMessageTotalCount+=e.messages.length}const n=e.nextKey;if(e.isLast)return this.finishOfflineMessageQueue(s),this.removeQueueEntry(r),this.nextKey=null,this.currentQueueId=null,this.currentQueue=null,void this.sendNextQueue();if(n){if(n!==this.nextKey||!this.isSameQueue(r,this.currentQueue))return this.nextKey=n,this.currentQueueId=s,this.currentQueue=r,void this.sendLastSession(r,n);this.removeQueueEntry(r),this.sendNextQueue()}}resolveSyncQueueState(e){const t=e.queue&&"object"==typeof e.queue?e.queue:void 0,r=t?this.getQueueName(t):null,s=t?this.getQueueId(t):null,n=void 0!==t&&null!==s&&(0===this.queues.length||this.queues.some(e=>this.isSameQueue(e,t)));if(t&&s&&n)return{queue:t,queueId:s};const i=this.currentQueue&&this.queues.some(e=>this.isSameQueue(e,this.currentQueue))?this.currentQueue:void 0,o=this.currentQueueId?this.queues.find(e=>this.getQueueId(e)===this.currentQueueId):void 0,a=i??o??this.queues[0],c=a?this.getQueueName(a):null,d=a?this.getQueueId(a):null;return a&&d?(Si("Sync queue response did not match a tracked queue, fallback to local queue",{responseQueueName:r,responseQueueId:s,fallbackQueueName:c,fallbackQueueId:d,currentQueueId:this.currentQueueId,firstQueueName:this.getQueueName(this.queues[0]??{}),firstQueueId:this.getQueueId(this.queues[0]??{}),isLast:e.isLast,hasNextKey:Boolean(e.nextKey)}),{queue:a,queueId:d}):null}handleLogoutMessage(e){const t=this.msyncCodec.decodeLogout(e);Si("Logout message received",t)}resolveStatisticDisconnectError(e){for(const t of e)switch(t.operation){case 1:return new Wr("User has been removed",{code:Ht,details:{stage:"statistics",operation:t.operation,retryable:!1}});case 2:return new Wr("The user is already logged on another device",{code:Kt,details:{stage:"statistics",operation:t.operation,retryable:!1,...t.reason?{loginInfoCustomExt:t.reason}:{}}});case 3:return new Wr("The user was kicked by changing password",{code:Vt,details:{stage:"statistics",operation:t.operation,retryable:!1}});case 4:return new Wr("The user was kicked by other device",{code:Wt,details:{stage:"statistics",operation:t.operation,retryable:!1}})}return null}resetProvisionHandlers(){this.provisionResolve=null,this.provisionReject=null,this.provisionPromise=null}rejectPendingProvision(e){const t=this.provisionReject;return!!t&&(this.provisionTimeoutId&&(clearTimeout(this.provisionTimeoutId),this.provisionTimeoutId=null),t(e),this.resetProvisionHandlers(),!0)}disconnect(){return this.provisionTimeoutId&&(clearTimeout(this.provisionTimeoutId),this.provisionTimeoutId=null),this.clearReconnectTimer(),this.clearTokenTimers(),this.tokenLifecycle=null,this.resetProvisionHandlers(),this.stopHeartbeat(),this.reconnectPaused=!0,this.reconnectInProgress=!1,this.isLoginPhase=!1,this.isLoggedIn=!1,this.offlineRecoverPending=!1,this.closeWebSocket(R,!0,!0),this.updateStatus(t,R,!0),this.resetSyncState(),this.reconnectAttempts=0,this.connection.reconnectAttempts=0,this.connection.error=void 0,this.hasEverConnected=!1,this.connectionEventNormalizer.reset(),Si("Connection disconnected"),Promise.resolve()}destroy(){this.disconnect(),this.eventHub.removeEventHandler(this.internalHandlerId)}resolveSocketAdapter(e){if(e.socketAdapter)return e.socketAdapter;const t=Ld({webSocketCtor:"function"==typeof WebSocket?WebSocket:void 0});if(t)return t;throw Fi("Socket capability is missing for current platform",{code:"PLATFORM_MISSING_CAPABILITY",stage:"socket",retryable:!1,details:{capability:"socket"}})}attachSocketListeners(e,t){this.clearSocketListeners(),this.socketDisposers=[e.onMessage(r=>{this.websocket===e&&(this.inboundMessageQueue=this.inboundMessageQueue.catch(()=>{}).then(()=>this.handleWebSocketMessage(r,t)))}),e.onError(()=>{if(this.websocket!==e)return;Si("WebSocket error",{stage:"ws"});const t=new Wr("WebSocket connection error",{code:gt,details:{stage:"ws"}});this.handleConnectionError(t,A)}),e.onClose(t=>{this.websocket===e&&this.handleWebSocketClose(t)})]}clearSocketListeners(){for(const e of this.socketDisposers)e();this.socketDisposers=[]}sendMsyncPayload(e){if(this.websocket&&this.websocket.readyState===ji)try{const t=this.msyncCodec.prepareOutgoing(e);Ci("WebSocket send payload",{length:t.length}),Promise.resolve(this.websocket.send(t)).catch(e=>{Ti("Failed to send mSync payload",e),this.websocket?.close()})}catch(t){Ti("Failed to send mSync payload",t),this.websocket?.close()}}sendBackqueue(e){this.currentQueue=e,this.currentQueueId=this.getQueueId(e),this.nextKey=null;const t=this.msyncCodec.encodeBackQueue(e);Ci("sendBackqueue payload",{length:t.length}),this.sendMsyncPayload(t)}sendLastSession(e,t){Ci("sendLastSession queue",{queueName:this.getQueueName(e),nextKey:t});const r=this.msyncCodec.encodeLastSession(e,t);this.sendMsyncPayload(r)}sendNextQueue(){Ci("sendNextQueue queues",{size:this.queues.length});const e=this.queues[0];e&&this.sendBackqueue(e)}removeQueueEntry(e){const t=this.queues.findIndex(t=>this.isSameQueue(t,e));t>=0&&this.queues.splice(t,1)}startOfflineMessageSync(e){const t=new Set;for(const r of e){const e=this.getQueueId(r);e&&t.add(e)}if(0!==t.size){for(const e of t)this.offlineMessageQueueNames.add(e);if(!this.offlineMessageSyncing){this.offlineMessageSyncing=!0,this.offlineMessageSyncLifecycleActive=!this.offlineMessageSyncLifecycleDispatched,this.offlineMessageSyncLifecycleActive&&(this.offlineMessageSyncLifecycleDispatched=!0),this.offlineMessageTotalCount=0,this.offlineMessageQueueCounts.clear(),this.offlineMessageQueueReports.clear(),this.offlineMessageReport=Wh({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(p,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(h,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 Qh=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()}},Yh=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},Xh=()=>{const e=Vi().crypto;return e&&"function"==typeof e.randomUUID?e.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`},em=new Uint8Array([99,109]),tm=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),rm=e=>Array.isArray(e)&&e.every(tm),sm=e=>"string"==typeof e?e:void 0,nm=e=>"number"==typeof e&&Number.isFinite(e)?e:void 0,im=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},om=(e,t)=>{const r=e[t],s=e[t+1],n=e[t+2],i=e[t+3];if("number"!=typeof r||"number"!=typeof s||"number"!=typeof n||"number"!=typeof i)throw new Yr("Combine payload length header is invalid",{code:lr});return r<<24|s<<16|n<<8|i},am=e=>{let t=0;for(let r=2;r<e.length;r+=1)r%2==1&&(t^=e[r]??0);return t},cm=(e,t)=>{const r=cl().lookupType(e).decode(t);if(!tm(r))throw new Error(`${e} decoded result is invalid`);return r},dm=e=>tm(e)&&"string"==typeof e.name?e.name:"",um=(e,t,r)=>{const s=(rm(e.contents)?e.contents:[])[0];if(!s)throw new Error("MessageBody contents is empty");const n=(e=>{const t=nm(e.type)??ys,r=Boolean(sm(e.remotePath))||Boolean(sm(e.title))||Boolean(sm(e.summary))||(nm(e.combineLevel)??0)>0,s=t===ys&&0===e.subType&&r;if(t===_s||s){const t=nm(e.combineLevel)??0;return{type:"combine",body:{title:sm(e.title)??"",summary:sm(e.summary)??"",filename:sm(e.displayName)??"combine",filetype:"application/octet-stream",url:sm(e.remotePath),secret:sm(e.secretKey),fileLength:nm(e.fileLength),combineLevel:t},combineLevel:t}}if(t===ys)return{type:"text",body:{content:sm(e.text)??""}};if(t===Ss)return{type:"cmd",body:{action:sm(e.action)??""}};if(t===Ts){const t=gl(rm(e.customExts)?e.customExts:void 0);return{type:"custom",body:{event:sm(e.customEvent)??"",params:t}}}if(t===Is)return{type:"location",body:{latitude:nm(e.latitude)??0,longitude:nm(e.longitude)??0,address:sm(e.address),buildingName:sm(e.buildingName)}};if(t===vs){const t=tm(e.size)?e.size:{},r=sm(e.remotePath)??"",s=ni(r),n=sm(e.thumbnailRemotePath),i=oi(e.imageType)===Wn;return{type:"image",body:{localUrl:"",filename:sm(e.displayName)??"image",filetype:"application/octet-stream",width:nm(t.width)??0,height:nm(t.height)??0,isGif:1===e.subType,isOriginalImage:i,originalImageUrl:s.originalImageUrl,bigImageUrl:s.bigImageUrl,secret:sm(e.secretKey),fileLength:nm(e.fileLength),thumbnailUrl:n??s.thumbnailUrl}}}if(t===bs){const t=tm(e.size)?e.size:{};return{type:"video",body:{url:sm(e.remotePath)??"",filename:sm(e.displayName)??"video",filetype:"application/octet-stream",duration:nm(e.duration)??0,width:nm(t.width),height:nm(t.height),secret:sm(e.secretKey),fileLength:nm(e.fileLength),thumbnailUrl:sm(e.thumbnailRemotePath)}}}if(t===ws)return{type:"voice",body:{url:sm(e.remotePath)??"",filename:sm(e.displayName)??"voice",filetype:"application/octet-stream",duration:nm(e.duration)??0,secret:sm(e.secretKey),fileLength:nm(e.fileLength)}};if(t===Cs)return{type:"file",body:{url:sm(e.remotePath)??"",filename:sm(e.displayName)??"file",filetype:"application/octet-stream",secret:sm(e.secretKey),fileLength:nm(e.fileLength)}};return null})(s);if(!n)throw new Error("MessageBody content type is unsupported");const i=dm(e.from)||dm(r?.from)||`unknown-${t}`,o=dm(e.to)||dm(r?.to)||`unknown-${t}`,a=(c=e.type)===us?"groupChat":c===ls?"chatRoom":"singleChat";var c;const d=o||i,u=Number(ml(r?.timestamp))||Date.now(),l=gl(rm(e.ext)?e.ext:void 0),p={msgServerId:ml(r?.id),msgLocalId:"",type:n.type,sender:{userId:i},conversationId:d,conversationType:a,timestamp:u,body:n.body,ext:l};return"number"==typeof n.combineLevel&&(p.body.combineLevel=n.combineLevel),p},lm=(e,t)=>{const r=[];try{const n=cm("easemob.pb.Meta",e),i=(s=n.payload)instanceof Uint8Array?s:s instanceof ArrayBuffer?new Uint8Array(s):ArrayBuffer.isView(s)?new Uint8Array(s.buffer,s.byteOffset,s.byteLength):void 0;if(i&&i.length>0){const e=cm("easemob.pb.MessageBody",i);return um(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=cm("easemob.pb.MessageBody",e);return um(r,t)}catch(n){r.push(n instanceof Error?n.message:String(n))}try{const r=cm("easemob.pb.MessageBody.Content",e);return um({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("; "))},pm=(e,t)=>{const r=Ri(e);try{const e=JSON.parse(r);if(!tm(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 lm(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)}})}}},hm=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),mm=(e,t,r)=>{throw new Zr(e,{code:r,details:{fields:[{path:t,message:e,rule:"invalid_format"}]}})},fm=e=>{if("combine"!==e.type)return 0;const t=e.combineLevel;return"number"==typeof t?t:hm(e.body)&&"number"==typeof e.body.combineLevel?e.body.combineLevel:0},gm=(e,t)=>{if(e.sender.userId||mm(`messageList[${t}] sender.userId is required`,`messageList[${t}].sender.userId`,or),e.conversationId&&["singleChat","groupChat","chatRoom"].includes(e.conversationType)||mm(`messageList[${t}] conversation is invalid`,`messageList[${t}].conversationId`,or),(!Number.isInteger(e.timestamp)||e.timestamp<=0)&&mm(`messageList[${t}] timestamp must be positive integer`,`messageList[${t}].timestamp`,or),hm(e.body)||mm(`messageList[${t}] body must be object`,`messageList[${t}].body`,or),"combine"===e.type){const r=fm(e);(!Number.isInteger(r)||r<0)&&mm(`messageList[${t}] combineLevel is invalid`,`messageList[${t}].combineLevel`,or),r>10&&mm(`messageList[${t}] combineLevel exceeds limit`,`messageList[${t}].combineLevel`,ar)}},ym=(e,t=300)=>{(!Number.isInteger(e)||e<=0)&&mm("messageList must not be empty","messageList",or),(!Number.isInteger(t)||t<=0||t>300)&&mm("max items is invalid","maxItems",or),e>t&&mm(`messageList max length is ${t}`,"messageList",cr)},vm=e=>{ym(e.length);for(let t=0;t<e.length;t+=1){const r=e[t];void 0!==r?gm(r,t):mm(`messageList[${t}] is required`,`messageList[${t}]`,or)}},bm=e=>{let t=0;for(const r of e){if("combine"!==r.type)continue;const e=fm(r);e>t&&(t=e)}return t+1},Im=e=>{(!Number.isInteger(e)||e<=0)&&mm("combineLevel must be positive integer","combineLevel",or),e>10&&mm("combineLevel must be <= 10","combineLevel",ar)},wm=e=>"groupChat"===e?1:"chatRoom"===e?2:0;class Cm{constructor(e,t,r,s){this.websocket=null,this.pendingMessages=new Map,this.ackTimeout=15e3,this.attachmentUploader=null,this.messageReportCount=0,this.chatRoomReportCount=0,this.messageReportSaturated=!1,this.chatRoomReportSaturated=!1,this.websocket=t,this.eventHub=r,this.msyncCodec=e,this.attachmentUploader=s??null}updateAuthToken(e){this.attachmentUploader?.updateAuthToken(e)}async sendMessage(e,t){const r=this.msyncCodec.toProtocolId(e.msgLocalId);if(st(e))throw new Qr("Stream message send is not supported",{code:ir,details:{msgLocalId:e.msgLocalId,retryable:!1}});if(!this.websocket||this.websocket.readyState!==ji){const t=this.msyncCodec.toProtocolId(e.msgLocalId);throw new Qr("WebSocket is not connected",{code:St,details:{msgLocalId:e.msgLocalId,protocolId:t,retryable:!0}})}let s={...e,sendStatus:"sending"};lp(e,s),Ci("Message send queued",{msgLocalId:e.msgLocalId,protocolId:r,type:e.type,conversationType:e.conversationType,conversationId:e.conversationId});try{const e="combine"===s.type?this.prepareCombineMessage(s):s,r={...this.attachmentUploader?await this.attachmentUploader.prepareMessage(e,t):e,sendStatus:"sending"};lp(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 lp(s,e),t?.onFailed?.(e,n instanceof Error?n:new Error(String(n))),n}}async sendAction(e,t){const r=this.msyncCodec.toProtocolId(`${e.kind}:${e.messageId??e.conversationId}:${Date.now()}`);"clearAllConversationUnreadMessageCount"===e.kind&&Ci("Clear-all unread action encode started",{operation:"message.action.clear-all-unread.encode",protocolId:r,conversationId:e.conversationId,conversationType:e.conversationType,sendToPeer:e.sendToPeer,clearAllUnreadMessageCount:e.clearAllUnreadMessageCount});const s=this.msyncCodec.encodeActionMessage(e,r);"clearAllConversationUnreadMessageCount"===e.kind&&Ci("Clear-all unread action encoded",{operation:"message.action.clear-all-unread.encoded",protocolId:r,payloadBytes:s.byteLength});const n="recall"===e.kind?"MSYNC_RECALLMESSAGE":"update"===e.kind?"MSYNC_MODIFYMESSAGE":`MSYNC_${e.kind.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toUpperCase()}`;return this.sendProtocolPayload(r,s,t,this.createPendingDataReport({category:"message",operationName:n,operationType:"MESSAGE",requestName:n,msgId:e.messageId,messageType:wm(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:wm(e.conversationType)});return new Promise((r,s)=>{const n=this.msyncCodec.toProtocolId(e.msgLocalId),i=setTimeout(()=>{this.pendingMessages.delete(n),this.finishPendingDataReport(t,{code:Tt,success:!1,description:"Message ACK timeout"}),s(new Qr("Message ACK timeout",{code:Tt,details:{msgLocalId:e.msgLocalId,protocolId:n,retryable:!0}}))},this.ackTimeout);this.pendingMessages.set(n,{kind:"message",message:e,protocolId:n,timeoutId:i,resolve:e=>{clearTimeout(i),r(e)},reject:e=>{clearTimeout(i),s(e)},report:t});try{if(!this.websocket||this.websocket.readyState!==ji)throw new Qr("WebSocket is not connected",{code:St,details:{msgLocalId:e.msgLocalId,protocolId:n,retryable:!0}});const r=this.msyncCodec.encodeChatMessage(e,n),o=this.msyncCodec.prepareOutgoing(r);Promise.resolve(this.websocket.send(o)).catch(r=>{const o=r instanceof Error?r.message:String(r);this.pendingMessages.delete(n),clearTimeout(i),this.finishPendingDataReport(t,{code:-1,success:!1,description:o}),Si("Message send socket failure",{msgLocalId:e.msgLocalId,protocolId:n,websocketReadyState:this.websocket?.readyState??null,cause:o}),s(new Qr(`WebSocket send failed: ${o}`,{code:St,details:{msgLocalId:e.msgLocalId,protocolId:n,retryable:!0,cause:o}}))}),Ci("Message sent",{msgLocalId:e.msgLocalId,protocolId:n})}catch(o){if(this.pendingMessages.delete(n),clearTimeout(i),this.finishPendingDataReport(t,{code:o instanceof Qr?o.code:At,success:!1,description:o instanceof Error?o.message:String(o)}),o instanceof Qr)throw o;throw new Qr("Message encode failed",{code:At,details:{msgLocalId:e.msgLocalId,protocolId:n,retryable:!0}})}})}async sendProtocolPayload(e,t,r,s){return new Promise((n,i)=>{const o=setTimeout(()=>{this.pendingMessages.delete(e),this.finishPendingDataReport(s,{code:Tt,success:!1,description:"Message ACK timeout"}),i(new Qr("Message ACK timeout",{code:Tt,details:{protocolId:e,retryable:!0}}))},this.ackTimeout);this.pendingMessages.set(e,{kind:"action",protocolId:e,timeoutId:o,createAckError:r,resolve:n,reject:i,report:s});try{if(!this.websocket||this.websocket.readyState!==ji)throw new Qr("WebSocket is not connected",{code:St,details:{protocolId:e,retryable:!0}});const r=this.msyncCodec.prepareOutgoing(t);Promise.resolve(this.websocket.send(r)).catch(t=>{const r=t instanceof Error?t.message:String(t);this.pendingMessages.delete(e),clearTimeout(o),this.finishPendingDataReport(s,{code:-1,success:!1,description:r}),i(new Qr(`WebSocket action send failed: ${r}`,{code:St,details:{protocolId:e,retryable:!0,cause:r}}))})}catch(a){if(this.pendingMessages.delete(e),clearTimeout(o),this.finishPendingDataReport(s,{code:a instanceof Qr?a.code:At,success:!1,description:a instanceof Error?a.message:String(a)}),a instanceof Qr)throw a;i(new Qr("Message encode failed",{code:At,details:{protocolId:e,retryable:!1}}))}})}prepareCombineMessage(e){const t=e.body,r=t.messageList??[];vm(r);const s=bm(r);Im(s);const n=(e=>{try{const t=e.map((e,t)=>{const r=JSON.stringify(e);if(!r)throw new Qr("Combine payload item encode failed",{code:dr,details:{index:t}});return _i(r)}),r=em.length+t.reduce((e,t)=>e+4+t.length,0)+1,s=new Uint8Array(r);let n=0;s.set(em,n),n+=em.length;for(const e of t){const t=im(e.length);s.set(t,n),n+=t.length,s.set(e,n),n+=e.length}const i=am(s.subarray(0,s.length-1));return s[s.length-1]=i,s}catch(t){if(t instanceof Qr)throw t;throw new Qr("Combine payload encode failed",{code:dr,details:{cause:t instanceof Error?t.message:String(t)}})}})(r),i=new ArrayBuffer(n.byteLength);new Uint8Array(i).set(n);const o=new File([i],t.filename||"combine",{type:t.filetype||"application/octet-stream"}),a=Yh(o);if(!a&&!this.attachmentUploader)throw new Qr("Combine payload local url generation failed",{code:dr});Qh.set(e.msgLocalId,o);const c={...e,body:{...t,combineLevel:s,fileLength:n.byteLength,filename:t.filename||"combine",filetype:t.filetype||"application/octet-stream",url:a??t.url}};return lp(e,c),gp(e,c),c}handleAck(e,t,r,s){const n=this.pendingMessages.get(e);if(!n)return void Ci("Received ACK without a tracked pending message",{protocolId:e});if("action"===n.kind)return this.pendingMessages.delete(e),this.finishPendingDataReport(n.report,{code:200,success:!0}),void n.resolve({protocolId:e,serverId:t??"",statusCode:0,chatRoomInfo:s});const i={...n.message,...this.resolveReplacedMessage(n.message,r),sendStatus:"sent",msgServerId:t||r?.msgServerId||n.message.msgServerId};lp(n.message,i),this.pendingMessages.delete(e),this.finishPendingDataReport(n.report,{code:200,success:!0}),"image"!==i.type&&"video"!==i.type&&"voice"!==i.type&&"file"!==i.type&&"combine"!==i.type||Qh.delete(i.msgLocalId),Ci("Message ACK matched",{protocolId:e,msgLocalId:i.msgLocalId,msgServerId:i.msgServerId??null,type:i.type,conversationType:i.conversationType,conversationId:i.conversationId}),this.eventHub.dispatch(b,i),n.resolve(i)}resolveReplacedMessage(e,t){return t?{type:t.type,body:t.body,ext:t.ext,timestamp:t.timestamp||e.timestamp}:{}}handleSendError(e,t){const r=this.pendingMessages.get(e);if(!r)return;if("action"===r.kind)return this.pendingMessages.delete(e),this.finishPendingDataReport(r.report,{code:t instanceof Qr?t.code:-1,success:!1,description:t.message}),void r.reject(t);const s={...r.message,sendStatus:"failed"};lp(r.message,s),this.pendingMessages.delete(e),this.finishPendingDataReport(r.report,{code:t instanceof Qr?t.code:-1,success:!1,description:t.message}),Si("Message send failed after ACK/error",{protocolId:e,msgLocalId:s.msgLocalId,type:s.type,conversationType:s.conversationType,conversationId:s.conversationId,error:t.message}),r.reject(t)}handleAckFailure(e,t,r,s){const n=this.pendingMessages.get(e);if(n)return"action"===n.kind?(this.pendingMessages.delete(e),this.finishPendingDataReport(n.report,{code:t,success:!1,description:r??s.message}),void n.reject(n.createAckError?.(t,r)??s)):void this.handleSendError(e,s)}setWebSocket(e){this.websocket=e}destroy(){for(const[e,t]of this.pendingMessages)clearTimeout(t.timeoutId),this.finishPendingDataReport(t.report,{code:-1,success:!1,description:"Message sender destroyed"}),t.reject(new Qr("Message sender destroyed",{code:Rt,details:"message"===t.kind?{msgLocalId:t.message.msgLocalId,protocolId:e,retryable:!1}:{protocolId:e,retryable:!1}}));this.pendingMessages.clear()}createPendingDataReport(e){if(("message"===e.category?this.messageReportCount:this.chatRoomReportCount)>=Dh){return void(("message"===e.category?this.messageReportSaturated:this.chatRoomReportSaturated)||(Si("DataReport correlation limit reached",{category:e.category}),"message"===e.category?this.messageReportSaturated=!0:this.chatRoomReportSaturated=!0))}const t=Wh({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<Dh&&(this.messageReportSaturated=!1)):(this.chatRoomReportCount=Math.max(0,this.chatRoomReportCount-1),this.chatRoomReportCount<Dh&&(this.chatRoomReportSaturated=!1)))}}class Sm{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 Tm{constructor(e,t){this.completedIds=new Set,this.eventHub=e,this.cache=t??new Sm}handle(e){const t=this.resolveMessageId(e);if(!t)return void Si("stream message id missing, skip dispatch");if(this.completedIds.has(t))return void Ci("stream message already completed, ignore",{msgId:t});if(e.stream.status===rt.FULL)return void this.handleFullChunk(t,e);const r=this.cache.get(t);if(r?.completed)return void Ci("stream session completed, ignore chunk",{msgId:t,seq:e.stream.seq});const{duplicate:s}=this.cache.addChunk(t,e);s?Ci("stream duplicate chunk ignored",{msgId:t,seq:e.stream.seq}):e.stream.errorType>0?this.dispatchServerError(t,e):this.dispatchSequentialChunks(t)}destroy(){this.cache.clearAll(),this.completedIds.clear()}dispatchSequentialChunks(e){const t=this.cache.getSequentialChunks(e);if(0!==t.length)for(const r of t){const t=this.cache.get(e);if(!t)return;const s=t.fullText,n=r.stream.deltaText,i=`${s}${n}`,o=r.stream.errorType>0?rt.ERROR:r.stream.status,a=this.buildDispatchMessage(r,{status:o,fullText:i,deltaText:n});if(this.eventHub.dispatch(N,a),this.cache.markDispatched(e,r,i),o===rt.START_COMPLETED||o===rt.COMPLETED||o===rt.ERROR){const t=o===rt.ERROR?"timeout_error":"normal";return this.cache.markCompleted(e,t,i),this.cache.clear(e),void this.markCompleted(e)}}else Ci("stream chunks pending for missing seq",{msgId:e})}handleFullChunk(e,t){const r=this.cache.get(e),s=r?.fullText??"",n=this.resolveFullText(t,s),i=this.resolveDeltaText(s,n,t.stream.deltaText),o=!r||-1===r.lastDispatchedSeq&&0===r.chunksBySeq.size,a=t.stream.errorType>0?rt.ERROR:o?rt.START_COMPLETED:rt.COMPLETED,c=this.buildDispatchMessage(t,{status:a,fullText:n,deltaText:i});this.eventHub.dispatch(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),i=this.resolveDeltaText(s,n,t.stream.deltaText),o=this.buildDispatchMessage(t,{status:rt.ERROR,fullText:n,deltaText:i});this.eventHub.dispatch(N,o),this.cache.markCompleted(e,"timeout_error",n),this.cache.clear(e),this.markCompleted(e)}buildDispatchMessage(e,t){return{...e,body:{...e.body,content:t.fullText},stream:{...e.stream,status:t.status,fullText:t.fullText,deltaText:t.deltaText}}}resolveMessageId(e){return e.msgServerId&&e.msgServerId.length>0?e.msgServerId:e.msgLocalId}resolveFullText(e,t){const r=e.stream.fullText;if(r&&r.length>=t.length)return r;const s=e.body.content;return s&&s.length>=t.length?s:`${t}${e.stream.deltaText}`}resolveDeltaText(e,t,r){return t.startsWith(e)?t.slice(e.length):r}markCompleted(e){if(this.completedIds.add(e),this.completedIds.size<=2048)return;const t=this.completedIds.values().next().value;t&&this.completedIds.delete(t)}}class _m{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 Rm=e=>"object"==typeof e&&null!==e&&!Array.isArray(e);class Am{constructor(e,t,r){this.eventHub=r,this.messageSender=t,this.msyncCodec=e,this.streamMessageHandler=new Tm(r),this.messageContexts=new Map,this.recentMessageIds=new _m(100),this.enableDeliveryReceipt=!1}setDeliveryAckEnabled(e){this.enableDeliveryReceipt=e}rememberSentMessageContext(e){"sent"===e.sendStatus&&(this.rememberMessageContext(e),this.recentMessageIds.checkAndRecord(this.resolveMessageContextId(e)))}handleSyncPayload(e){try{Ci("handleSyncPayload payload",{length:e.length});const t=this.msyncCodec.decodeSync(e);Ci("handleSyncPayload result",{ack:Boolean(t.ack),messageCount:t.messages.length});const{ack:r,messages:s}=t;t.notifies&&t.notifies.length>0&&this.handleNotifies(t.notifies),r&&(Ci("Decoded sync ACK",{ok:r.ok,protocolId:r.protocolId,serverId:r.serverId??null,statusCode:r.statusCode??null,reason:r.reason??null,hasReplacedMessage:Boolean(t.replacedMessage)}),this.handleAck(r,t.replacedMessage));for(const e of s)this.dispatchMessage(e);return t}catch(t){Ti("Failed to decode sync payload",t)}return null}handleAck(e,t){if(e.ok)return Ci("ACK accepted",{protocolId:e.protocolId,serverId:e.serverId??null,hasReplacedMessage:Boolean(t)}),void(e.chatRoomInfo?this.messageSender.handleAck(e.protocolId,e.serverId,t,e.chatRoomInfo):this.messageSender.handleAck(e.protocolId,e.serverId,t));Si("ACK rejected",{protocolId:e.protocolId,statusCode:e.statusCode,reason:e.reason,hasReplacedMessage:Boolean(t)});const r=((e,t)=>{const r=Nn(e,t),s=r.code===Br?_t:r.code;return{code:s,message:On[s]??(t?`Message send failed: ${t}`:"Message send failed for an unknown reason"),retryable:r.retryable}})(e.statusCode,e.reason),s=new Qr(r.message,{code:r.code,details:{protocolId:e.protocolId,serverCode:e.statusCode,reason:e.reason,retryable:!1}});this.messageSender.handleAckFailure(e.protocolId,e.statusCode,e.reason,s)}dispatchMessage(e){if(st(e))return void this.streamMessageHandler.handle(e);this.rememberMessageContext(e),this.sendDeliveryAckIfNeeded(e);const t=this.resolveMessageContextId(e);this.recentMessageIds.checkAndRecord(t)?Ci("Duplicate message ignored",{messageId:t}):(this.eventHub.dispatch(k,e),Ci("Message received",{msgServerId:e.msgServerId}))}sendDeliveryAckIfNeeded(e){if(!this.enableDeliveryReceipt)return;if("singleChat"!==e.conversationType)return;const t=this.msyncCodec.getContext().userId;t&&e.from!==t&&this.messageSender.sendAction({kind:"deliveryAck",conversationId:e.from,conversationType:"singleChat",messageId:e.msgServerId??e.msgLocalId}).catch(e=>{Si("Failed to send delivery ack",e)})}handleNotifies(e){const t=[];for(const r of e)if("presence"===r.type)this.handlePresenceNotify(r);else if("contact"===r.type)this.handleContactNotify(r);else if("group"===r.type)this.handleGroupNotify(r);else if("thread"===r.type)this.handleChatThreadNotify(r);else if("chatroom"===r.type)this.handleChatRoomNotify(r);else if("reaction"===r.type)this.handleReactionNotify(r);else if("conv"===r.type)this.handleConversationNotify(r);else if("multiDevice"===r.type)this.handleMultiDeviceNotify(r);else if("message_receipts"===r.type){const e=this.toMessageReceiptPayload(r);e&&t.push(e)}else"message_recalled"===r.type?this.handleMessageRecalledNotify(r):"message_updated"===r.type?this.handleMessageUpdatedNotify(r):"message_delivered"===r.type?this.handleMessageDeliveredNotify(r):this.handleUserInfoNotify(r);t.length>0&&this.eventHub.dispatch(x,t)}handleUserInfoNotify(e){const t="subscribe_metadata_updated"===e.type||"contact_metadata_updated"===e.type||"user_metadata_updated"===e.type?e.type:"subscribe_metadata_updated"===e.eventName||"contact_metadata_updated"===e.eventName||"user_metadata_updated"===e.eventName?e.eventName:null;if(!t)return;const r=e.data;if(!r||"object"!=typeof r)return;const s=r,n="string"==typeof s.username?s.username:"string"==typeof s.userId?s.userId:"user_metadata_updated"===t?this.msyncCodec.getContext().userId:"",i=s.metadata&&"object"==typeof s.metadata&&!Array.isArray(s.metadata)?s.metadata:null,o="number"==typeof s.lastModified?s.lastModified:"string"==typeof s.lastModified?Number(s.lastModified):Number.NaN;if(!n||!i||!Number.isFinite(o))return;const a={notifyType:t,userId:n,metadata:i,lastModified:o};this.eventHub.dispatch(v,a)}handleContactNotify(e){if(Ci("[RosterSync] handleContactNotify",{eventName:e.eventName,type:e.type}),"string"!=typeof e.eventName)return;if(e.eventName!==K&&e.eventName!==H&&e.eventName!==V&&e.eventName!==W&&e.eventName!==J)return;const t=e.data;if(!t||"object"!=typeof t)return;const r=t;"string"==typeof r.from&&r.from&&"string"==typeof r.to&&r.to&&"string"==typeof r.message&&this.eventHub.dispatch(e.eventName,r)}handlePresenceNotify(e){const t=e.data;if(!t||"object"!=typeof t)return;const r=t,s=Array.isArray(r.values)?r.values:[];if(0===s.length)return;const n=[];for(const i of s){if(!i||"object"!=typeof i)continue;const e=i,t=this.normalizePresenceStatus(e.status),r="string"==typeof e.uid?e.uid:"";r&&n.push({userId:r,statusDetails:t,ext:"string"==typeof e.ext?e.ext:"",lastTime:Number(e.last_time)||0,expire:Number(e.expiry)||0})}0!==n.length&&this.eventHub.dispatch(z,n)}handleGroupNotify(e){const t=e.data;if(!t||"object"!=typeof t)return;const r=t;"string"==typeof r.eventName&&r.payload&&"object"==typeof r.payload&&this.eventHub.dispatch(f,r)}handleChatRoomNotify(e){const t=e.data;if(!t||"object"!=typeof t)return;const r=t;"string"==typeof r.eventName&&r.payload&&"object"==typeof r.payload&&this.eventHub.dispatch(g,r)}handleReactionNotify(e){const t=Array.isArray(e.data)?e.data:[];for(const r of t){if(!Rm(r)||"string"!=typeof r.messageId)continue;const e=this.resolveReactionConversationContext(r);e&&this.eventHub.dispatch(q,{messageId:r.messageId,conversationId:e.conversationId,conversationType:e.conversationType,from:e.from,to:e.to,reactions:this.normalizeReactionList(r.reactions),timestamp:this.normalizeTimestamp(r.ts)})}}handleConversationNotify(e){if(!Rm(e.data))return;const t=e.data;if("pin"!==t.op&&"pin_delete"!==t.op)return;const r=this.msyncCodec.getContext();if("string"==typeof t.res&&t.res===r.clientResource&&"string"==typeof t.from&&t.from===r.userId)return;const s="string"==typeof t.ext?t.ext:"",n="string"==typeof t.type?t.type:"",i="string"==typeof t.from?t.from:"",o="string"==typeof t.id?t.id:"";s&&i&&o&&this.eventHub.dispatch($,{messageId:s,conversationId:"chat"===n?i:o,conversationType:"chat"===n?"singleChat":"groupChat",operation:"pin"===t.op?"pin":"unpin",operatorId:i,pinTime:"number"==typeof t.ts?t.ts:Number(t.ts)||void 0})}handleMultiDeviceNotify(e){if(!Rm(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(!Rm(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(!Rm(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(!Rm(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(!Rm(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(!Rm(e.data))return;const t=e.data;if("string"!=typeof t.messageId||"string"!=typeof t.conversationId||"string"!=typeof t.conversationType||!Rm(t.message)||"string"!=typeof t.message.type||!Rm(t.message.body)||!Rm(t.message.ext))return;const r={type:t.message.type,body:this.normalizeUpdatedMessageBody(t.message.type,t.message.body),ext:t.message.ext,...Rm(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)Rm(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)!Rm(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 Mm=e=>e instanceof Error?e.message:String(e);class Em{constructor(e){this.requestAdapter=(e=>e||("function"==typeof fetch?Md({fetchImpl:fetch}):void 0))(e)}async downloadAndParse(e){const t=e.url.trim();if(!t)throw new Zr("Combine message url is required",{code:or,details:{fields:[{path:"url",message:"Combine message url is required",rule:"required"}]}});const r="number"==typeof e.maxItems?e.maxItems:300;ym(1,r);const s=this.requestAdapter;if(!s)throw new Yr("Request adapter is required for combine message download",{code:ur});const n=ri(t,e.secret);try{const t=await s.request({url:n,method:"GET",responseType:"arraybuffer",timeoutMs:e.timeoutMs??15e3,headers:{[vl]:yl()}});if(401===t.status||403===t.status)throw new Jr(401===t.status?"Combine payload download unauthorized":"Combine payload download forbidden",{code:401===t.status?dt:ut,details:{url:n,httpStatus:t.status}});if(t.status>=400)throw new Yr("Combine payload download failed",{code:ur,details:{status:t.status,url:n}});const i=(e=>{if(e.length<em.length+1)throw new Yr("Combine payload is too short",{code:lr});const t=e.subarray(0,em.length);if(t[0]!==em[0]||t[1]!==em[1])throw new Yr("Combine payload header is invalid",{code:lr});const r=e.subarray(0,e.length-1),s=am(r),n=e[e.length-1]??0;if(n!==s)throw new Yr("Combine payload checksum failed",{code:lr,details:{expectedChecksum:s,actualChecksum:n}});const i=[];let o=em.length;const a=e.length-1;for(;o<a;){if(o+4>a)throw new Yr("Combine payload length header is incomplete",{code:lr});const t=om(e,o);if(o+=4,t<=0||o+t>a)throw new Yr("Combine payload item length is invalid",{code:lr,details:{itemLength:t}});const r=e.subarray(o,o+t);o+=t;const s=pm(r,i.length);i.push(s)}if(o!==a)throw new Yr("Combine payload has unexpected trailing bytes",{code:lr,details:{offset:o,expected:a}});return i})((e=>{if(e instanceof Uint8Array)return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);if("string"==typeof e)return _i(e);throw new Yr("Combine payload response type is invalid",{code:ur})})(t.data));return ym(i.length,r),vm(i),i.map(e=>({msgServerId:e.msgServerId??"",msgLocalId:e.msgLocalId??"",from:e.sender.userId,to:e.conversationId,sender:e.sender,conversationId:e.conversationId,conversationType:e.conversationType,type:e.type,sendStatus:"sent",ext:e.ext??{},timestamp:e.timestamp,body:e.body,direct:"RECEIVE"}))}catch(i){if(i instanceof Zr||i instanceof Jr||i instanceof Yr)throw i;throw new Yr("Combine payload download or parse failed",{code:ur,details:{cause:Mm(i),url:n}})}}}const Um=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"}},km=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 Nm{constructor(e){this.requestAdapter=(e=>e||("function"==typeof fetch?Md({fetchImpl:fetch}):void 0))(e)}async download(e,t=15e3){if("image"!==e.type&&"video"!==e.type&&"voice"!==e.type&&"file"!==e.type)throw new Zr("message does not contain downloadable attachment",{code:Ot,details:{fields:[{path:"message.type",message:"does not contain downloadable attachment",rule:"attachment_type"}]}});const{url:r,secret:s}=(e=>{switch(e.type){case"image":{const t=e.body;return{url:t.originalImageUrl??t.bigImageUrl??t.thumbnailUrl??"",secret:t.secret}}case"video":case"voice":case"file":{const t=e.body;return{url:t.url??"",secret:t.secret}}default:return{url:""}}})(e);if(!r)throw new Zr("attachment url is required",{code:Ot,details:{fields:[{path:"message.body.url",message:"is required",rule:"required"}]}});if(!this.requestAdapter)throw new Vr("request adapter is required for attachment download");const n=await this.requestAdapter.request({url:ri(r,s),method:"GET",responseType:"arraybuffer",timeoutMs:t,headers:{[vl]:yl()}});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",Fr);if(n.status>=400)throw new Hr("attachment download failed",er,{details:{status:n.status,url:r}});return{filename:Um(e),mimeType:km(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 Om=(e,t,r)=>({Authorization:`Bearer ${e}`,Accept:t,[vl]:yl(),...r??{}}),xm=async e=>{const t=Om(e.token,"application/json",e.headers),r=Date.now(),s="upload.multipart.init"===e.operation?"REST_INIT_UPLOAD_TASK_IN_PARTS":"upload.multipart.complete"===e.operation?"REST_COMPLETE_UPLOAD_PART":"REST_ABORT_UPLOAD_PART",n=e.dataReportOperation?.startRequest({requestName:s,method:e.method,url:e.url});let i=0;if(Ci("Upload request start",{operation:e.operation,method:e.method}),e.requestAdapter)try{const s=await e.requestAdapter.request({url:e.url,method:e.method,headers:t,responseType:"json",timeoutMs:xn});i=s.status;const a=Date.now()-r;if(s.status<200||s.status>=300)throw Si("Upload response error",{operation:e.operation,method:e.method,status:s.status,duration:a}),new rs("Upload request failed",{code:qr,details:{url:e.url,status:s.status}});Ci("Upload response success",{operation:e.operation,method:e.method,status:s.status,duration:a});const c="string"==typeof(o=s.data)?JSON.parse(o):o;return n?.finish({code:s.status,success:!0}),c}catch(d){if(n?.finish({code:0!==i?i:d instanceof rs?d.code:qr,success:!1,description:d instanceof Error?d.message:String(d)}),d instanceof rs)throw d;throw Si("Upload request failed",{operation:e.operation,method:e.method}),new rs("Upload request failed",{code:qr,details:{url:e.url}})}var o;const a=new AbortController,c=setTimeout(()=>a.abort(),xn);try{const s=await fetch(e.url,{method:e.method,headers:t,signal:a.signal});i=s.status;const o=Date.now()-r;if(!s.ok)throw Si("Upload response error",{operation:e.operation,method:e.method,status:s.status,duration:o}),new rs("Upload request failed",{code:qr,details:{url:e.url,status:s.status}});return Ci("Upload response success",{operation:e.operation,method:e.method,status:s.status,duration:o}),n?.finish({code:s.status,success:!0}),await s.json()}catch(d){if(n?.finish({code:0!==i?i:d instanceof rs?d.code:qr,success:!1,description:d instanceof Error?d.message:String(d)}),d instanceof rs)throw d;if(d instanceof Error&&"AbortError"===d.name)throw Si("Upload request timeout",{operation:e.operation,method:e.method,timeout:xn}),new rs("Upload timeout",{code:$r,details:{url:e.url,timeout:xn}});throw Si("Upload request failed",{operation:e.operation,method:e.method}),new rs("Upload request failed",{code:qr,details:{url:e.url}})}finally{clearTimeout(c)}},Lm=(e,t,r,s,n,i)=>new Promise((o,a)=>{const c=new XMLHttpRequest,d=Date.now(),u=i?.startRequest({requestName:"REST_UPLOAD_PART",method:"PUT",url:e});Ci("Upload part start",{operation:"upload.multipart.part",partNumber:r}),c.upload&&n&&c.upload.addEventListener("progress",e=>{n(e.loaded)},!1),c.addEventListener("abort",()=>{u?.finish({code:Gr,success:!1,description:"Upload aborted"}),Si("Upload part aborted",{operation:"upload.multipart.part",partNumber:r}),a(new rs("Upload aborted",{code:Gr,details:{url:e,partNumber:r}}))},!1),c.addEventListener("error",()=>{u?.finish({code:qr,success:!1,description:"Upload part failed"}),Si("Upload part failed",{operation:"upload.multipart.part",partNumber:r}),a(new rs("Upload part failed",{code:qr,details:{url:e,partNumber:r}}))},!1),c.addEventListener("timeout",()=>{u?.finish({code:$r,success:!1,description:"Upload timeout"}),Si("Upload part timeout",{operation:"upload.multipart.part",partNumber:r,timeout:xn}),a(new rs("Upload timeout",{code:$r,details:{url:e,partNumber:r}}))},!1),c.addEventListener("load",()=>{const t=Date.now()-d;if(200!==c.status)return u?.finish({code:c.status,success:!1,description:"Upload part failed"}),Si("Upload part error",{operation:"upload.multipart.part",partNumber:r,status:c.status,duration:t}),void a(new rs("Upload part failed",{code:qr,details:{url:e,partNumber:r,status:c.status}}));Ci("Upload part success",{operation:"upload.multipart.part",partNumber:r,duration:t}),u?.finish({code:c.status,success:!0}),o()},!1);const l=new FormData;l.append("part_file",s),l.append("part_number",r),c.timeout=xn,c.open("PUT",e),Object.entries(Om(t,"*/*",{"restrict-access":"true"})).forEach(([e,t])=>{c.setRequestHeader(e,t)}),c.send(l)}),Pm=async e=>{if(e.fileSize<=jn)throw new rs("Multipart not required",{code:qr,details:{reason:"file size below threshold"}});const{config:t,file:r,conversationId:s,conversationType:n,fileName:i,fileType:o,fileSize:a,messageType:c,imageType:d,md5:u,width:l,height:p}=e,{orgName:h,appName:m}=Qn(t.appKey),f=`${t.restBaseUrl}/${h}/${m}/sdk/chatfiles/part-upload`;let g;try{g=await xm({url:f,method:"POST",token:t.token,operation:"upload.multipart.init",requestAdapter:t.requestAdapter,dataReportOperation:e.dataReportOperation})}catch(M){throw new rs("Multipart init failed",{code:qr,details:{stage:"init",cause:M,url:f}})}const y=(e=>{const t=e.entities?.[0],r="number"==typeof t?.file_upper_limit?t.file_upper_limit:0,s="number"==typeof t?.part_lower_limit?t.part_lower_limit:zn,n="string"==typeof t?.uuid?t.uuid:"";if(!n)throw new rs("Multipart init failed",{code:qr,details:{response:e}});return{fileMaxSize:r,partMinSize:s,uuid:n}})(g);if(y.fileMaxSize&&a>y.fileMaxSize)throw new rs("File size exceeds limit",{code:Dr,details:{fileSize:a,maxSize:y.fileMaxSize}});const v=y.partMinSize||zn,b=Math.ceil(a/v),I=Array.from({length:b},()=>0),w=`${t.restBaseUrl}/${h}/${m}/sdk/chatfiles/part-upload/${y.uuid}`,C=[],S=(t,r)=>{I[t]=r;const s=I.reduce((e,t)=>e+t,0),n=a?s/a*100:void 0;e.callbacks?.onFileUploadProgress?.({loaded:s,total:a,percent:n})};for(let E=0;E<b;E+=1){const s=E*v,n=Math.min(a,s+v),i=r.slice(s,n),o=String(E+1),c=Lm(w,t.token,o,i,e=>S(E,e),e.dataReportOperation).finally(()=>{const e=C.indexOf(c);e>=0&&C.splice(e,1)});C.push(c),C.length>=4&&await Promise.race(C)}await Promise.all(C);const T=Yn(n),_=ti(`${t.restBaseUrl}/${h}/${m}/sdk/chatfiles/part-upload/${y.uuid}`,{"restrict-access":"true","chat-type":T,"chat-target":s,"thumbnail-width":e.thumbnailWidth,"thumbnail-height":e.thumbnailHeight,md5:u??"",..."image"===c?{imageType:ii(d),width:l,height:p}:{}}),R=await xm({url:_,method:"POST",token:t.token,operation:"upload.multipart.complete",requestAdapter:t.requestAdapter,dataReportOperation:e.dataReportOperation}),A=ai({response:R,restBaseUrl:t.restBaseUrl,orgName:h,appName:m,fileType:o,fileName:i,fallbackSize:a,messageType:c,imageType:d,useCustomAttachmentUpload:t.useCustomAttachmentUpload});return e.callbacks?.onFileUploadComplete?.(A),A},Dm=e=>new Promise((t,r)=>{const{config:s,file:n,conversationId:i,conversationType:o,messageType:a,imageType:c,md5:d,width:u,height:l,fileName:p,fileType:h,fileSize:m}=e,{orgName:f,appName:g}=Qn(s.appKey),y=Yn(o),v=ti(`${s.restBaseUrl}/${f}/${g}/chatfiles`,{"chat-type":y,"chat-target":i,md5:d??"",..."image"===a?{imageType:ii(c),width:u,height:l}:{}}),b=Date.now(),I=e.dataReportOperation?.startRequest({requestName:"UPLOAD_MSG_ATTACH",method:"POST",url:v});Ci("Upload request start",{operation:"upload.simple",method:"POST",fileSize:m,messageType:a});const w=new XMLHttpRequest;w.upload&&e.callbacks?.onFileUploadProgress&&w.upload.addEventListener("progress",t=>{if(!t.lengthComputable)return void e.callbacks?.onFileUploadProgress?.({loaded:t.loaded});const r=t.total?t.loaded/t.total*100:void 0;e.callbacks?.onFileUploadProgress?.({loaded:t.loaded,total:t.total,percent:r})},!1),w.addEventListener("abort",()=>{I?.finish({code:Gr,success:!1,description:"Upload canceled"}),Si("Upload request aborted",{operation:"upload.simple"}),e.callbacks?.onFileUploadCanceled?.(),r(new rs("Upload canceled",{code:Gr,details:{url:v}}))},!1),w.addEventListener("error",()=>{I?.finish({code:qr,success:!1,description:"Upload failed"}),Si("Upload request failed",{operation:"upload.simple"}),r(new rs("Upload failed",{code:qr,details:{url:v}}))},!1),w.addEventListener("timeout",()=>{I?.finish({code:$r,success:!1,description:"Upload timeout"}),Si("Upload request timeout",{operation:"upload.simple",timeout:xn}),r(new rs("Upload timeout",{code:$r,details:{url:v,timeout:xn}}))},!1),w.addEventListener("load",()=>{try{const r=Date.now()-b,n=JSON.parse(w.responseText);if(w.status>=400)throw I?.finish({code:w.status,success:!1,description:"Upload failed"}),Si("Upload response error",{operation:"upload.simple",status:w.status,duration:r}),new rs("Upload failed",{code:qr,details:{status:w.status,response:n}});Ci("Upload response success",{operation:"upload.simple",status:w.status,duration:r});const i=ai({response:n,restBaseUrl:s.restBaseUrl,orgName:f,appName:g,fileType:h,fileName:p,fallbackSize:m,messageType:a,imageType:c,useCustomAttachmentUpload:s.useCustomAttachmentUpload});e.callbacks?.onFileUploadComplete?.(i),I?.finish({code:w.status||200,success:!0}),t(i)}catch(n){I?.finish({code:n instanceof rs?n.code:qr,success:!1,description:n instanceof Error?n.message:String(n)}),r(n instanceof Error?n:new Error(String(n)))}},!1),w.timeout=xn,w.open("POST",v),w.setRequestHeader("restrict-access","true"),w.setRequestHeader("Accept","*/*"),w.setRequestHeader("Authorization",`Bearer ${s.token}`),w.setRequestHeader(vl,yl());const C=new FormData;C.append("file",n,p),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)}),qm=ru(),$m=e=>Object.prototype.toString.call(e),Gm=e=>{const t=e&&"object"==typeof e?e:null,r="string"==typeof t?.path?t.path:void 0,s="string"==typeof t?.uri?t.uri:void 0,n="string"==typeof t?.name?t.name:void 0,i="string"==typeof t?.type?t.type:void 0,o="number"==typeof t?.size?t.size:void 0;return{kind:$m(e),isFile:"undefined"!=typeof File&&e instanceof File,isBlob:"undefined"!=typeof Blob&&e instanceof Blob,hasPath:"string"==typeof r&&r.length>0,pathPrefix:r?r.slice(0,48):void 0,hasUri:"string"==typeof s&&s.length>0,uriPrefix:s?s.slice(0,48):void 0,name:n,type:i,size:o}},Fm=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}),Bm=e=>"image"===e||"video"===e||"voice"===e||"file"===e||"combine"===e,jm=e=>"object"==typeof e&&null!==e,zm=(e,t)=>{const r=jm(t)?t:void 0,s=r?.code===Pi&&r.stage===xi;return"miniapp-path"===e&&(e=>{if(!jm(e))return!1;const t=jm(e.details)?e.details:void 0;return e.code===Pi&&e.stage===xi&&"string"==typeof t?.capability&&t.capability.includes("FileSystem")})(t)||"rn-uri"===e&&s};class Km{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(!Bm(e.type))return e;const r=e.body;if(this.hasUploadedRemoteResource(e.type,r))return e;const s=this.resolveUploadUrl(e.type,r),n=Qh.get(e.msgLocalId),i=Boolean(n);if(Si("Attachment upload prepare entry",{operation:"upload.prepare.entry",msgLocalId:e.msgLocalId,messageType:e.type,conversationType:e.conversationType,hasFile:i,uploadUrl:s,cachedFile:Gm(n),adapter:{hasRequestAdapter:Boolean(this.config?.requestAdapter),hasUploadAdapter:Boolean(this.config?.uploadAdapter),hasImageProcessor:Boolean(this.config?.imageProcessor),restBaseUrl:Boolean(this.config?.restBaseUrl),useCustomAttachmentUpload:this.config?.useCustomAttachmentUpload}}),!((e,t)=>!!t||!e||!Zn(e))(s,i))return e;if(!n)throw new rs("Attachment file is required",{code:Lr,details:{msgLocalId:e.msgLocalId,url:s}});if(!this.config?.restBaseUrl)throw new rs("REST base url is required for upload",{code:Lr,details:{reason:"restBaseUrl missing"}});let o,a,c;try{o=await this.prepareAttachmentUpload(e,r,n),o.precheck?.hit||(c=Wh({operationName:"UPLOAD_MSG_ATTACH",operationType:"REST",msgId:e.msgLocalId,messageType:e.type})),a=o.precheck?.hit?this.buildPrecheckedUploadResult(e,o,t):await this.uploadAttachment(e,o,t,c),c?.finish({code:0,success:!0})}catch(d){const e=tl(d);throw c?.finish({code:e.code,success:!1,description:e.message}),e.code===Gr&&t?.onFileUploadCanceled?.(),t?.onFileUploadError?.(e),e}return this.buildPreparedMessage(e,o,a)}resolveUploadUrl(e,t){if("image"===e){const e=t;return("string"==typeof e.localUrl?e.localUrl.trim():"")||("string"==typeof e.originalImageUrl?e.originalImageUrl.trim():"")}return"url"in t&&"string"==typeof t.url?t.url.trim():""}hasUploadedRemoteResource(e,t){if("image"===e){const e=t;return"string"==typeof e.originalImageUrl&&Zn(e.originalImageUrl)}return"url"in t&&"string"==typeof t.url&&Zn(t.url)}async prepareAttachmentUpload(e,t,r){const s=((e,t)=>{if(!e)throw new rs("Attachment file is required",{code:Lr,details:{reason:"file missing"}});const r=("number"==typeof t.fileLength?t.fileLength:void 0)??("fileSize"in t&&"number"==typeof t.fileSize?t.fileSize:void 0),s=Bn({file:e,fallbackName:t.filename,fallbackMimeType:t.filetype,fallbackSize:r});if("web-file"===s.source.sourceType&&!s.webFile)throw new rs("Attachment file is required",{code:Lr,details:{reason:"web file missing"}});return s})(r,t);if(Si("Attachment file normalized",{operation:"upload.prepare.normalized",messageType:e.type,fileInfo:Fm(s)}),"image"!==e.type){return{body:t,fileInfo:s,md5FileInfo:s,precheck:await this.maybePrecheck(e,s,s,void 0)}}const n=t,i=await this.resolveImageCandidate(n,s),o={...n,width:i.width,height:i.height,isOriginalImage:i.imagePolicy.resolvedImageType===Wn},a=await this.maybePrecheck(e,i.fileInfo,s,i.imagePolicy.resolvedImageType);return{body:o,fileInfo:i.fileInfo,md5FileInfo:s,imageType:i.imagePolicy.resolvedImageType,precheck:a,originalWidth:n.width,originalHeight:n.height}}async resolveImageCandidate(e,t){const r=(e=>e.isGif?{resolvedImageType:Wn,reason:"gif-force-origin"}:e.isOriginalImage?{resolvedImageType:Wn,reason:"explicit-original"}:{resolvedImageType:Jn,reason:"default-large"})(e);if(Si("Image send policy resolved",{operation:"upload.image.policy",reason:r.reason,imageType:r.resolvedImageType,isGif:e.isGif,source:Fm(t)}),r.resolvedImageType===Wn){let s=e.width,n=e.height;if(!s||!n){const e=this.resolveImageProcessor(t.source.sourceType);Si("Image original info resolving",{operation:"upload.image.info",processorSourceType:t.source.sourceType,source:Fm(t)});const r=await e.getImageInfo(t.source);s=r.width,n=r.height}return{imagePolicy:r,sourceKind:"origin",fileInfo:t,width:s,height:n}}try{const e=this.resolveImageProcessor(t.source.sourceType);Si("Image big generation start",{operation:"upload.image.big.start",processorSourceType:t.source.sourceType,source:Fm(t)});const s=await e.generateBigImage(t.source,{maxShortEdge:720,quality:.85});return{imagePolicy:r,sourceKind:"big",fileInfo:{source:s.source,fileName:s.fileName??t.fileName,fileType:s.fileType??t.fileType,fileSize:s.fileSize??t.fileSize,webFile:s.webFile},width:s.width,height:s.height}}catch(s){return Si("Image big generation failed, fallback to original",{operation:"upload.image.big-fallback",reason:r.reason,error:s instanceof Error?s.message:String(s),source:Fm(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(!Bm(e.type))return;if(!0!==this.config?.enableMd5Check)return void Ci("Attachment precheck skipped because MD5 check is disabled",{operation:"upload.precheck.skip",reason:"md5-check-disabled",messageType:e.type,imageType:s,fileSize:t.fileSize});const n=si({messageType:e.type,fileSize:t.fileSize,imageType:s});if(!n.shouldPrecheck)return void Ci("Attachment precheck skipped",{operation:"upload.precheck.skip",messageType:e.type,imageType:s,fileSize:t.fileSize,thresholdBytes:n.thresholdBytes});let i;try{i=await this.computeMd5(r)}catch(a){if(zm(r.source.sourceType,a))return void Si("Attachment precheck skipped because md5 is unavailable",{operation:"upload.precheck.md5-unavailable",messageType:e.type,imageType:s,thresholdType:n.thresholdType,source:Fm(r),error:a instanceof Error?a.message:String(a)});throw a}const o=await this.requestPrecheck(e,n.thresholdType,i,s);return Ci(o.hit?"Attachment precheck hit":"Attachment precheck miss",{operation:o.hit?"upload.precheck.hit":"upload.precheck.miss",messageType:e.type,imageType:s,exists:o.exists,existsType:o.existsType,uuid:o.uuid,hasShareSecret:"string"==typeof o.shareSecret&&o.shareSecret.length>0}),{...o,md5:i}}async computeMd5(e){const t=this.resolveImageProcessor(e.source.sourceType);return Si("Attachment md5 compute start",{operation:"upload.md5.start",source:Fm(e)}),t.computeMd5(e.source)}resolveImageProcessor(e){if(this.config?.imageProcessor)return Si("Image processor resolved from platform adapter",{operation:"upload.image.processor",sourceType:e,processor:"platform"}),this.config.imageProcessor;if("web-file"===e)return Si("Image processor resolved from web fallback",{operation:"upload.image.processor",sourceType:e,processor:"web-fallback"}),qm;throw Si("Image processor missing",{operation:"upload.image.processor-missing",sourceType:e}),Fi("Image processor capability is missing for current platform",{code:Pi,stage:xi,retryable:!1,details:{capability:"imageProcessor",sourceType:e}})}async requestPrecheck(e,t,r,s){if(!this.config)throw new rs("Upload config is required",{code:Lr});const{orgName:n,appName:i}=Qn(this.config.appKey),o=ti(`${this.config.restBaseUrl}/${n}/${i}/chatfiles/exists`,{md5:r,..."image"===e.type?{imageType:ii(s)}:{}}),a=await this.requestJson({url:o,method:"GET",headers:{Authorization:`Bearer ${this.config.token}`,Accept:"application/json"},operation:"upload.precheck"}).catch(n=>{Si("Attachment precheck failed, fallback to upload",{operation:"upload.precheck.fail-open",messageType:e.type,imageType:s,thresholdType:t,md5:r,error:n instanceof Error?n.message:String(n)})});return a?(e=>{const t=e.entities?.[0],r=!0===t?.exists,s="string"==typeof t?.uuid&&t.uuid.length>0?t.uuid:void 0,n=t,i=n?.["exists-type"]??n?.existsType,o="origin"===i?Wn:i===Jn||i===Wn?i:void 0,a="string"==typeof t?.["share-secret"]?t["share-secret"]:void 0;if(r&&!s)throw new rs("Upload precheck response missing uuid",{code:qr,details:{response:e}});return{uuid:s,exists:r,existsType:o,shareSecret:a,hit:(c={exists:r,uuid:s},c.exists&&"string"==typeof c.uuid&&c.uuid.length>0)};var c})(a):{exists:!1,hit:!1}}async requestJson(e){return this.config?.requestAdapter?this.requestByAdapter(this.config.requestAdapter,e):this.requestByFetch(e)}async requestByAdapter(e,t){const r=await e.request({url:t.url,method:t.method,headers:t.headers,responseType:"json",timeoutMs:xn});if(r.status>=400)throw new rs("Upload precheck request failed",{code:qr,details:{url:t.url,status:r.status,operation:t.operation}});return r.data}async requestByFetch(e){if("function"!=typeof fetch)throw Fi("Request capability is missing for current platform",{code:Pi,stage:Ui,retryable:!1,details:{operation:e.operation}});const t=new AbortController,r=setTimeout(()=>t.abort(),xn);try{const r=await fetch(e.url,{method:e.method,headers:e.headers,signal:t.signal});if(!r.ok)throw new rs("Upload precheck request failed",{code:qr,details:{url:e.url,status:r.status,operation:e.operation}});return await r.json()}finally{clearTimeout(r)}}buildPrecheckedUploadResult(e,t,r){if(!this.config||!t.precheck)throw new rs("Precheck result is required",{code:qr});if(!t.precheck.uuid)throw new rs("Precheck hit missing uuid",{code:qr,details:{precheck:t.precheck}});if(!Bm(e.type))throw new rs("Attachment message type is invalid",{code:Lr,details:{messageType:e.type}});const{orgName:s,appName:n}=Qn(this.config.appKey),i="image"===e.type?t.precheck.existsType??t.imageType:void 0,o="image"===e.type&&i===Wn?t.md5FileInfo:t.fileInfo,a="image"===e.type&&i===Wn?t.originalWidth:"image"===e.type?t.body.width:void 0,c="image"===e.type&&i===Wn?t.originalHeight:"image"===e.type?t.body.height:void 0,d={entities:[{uuid:t.precheck.uuid,...t.precheck.shareSecret?{"share-secret":t.precheck.shareSecret}:{}}]},u=ai({response:d,restBaseUrl:this.config.restBaseUrl,orgName:s,appName:n,fileType:o.fileType,fileName:o.fileName,fallbackSize:o.fileSize,messageType:e.type,imageType:i,width:a,height:c,useCustomAttachmentUpload:this.config.useCustomAttachmentUpload});return r?.onFileUploadComplete?.(u),u}async uploadAttachment(e,t,r,s){if(!this.config)throw new rs("Upload config is required",{code:Lr});if(!Bm(e.type))throw new rs("Attachment message type is invalid",{code:Lr,details:{messageType:e.type}});const n=e.type,i=await this.resolveUploadMetadata(n,t);if(this.config.uploadAdapter)return Si("Attachment upload adapter selected",{operation:"upload.adapter.selected",messageType:n,source:Fm(t.fileInfo),adapter:"platform",hasUploadAdapter:!0}),this.uploadByAdapter(this.config.uploadAdapter,e,t,i,r);if(!t.fileInfo.webFile)throw new rs("Upload adapter is required for non-web file source",{code:Lr,details:{sourceType:t.fileInfo.source.sourceType}});const o={message:e,file:t.fileInfo.webFile,conversationId:e.conversationId,conversationType:e.conversationType,messageType:n,imageType:t.imageType,md5:i.md5,width:i.width,height:i.height,fileName:t.fileInfo.fileName,fileType:t.fileInfo.fileType,fileSize:t.fileInfo.fileSize,thumbnailWidth:this.resolveThumbnailWidth(n,t.body),thumbnailHeight:this.resolveThumbnailHeight(n,t.body),callbacks:r,config:this.config,dataReportOperation:s},a=!1!==this.config?.enableMultipartUpload,c=a&&t.fileInfo.fileSize>jn;if(Si("Attachment web upload selected",{operation:"upload.web.selected",messageType:n,source:Fm(t.fileInfo),multipartEnabled:a,uploadMode:c?"multipart":"simple"}),c)try{return await Pm(o)}catch(d){const e=d instanceof rs?d.details:void 0;if(e&&"object"==typeof e&&"init"===e.stage)return Dm(o);throw d}return Dm(o)}async uploadByAdapter(e,t,r,s,n){if(!this.config)throw new rs("Upload config is required",{code:Lr});const{orgName:i,appName:o}=Qn(this.config.appKey),a=Yn(t.conversationType);if(!Bm(t.type))throw new rs("Attachment message type is invalid",{code:Lr,details:{messageType:t.type}});const c=t.type,d=ti(`${this.config.restBaseUrl}/${i}/${o}/chatfiles`,{"chat-type":a,"chat-target":t.conversationId,md5:s.md5,..."image"===c?{imageType:ii(r.imageType),width:s.width,height:s.height}:{}}),u={},l={"restrict-access":"true",Accept:"*/*",Authorization:`Bearer ${this.config.token}`,[vl]:yl()},p=this.resolveThumbnailWidth(c,r.body),h=this.resolveThumbnailHeight(c,r.body);void 0!==p&&(u["thumbnail-width"]=String(p)),void 0!==h&&(u["thumbnail-height"]=String(h)),Si("Attachment adapter upload start",{operation:"upload.adapter.start",messageType:c,source:Fm(r.fileInfo),uploadUrl:d,fields:u});const m=await e.upload({url:d,headers:l,source:r.fileInfo.source,fields:u,onProgress:e=>{n?.onFileUploadProgress?.(e)}});if(m.status>=400){const e=m.body??"",t=413===m.status?tr:"string"==typeof e&&e.includes("content improper")?rr:qr;throw new rs("Upload failed",{code:t,details:{status:m.status,response:m.body}})}let f;try{f=JSON.parse(m.body)}catch(y){throw new rs("Upload response parse failed",{code:qr,details:{response:m.body,cause:y instanceof Error?y.message:String(y)}})}const g=ai({response:f,restBaseUrl:this.config.restBaseUrl,orgName:i,appName:o,fileType:r.fileInfo.fileType,fileName:r.fileInfo.fileName,fallbackSize:r.fileInfo.fileSize,messageType:c,imageType:r.imageType,width:s.width,height:s.height,useCustomAttachmentUpload:this.config.useCustomAttachmentUpload});return n?.onFileUploadComplete?.(g),g}buildPreparedMessage(e,t,r){if("image"===e.type){const s=t.body,n={...e,body:{...s,isOriginalImage:r.isOriginalImage??s.isOriginalImage,originalImageUrl:r.originalImageUrl??s.originalImageUrl,bigImageUrl:r.bigImageUrl??s.bigImageUrl,secret:r.secret??s.secret,fileLength:r.fileLength??s.fileLength??t.fileInfo.fileSize,filetype:r.filetype??s.filetype,filename:r.filename??s.filename,thumbnailUrl:r.thumbnailUrl??s.thumbnailUrl,width:r.width??s.width,height:r.height??s.height}};return lp(e,n),gp(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 lp(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 lp(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 lp(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 lp(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(!zm(t.md5FileInfo.source.sourceType,n))throw n;Si("Attachment upload continues without md5",{operation:"upload.md5.unavailable",messageType:e,source:Fm(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 Hm{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 Vm="__internal:core";class Wm{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 Zh({...e,socketAdapter:e.socketAdapter??e.platformAdapter?.socket},this.eventHub);const r=this.connectionManager.getMsyncCodec(),s=e.restBaseUrl?new Km({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 Cm(r,null,this.eventHub,s),this.messageReceiver=new Am(r,this.messageSender,this.eventHub),e.enableDeliveryReceipt&&this.messageReceiver.setDeliveryAckEnabled(!0),this.combineMessageDownloader=new Em(e.platformAdapter?.request),this.attachmentDownloader=new Nm(e.platformAdapter?.request),this.connectionManager.setMessageReceiver(this.messageReceiver),this.platformAdapter=e.platformAdapter??null,this.setupEventHandlers(),this.registerNetworkListeners()}setupEventHandlers(){this.eventHub.addEventHandler(Vm,{[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 Hm(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(Vm),Qh.clear()}}const Jm=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)},Zm=e=>{const t=new Uint8Array(Dc.util.base64.length(e));return Dc.util.base64.decode(e,t,0),t};class Qm{getCrypto(){return Vi().crypto}constructor(e,t){if(this.enabled=(()=>{const e=Vi();if([e.wx,e.qq,e.tt,e.swan,e.my,e.dd,e.jd,e.ks,e.uni].some(e=>void 0!==e))return!1;const t=co(e);if("web"!==t.framework&&"worker"!==t.framework&&t.platform!==Mi.ELECTRON_RENDERER)return!1;const r=e.crypto;return void 0!==r&&void 0!==r.subtle&&"function"==typeof r.getRandomValues&&"undefined"!=typeof TextEncoder&&"undefined"!=typeof TextDecoder})(),this.enabled){const r=`${e}:${t}`;this.keyPromise=this.deriveKey(r)}else this.keyPromise=null}isEnabled(){return this.enabled}async encrypt(e){if(!this.enabled||!this.keyPromise)return e;const t=await this.keyPromise,r=new TextEncoder,s=this.getCrypto().getRandomValues(new Uint8Array(12)),n=r.encode(e),i=await this.getCrypto().subtle.encrypt({name:"AES-GCM",iv:s},t,n),o={__enc:!0,v:1,alg:"AES-GCM",kdf:"SHA-256",iv:Jm(s),ct:Jm(new Uint8Array(i))};return JSON.stringify(o)}async decrypt(e){if(!this.enabled||!this.keyPromise)return e;let t;try{t=JSON.parse(e)}catch{return e}if(!(e=>{if(!e||"object"!=typeof e)return!1;const t=e;return!0===t.__enc&&1===t.v&&"AES-GCM"===t.alg&&"SHA-256"===t.kdf&&"string"==typeof t.iv&&"string"==typeof t.ct})(t))return e;try{const e=await this.keyPromise,r=Zm(t.iv),s=Zm(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 Ym="conversationMap",Xm="userInfoMap",ef="groupNamecardMap",tf="contactRelationMap",rf="contactVersion",sf="contactMeta",nf="sessionListMap",of="sessionListCheckpoint",af="joinedGroupPreview",cf="metadata",df=(e,t)=>`IMSDK_${e.appKey}_${e.userId}_${t}_v${e.schemaVersion}`;class uf{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 lf=()=>{const e="undefined"!=typeof window?window.localStorage:void 0;if(e&&"function"==typeof e.getItem)return e;const t=Vi().localStorage;return t&&"function"==typeof t.getItem?t:null};class pf{constructor(e,t){this.storage=t??pf.createLocalStorageAdapter(),this.cryptoAdapter=e??null}static createLocalStorageAdapter(){if(!pf.checkAvailable())return null;const e=lf();return e?{getItem:t=>Promise.resolve(e.getItem(t)),setItem:(t,r)=>(e.setItem(t,r),Promise.resolve()),removeItem:t=>(e.removeItem(t),Promise.resolve())}:null}static checkAvailable(){const e=lf();if(!e)return!1;try{const t="__im_sdk_cache_test__";return e.setItem(t,"1"),e.removeItem(t),!0}catch{return!1}}async readAsync(e,t){if(!this.storage)return t;try{const r=await this.storage.getItem(e);if(!r)return t;let s=r;if(this.cryptoAdapter&&this.cryptoAdapter.isEnabled()){const e=await this.cryptoAdapter.decrypt(r);if(null===e)return t;s=e}return Ul(s,t)}catch(r){return Si("CacheStore read failed",r),t}}async writeAsync(e,t){await this.writeInternal(e,t,!1)}async writeStrictAsync(e,t){await this.writeInternal(e,t,!0)}async writeInternal(e,t,r){if(!this.storage)return;const s=(e=>{try{return JSON.stringify(e)}catch{return null}})(t);if(null!==s)try{const t=this.cryptoAdapter&&this.cryptoAdapter.isEnabled()?await this.cryptoAdapter.encrypt(s):s;await this.storage.setItem(e,t)}catch(n){if(mu(n))throw n;if(r)throw n;Si("CacheStore write failed",n)}else if(r)throw new TypeError("CacheStore value cannot be serialized")}async remove(e){if(this.storage)try{await this.storage.removeItem(e)}catch(t){Si("CacheStore remove failed",t)}}}const hf={version:"",lastVersionCheckAt:0,lastVersionSource:"metadata"},mf={cacheIntegrity:"incomplete",reason:"first_sync_pending",lastSyncTs:0,lastSuccessfulVersion:"",lastSyncMode:"skipped"};class ff{constructor(){this.items=new Map,this.versionState=hf,this.meta=mf}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(!El(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 El(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"}:hf}normalizeMeta(e){return El(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"}:mf}}const gf=(e,t,r)=>{if(t<=0)return{kept:e,removed:[]};const s=[],n=[];for(const i of e)r-i.lastUpdate>t?n.push(i):s.push(i);return{kept:s,removed:n}},yf=(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}},vf=e=>{if(!Array.isArray(e))return[];const t=new Set,r=[],s=e;for(const n of s){const e="string"==typeof n&&n.startsWith("mark_")?n.slice(5):n,s="number"==typeof e?e:"string"==typeof e?Number.parseInt(e,10):Number.NaN;if(!Number.isInteger(s)||s<0||s>19)continue;const i=s;t.has(i)||(t.add(i),r.push(i))}return r};class bf{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=gf(this.items,e,t);return this.items=[...r.kept],r.removed.length>0}evictByLru(e){const t=yf(this.items,e);return this.items=[...t.kept],t.removed.length>0}trimMax(e){if(!e||this.items.length<=e)return!1;const t=[...this.items].sort((e,t)=>e.lastAccess-t.lastAccess),r=Math.max(this.items.length-e,0),s=t.slice(0,r),n=new Set(s);return this.items=this.items.filter(e=>!n.has(e)),s.length>0}findIndex(e,t){return this.items.findIndex(r=>r.conversationId===e&&r.type===t)}normalizeItem(e,t){if(!e||"object"!=typeof e)return null;const r=e;if("string"!=typeof r.conversationId||0===r.conversationId.length)return null;const s="single"===(n=r.type)||"chat"===n||"singleChat"===n?"singleChat":"group"===n||"groupchat"===n||"groupChat"===n?"groupChat":"room"===n||"chatroom"===n||"chatRoom"===n?"chatRoom":null;var n;if(!s)return null;const i=this.normalizeMessage(r.lastMessage);return{conversationId:r.conversationId,type:s,lastMessage:i,unreadCount:"number"==typeof r.unreadCount?r.unreadCount:0,isPinned:"boolean"==typeof r.isPinned?r.isPinned:void 0,pinnedTime:"number"==typeof r.pinnedTime?r.pinnedTime:void 0,marks:vf(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(!El(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=El(e.body)?e.body:{},i="number"==typeof e.userInfoUpdateTime?e.userInfoUpdateTime:void 0,o="number"==typeof e.namecardUpdateTime?e.namecardUpdateTime:void 0;return t?{msgId:t,type:r,body:n,timestamp:s,userInfoUpdateTime:i,namecardUpdateTime:o}:null}}const If=(e,t)=>`${e}:${t}`;class wf{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(If(e.groupId,e.userId),e)}}getAll(){return Array.from(this.items.values())}get(e,t,r,s){const n=If(e,t),i=this.items.get(n);return i?(s&&this.items.set(n,{...i,lastAccess:r}),i):null}getByGroupId(e,t,r){const s=[];for(const n of this.items.values())n.groupId===e&&(s.push(n),r&&this.items.set(If(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=If(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(If(t.groupId,t.userId))}removeExpired(e,t,r=new Set){const s=Array.from(this.items.values()),n=s.filter(e=>!r.has(e.userId)),i=gf(n,e,t),o=new Set(i.removed.map(e=>If(e.groupId,e.userId)));this.items.clear();for(const a of s)o.has(If(a.groupId,a.userId))||this.items.set(If(a.groupId,a.userId),a);return i.removed.length>0}evictByLru(e,t=new Set){const r=Array.from(this.items.values()),s=r.filter(e=>!t.has(e.userId)),n=yf(s,Math.min(e,s.length)),i=new Set(n.removed.map(e=>If(e.groupId,e.userId)));this.items.clear();for(const o of r)i.has(If(o.groupId,o.userId))||this.items.set(If(o.groupId,o.userId),o);return n.removed.length>0}trimMax(e,t=new Set){return!(e<=0||this.items.size<=e)&&this.evictByLru(Math.max(this.items.size-e,0),t)}normalizeItem(e,t){if(!e||!El(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 Cf=100,Sf=3e3,Tf=e=>({...e}),_f=e=>"object"==typeof e&&null!==e,Rf=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 Af{constructor(){this.items=[],this.meta={integrity:"unknown",limited:!1,storageLimit:Cf,serverLimit:Sf,source:"localPreview"}}load(e){if(!e)return this.items=[],void(this.meta={integrity:"unknown",limited:!1,storageLimit:Cf,serverLimit:Sf,source:"localPreview"});const t=Array.isArray(e.items)?e.items.map(e=>{return _f(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:Rf(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,Cf),this.meta=(e=>{const t=_f(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:Cf,serverLimit:"number"==typeof t.serverLimit?t.serverLimit:Sf,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=>Tf(e)).slice(0,Cf),this.meta={...e.meta,source:"localPreview",storageLimit:Cf,serverLimit:Sf,integrity:e.meta.limited?"limited":e.meta.integrity}}getSnapshot(){return{items:this.items.map(e=>Tf(e)),meta:{...this.meta,source:"localPreview"}}}exportRecord(){return{items:this.items.map(e=>Tf(e)),meta:{...this.meta,source:"localPreview"}}}}const Mf=e=>"singleChat"===e||"groupChat"===e||"chatRoom"===e?e:null,Ef=e=>{const t={...e};return delete t.type,t},Uf=e=>{if(!El(e))return null;const t="string"==typeof e.msgServerId?e.msgServerId:null;if(null===t||"string"!=typeof e.from||"number"!=typeof e.timestamp||!El(e.body))return null;const r=((e,t)=>{if(El(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=Mf(e.conversationType),n=(e=>{if("sending"===e||"sent"===e||"failed"===e)return e})(e.sendStatus??e.status),i=(e=>{if("SEND"===e||"RECEIVE"===e)return e})(e.direct),o=(e=>{if(El(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:Ef(e.body),timestamp:e.timestamp,..."string"==typeof e.conversationId?{conversationId:e.conversationId}:{},...s?{conversationType:s}:{},..."string"==typeof e.type&&e.type.length>0?{type:e.type}:{},...n?{sendStatus:n}:{},...i?{direct:i}:{},...o?{modifiedInfo:o}:{},...void 0!==a?{userInfoUpdateTime:a}:{},...void 0!==c?{namecardUpdateTime:c}:{}}},kf=e=>{if(!Array.isArray(e))return[];const t=new Set,r=[],s=e;for(const n of s){const e="string"==typeof n&&n.startsWith("mark_")?n.slice(5):n,s="number"==typeof e?e:"string"==typeof e?Number.parseInt(e,10):Number.NaN;if(!Number.isInteger(s)||s<0||s>19)continue;const i=s;t.has(i)||(t.add(i),r.push(i))}return r},Nf=(e,t)=>{const r="number"==typeof e.pinnedTimestamp?e.pinnedTimestamp:0,s="number"==typeof t.pinnedTimestamp?t.pinnedTimestamp:0;if(r!==s)return s-r;const n=e.lastMessageAt??e.updatedAt,i=t.lastMessageAt??t.updatedAt;return n!==i?i-n:e.conversationId.localeCompare(t.conversationId)};class Of{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(Nf)}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(Nf)}exportItems(){return this.items.map(({updatedAt:e,...t})=>t)}normalizeItem(e,t){if(!El(e))return null;const r=e,s="string"==typeof r.conversationId?r.conversationId:"";if(!s)return null;const n=Mf(r.conversationType);if(!n)return null;const i="string"==typeof r.conversationName&&r.conversationName.length>0?r.conversationName:s,o="string"==typeof r.conversationAvatar?r.conversationAvatar:void 0;return{conversationId:s,conversationType:n,unreadCount:"number"==typeof e.unreadCount&&e.unreadCount>=0?Math.floor(e.unreadCount):0,lastMessage:Uf(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:kf(e.marks),readAt:"number"==typeof r.readAt?r.readAt:void 0,remindType:(a=e.remindType,"DEFAULT"===a||"ALL"===a||"AT"===a||"NONE"===a?a:"mentionOnly"===a?"AT":"mute"===a?"NONE":"DEFAULT"),conversationName:i,conversationAvatar:o,updatedAt:"number"==typeof e.updatedAt?e.updatedAt:t};var a}}class xf{constructor(){this.items=new Map}load(e,t){this.items.clear();for(const r of e){const e=this.normalizeItem(r,t);e&&this.items.set(e.userId,e)}}getAll(){return Array.from(this.items.values())}getByIds(e,t,r){const s=[];for(const n of e){const e=this.items.get(n);e&&(s.push(e),r&&this.items.set(n,{...e,lastAccess:t}))}return s}setAll(e,t){for(const r of e){const e=this.normalizeItem(r,t);if(!e)continue;const s=this.items.get(e.userId),n=s?.lastAccess??e.lastAccess;this.items.set(e.userId,{...e,lastAccess:n,lastUpdate:e.lastUpdate})}}remove(e){for(const t of e)this.items.delete(t)}removeExpired(e,t,r=new Set){const s=Array.from(this.items.values()),n=s.filter(e=>!r.has(e.userId)),i=gf(n,e,t),o=new Set(i.removed.map(e=>e.userId));this.items.clear();for(const a of s)o.has(a.userId)||this.items.set(a.userId,a);return i.removed.length>0}evictByLru(e,t=new Set){const r=Array.from(this.items.values()),s=r.filter(e=>!t.has(e.userId)),n=yf(s,Math.min(e,s.length)),i=new Set(n.removed.map(e=>e.userId));this.items.clear();for(const o of r)i.has(o.userId)||this.items.set(o.userId,o);return n.removed.length>0}trimMax(e,t=new Set){if(e<=0||this.items.size<=e)return!1;const r=Array.from(this.items.values()),s=Math.max(r.length-e,0);return this.evictByLru(s,t)}normalizeItem(e,t){if(!e||"object"!=typeof e)return null;if(!El(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 Lf=e=>"number"==typeof e.pinnedTimestamp?e.pinnedTimestamp:0,Pf=e=>e.lastMessageAt??e.updatedAt,Df=e=>[...e].sort((e,t)=>{const r=Lf(t)-Lf(e);if(0!==r)return r;const s=Pf(t)-Pf(e);return 0!==s?s:e.conversationId.localeCompare(t.conversationId)}),qf=e=>`${e.conversationType}:${e.conversationId}`,$f=(e,t)=>t.lastMessage?e.lastMessage?t.lastMessage.timestamp>=e.lastMessage.timestamp?t.lastMessage:e.lastMessage:t.lastMessage:e.lastMessage,Gf=(e,t)=>((e,t)=>Pf(t)>Pf(e))(e,t)?{...e,unreadCount:Math.max(e.unreadCount,t.unreadCount),lastMessage:$f(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,Ff=e=>{const t=new Map,r=new Set;for(const i of e.snapshot)r.add(qf(i));for(const i of e.existing)t.set(qf(i),i);const s=e.snapshot.map(e=>{const r=t.get(qf(e));return r?Gf(e,r):e}),n=e.existing.filter(t=>!r.has(qf(t))&&((e,t)=>"number"==typeof t&&e.updatedAt>t)(t,e.syncStartedAt));return Df([...s,...n])},Bf=["userId","nickname","avatarUrl","mail","phone","gender","sign","birth","ext"],jf=e=>({userId:e.userId,nickname:e.nickname,avatarUrl:e.avatarUrl,sign:e.sign,ext:e.ext}),zf=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 Kf{constructor(){this.records=new Map}clear(){this.records.clear()}get(e,t=!1,r=Date.now()){const s=this.records.get(e)??null;if(!s||!t)return s;const n={...s,lastAccess:r};return this.records.set(e,n),n}setAll(e,t=Date.now()){for(const r of e){const e=r.lastModified??t,s=this.records.get(r.profile.userId),n=s?.lastAccess??t;this.records.set(r.profile.userId,{profile:r.profile,lastModified:e,lastAccess:n,source:r.source})}}applyPatch(e,t,r=Date.now()){const s=this.records.get(e.userId),n={userId:e.userId,...t??{},...s?.profile??{}};if(s&&e.lastModified<s.lastModified)return{applied:!1,reason:"stale",record:s};const i={...n,...e.attributes,userId:e.userId};if(s&&e.lastModified===s.lastModified&&(o=s.profile,a=i,Bf.every(e=>o[e]===a[e])))return{applied:!1,reason:"duplicate",record:s};var o,a;const c={profile:i,lastModified:e.lastModified,lastAccess:s?.lastAccess??r,source:"subscription"===e.source?"subscription_notify":"contact"===e.source?"contact_notify":"own_notify"};return this.records.set(e.userId,c),{applied:!0,reason:"applied",record:c}}}const Hf=["conversation","userInfo","groupNamecard","sessionList","joinedGroupPreview","contactRelation","contactVersion","contactMeta"];class Vf{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 Qm(e.appKey,e.userId);this.store=new pf(t??void 0,e.storageAdapter);const r={appKey:e.appKey,userId:e.userId,schemaVersion:this.config.schemaVersion};this.conversationKey=df(r,Ym),this.userInfoKey=df(r,Xm),this.groupNamecardKey=df(r,ef),this.sessionListKey=df(r,nf),this.sessionListCheckpointKey=df(r,of),this.joinedGroupPreviewKey=df(r,af),this.contactRelationKey=df(r,tf),this.contactVersionKey=df(r,rf),this.contactMetaKey=df(r,sf),this.metadataKey=df(r,cf),this.metadataStore=new uf(this.store,this.metadataKey,this.config.schemaVersion),this.conversationCache=new bf,this.userInfoCache=new xf,this.groupNamecardCache=new wf,this.sessionListCache=new Of,this.joinedGroupPreviewCache=new Af,this.contactCache=new ff,this.userInfoRuntimeStore=new Kf,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 Af;if(r.setSnapshot(e),await this.store.writeStrictAsync(this.joinedGroupPreviewKey,r.exportRecord()),this.getDomainRevision("joinedGroupPreview")!==t)return this.ensureFlushScheduled(),this.loadJoinedGroupPreviewSnapshot();this.joinedGroupPreviewCache.setSnapshot(e),this.mutationRevision+=1,this.domainRevisions.set("joinedGroupPreview",this.mutationRevision);const s=this.pendingDirtyRevisions.get("joinedGroupPreview");return void 0!==s&&s<=this.mutationRevision&&this.pendingDirtyRevisions.delete("joinedGroupPreview"),await this.metadataStore.touchLastFlush(),this.loadJoinedGroupPreviewSnapshot()}async removeJoinedGroupPreview(e){const t=this.loadJoinedGroupPreviewSnapshot(),r=t.items.filter(t=>t.groupId!==e);return r.length===t.items.length?t:(this.applyJoinedGroupPreviewSnapshot({items:r,meta:{...t.meta}}),await this.flushPending(),this.loadJoinedGroupPreviewSnapshot())}loadSessionListCheckpoint(){return this.sessionListCheckpoint}async flushPending(){null!==this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null),null!==this.flushIdleHandle&&"undefined"!=typeof cancelIdleCallback&&(cancelIdleCallback(this.flushIdleHandle),this.flushIdleHandle=null),await this.flushNow(),this.activeFlushPromise&&await this.activeFlushPromise,this.pendingDirtyRevisions.size>0&&await this.flushNow()}resetSessionListCheckpoint(){this.sessionListCheckpoint={lastSyncTime:0,lastSyncFinishedTs:0,sessionsLastSyncTs:0,lastSuccessfulAt:0},this.scheduleFlush(["sessionList"])}loadUserInfoSummaries(){return this.userInfoCache.getAll()}loadGroupNamecards(e){return e?this.groupNamecardCache.getByGroupId(e,Date.now(),!1):this.groupNamecardCache.getAll()}loadContactSnapshot(e="cache"){const t=this.contactCache.buildSnapshot(this.userInfoCache.getAll(),e);return{...t,items:t.items.map(e=>({...e,userInfo:this.userInfoRuntimeStore.get(e.userId,!1)?.profile??e.userInfo}))}}loadContactRelationRecords(){return this.contactCache.getAll()}loadContactVersionState(){return this.contactCache.getVersionState()}loadContactCacheMeta(){return this.contactCache.getMeta()}markConversationAccess(e){const t=Date.now();this.conversationCache.updateLastAccess(e,t)&&this.scheduleFlush(["conversation"])}setCurrentConversation(e){this.currentConversation={conversationId:e.conversationId,type:e.type}}resetCurrentConversation(){this.currentConversation=null}getCurrentConversation(){return this.currentConversation}clearConversationUnreadMessageCount(e){const t=e.readAt??Date.now();let r=!1,s=!1;const n=this.conversationCache.getAll().map(n=>n.conversationId!==e.conversationId||n.type!==e.type?n:(r=!0,0===n.unreadCount?n:(s=!0,{...n,unreadCount:0,lastUpdate:t})));let i=!1;const o=this.sessionListCache.getAll().map(s=>s.conversationId!==e.conversationId||s.conversationType!==e.type?s:(r=!0,0===s.unreadCount&&s.readAt===t?s:(i=!0,{...s,unreadCount:0,readAt:t,updatedAt:t})));return s||i?(s&&this.conversationCache.setAll(n),i&&this.sessionListCache.setAll(o),this.scheduleFlush(["conversation","sessionList"]),{items:this.sessionListCache.exportItems(),changed:!0,matched:r}):{items:this.sessionListCache.exportItems(),changed:!1,matched:r}}clearAllConversationUnreadMessageCount(e){const t=e?.readAt??Date.now(),r=this.conversationCache.getAll(),s=r.map(e=>0===e.unreadCount?e:{...e,unreadCount:0,lastUpdate:t}),n=this.sessionListCache.getAll(),i=n.map(e=>0===e.unreadCount&&e.readAt===t?e:{...e,unreadCount:0,readAt:t,updatedAt:t}),o=!this.isConversationListEqual(r,s),a=!this.isSessionListEqual(n,i);return o||a?(o&&this.conversationCache.setAll(s),a&&this.sessionListCache.setAll(i),this.scheduleFlush(["conversation","sessionList"]),{items:this.sessionListCache.exportItems(),changed:!0}):{items:this.sessionListCache.exportItems(),changed:!1}}applyConversationPinnedMutation(e){const t=Date.now(),r=this.conversationCache.getAll(),s=this.conversationCache.getAll().map(r=>r.conversationId!==e.conversationId||r.type!==e.type?r:{...r,isPinned:e.isPinned,pinnedTime:e.isPinned?e.pinnedTime??t:0,lastUpdate:t}),n=this.sessionListCache.getAll(),i=n.map(r=>r.conversationId!==e.conversationId||r.conversationType!==e.type?r:{...r,isPinned:e.isPinned,pinnedTimestamp:e.isPinned?e.pinnedTime??t:0,updatedAt:t}),o=!this.isConversationListEqual(r,s),a=!this.isSessionListEqual(n,i);return o||a?(o&&this.conversationCache.setAll(s),a&&this.sessionListCache.setAll(i),this.scheduleFlush(["conversation","sessionList"]),{items:this.sessionListCache.exportItems(),changed:!0}):{items:this.sessionListCache.exportItems(),changed:!1}}deleteConversation(e){const t=this.conversationCache.getAll(),r=this.sessionListCache.getAll();if("number"==typeof e.deletedAt&&this.getConversationLatestUpdate(t,r,e.conversationId,e.type)>e.deletedAt)return{items:this.sessionListCache.exportItems(),changed:!1};if("number"==typeof e.deletedAt){const t=this.buildConversationKey(e.conversationId,e.type),r=this.conversationDeletionTimestamps.get(t)??0;this.conversationDeletionTimestamps.set(t,Math.max(r,e.deletedAt))}const s=t.filter(t=>t.conversationId!==e.conversationId||t.type!==e.type),n=r.filter(t=>t.conversationId!==e.conversationId||t.conversationType!==e.type),i=s.length!==t.length,o=n.length!==r.length;return i||o?(i&&this.conversationCache.setAll(s),o&&this.sessionListCache.setAll(n),this.scheduleFlush(["conversation","sessionList"]),{items:this.sessionListCache.exportItems(),changed:!0}):{items:this.sessionListCache.exportItems(),changed:!1}}clearConversations(){const e=this.conversationCache.getAll().length>0,t=this.sessionListCache.getAll().length>0;return e||t?(e&&this.conversationCache.setAll([]),t&&this.sessionListCache.setAll([]),this.scheduleFlush(["conversation","sessionList"]),{items:this.sessionListCache.exportItems(),changed:!0}):{items:this.sessionListCache.exportItems(),changed:!1}}applyConversationMarkMutation(e){const t=new Set(e.conversations.filter(e=>e.applied).map(e=>`${e.conversationType}:${e.conversationId}`));if(0===t.size)return{items:this.sessionListCache.exportItems(),changed:!1};const r=Date.now(),s=t=>"addMark"===e.operation?t.includes(e.mark)?t:[...t,e.mark]:t.filter(t=>t!==e.mark),n=this.conversationCache.getAll(),i=n.map(e=>{const n=`${e.type}:${e.conversationId}`;if(!t.has(n))return e;const i=s(e.marks);return this.areConversationMarksEqual(i,e.marks)?e:{...e,marks:i,lastUpdate:r}}),o=this.sessionListCache.getAll(),a=o.map(e=>{const n=`${e.conversationType}:${e.conversationId}`;if(!t.has(n))return e;const i=s(e.marks);return this.areConversationMarksEqual(i,e.marks)?e:{...e,marks:i,updatedAt:r}}),c=!this.isConversationListEqual(n,i),d=!this.isSessionListEqual(o,a);return c||d?(c&&this.conversationCache.setAll(i),d&&this.sessionListCache.setAll(a),this.scheduleFlush(["conversation","sessionList"]),{items:this.sessionListCache.exportItems(),changed:!0}):{items:this.sessionListCache.exportItems(),changed:!1}}replaceSessionList(e,t,r){const s=Date.now(),n=e.map(e=>({...e,updatedAt:e.lastMessageAt??s})),i=Ff({snapshot:n,existing:this.sessionListCache.getAll(),syncStartedAt:r?.syncStartedAt});this.sessionListCache.setAll(this.hydrateSessionListRecordsFromLocalProfiles(i,s)),t&&(this.sessionListCheckpoint={...this.sessionListCheckpoint,...t}),this.scheduleFlush(["sessionList"])}mergeSessionListIncremental(e,t){this.sessionListCache.setAll(this.hydrateSessionListRecordsFromLocalProfiles(this.buildIncrementalSessionListRecords(e))),t&&(this.sessionListCheckpoint={...this.sessionListCheckpoint,...t}),this.scheduleFlush(["sessionList"])}async commitSessionListSync(e){this.activeFlushPromise&&await this.activeFlushPromise,this.sessionListCommitInProgress=!0;let t=[],r=this.getDomainRevision("sessionList");try{let s=!1;for(;!s;){const n=this.getDomainRevision("sessionList");t=this.buildSessionListSyncCandidate(e),await this.writeSessionListStorageRecord(t,e.checkpoint,!0),r=this.getDomainRevision("sessionList"),r===n&&(s=!0)}this.sessionListCache.setAll(t),this.sessionListCheckpoint=e.checkpoint;const n=this.pendingDirtyRevisions.get("sessionList");return void 0!==n&&n<=r&&this.pendingDirtyRevisions.delete("sessionList"),await this.metadataStore.touchLastFlush(),{items:this.sessionListCache.exportItems(),checkpoint:this.sessionListCheckpoint}}finally{this.sessionListCommitInProgress=!1,this.pendingDirtyRevisions.size>0&&this.ensureFlushScheduled()}}setUserInfoSummaries(e){const t=Date.now();this.userInfoCache.setAll(e,t),this.userInfoCache.trimMax(this.config.maxUserInfoCount),this.refreshContactCacheIntegrity(!1),this.scheduleFlush(["userInfo","contactMeta"])}upsertRuntimeUserInfos(e){0!==e.length&&this.userInfoRuntimeStore.setAll(e)}getRuntimeUserInfo(e,t=!1){return this.userInfoRuntimeStore.get(e,t)?.profile??null}applyUserInfoNotifyPatch(e){const t=this.userInfoCache.getByIds([e.userId],Date.now(),!1)[0],r=t?jf(t):void 0;return this.userInfoRuntimeStore.applyPatch(e,r)}updateUserInfoSummaryFromRuntime(e){const t=this.userInfoRuntimeStore.get(e,!1);t&&this.setUserInfoSummaries([zf(t)])}getUserInfoSummaries(e,t){const r=Date.now(),s=this.userInfoCache.getByIds(e,r,t);return t&&this.scheduleFlush(["userInfo"]),s}removeUserInfo(e){this.userInfoCache.remove(e),this.refreshContactCacheIntegrity(!1),this.scheduleFlush(["userInfo","contactMeta"])}getGroupNamecard(e,t,r){const s=this.groupNamecardCache.get(e,t,Date.now(),r);return r&&s&&this.scheduleFlush(["groupNamecard"]),s}setGroupNamecards(e){const t=Date.now();this.groupNamecardCache.setAll(e,t),"number"==typeof this.config.maxGroupNamecardCount&&this.groupNamecardCache.trimMax(this.config.maxGroupNamecardCount),this.scheduleFlush(["groupNamecard"])}removeGroupNamecards(e){this.groupNamecardCache.remove(e),this.scheduleFlush(["groupNamecard"])}setContactVersionState(e){this.contactCache.setVersionState(e),this.scheduleFlush(["contactVersion"])}markContactCacheIncomplete(e){this.contactCache.updateMeta({cacheIntegrity:"incomplete",reason:e}),this.scheduleFlush(["contactMeta"])}applyContactSync(e){const t=this.loadContactSnapshot("cache"),r=Date.now();this.userInfoCache.setAll(e.userInfos.map(e=>({userId:e.userId,nickname:e.nickname,avatarUrl:e.avatarUrl,sign:e.sign,ext:e.ext,lastAccess:r,lastUpdate:r})),r),"full"===e.mode?this.contactCache.replaceAll(e.relations):this.contactCache.upsert(e.relations),this.userInfoCache.trimMax(this.config.maxUserInfoCount),this.contactCache.setVersionState({version:e.version,lastVersionCheckAt:r,lastVersionSource:"sync_page"}),this.contactCache.updateMeta({cacheIntegrity:"complete",lastSyncTs:e.lastSyncTs,lastSuccessfulVersion:e.version,lastSyncMode:e.mode}),this.refreshContactCacheIntegrity(!1),this.scheduleFlush(["userInfo","contactRelation","contactVersion","contactMeta"]);const s=this.loadContactSnapshot("sync");return{snapshot:s,changed:this.buildContactSnapshotSignature(t)!==this.buildContactSnapshotSignature(s)}}refreshSessionListDisplayFromUserInfos(e){const t=new Map;for(const d of e){if(!d.userId)continue;const e=t.get(d.userId);"number"==typeof e&&"number"==typeof d.lastModified&&e>=d.lastModified||t.set(d.userId,d.lastModified)}if(0===t.size)return{items:this.sessionListCache.exportItems(),changed:!1};const r=Date.now(),s=this.loadContactSnapshot("cache").items,n=new Map(s.map(e=>[e.userId,e])),i=new Map(this.userInfoCache.getAll().map(e=>[e.userId,e])),o=this.sessionListCache.getAll().map(e=>{let s=e;if("singleChat"===e.conversationType&&!this.shouldSkipSessionUserDisplayRefresh(e.conversationId,t,i)){const t=n.get(e.conversationId),o=this.resolveSessionDisplayUserInfo(e.conversationId,i),a=this.buildSingleSessionDisplayFields(e.conversationId,t,o,e.conversationName,e.conversationAvatar);e.conversationName===a.conversationName&&e.conversationAvatar===a.conversationAvatar||(s={...s,conversationName:a.conversationName,conversationAvatar:a.conversationAvatar,updatedAt:r})}const o=s.lastMessage;if(o&&!this.shouldSkipSessionUserDisplayRefresh(o.sender.userId,t,i)){const e=n.get(o.sender.userId),t=this.resolveSessionDisplayUserInfo(o.sender.userId,i),a=this.buildSessionMessageSender(o.sender.userId,o.sender,e,t);this.isSenderEqual(o.sender,a)||(s={...s,lastMessage:{...o,sender:a},updatedAt:r})}return s}),a=this.sessionListCache.getAll(),c=!this.isSessionListEqual(a,o);return c&&(this.sessionListCache.setAll(o),this.scheduleFlush(["sessionList"])),{items:this.sessionListCache.exportItems(),changed:c}}refreshSessionListDisplayFromJoinedGroups(e,t){const r=new Map;for(const a of e){const e=a.groupId.trim();e&&r.set(e,a)}if(0===r.size)return{items:this.sessionListCache.exportItems(),changed:!1};const s=Date.now(),n=this.sessionListCache.getAll().map(e=>{if("groupChat"!==e.conversationType)return e;const n=r.get(e.conversationId);if(!n)return e;const i=Boolean(e.conversationName.trim())&&e.conversationName!==e.conversationId;if(t?.onlyWhenNameMissing&&i)return e;const o=n.name?.trim(),a=o||e.conversationName,c=n.avatarUrl??e.conversationAvatar,d=this.mapJoinedGroupRemindTypeToSession(n.remindType),u=void 0!==d&&d!==e.remindType;return a!==e.conversationName||c!==e.conversationAvatar||u?{...e,conversationName:a,conversationAvatar:c,remindType:u?d:e.remindType,updatedAt:s}:e}),i=this.sessionListCache.getAll(),o=!this.isSessionListEqual(i,n);return o&&(this.sessionListCache.setAll(n),this.scheduleFlush(["sessionList"])),{items:this.sessionListCache.exportItems(),changed:o}}removeContact(e){return this.applyContactLocalPatch(()=>this.contactCache.remove(e))}updateContactRemark(e,t){return this.applyContactLocalPatch(()=>this.contactCache.updateRemark(e,t,Date.now()))}applyContactRosterNotice(e){const t=this.loadContactSnapshot("cache"),r=Date.now(),s="add"===e.action?this.contactCache.addByNotice(e.userId,r):this.contactCache.remove(e.userId),n="string"==typeof e.rosterVersion&&e.rosterVersion.trim().length>0&&this.contactCache.updateVersionFromNotice(e.rosterVersion,r);(s||n)&&(this.refreshContactCacheIntegrity(!1),this.scheduleFlush(["contactRelation","contactVersion","contactMeta"]));const i=this.loadContactSnapshot("cache");return{snapshot:i,changed:this.buildContactSnapshotSignature(t)!==this.buildContactSnapshotSignature(i)}}updateConversationsFromServer(e,t){const r=Date.now(),s=this.conversationCache.getAll(),n=this.mergeConversationLists(s,e,r,t?.syncStartedAt),i=!this.isConversationListEqual(s,n);return this.conversationCache.setAll(n),this.config.maxConversations&&this.conversationCache.trimMax(this.config.maxConversations),this.scheduleFlush(["conversation"]),{items:n,changed:i}}applyIncomingMessageToConversations(e){const t=this.resolveConversationFromMessage(e);if(!t)return{items:this.conversationCache.getAll(),changed:!1};const r=Date.now(),s=this.conversationCache.getAll(),n=s.findIndex(e=>e.conversationId===t.conversationId&&e.type===t.type),i=n>=0?s[n]:void 0,o=this.buildConversationFromMessage(e,i,r);if(!o)return{items:s,changed:!1};const a=[o,...s.filter((e,t)=>t!==n)];return this.isConversationListEqual(s,a)?{items:s,changed:!1}:(this.conversationCache.setAll(a),this.config.maxConversations&&this.conversationCache.trimMax(this.config.maxConversations),this.scheduleFlush(["conversation"]),{items:this.conversationCache.getAll(),changed:!0})}applyIncomingMessageToSessionList(e){const t=this.resolveConversationFromMessage(e);if(!t)return{items:this.sessionListCache.exportItems(),changed:!1};const r=this.sessionListCache.getAll(),s=r.find(e=>e.conversationId===t.conversationId&&e.conversationType===t.type),n=this.conversationCache.getAll().find(e=>e.conversationId===t.conversationId&&e.type===t.type)??this.buildConversationFromMessage(e,void 0,Date.now());if(!n)return{items:this.sessionListCache.exportItems(),changed:!1};const i=(e=>{const t=qf(e.nextRecord),r=e.existing.filter(e=>qf(e)!==t);return Df([e.nextRecord,...r])})({existing:r,nextRecord:this.buildSessionListRecordFromConversation(n,e,s,Date.now())});return this.isSessionListEqual(r,i)?{items:this.sessionListCache.exportItems(),changed:!1}:(this.sessionListCache.setAll(i),this.scheduleFlush(["sessionList"]),{items:this.sessionListCache.exportItems(),changed:!0})}async loadFromStorage(){const e=Date.now(),t=await this.readDump(this.conversationKey);this.conversationCache.load(t,e);const r=await this.readDump(this.userInfoKey);this.userInfoCache.load(r,e);const s=await this.readDump(this.groupNamecardKey);this.groupNamecardCache.load(s,e);const n=await this.readValue(this.sessionListKey,null),i=n&&El(n)&&Array.isArray(n.items)?n.items:[];this.sessionListCache.load(i,e);const o=(n&&El(n)&&El(n.checkpoint)?n.checkpoint:null)??await this.readValue(this.sessionListCheckpointKey,null);this.sessionListCheckpoint=this.normalizeSessionListCheckpoint(o);const a=await this.readValue(this.joinedGroupPreviewKey,null);this.joinedGroupPreviewCache.load(a);const c=await this.readDump(this.contactRelationKey),d=await this.readValue(this.contactVersionKey,null),u=await this.readValue(this.contactMetaKey,null);this.contactCache.load(c,d,u),this.refreshContactCacheIntegrity(!1),await this.metadataStore.load()}async readDump(e){const t=await this.store.readAsync(e,{items:[]});return t&&El(t)&&Array.isArray(t.items)?t.items:[]}async readValue(e,t){return await this.store.readAsync(e,t)}normalizeSessionListCheckpoint(e){return e&&El(e)?{lastSyncTime:"number"==typeof e.lastSyncTime?e.lastSyncTime:0,lastSyncFinishedTs:"number"==typeof e.lastSyncFinishedTs?e.lastSyncFinishedTs:0,sessionsLastSyncTs:"number"==typeof e.sessionsLastSyncTs?e.sessionsLastSyncTs:0,lastSuccessfulAt:"number"==typeof e.lastSuccessfulAt?e.lastSuccessfulAt:0}:{lastSyncTime:0,lastSyncFinishedTs:0,sessionsLastSyncTs:0,lastSuccessfulAt:0}}scheduleFlush(e){this.markDirty(e),this.ensureFlushScheduled()}markDirty(e){if(0!==e.length){this.mutationRevision+=1;for(const t of e)this.domainRevisions.set(t,this.mutationRevision),this.pendingDirtyRevisions.set(t,this.mutationRevision)}}getDomainRevision(e){return this.domainRevisions.get(e)??0}ensureFlushScheduled(){null===this.flushTimer&&null===this.flushIdleHandle&&("undefined"==typeof requestIdleCallback?this.flushTimer=setTimeout(()=>{this.flushTimer=null,this.flushNow()},this.config.flushIntervalMs):this.flushIdleHandle=requestIdleCallback(()=>{this.flushIdleHandle=null,this.flushNow()},{timeout:this.config.flushIntervalMs}))}takePendingDirtyBatch(){const e=this.pendingDirtyRevisions;return this.pendingDirtyRevisions=new Map,e}restoreDirtyBatch(e){for(const[t,r]of e){const e=this.pendingDirtyRevisions.get(t)??0;this.pendingDirtyRevisions.set(t,Math.max(r,e))}}addQuotaCleanupDomains(e,t){"none"!==t&&(this.mutationRevision+=1,this.domainRevisions.set(t,this.mutationRevision),this.domainRevisions.set("contactMeta",this.mutationRevision),e.set(t,this.mutationRevision),e.set("contactMeta",this.mutationRevision))}async flushNow(){if(this.activeFlushPromise)return void(await this.activeFlushPromise);const e=this.takePendingDirtyBatch();if(this.sessionListCommitInProgress){const t=e.get("sessionList");void 0!==t&&(e.delete("sessionList"),this.restoreDirtyBatch(new Map([["sessionList",t]])))}if(0===e.size)return;const t=this.flushDirtyBatch(e);this.activeFlushPromise=t;try{await t}finally{this.activeFlushPromise=null,this.pendingDirtyRevisions.size>0&&this.ensureFlushScheduled()}}async flushDirtyBatch(e){try{const s=6;for(let n=0;n<=s;n+=1)try{return await this.writeDirtyDomains(e),void(await this.metadataStore.touchLastFlush())}catch(t){if(!mu(t))return this.restoreDirtyBatch(e),void Si("Cache flush failed",t);const s=this.handleQuotaExceeded();if(this.addQuotaCleanupDomains(e,s),"none"===s)return void Si("Cache flush failed: no cache entry can be evicted",t);try{await this.writeDomain(s)}catch(r){if(!mu(r))return this.restoreDirtyBatch(e),void Si("Cache quota cleanup persistence failed",r)}}Si("Cache flush failed after quota cleanup attempts")}finally{}}async writeDirtyDomains(e){for(const t of Hf)e.has(t)&&await this.writeDomain(t)}async writeDomain(e){switch(e){case"conversation":return void(await this.store.writeAsync(this.conversationKey,{items:this.conversationCache.getAll()}));case"userInfo":return void(await this.store.writeAsync(this.userInfoKey,{items:this.userInfoCache.getAll()}));case"groupNamecard":return void(await this.store.writeAsync(this.groupNamecardKey,{items:this.groupNamecardCache.getAll()}));case"sessionList":return void(await this.writeSessionListStorageRecord());case"joinedGroupPreview":return void(await this.store.writeAsync(this.joinedGroupPreviewKey,this.joinedGroupPreviewCache.exportRecord()));case"contactRelation":return void(await this.store.writeAsync(this.contactRelationKey,{items:this.contactCache.getAll()}));case"contactVersion":return void(await this.store.writeAsync(this.contactVersionKey,this.contactCache.getVersionState()));case"contactMeta":await this.store.writeAsync(this.contactMetaKey,this.contactCache.getMeta())}}async writeSessionListStorageRecord(e=this.sessionListCache.getAll(),t=this.sessionListCheckpoint,r=!1){const s={items:e,checkpoint:t};r?await this.store.writeStrictAsync(this.sessionListKey,s):await this.store.writeAsync(this.sessionListKey,s),await this.store.remove(this.sessionListCheckpointKey)}buildIncrementalSessionListRecords(e){const t=this.sessionListCache.getAll(),r=new Map;for(const n of t)r.set(`${n.conversationType}:${n.conversationId}`,n);const s=Date.now();return(e=>{const t=e.incoming.filter(e=>Lf(e)>0),r=new Map;for(const n of e.incoming)r.set(qf(n),n);const s=t.length>0?e.existing.filter(e=>!r.has(qf(e))&&0===Lf(e)):e.existing.filter(e=>!r.has(qf(e)));return Df([...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(Ff({snapshot:r,existing:this.sessionListCache.getAll(),syncStartedAt:e.syncStartedAt}),t)}filterItemsAgainstConversationDeletions(e){return e.filter(e=>{const t=this.buildConversationKey(e.conversationId,e.conversationType),r=this.conversationDeletionTimestamps.get(t);if(void 0===r)return!0;return Math.max(e.lastMessageAt??0,e.lastMessage?.timestamp??0)>r})}getConversationLatestUpdate(e,t,r,s){const n=e.find(e=>e.conversationId===r&&e.type===s),i=t.find(e=>e.conversationId===r&&e.conversationType===s);return Math.max(n?.lastUpdate??0,n?.lastMessage?.timestamp??0,i?.updatedAt??0,i?.lastMessageAt??0,i?.lastMessage?.timestamp??0)}handleQuotaExceeded(){const e=Date.now(),t=1e3*this.config.ttlSeconds;if(this.groupNamecardCache.removeExpired(t,e))return this.contactCache.updateMeta({cacheIntegrity:"incomplete",reason:"quota_exceeded"}),this.refreshContactCacheIntegrity(!1),"groupNamecard";const r=this.groupNamecardCache.getAll().length;if(r>0){const e=this.calculateEvictCount(r,.2);if(this.groupNamecardCache.evictByLru(e))return this.contactCache.updateMeta({cacheIntegrity:"incomplete",reason:"quota_exceeded"}),this.refreshContactCacheIntegrity(!1),"groupNamecard"}if(this.userInfoCache.removeExpired(t,e))return this.contactCache.updateMeta({cacheIntegrity:"incomplete",reason:"quota_exceeded"}),this.refreshContactCacheIntegrity(!1),"userInfo";const s=this.evictByPolicy();return this.contactCache.updateMeta({cacheIntegrity:"incomplete",reason:"quota_exceeded"}),this.refreshContactCacheIntegrity(!1),s}evictByPolicy(){const e=this.userInfoCache.getAll().length;if(e>0){const t=this.calculateEvictCount(e,.2);return t>0?(this.userInfoCache.evictByLru(t),"userInfo"):"none"}const t=this.conversationCache.getAll().length,r=this.calculateEvictCount(t,.05);return r>0?(this.conversationCache.evictByLru(r),"conversation"):"none"}calculateEvictCount(e,t){if(e<=0)return 0;const r=Math.floor(e*t);return Math.max(r,1)}mergeConversationLists(e,t,r,s){const n=new Map,i=new Map;for(const d of e){const e=this.buildConversationKey(d.conversationId,d.type);n.set(e,d.lastAccess),i.set(e,d)}const o=[],a=new Set;for(const d of t){const e=this.buildConversationKey(d.conversationId,d.type);a.add(e);const t=n.get(e)??r;o.push({...d,marks:Array.isArray(d.marks)?d.marks:[],lastAccess:t,lastUpdate:r})}const c=e.filter(e=>{const t=this.buildConversationKey(e.conversationId,e.type);return!a.has(t)&&("number"==typeof s&&e.lastUpdate>s)});return[...o,...c]}isConversationListEqual(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r+=1){const s=e[r],n=t[r];if(!s||!n)return!1;if(this.buildConversationSignature(s)!==this.buildConversationSignature(n))return!1}return!0}buildConversationSignature(e){const t=e.lastMessage,r=t?`${t.msgId}:${t.type}:${t.timestamp}:${JSON.stringify(t.body)}`:"none",s=e.isPinned?"1":"0",n="number"==typeof e.pinnedTime?e.pinnedTime:0,i=e.marks.join(",");return`${e.type}:${e.conversationId}:${e.unreadCount}:${s}:${n}:${i}:${r}`}buildConversationKey(e,t){return`${t}:${e}`}areConversationMarksEqual(e,t){return e.length===t.length&&e.every((e,r)=>e===t[r])}buildConversationFromMessage(e,t,r=Date.now()){const s=this.resolveConversationFromMessage(e);if(!s)return null;const n=e.msgServerId||e.msgLocalId,i=t?.lastMessage?.msgId!==n&&this.shouldIncreaseUnreadForMessage(e)?(t?.unreadCount??0)+1:t?.unreadCount??0,o="SEND"===e.direct?r:t?.lastAccess??r;return{conversationId:s.conversationId,type:s.type,lastMessage:this.buildMessageSnippet(e),unreadCount:i,isPinned:t?.isPinned,pinnedTime:t?.pinnedTime,marks:t?.marks??[],lastAccess:o,lastUpdate:r}}resolveConversationFromMessage(e){if(e.isChatThread||"cmd"===e.type)return null;if("string"!=typeof e.conversationId||!e.conversationId)return null;if("singleChat"===e.conversationType){const t="RECEIVE"===e.direct&&e.from.startsWith(`${this.userId}/`)&&e.sender.userId===this.userId,r="SEND"===e.direct||t?e.conversationId:"string"==typeof e.sender.userId?e.sender.userId:"";return r?{conversationId:r,type:"singleChat"}:null}return"groupChat"===e.conversationType?{conversationId:e.conversationId,type:"groupChat"}:"chatRoom"===e.conversationType?{conversationId:e.conversationId,type:"chatRoom"}:null}buildMessageSnippet(e){const t=(e=>{const t=up(e);return{userInfoUpdateTime:t?.userInfoUpdateTime,namecardUpdateTime:"groupChat"===e.conversationType?t?.namecardUpdateTime:void 0}})(e);return{msgId:e.msgServerId||e.msgLocalId,type:e.type,body:this.normalizeMessageBody(e.body),timestamp:e.timestamp,userInfoUpdateTime:t.userInfoUpdateTime,namecardUpdateTime:t.namecardUpdateTime,modifiedInfo:e.modifiedInfo}}normalizeMessageBody(e){return e&&"object"==typeof e&&!Array.isArray(e)?e:{}}buildSessionListRecordFromConversation(e,t,r,s=Date.now()){const n=new Map(this.loadContactSnapshot("cache").items.map(e=>[e.userId,e])),i=n.get(e.conversationId),o=this.userInfoRuntimeStore.get(e.conversationId,!1)?.profile,a=this.userInfoCache.getByIds([e.conversationId],s,!1)[0],c=o??(a?{userId:a.userId,nickname:a.nickname,avatarUrl:a.avatarUrl,sign:a.sign,ext:a.ext}:null),d=e.lastMessage,u=r?.conversationName,l=r?.conversationAvatar,p="string"==typeof t.sender.userId?t.sender.userId:"",h=this.resolveSessionDisplayUserInfo(p),m=this.buildSessionMessageSender(p,t.sender,n.get(p),h),f="singleChat"===e.type?"SEND"===t.direct?e.conversationId:this.userId:e.conversationId,g="singleChat"===e.type?this.buildSingleSessionDisplayFields(e.conversationId,i,c,u,l):"chatRoom"===e.type?this.buildChatRoomSessionDisplayFields(e.conversationId,u,l):this.buildGroupSessionDisplayFields(e.conversationId,u,l);return{conversationId:e.conversationId,conversationType:e.type,unreadCount:this.resolveSessionListUnreadCount(e,t,r),lastMessage:d?{msgServerId:d.msgId,from:p,to:f,sender:m,conversationId:e.conversationId,conversationType:e.type,type:t.type,sendStatus:t.sendStatus,timestamp:d.timestamp,direct:t.direct,body:d.body}:null,lastMessageAt:d?.timestamp??e.lastUpdate,isPinned:e.isPinned,pinnedTimestamp:e.pinnedTime,marks:[],readAt:r?.readAt,remindType:r?.remindType??"DEFAULT",conversationName:g.conversationName,conversationAvatar:g.conversationAvatar,updatedAt:s}}resolveSessionListUnreadCount(e,t,r){const s=r?.unreadCount,n=t.msgServerId||t.msgLocalId;return r?.lastMessage?.msgServerId!==n&&this.shouldIncreaseUnreadForMessage(t)?"number"==typeof s?Math.max(e.unreadCount,s+1):e.unreadCount:"number"==typeof s?Math.max(e.unreadCount,s):e.unreadCount}shouldIncreaseUnreadForMessage(e){if("RECEIVE"!==e.direct||!1===e.isOnline)return!1;const t=this.resolveConversationFromMessage(e);return!t||!this.currentConversation||(this.currentConversation.conversationId!==t.conversationId||this.currentConversation.type!==t.type)}buildSingleSessionDisplayFields(e,t,r,s,n){const i=t?.remark?.trim(),o=t?.userInfo.avatarUrl??r?.avatarUrl??n;if(i)return{conversationName:i,conversationAvatar:o};const a=t?.userInfo.nickname?.trim()||r?.nickname?.trim();return a?{conversationName:a,conversationAvatar:o}:s?{conversationName:s,conversationAvatar:o}:{conversationName:e,conversationAvatar:o}}shouldSkipSessionUserDisplayRefresh(e,t,r){if(!t.has(e))return!0;const s=t.get(e),n=r.get(e);return"number"==typeof s&&"number"==typeof n?.lastUpdate&&n.lastUpdate>s}hydrateSessionListRecordsFromLocalProfiles(e,t=Date.now()){const r=this.loadContactSnapshot("cache").items,s=new Map(r.map(e=>[e.userId,e])),n=new Map(this.userInfoCache.getAll().map(e=>[e.userId,e]));return e.map(e=>{const r=e.lastMessage;if(!r)return e;const i=r.sender.userId,o=s.get(i),a=this.resolveSessionDisplayUserInfo(i,n),c="singleChat"===e.conversationType&&i===e.conversationId?this.buildSingleChatPeerMessageSender(i,r.sender,o,a):this.buildSessionMessageSender(i,r.sender,o,a);return this.isSenderEqual(r.sender,c)?e:{...e,lastMessage:{...r,sender:c},updatedAt:t}})}resolveSessionDisplayUserInfo(e,t){const r=this.userInfoRuntimeStore.get(e,!1)?.profile;if(r)return r;const s=t?.get(e)??this.userInfoCache.getByIds([e],Date.now(),!1)[0];return s?jf(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 Wf{constructor(){this.handlers=new Map}addEventHandler(e,t){this.handlers.set(e,t)}removeEventHandler(e){this.handlers.delete(e)}dispatch(e,t){const r=[],s=[];for(const i of this.handlers.entries()){const[e]=i;e.startsWith("__internal")?r.push(i):s.push(i)}const n=this.dispatchToHandlers(e,t,r);n?n.then(()=>{this.dispatchToHandlers(e,t,s)}):this.dispatchToHandlers(e,t,s)}dispatchToHandlers(e,t,r){let s=null;for(const[,n]of r){const r=n[e];r&&(s=s?s.then(async()=>{await this.invokeHandler(e,t,r)}):this.invokeHandler(e,t,r))}return s}invokeHandler(e,t,r){try{const s=r(t);return this.isPromiseLike(s)?Promise.resolve(s).then(()=>{}).catch(t=>{Ti(`Event handler error for ${e}`,t)}):null}catch(s){return Ti(`Event handler error for ${e}`,s),null}}isPromiseLike(e){return"object"==typeof e&&null!==e&&"then"in e&&"function"==typeof e.then}}const Jf={maxAttempts:3,initialDelay:1e3,maxDelay:6e4,backoffMultiplier:2,jitter:!0};function Zf(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 Qf(e){return new Promise(t=>setTimeout(t,e))}const Yf=e=>{const t={...e};return delete t.type,t},Xf=(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:Yf(r.body),modifiedInfo:r.modifiedInfo,userInfoUpdateTime:r.userInfoUpdateTime,namecardUpdateTime:r.namecardUpdateTime}},eg=async(e,t)=>{const r=(e=>{const t=e.groupManager;return"function"==typeof t?.getGroupInfoList?t:null})(t);if(!r)return new Map;const s=[...new Set(e.filter(e=>"groupChat"===e.type).map(e=>e.conversationId))];if(0===s.length)return new Map;const n=[];for(let a=0;a<s.length;a+=50)n.push(s.slice(a,a+50));const i=new Map;let o=0;return await Promise.all(Array.from({length:Math.min(3,n.length)},async()=>await(async()=>{for(;o<n.length;){const e=o;o+=1;const t=n[e];if(t)try{const e=await r.getGroupInfoList({groupIds:t});for(const t of e)t.groupId&&i.set(t.groupId,t)}catch{}}})())),i},tg=async(e,t)=>{const r=await eg(e,t);return e.map(e=>((e,t,r)=>{const s=t.getContactSnapshot()?.items.find(t=>t.userId===e.conversationId),n=((e,t)=>{const r=e.getCacheManager();if(!r)return null;const s=r.getRuntimeUserInfo(t,!1);if(s)return s;const n=r.getUserInfoSummaries([t],!1)[0];return n?{userId:n.userId,nickname:n.nickname,avatarUrl:n.avatarUrl,sign:n.sign,ext:n.ext}:null})(t,e.conversationId),i="singleChat"===e.type?((e,t,r)=>{const s=t?.remark?.trim();if(s)return{conversationName:s,conversationAvatar:t?.userInfo.avatarUrl??r?.avatarUrl};const n=t?.userInfo.nickname?.trim()||r?.nickname?.trim();return n?{conversationName:n,conversationAvatar:t?.userInfo.avatarUrl??r?.avatarUrl}:{conversationName:e,conversationAvatar:t?.userInfo.avatarUrl??r?.avatarUrl}})(e.conversationId,s,n):"groupChat"===e.type?(o=e.conversationId,a=r.get(e.conversationId),a?.name?{conversationName:a.name,conversationAvatar:a.avatarUrl}:{conversationName:o}):(e=>({conversationName:e}))(e.conversationId);var o,a;return{conversationId:e.conversationId,conversationType:e.type,unreadCount:e.unreadCount,lastMessage:Xf(e,t),lastMessageAt:e.lastMessage?.timestamp??e.lastUpdate,isPinned:e.isPinned,pinnedTimestamp:e.pinnedTime,marks:[],readAt:void 0,remindType:"DEFAULT",conversationName:i.conversationName,conversationAvatar:i.conversationAvatar}})(e,t,r))};class rg{constructor(e=`session-list-${Xh()}`){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 sg=0,ng=5,ig=10,og=11,ag=1,cg=2,dg=1,ug=2,lg=3,pg=e=>e===ag?"groupChat":e===cg?"chatRoom":"singleChat",hg=()=>cl().lookupType("easemob.pb.MessageBody"),mg=e=>{const t=hg().toObject(hg().decode(e),{longs:Number,bytes:Uint8Array}),r=Array.isArray(t.contents)?t.contents:[],s=(n=r[0])&&"object"==typeof n&&!Array.isArray(n)?n:{};var n;const i="number"==typeof s.type?s.type:0;return 0===i?{type:"text",content:"string"==typeof s.text?s.text:""}:1===i?{type:"image",filename:"string"==typeof s.displayName?s.displayName:"image",remotePath:"string"==typeof s.remotePath?s.remotePath:""}:2===i?{type:"video",filename:"string"==typeof s.displayName?s.displayName:"video",remotePath:"string"==typeof s.remotePath?s.remotePath:""}:3===i?{type:"location",latitude:"number"==typeof s.latitude?s.latitude:0,longitude:"number"==typeof s.longitude?s.longitude:0,address:"string"==typeof s.address?s.address:void 0}:4===i?{type:"voice",filename:"string"==typeof s.displayName?s.displayName:"voice",remotePath:"string"==typeof s.remotePath?s.remotePath:"",duration:"number"==typeof s.duration?s.duration:0}:5===i?{type:"file",filename:"string"==typeof s.displayName?s.displayName:"file",remotePath:"string"==typeof s.remotePath?s.remotePath:""}:6===i?{type:"cmd",action:"string"==typeof s.action?s.action:""}:7===i?{type:"custom",event:"string"==typeof s.customEvent?s.customEvent:""}:8===i?{type:"combine",title:"string"==typeof s.title?s.title:"",summary:"string"==typeof s.summary?s.summary:""}:{}},fg=e=>{const t=e.session_id??"",r=(e=>{if(!e)return null;try{const t=JSON.parse(e);if(t&&"object"==typeof t&&!Array.isArray(t))return t}catch{return null}return null})(e.metadata),s="string"==typeof r?.nickname?r.nickname:void 0,n="string"==typeof r?.remark?r.remark:void 0,i="string"==typeof r?.avatarurl?r.avatarurl:"string"==typeof r?.avatarUrl?r.avatarUrl:void 0;return n?{conversationName:n,conversationAvatar:i}:s?{conversationName:s,conversationAvatar:i}:{conversationName:t,conversationAvatar:i}},gg=e=>{const t={...e};return delete t.type,t},yg=e=>"singleChat"===e.conversationType?e.from===e.currentUserId?e.conversationId:e.currentUserId:e.conversationId,vg=(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:yg({conversationId:r.conversationId,conversationType:r.conversationType,from:s,currentUserId:r.currentUserId}),sender:n,conversationId:r.conversationId,conversationType:r.conversationType,type:(i=t.type,"text"===i||"image"===i||"file"===i||"voice"===i||"video"===i||"location"===i||"custom"===i||"cmd"===i||"combine"===i?i:"text"),timestamp:e.timestamp??0,body:gg(t)};var i},bg=e=>{if(!Array.isArray(e))return[];const t=new Set,r=[],s=e;for(const n of s){const e="string"==typeof n&&n.startsWith("mark_")?n.slice(5):n,s="number"==typeof e?e:"string"==typeof e?Number.parseInt(e,10):Number.NaN;if(!Number.isInteger(s)||s<0||s>19)continue;const i=s;t.has(i)||(t.add(i),r.push(i))}return r},Ig=(e,t)=>e.sessions.map(e=>{const r=(e=>{if(!e||0===e.byteLength)return{};try{return mg(e)}catch{return{}}})(e.last_message?.payload),s=e.session_id??"",n=pg(e.session_type),i=(e=>{const t=e.session_id??"",r=pg(e.session_type);return"groupChat"===r||"chatRoom"===r?{conversationName:e.group_name??t,conversationAvatar:e.group_avatar}:fg(e)})(e);return{conversationId:s,conversationType:n,unreadCount:e.unread_count??0,lastMessage:vg(e.last_message,r,{conversationId:s,conversationType:n,currentUserId:t,singleChatPeerDisplay:"singleChat"===n?i:void 0}),lastMessageAt:e.updated_at,isPinned:"number"==typeof e.pinned_time?e.pinned_time>0:void 0,pinnedTimestamp:e.pinned_time,marks:bg(e.marks),readAt:e.read_receipt,remindType:(o=e.remind_type,o===dg?"ALL":o===ug?"AT":o===lg?"NONE":"DEFAULT"),conversationName:i.conversationName,conversationAvatar:i.conversationAvatar};var o}),wg={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 Cg=null,Sg=!1;const Tg=()=>Cg||(Sg||(Dc.util.Long=mo,Dc.configure(),Sg=!0),hd(),Cg=Dc.Root.fromJSON(wg),pd(Cg),Cg),_g=e=>Tg().lookupType(e),Rg=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}},Ag=e=>{if(!e||"object"!=typeof e)return;const t=e;return{resource:"string"==typeof t.resource?t.resource:"",timestamp:Rg(t.timestamp)??0,requestId:"string"==typeof t.request_id?t.request_id:"string"==typeof t.requestId?t.requestId:"",protocolVersion:Rg(t.protocol_version)??Rg(t.protocolVersion)??0}},Mg=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}},Eg=e=>{if(!e||"object"!=typeof e)return;const t=e;return{id:"string"==typeof t.id?t.id:void 0!==Rg(t.id)?String(Rg(t.id)):void 0,from:Mg(t.from),timestamp:Rg(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 Ug{constructor(){this.requestType=_g("easemob.sessionlist.GetSessionListRequest"),this.responseType=_g("easemob.sessionlist.GetSessionListResponse"),this.errorType=_g("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:sg}}tryDecodeRequest(e){try{const t=this.requestType.toObject(this.requestType.decode(e),{longs:String,bytes:Uint8Array}),r=Rg(t.type);return r!==ig?null:{type:r,header:Ag(t.header),org:"string"==typeof t.org?t.org:"",app:"string"==typeof t.app?t.app:"",username:"string"==typeof t.username?t.username:"",lastSyncTime:Rg(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=Rg(t.type);return r!==og?null:{type:r,header:Ag(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:Rg(t.session_type),last_message:Eg(t.last_message),updated_at:Rg(t.updated_at),pinned_time:Rg(t.pinned_time),unread_count:Rg(t.unread_count),marks:Array.isArray(t.marks)?t.marks.filter(e=>"string"==typeof e):void 0,read_receipt:Rg(t.read_receipt),remind_type:Rg(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:Rg(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=Rg(t.type);return r!==ng?null:{type:r,header:Ag(t.header),code:Rg(t.code)??0,message:"string"==typeof t.message?t.message:"Unknown session-list error"}}catch{return null}}}const kg=async e=>{const t=e.client.getCacheManager(),r=e.client.getRestContext(),s=e.client.getSessionListSyncWsUrls();if(!t||0===s.length)throw new Wr("session-list sync websocket is unavailable",{code:gt,details:{protocol:"session-list",stage:"socket_connect"}});const[n,i]=r.appKey.split("#");if(!n||!i)throw new Zr("session-list appKey is invalid",{code:it,details:{appKey:r.appKey}});const o=t.loadSessionListCheckpoint(),a=(e=>({type:10,header:{resource:e.resource,timestamp:Date.now(),requestId:e.requestId,protocolVersion:e.protocolVersion??1},org:e.org,app:e.app,username:e.username,lastSyncTime:e.lastSyncTime,includeEmpty:e.params?.includeEmpty??!1,includeMark:!0}))({requestId:e.session.getRequestId(),resource:r.clientResource,org:n,app:i,username:r.userId,lastSyncTime:(c=o.sessionsLastSyncTs,Math.max(0,c-2e4)),params:e.params});var c;const d=new Ug;let u=0,l=o.sessionsLastSyncTs;return await e.client.getSharedSyncWebSocketSession().request({dataType:"conversation",label:"session-list-sync",requestId:e.session.getRequestId(),encode:()=>d.encodeRequest(a),decode:e=>{const t=d.decode(e);return{type:t.type,requestId:"header"in t?t.header?.requestId:void 0,frame:t}},onFrame:t=>{if(5===t.type&&"code"in t&&"message"in t)throw 1002===(s=t).code?new Jr(s.message,{code:lt,details:{protocol:"session-list",responseCode:s.code}}):1003===s.code?new Hr(s.message,kt,{details:{protocol:"session-list",responseCode:s.code}}):1501===s.code||1001===s.code?new Zr(s.message,{code:it,details:{protocol:"session-list",responseCode:s.code}}):1503===s.code?new Hr(s.message,Ut,{details:{protocol:"session-list",responseCode:s.code}}):(s.code,new Hr(s.message,fr,{details:{protocol:"session-list",responseCode:s.code}}));var s;if(11!==t.type)throw new Hr("session-list response type is invalid",Mt,{details:{responseType:t.type}});const n=t,i=n.header?.requestId;if(i&&i!==e.session.getRequestId())return;u+=1,Ci("Decoded session-list sync raw response",{requestId:e.session.getRequestId(),batchSequence:u,response:n});const o=Ig(n,r.userId),a=e.session.pushBatch({requestId:e.session.getRequestId(),batchSequence:u,sessions:o,isLastBatch:!0===n.isLastBatch,lastSyncFinishedTs:n.lastSyncFinishedTs});if("number"==typeof n.lastSyncFinishedTs&&(l=n.lastSyncFinishedTs),!a.done)return;return{done:!0,result:{items:e.session.getItems(),lastSyncFinishedTs:l}}}})},Ng=e=>new Zr(`${e} must be a local paging cursor returned by SDK`,{code:it,details:{fields:[{path:e,message:`${e} must be a local paging cursor returned by SDK`,rule:"invalid_format"}]}}),Og=(e,t,r)=>{const s=e+t;return s<r?String(s):""},xg=e=>({...e}),Lg=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}},Pg=e=>"AT"===e||"NONE"===e||"ALL"===e?e:null,Dg=e=>{if(!Number.isInteger(e.pageSize)||e.pageSize<=0)throw new Zr("pageSize must be a positive integer",{code:it,details:{fields:[{path:"pageSize",message:"pageSize must be a positive integer",rule:"range"}]}});const t=((e,t)=>{if(void 0===e||""===e)return 0;if(!/^\d+$/.test(e))throw Ng(t);const r=Number.parseInt(e,10);if(!Number.isSafeInteger(r)||r<0)throw Ng(t);return r})(e.cursor,"cursor"),r=[];for(const s of e.items){if("chatRoom"===s.conversationType)continue;const e=Pg(s.remindType);e&&r.push({conversationId:s.conversationId,conversationType:s.conversationType,remindType:e})}return{conversations:r.slice(t,t+e.pageSize),cursor:Og(t,e.pageSize,r.length)}},qg=()=>Date.now(),$g={maxAttempts:3,initialDelay:3e3,maxDelay:5e3,backoffMultiplier:1,jitter:!0},Gg=(e,t)=>({status:e,determinedAt:qg(),reason:t}),Fg=e=>e instanceof Hr&&(e.code===kt||1103===e.code),Bg=e=>({dataType:"conversation",code:e.code,stage:"fallback",message:e.message,retryable:Fg(e)});class jg{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 rg,this.currentSession.start(),this.running=this.runRefresh(this.currentSession,{includeEmpty:e.includeEmpty,includeMark:!0}),this.running.finally(()=>{this.running=null,this.currentSession=null})),this.running}async runRefresh(e,t){const r=this.client.getCacheManager();if(!r)return[];this.client.emitSyncDataStart("conversation");const s=await this.tryDirectFallback(r);if(s)return this.client.emitConversationListUpdate("conversation",!0),this.client.emitSyncDataFinished({dataType:"conversation",status:"success"}),s;try{const s=r.loadSessionListCheckpoint().sessionsLastSyncTs>0?"incremental":"full";let i=0;const o=await async function(e,t,r={}){const s={...Jf,...r};let n;for(let o=1;o<=s.maxAttempts;o++)try{return await e()}catch(i){if(n=i,!t(i))throw i;if(o>=s.maxAttempts)throw i;const e=Zf(o,s);await Qf(e)}throw n}(async()=>{i+=1;const r=1===i?e:this.createRetrySession();r.start();try{return await kg({client:this.client,session:r,params:t})}catch(s){throw r.fail(),s}},Fg,$g),a={result:o,syncStartedAt:e.getStartedAt()},c=a.result.items;this.capabilityState={status:"available",determinedAt:qg()};const d={lastSyncTime:a.result.lastSyncFinishedTs,lastSyncFinishedTs:a.result.lastSyncFinishedTs,sessionsLastSyncTs:a.result.lastSyncFinishedTs,lastSuccessfulAt:qg()};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:Bg(t)}),r.loadSessionList()}const u=r.loadSessionList();return r.updateConversationsFromServer(u.map(Lg),{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:Gg("unsupported",e.message),shouldUseFallback:!0}:e.code===lt||e.code===pt?{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 i=await this.buildFallbackSessionList(r);return s.shouldUseFallback&&r.replaceSessionList(i),this.client.emitConversationListUpdate("conversation",!0),this.client.emitSyncDataFinished({dataType:"conversation",status:"failed",error:Bg(t)}),i}}async tryDirectFallback(e){if("unsupported"===(t=this.capabilityState).status||"unconfigured"===t.status){const t=await this.buildFallbackSessionList(e);return e.replaceSessionList(t),t}var t;const r=Boolean(this.client.getServerUrlsConfig()?.syncWsUrl),s=this.client.isSessionListDnsProbeAvailable();if(!r&&!s){this.capabilityState=Gg("unconfigured","session-list sync websocket is unavailable");const t=await this.buildFallbackSessionList(e);return e.replaceSessionList(t),t}return null}createRetrySession(){return new rg}async buildFallbackSessionList(e){return await(async(e,t)=>await tg(e,t))(e.loadConversationSummaries(),this.client)}}const zg=e=>"[object ArrayBuffer]"===Object.prototype.toString.call(e),Kg=async e=>{if("string"==typeof e||zg(e)||ArrayBuffer.isView(e))return(e=>"string"==typeof e?(new TextEncoder).encode(e):zg(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}})},Hg=e=>{const t=Math.max(e-1,0),r=1e3*Math.pow(2,t);return Math.min(r,5e3)},Vg=async e=>{await new Promise(t=>{setTimeout(t,e)})},Wg=e=>e instanceof Error?e:new Error(String(e));class Jg{constructor(e){this.pending=new Map,this.socket=null,this.state="idle",this.connectPromise=null,this.activeUrl="",this.urlIndex=0,this.attempt=0,this.connectTimer=null,this.idleTimer=null,this.retryTimer=null,this.completeCloseTimer=null,this.cancelled=!1,this.getUrls=e.getUrls,this.socketAdapter=e.socketAdapter}async request(e){if(this.cancelled)throw new Hr("sync websocket session is cancelled",_r,{details:{stage:"cancelled",requestId:e.requestId}});if(this.pending.has(e.requestId))throw new Hr("sync websocket requestId is duplicated",it,{details:{stage:"request_send",requestId:e.requestId}});this.clearCompleteCloseTimer();const t=new Promise((t,r)=>{this.pending.set(e.requestId,{...e,resolve:t,reject:r})});t.catch(()=>{});try{await this.ensureConnected(),this.sendPendingRequest(this.pending.get(e.requestId))}catch(r){this.rejectPending(e.requestId,Wg(r))}return await t}cancel(e="sync-websocket-cancelled"){this.cancelled=!0;const t=new Hr("sync websocket cancelled",_r,{details:{stage:"cancelled",reason:e}});this.rejectAll(t),this.closeSocket(4001,e),this.clearTimers(),this.connectPromise=null,this.state="idle"}close(e="sync-websocket-closed"){this.closeSocket(1e3,e),this.clearTimers(),this.connectPromise=null,this.state="idle"}async ensureConnected(){if("open"!==this.state||this.socket?.readyState!==ji){if(this.connectPromise)return await this.connectPromise;this.connectPromise=this.connectWithRetry();try{await this.connectPromise}finally{this.connectPromise=null}}}async connectWithRetry(){let e=null;for(;!this.cancelled&&this.pending.size>0&&this.attempt<3;){this.attempt+=1,this.attempt>1&&Si("sync websocket retry started",this.buildLogContext({reason:e?.message}));try{return void(await this.openSocket())}catch(t){if(e=Wg(t),this.cancelled||0===this.pending.size)throw e;if(this.attempt>=3)throw Si("sync websocket retry exhausted",this.buildLogContext({reason:e.message})),e;const r=Hg(this.attempt);Si("sync websocket retry scheduled",this.buildLogContext({delayMs:r,reason:e.message})),await Vg(r)}}throw new Wr("sync websocket retry exhausted",{code:Cr,details:{stage:"socket_connect",reason:e?.message??"unknown"}})}async openSocket(){const e=await this.getUrls();if(0===e.length)throw new Wr("sync websocket urls are unavailable",{code:Cr,details:{stage:"socket_connect"}});const t=e[this.urlIndex%e.length];if(this.urlIndex+=1,!t)throw new Wr("sync websocket url is invalid",{code:Cr,details:{stage:"socket_connect"}});this.activeUrl=t,this.state="connecting",Si("sync websocket connect started",this.buildLogContext());const r=Vi(),s=this.socketAdapter??Ld({webSocketCtor:r.WebSocket});if(!s)throw this.state="idle",this.buildConnectionError("sync websocket adapter is unavailable","socket_connect");let n=null;try{const e=await Promise.race([s.connect({url:t}),new Promise((e,t)=>{n=setTimeout(()=>{t(this.buildConnectionError("sync websocket socket connect timeout","socket_connect"))},5e3)})]);n&&clearTimeout(n),this.socket=e,e.onMessage(t=>{this.socket===e&&this.handleMessage(t)}),e.onError(()=>{this.socket===e&&this.handleSocketFailure(this.buildConnectionError("sync websocket runtime error","sync_page"))}),e.onClose(t=>{if(this.socket===e)return"closing"===this.state||0===this.pending.size?(this.clearTimers(),this.socket=null,void(this.state="idle")):void this.handleSocketFailure(this.buildConnectionError("sync websocket socket closed","sync_page",{closeCode:t.code,closeReason:t.reason}))}),this.state="open",this.resetIdleTimer(),Si("sync websocket connected",this.buildLogContext())}catch(i){if(n&&clearTimeout(n),this.state="idle",this.closeSocket(4e3,"sync-websocket-connect-failed"),i instanceof Wr)throw i;throw this.buildConnectionError("sync websocket socket create failed","socket_connect",{cause:i instanceof Error?i.message:String(i)})}}async handleMessage(e){try{this.resetIdleTimer();const t=await Kg(e);if(!(await this.routeFrame(t)))return}catch(t){const e=Wg(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(Wg(s)),this.closeIfComplete()}return!0}t.requestId||1!==t.type||r||(r={pending:n,frame:t.frame})}catch(s){t.push(Wg(s))}if(r)return await r.pending.onFrame(r.frame,this.socket),!0;if(this.pending.size>0&&t.length===this.pending.size)throw new Hr("sync websocket frame decode failed",Tr,{details:{stage:"response_decode",cause:t[0]?.message}});return Si("sync websocket frame ignored",this.buildLogContext({reason:t[0]?.message??"requestId not matched"})),!1}handleSocketFailure(e){if(this.closeSocket(4e3,"sync-websocket-failed"),this.clearTimers(),this.state="idle",!this.cancelled&&0!==this.pending.size)return this.attempt>=3?(Si("sync websocket retry exhausted",this.buildLogContext({reason:e.message})),void this.rejectAll(e)):void(this.connectPromise=this.connectWithRetry().then(()=>{this.resendPendingRequests()}).catch(e=>{this.rejectAll(Wg(e))}).finally(()=>{this.connectPromise=null}))}resendPendingRequests(){for(const e of this.pending.values())this.sendPendingRequest(e)}sendPendingRequest(e){if(e&&this.socket&&this.socket.readyState===ji)try{this.socket.send(e.encode()).catch(t=>{this.rejectPending(e.requestId,this.buildConnectionError("sync websocket request send failed","request_send",{cause:t instanceof Error?t.message:String(t)}))}),Si("sync websocket request sent",this.buildLogContext({requestId:e.requestId,dataTypes:[e.dataType]})),this.resetIdleTimer()}catch(t){this.rejectPending(e.requestId,this.buildConnectionError("sync websocket request send failed","request_send",{cause:t instanceof Error?t.message:String(t)}))}}rejectPending(e,t){const r=this.pending.get(e);r&&(this.pending.delete(e),r.reject(t),this.closeIfComplete())}rejectAll(e){const t=[...this.pending.values()];this.pending.clear(),t.forEach(t=>{t.reject(e)})}closeIfComplete(){this.pending.size>0||(this.clearCompleteCloseTimer(),this.completeCloseTimer=setTimeout(()=>{this.completeCloseTimer=null,this.pending.size>0||(Si("sync websocket closed after complete",this.buildLogContext()),this.close("sync-websocket-complete"))},0))}resetIdleTimer(){this.clearIdleTimer(),0!==this.pending.size&&(this.idleTimer=setTimeout(()=>{this.handleSocketFailure(this.buildConnectionError("sync websocket socket idle timeout","sync_page"))},1e4))}clearTimers(){this.clearConnectTimer(),this.clearIdleTimer(),this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=null),this.clearCompleteCloseTimer()}clearConnectTimer(){this.connectTimer&&(clearTimeout(this.connectTimer),this.connectTimer=null)}clearIdleTimer(){this.idleTimer&&(clearTimeout(this.idleTimer),this.idleTimer=null)}clearCompleteCloseTimer(){this.completeCloseTimer&&(clearTimeout(this.completeCloseTimer),this.completeCloseTimer=null)}closeSocket(e,t){const r=this.socket;this.socket=null,!r||r.readyState>=zi||(this.state="closing",r.close(e,t))}buildConnectionError(e,t,r={}){return new Wr(e,{code:Cr,details:{stage:t,url:this.activeUrl,...r}})}buildLogContext(e={}){return{attempt:this.attempt,maxAttempts:3,url:zr(this.activeUrl),pendingCount:this.pending.size,dataTypes:[...new Set([...this.pending.values()].map(e=>e.dataType))],...e}}}const Zg=(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 Qg(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 Yg={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"}},Xg=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/[^a-zA-Z0-9]+/g,"_").replace(/^_+|_+$/g,"").toUpperCase(),ey=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 ty{constructor(e,t){this.baseUrl=e.replace(/\/$/,""),this.timeout=t?.timeout??15e3,this.errorMap=t?.errorMap,this.requestAdapter=t?.requestAdapter,this.includeRequestId=t?.includeRequestId??!1,this.defaultHeaders={Accept:"application/json",...t?.headers}}sanitizeUrl(e){try{const t=new URL(e),r=t.searchParams;for(const e of r.keys())r.set(e,"***");const s=r.toString(),n=s?`?${s}`:"";return`${t.origin}${t.pathname}${n}`}catch{return e.split("?")[0]??e}}setAuthToken(e){this.defaultHeaders.Authorization=`Bearer ${e}`}removeAuthToken(){delete this.defaultHeaders.Authorization}buildHttpStatusFallbackError(e,t,r,s){const n={...t.operation?{api:t.operation}:{},url:t.url,method:t.method,httpStatus:e,serverCode:r,serverMessage:s,mapped:!1};if(400===e)return new Zr("Invalid request parameters",{code:ot,details:{...n,canonicalCode:ot}});if(401===e){const e=[r,s].some(e=>"string"==typeof e&&/token[ _-]?(?:has[ _-]?)?expired/i.test(e)),t=e?lt:dt;return new Jr(e?"Authentication token expired":"Authentication failed",{code:t,details:{...n,reasonKey:e?"token_expired":"unauthorized",canonicalCode:t}})}return 403===e?new Jr("Access forbidden",{code:ut,details:{...n,canonicalCode:ut}}):429===e?new ts("REST rate limit exceeded",{code:Fr,details:{...n,retryable:!0,reasonKey:"request_rate_limited",canonicalCode:Fr}}):e>=500?new ts("REST business error: request failed",{code:fr,details:{...n,retryable:!0,reasonKey:"server_unknown_error",canonicalCode:fr}}):void 0}async request(e,t={}){const r=`${this.baseUrl}${e}`,s=t.method??"GET",n=Date.now(),i=this.sanitizeUrl(r);Ci("REST request",{method:s,url:i,operation:t.operation});const o=t.operation?(e=>{const t=Yg[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_${Xg(e)}`,operationType:r}})(t.operation):void 0,a=o?Wh(o):void 0,c=a?.startRequest({requestName:o?.operationName,method:s,url:r});let d=0;const u={...this.defaultHeaders,...t.headers};this.includeRequestId&&(u[vl]=yl());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 h of Object.keys(u))"content-type"===h.toLowerCase()&&delete u[h];try{if(this.requestAdapter){const e=await this.requestAdapter.request({url:r,method:s,headers:u,body:t.body,timeoutMs:t.timeout??this.timeout});d=e.status;const o=((e,t)=>{if("string"!=typeof e)return e;const r=Object.entries(t).find(([e])=>"content-type"===e.toLowerCase()),s=e.trim();if(!(r?.[1].includes("application/json")||s.startsWith("{")&&s.endsWith("}")||s.startsWith("[")&&s.endsWith("]")))return e;try{return JSON.parse(s)}catch{return e}})(e.data,e.headers),l=Date.now()-n;(e.status<200||e.status>=300)&&(Si("REST response error",{method:s,url:i,status:e.status,duration:l}),this.handleErrorPayload(e.status,"",o,{operation:t.operation,url:r,method:s})),Ci("REST response",{method:s,url:i,status:e.status,duration:l});const p=ey(o);return c?.finish({code:e.status,success:!0,resultCount:p}),a?.finish({code:0,success:!0,resultCount:p}),o}const e=new AbortController,o=setTimeout(()=>e.abort(),t.timeout??this.timeout),p=await fetch(r,{...l,signal:e.signal});d=p.status,clearTimeout(o);const h=Date.now()-n;p.ok||(Si("REST response error",{method:s,url:i,status:p.status,duration:h}),await this.handleErrorResponse(p,{operation:t.operation,url:r,method:s})),Ci("REST response",{method:s,url:i,status:p.status,duration:h});const m=p.headers.get("content-type");if(m?.includes("application/json")){const e=await p.json(),t=ey(e);return c?.finish({code:p.status,success:!0,resultCount:t}),a?.finish({code:0,success:!0,resultCount:t}),e}const f=await p.text();return c?.finish({code:p.status,success:!0}),a?.finish({code:0,success:!0}),f}catch(p){const e=0!==d?d:p instanceof Hr?p.code:-1,n=p instanceof Error?p.message:String(p);if(c?.finish({code:e,success:!1,description:n}),a?.finish({code:e,success:!1,description:n}),p instanceof Hr)throw p;if(p instanceof Error&&"AbortError"===p.name)throw Si("REST request timeout",{method:s,url:i,timeout:t.timeout??this.timeout}),new es(`Request timeout: ${r}`,{code:hr,details:{url:r,method:s,timeout:t.timeout??this.timeout}});throw Si("REST request failed",{method:s,url:i}),new es(`Request failed: ${r}`,{code:pr,details:{url:r,method:s}})}}async handleErrorResponse(e,t){let r;try{r=await e.json()}catch{r=await e.text()}this.handleErrorPayload(e.status,e.statusText,r,t)}handleErrorPayload(e,t,r,s){const n=r&&"object"==typeof r?r:{},i=((e,t)=>{if(!e.error||"object"!=typeof e.error||Array.isArray(e.error))return;const r=e.error,s=r.code;if("number"!=typeof s&&"string"!=typeof s)return;const n=String(s);return/^\d{7}$/.test(n)&&Number(n.slice(0,3))===t?r:void 0})(n,e),o=i?{...n,code:i.code,message:i.message}:r,a=function(e,t,r){if(!e)return;const s=r&&"object"==typeof r?r:{},n="string"==typeof s.error?s.error:void 0,i=(e=>"string"==typeof e.error_code||"number"==typeof e.error_code?e.error_code:"string"==typeof e.errorCode||"number"==typeof e.errorCode?e.errorCode:"string"==typeof e.error||"number"==typeof e.error?e.error:"string"==typeof e.code||"number"==typeof e.code?e.code:void 0)(s),o="string"==typeof s.error_description?s.error_description:"string"==typeof s.message?s.message:void 0,a=(e,t=!1)=>{const r=(e,r,s)=>({reasonKey:e,entry:r,matchedBy:t?"common":s});if(n&&e[n])return r(n,e[n],"key");for(const[n,i]of Object.entries(e))if(Zg(i,s))return r(n,i,"field");if(void 0!==i)for(const[s,n]of Object.entries(e)){if(n.code===i||n.canonicalCode===i)return r(s,n,"code");if(Array.isArray(n.aliases)&&n.aliases.includes(String(i)))return r(s,n,"alias")}if(o)for(const[s,n]of Object.entries(e))if(Array.isArray(n.aliases)&&n.aliases.includes(o))return r(s,n,"alias")},c=t?e.apis[t]:void 0,d=c?a(c.errors):void 0;if(d)return d;for(const u of Object.values(e.common)){const e=a(u.errors,!0);if(e)return e}}(this.errorMap,s.operation,o),c="string"==typeof n.error?n.error:void 0,d="number"==typeof n.error_code||"string"==typeof n.error_code?n.error_code:"number"==typeof n.errorCode||"string"==typeof n.errorCode?n.errorCode:"number"==typeof n.code||"string"==typeof n.code?n.code:"string"==typeof n.error?n.error:"number"==typeof i?.code||"string"==typeof i?.code?i.code:void 0,u="string"==typeof n.message?n.message:"string"==typeof n.error_description?n.error_description:"string"==typeof i?.message?i.message:void 0,l=!!(401!==e&&403!==e||void 0!==c&&"unauthorized"!==c&&"auth_failed"!==c&&"forbidden"!==c)&&(void 0!==c||"string"==typeof n.error_description||"string"==typeof n.message);if(s.operation&&a)throw Qg({apiName:s.operation,entry:a.entry,serverCode:d,serverMessage:u,httpStatus:e,mapped:!0,reasonKey:a.reasonKey,matchedBy:a.matchedBy});const p=this.buildHttpStatusFallbackError(e,s,d,u);if(p)throw p;if(s.operation&&l)throw Qg({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 ry=async(e,t,r)=>{const{orgName:s,appName:n}=Qn(e.appKey),i=`/${s}/${n}/user/${encodeURIComponent(e.userId)}/roster/metadata/version`,o=new ty(e.restBaseUrl,{requestAdapter:r,includeRequestId:!0});o.setAuthToken(e.token);try{return((e,t)=>{const r=Date.now(),s=e=>{const s="string"==typeof e.version?e.version:"string"==typeof e.rosterVersion?e.rosterVersion:"";return{version:s,requiresSync:("boolean"==typeof e.requiresSync?e.requiresSync:"boolean"==typeof e.needSync?e.needSync:"boolean"==typeof e.need_sync?e.need_sync:void 0)??s!==t,checkedAt:"number"==typeof e.checkedAt?e.checkedAt:"number"==typeof e.timestamp?e.timestamp:r}};if(El(e))return El(e.data)?s(e.data):s(e);throw new Zr("Invalid contact metadata response",{code:it,details:{payload:e}})})(await o.get(i),t)}catch(a){if(a instanceof Zr)throw a;const e=a instanceof Hr&&a.details?a.details:{};throw new es("Contact metadata request failed",{code:wr,details:{stage:"metadata",cause:a instanceof Error?a.message:String(a),httpStatus:"number"==typeof e.httpStatus?e.httpStatus:void 0,sourceCode:a instanceof Hr?a.code:void 0}})}};var sy,ny,iy;(ny=sy||(sy={})).assertEqual=e=>{},ny.assertIs=function(e){},ny.assertNever=function(e){throw new Error},ny.arrayToEnum=e=>{const t={};for(const r of e)t[r]=r;return t},ny.getValidEnumValues=e=>{const t=ny.objectKeys(e).filter(t=>"number"!=typeof e[e[t]]),r={};for(const s of t)r[s]=e[s];return ny.objectValues(r)},ny.objectValues=e=>ny.objectKeys(e).map(function(t){return e[t]}),ny.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},ny.find=(e,t)=>{for(const r of e)if(t(r))return r},ny.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&Number.isFinite(e)&&Math.floor(e)===e,ny.joinValues=function(e,t=" | "){return e.map(e=>"string"==typeof e?`'${e}'`:e).join(t)},ny.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t,(iy||(iy={})).mergeShapes=(e,t)=>({...e,...t});const oy=sy.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ay=e=>{switch(typeof e){case"undefined":return oy.undefined;case"string":return oy.string;case"number":return Number.isNaN(e)?oy.nan:oy.number;case"boolean":return oy.boolean;case"function":return oy.function;case"bigint":return oy.bigint;case"symbol":return oy.symbol;case"object":return Array.isArray(e)?oy.array:null===e?oy.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?oy.promise:"undefined"!=typeof Map&&e instanceof Map?oy.map:"undefined"!=typeof Set&&e instanceof Set?oy.set:"undefined"!=typeof Date&&e instanceof Date?oy.date:oy.object;default:return oy.unknown}},cy=sy.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 dy 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 dy))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,sy.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()}}dy.create=e=>new dy(e);const uy=(e,t)=>{let r;switch(e.code){case cy.invalid_type:r=e.received===oy.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case cy.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,sy.jsonStringifyReplacer)}`;break;case cy.unrecognized_keys:r=`Unrecognized key(s) in object: ${sy.joinValues(e.keys,", ")}`;break;case cy.invalid_union:r="Invalid input";break;case cy.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${sy.joinValues(e.options)}`;break;case cy.invalid_enum_value:r=`Invalid enum value. Expected ${sy.joinValues(e.options)}, received '${e.received}'`;break;case cy.invalid_arguments:r="Invalid function arguments";break;case cy.invalid_return_type:r="Invalid function return type";break;case cy.invalid_date:r="Invalid date";break;case cy.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}"`:sy.assertNever(e.validation):r="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case cy.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 cy.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 cy.custom:r="Invalid input";break;case cy.invalid_intersection_types:r="Intersection results could not be merged";break;case cy.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case cy.not_finite:r="Number must be finite";break;default:r=t.defaultError,sy.assertNever(e)}return{message:r}};let ly=uy;function py(e,t){const r=ly,s=(e=>{const{data:t,path:r,errorMaps:s,issueData:n}=e,i=[...r,...n.path||[]],o={...n,path:i};if(void 0!==n.message)return{...n,path:i,message:n.message};let a="";const c=s.filter(e=>!!e).slice().reverse();for(const d of c)a=d(o,{data:t,defaultError:a}).message;return{...n,path:i,message:a}})({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===uy?void 0:uy].filter(e=>!!e)});e.common.issues.push(s)}class hy{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 fy;"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 hy.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 fy;if("aborted"===n.status)return fy;"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 fy=Object.freeze({status:"aborted"}),gy=e=>({status:"dirty",value:e}),yy=e=>({status:"valid",value:e}),vy=e=>"aborted"===e.status,by=e=>"dirty"===e.status,Iy=e=>"valid"===e.status,wy=e=>"undefined"!=typeof Promise&&e instanceof Promise;var Cy,Sy;(Sy=Cy||(Cy={})).errToObj=e=>"string"==typeof e?{message:e}:e||{},Sy.toString=e=>"string"==typeof e?e:e?.message;class Ty{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 _y=(e,t)=>{if(Iy(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 dy(e.common.issues);return this._error=t,this._error}}};function Ry(e){if(!e)return{};const{errorMap:t,invalid_type_error:r,required_error:s,description:n}=e;if(t&&(r||s))throw new Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');if(t)return{errorMap:t,description:n};return{errorMap:(t,n)=>{const{message:i}=e;return"invalid_enum_value"===t.code?{message:i??n.defaultError}:void 0===n.data?{message:i??s??n.defaultError}:"invalid_type"!==t.code?{message:n.defaultError}:{message:i??r??n.defaultError}},description:n}}class Ay{get description(){return this._def.description}_getType(e){return ay(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:ay(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new hy,ctx:{common:e.parent.common,data:e.data,parsedType:ay(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(wy(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:ay(e)},s=this._parseSync({data:e,path:r.path,parent:r});return _y(r,s)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ay(e)};if(!this["~standard"].async)try{const r=this._parseSync({data:e,path:[],parent:t});return Iy(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=>Iy(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:ay(e)},s=this._parse({data:e,path:r.path,parent:r}),n=await(wy(s)?s:Promise.resolve(s));return _y(r,n)}refine(e,t){const r=e=>"string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(e):t;return this._refinement((t,s)=>{const n=e(t),i=()=>s.addIssue({code:cy.custom,...r(t)});return"undefined"!=typeof Promise&&n instanceof Promise?n.then(e=>!!e||(i(),!1)):!!n||(i(),!1)})}refinement(e,t){return this._refinement((r,s)=>!!e(r)||(s.addIssue("function"==typeof t?t(r,s):t),!1))}_refinement(e){return new Rv({schema:this,typeName:Dv.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 Av.create(this,this._def)}nullable(){return Mv.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return uv.create(this)}promise(){return _v.create(this,this._def)}or(e){return hv.create([this,e],this._def)}and(e){return fv.create(this,e,this._def)}transform(e){return new Rv({...Ry(this._def),schema:this,typeName:Dv.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new Ev({...Ry(this._def),innerType:this,defaultValue:t,typeName:Dv.ZodDefault})}brand(){return new Nv({typeName:Dv.ZodBranded,type:this,...Ry(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new Uv({...Ry(this._def),innerType:this,catchValue:t,typeName:Dv.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return Ov.create(this,e)}readonly(){return xv.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const My=/^c[^\s-]{8,}$/i,Ey=/^[0-9a-z]+$/,Uy=/^[0-9A-HJKMNP-TV-Z]{26}$/i,ky=/^[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,Ny=/^[a-z0-9_-]{21}$/i,Oy=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,xy=/^[-+]?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)?)??$/,Ly=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let Py;const Dy=/^(?:(?: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])$/,qy=/^(?:(?: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])$/,$y=/^(([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]))$/,Gy=/^(([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])$/,Fy=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,By=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,jy="((\\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])))",zy=new RegExp(`^${jy}$`);function Ky(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 Hy(e){return new RegExp(`^${Ky(e)}$`)}function Vy(e){let t=`${jy}T${Ky(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 Wy(e,t){return!("v4"!==t&&t||!Dy.test(e))||!("v6"!==t&&t||!$y.test(e))}function Jy(e,t){if(!Oy.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 Zy(e,t){return!("v4"!==t&&t||!qy.test(e))||!("v6"!==t&&t||!Gy.test(e))}class Qy extends Ay{_parse(e){this._def.coerce&&(e.data=String(e.data));if(this._getType(e)!==oy.string){const t=this._getOrReturnCtx(e);return py(t,{code:cy.invalid_type,expected:oy.string,received:t.parsedType}),fy}const t=new hy;let r;for(const s of this._def.checks)if("min"===s.kind)e.data.length<s.value&&(r=this._getOrReturnCtx(e,r),py(r,{code:cy.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),py(r,{code:cy.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),t.dirty());else if("length"===s.kind){const n=e.data.length>s.value,i=e.data.length<s.value;(n||i)&&(r=this._getOrReturnCtx(e,r),n?py(r,{code:cy.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):i&&py(r,{code:cy.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),t.dirty())}else if("email"===s.kind)Ly.test(e.data)||(r=this._getOrReturnCtx(e,r),py(r,{validation:"email",code:cy.invalid_string,message:s.message}),t.dirty());else if("emoji"===s.kind)Py||(Py=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Py.test(e.data)||(r=this._getOrReturnCtx(e,r),py(r,{validation:"emoji",code:cy.invalid_string,message:s.message}),t.dirty());else if("uuid"===s.kind)ky.test(e.data)||(r=this._getOrReturnCtx(e,r),py(r,{validation:"uuid",code:cy.invalid_string,message:s.message}),t.dirty());else if("nanoid"===s.kind)Ny.test(e.data)||(r=this._getOrReturnCtx(e,r),py(r,{validation:"nanoid",code:cy.invalid_string,message:s.message}),t.dirty());else if("cuid"===s.kind)My.test(e.data)||(r=this._getOrReturnCtx(e,r),py(r,{validation:"cuid",code:cy.invalid_string,message:s.message}),t.dirty());else if("cuid2"===s.kind)Ey.test(e.data)||(r=this._getOrReturnCtx(e,r),py(r,{validation:"cuid2",code:cy.invalid_string,message:s.message}),t.dirty());else if("ulid"===s.kind)Uy.test(e.data)||(r=this._getOrReturnCtx(e,r),py(r,{validation:"ulid",code:cy.invalid_string,message:s.message}),t.dirty());else if("url"===s.kind)try{new URL(e.data)}catch{r=this._getOrReturnCtx(e,r),py(r,{validation:"url",code:cy.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),py(r,{validation:"regex",code:cy.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),py(r,{code:cy.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),py(r,{code:cy.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),py(r,{code:cy.invalid_string,validation:{endsWith:s.value},message:s.message}),t.dirty());else if("datetime"===s.kind){Vy(s).test(e.data)||(r=this._getOrReturnCtx(e,r),py(r,{code:cy.invalid_string,validation:"datetime",message:s.message}),t.dirty())}else if("date"===s.kind){zy.test(e.data)||(r=this._getOrReturnCtx(e,r),py(r,{code:cy.invalid_string,validation:"date",message:s.message}),t.dirty())}else if("time"===s.kind){Hy(s).test(e.data)||(r=this._getOrReturnCtx(e,r),py(r,{code:cy.invalid_string,validation:"time",message:s.message}),t.dirty())}else"duration"===s.kind?xy.test(e.data)||(r=this._getOrReturnCtx(e,r),py(r,{validation:"duration",code:cy.invalid_string,message:s.message}),t.dirty()):"ip"===s.kind?Wy(e.data,s.version)||(r=this._getOrReturnCtx(e,r),py(r,{validation:"ip",code:cy.invalid_string,message:s.message}),t.dirty()):"jwt"===s.kind?Jy(e.data,s.alg)||(r=this._getOrReturnCtx(e,r),py(r,{validation:"jwt",code:cy.invalid_string,message:s.message}),t.dirty()):"cidr"===s.kind?Zy(e.data,s.version)||(r=this._getOrReturnCtx(e,r),py(r,{validation:"cidr",code:cy.invalid_string,message:s.message}),t.dirty()):"base64"===s.kind?Fy.test(e.data)||(r=this._getOrReturnCtx(e,r),py(r,{validation:"base64",code:cy.invalid_string,message:s.message}),t.dirty()):"base64url"===s.kind?By.test(e.data)||(r=this._getOrReturnCtx(e,r),py(r,{validation:"base64url",code:cy.invalid_string,message:s.message}),t.dirty()):sy.assertNever(s);return{status:t.value,value:e.data}}_regex(e,t,r){return this.refinement(t=>e.test(t),{validation:t,code:cy.invalid_string,...Cy.errToObj(r)})}_addCheck(e){return new Qy({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...Cy.errToObj(e)})}url(e){return this._addCheck({kind:"url",...Cy.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...Cy.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...Cy.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...Cy.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...Cy.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...Cy.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...Cy.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...Cy.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...Cy.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...Cy.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...Cy.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...Cy.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,...Cy.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,...Cy.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...Cy.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...Cy.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...Cy.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...Cy.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...Cy.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...Cy.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...Cy.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...Cy.errToObj(t)})}nonempty(e){return this.min(1,Cy.errToObj(e))}trim(){return new Qy({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Qy({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Qy({...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 Yy(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}Qy.create=e=>new Qy({checks:[],typeName:Dv.ZodString,coerce:e?.coerce??!1,...Ry(e)});class Xy extends Ay{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)!==oy.number){const t=this._getOrReturnCtx(e);return py(t,{code:cy.invalid_type,expected:oy.number,received:t.parsedType}),fy}let t;const r=new hy;for(const s of this._def.checks)if("int"===s.kind)sy.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),py(t,{code:cy.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),py(t,{code:cy.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),py(t,{code:cy.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),r.dirty())}else"multipleOf"===s.kind?0!==Yy(e.data,s.value)&&(t=this._getOrReturnCtx(e,t),py(t,{code:cy.not_multiple_of,multipleOf:s.value,message:s.message}),r.dirty()):"finite"===s.kind?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),py(t,{code:cy.not_finite,message:s.message}),r.dirty()):sy.assertNever(s);return{status:r.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,Cy.toString(t))}gt(e,t){return this.setLimit("min",e,!1,Cy.toString(t))}lte(e,t){return this.setLimit("max",e,!0,Cy.toString(t))}lt(e,t){return this.setLimit("max",e,!1,Cy.toString(t))}setLimit(e,t,r,s){return new Xy({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:Cy.toString(s)}]})}_addCheck(e){return new Xy({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:Cy.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Cy.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Cy.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Cy.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Cy.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:Cy.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:Cy.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Cy.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Cy.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&&sy.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)}}Xy.create=e=>new Xy({checks:[],typeName:Dv.ZodNumber,coerce:e?.coerce||!1,...Ry(e)});class ev extends Ay{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)!==oy.bigint)return this._getInvalidInput(e);let t;const r=new hy;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),py(t,{code:cy.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),py(t,{code:cy.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),py(t,{code:cy.not_multiple_of,multipleOf:s.value,message:s.message}),r.dirty()):sy.assertNever(s);return{status:r.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return py(t,{code:cy.invalid_type,expected:oy.bigint,received:t.parsedType}),fy}gte(e,t){return this.setLimit("min",e,!0,Cy.toString(t))}gt(e,t){return this.setLimit("min",e,!1,Cy.toString(t))}lte(e,t){return this.setLimit("max",e,!0,Cy.toString(t))}lt(e,t){return this.setLimit("max",e,!1,Cy.toString(t))}setLimit(e,t,r,s){return new ev({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:Cy.toString(s)}]})}_addCheck(e){return new ev({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:Cy.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Cy.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Cy.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Cy.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:Cy.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}}ev.create=e=>new ev({checks:[],typeName:Dv.ZodBigInt,coerce:e?.coerce??!1,...Ry(e)});class tv extends Ay{_parse(e){this._def.coerce&&(e.data=Boolean(e.data));if(this._getType(e)!==oy.boolean){const t=this._getOrReturnCtx(e);return py(t,{code:cy.invalid_type,expected:oy.boolean,received:t.parsedType}),fy}return yy(e.data)}}tv.create=e=>new tv({typeName:Dv.ZodBoolean,coerce:e?.coerce||!1,...Ry(e)});class rv extends Ay{_parse(e){this._def.coerce&&(e.data=new Date(e.data));if(this._getType(e)!==oy.date){const t=this._getOrReturnCtx(e);return py(t,{code:cy.invalid_type,expected:oy.date,received:t.parsedType}),fy}if(Number.isNaN(e.data.getTime())){return py(this._getOrReturnCtx(e),{code:cy.invalid_date}),fy}const t=new hy;let r;for(const s of this._def.checks)"min"===s.kind?e.data.getTime()<s.value&&(r=this._getOrReturnCtx(e,r),py(r,{code:cy.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),py(r,{code:cy.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),t.dirty()):sy.assertNever(s);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(e){return new rv({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:Cy.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:Cy.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}}rv.create=e=>new rv({checks:[],coerce:e?.coerce||!1,typeName:Dv.ZodDate,...Ry(e)});class sv extends Ay{_parse(e){if(this._getType(e)!==oy.symbol){const t=this._getOrReturnCtx(e);return py(t,{code:cy.invalid_type,expected:oy.symbol,received:t.parsedType}),fy}return yy(e.data)}}sv.create=e=>new sv({typeName:Dv.ZodSymbol,...Ry(e)});class nv extends Ay{_parse(e){if(this._getType(e)!==oy.undefined){const t=this._getOrReturnCtx(e);return py(t,{code:cy.invalid_type,expected:oy.undefined,received:t.parsedType}),fy}return yy(e.data)}}nv.create=e=>new nv({typeName:Dv.ZodUndefined,...Ry(e)});class iv extends Ay{_parse(e){if(this._getType(e)!==oy.null){const t=this._getOrReturnCtx(e);return py(t,{code:cy.invalid_type,expected:oy.null,received:t.parsedType}),fy}return yy(e.data)}}iv.create=e=>new iv({typeName:Dv.ZodNull,...Ry(e)});class ov extends Ay{constructor(){super(...arguments),this._any=!0}_parse(e){return yy(e.data)}}ov.create=e=>new ov({typeName:Dv.ZodAny,...Ry(e)});class av extends Ay{constructor(){super(...arguments),this._unknown=!0}_parse(e){return yy(e.data)}}av.create=e=>new av({typeName:Dv.ZodUnknown,...Ry(e)});class cv extends Ay{_parse(e){const t=this._getOrReturnCtx(e);return py(t,{code:cy.invalid_type,expected:oy.never,received:t.parsedType}),fy}}cv.create=e=>new cv({typeName:Dv.ZodNever,...Ry(e)});class dv extends Ay{_parse(e){if(this._getType(e)!==oy.undefined){const t=this._getOrReturnCtx(e);return py(t,{code:cy.invalid_type,expected:oy.void,received:t.parsedType}),fy}return yy(e.data)}}dv.create=e=>new dv({typeName:Dv.ZodVoid,...Ry(e)});class uv extends Ay{_parse(e){const{ctx:t,status:r}=this._processInputParams(e),s=this._def;if(t.parsedType!==oy.array)return py(t,{code:cy.invalid_type,expected:oy.array,received:t.parsedType}),fy;if(null!==s.exactLength){const e=t.data.length>s.exactLength.value,n=t.data.length<s.exactLength.value;(e||n)&&(py(t,{code:e?cy.too_big:cy.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&&(py(t,{code:cy.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&&(py(t,{code:cy.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 Ty(t,e,t.path,r)))).then(e=>hy.mergeArray(r,e));const n=[...t.data].map((e,r)=>s.type._parseSync(new Ty(t,e,t.path,r)));return hy.mergeArray(r,n)}get element(){return this._def.type}min(e,t){return new uv({...this._def,minLength:{value:e,message:Cy.toString(t)}})}max(e,t){return new uv({...this._def,maxLength:{value:e,message:Cy.toString(t)}})}length(e,t){return new uv({...this._def,exactLength:{value:e,message:Cy.toString(t)}})}nonempty(e){return this.min(1,e)}}function lv(e){if(e instanceof pv){const t={};for(const r in e.shape){const s=e.shape[r];t[r]=Av.create(lv(s))}return new pv({...e._def,shape:()=>t})}return e instanceof uv?new uv({...e._def,type:lv(e.element)}):e instanceof Av?Av.create(lv(e.unwrap())):e instanceof Mv?Mv.create(lv(e.unwrap())):e instanceof gv?gv.create(e.items.map(e=>lv(e))):e}uv.create=(e,t)=>new uv({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Dv.ZodArray,...Ry(t)});class pv extends Ay{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=sy.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==oy.object){const t=this._getOrReturnCtx(e);return py(t,{code:cy.invalid_type,expected:oy.object,received:t.parsedType}),fy}const{status:t,ctx:r}=this._processInputParams(e),{shape:s,keys:n}=this._getCached(),i=[];if(!(this._def.catchall instanceof cv&&"strip"===this._def.unknownKeys))for(const a in r.data)n.includes(a)||i.push(a);const o=[];for(const a of n){const e=s[a],t=r.data[a];o.push({key:{status:"valid",value:a},value:e._parse(new Ty(r,t,r.path,a)),alwaysSet:a in r.data})}if(this._def.catchall instanceof cv){const e=this._def.unknownKeys;if("passthrough"===e)for(const t of i)o.push({key:{status:"valid",value:t},value:{status:"valid",value:r.data[t]}});else if("strict"===e)i.length>0&&(py(r,{code:cy.unrecognized_keys,keys:i}),t.dirty());else if("strip"!==e)throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const e=this._def.catchall;for(const t of i){const s=r.data[t];o.push({key:{status:"valid",value:t},value:e._parse(new Ty(r,s,r.path,t)),alwaysSet:t in r.data})}}return r.common.async?Promise.resolve().then(async()=>{const e=[];for(const t of o){const r=await t.key,s=await t.value;e.push({key:r,value:s,alwaysSet:t.alwaysSet})}return e}).then(e=>hy.mergeObjectSync(t,e)):hy.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(e){return Cy.errToObj,new pv({...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:Cy.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new pv({...this._def,unknownKeys:"strip"})}passthrough(){return new pv({...this._def,unknownKeys:"passthrough"})}extend(e){return new pv({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new pv({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:Dv.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new pv({...this._def,catchall:e})}pick(e){const t={};for(const r of sy.objectKeys(e))e[r]&&this.shape[r]&&(t[r]=this.shape[r]);return new pv({...this._def,shape:()=>t})}omit(e){const t={};for(const r of sy.objectKeys(this.shape))e[r]||(t[r]=this.shape[r]);return new pv({...this._def,shape:()=>t})}deepPartial(){return lv(this)}partial(e){const t={};for(const r of sy.objectKeys(this.shape)){const s=this.shape[r];e&&!e[r]?t[r]=s:t[r]=s.optional()}return new pv({...this._def,shape:()=>t})}required(e){const t={};for(const r of sy.objectKeys(this.shape))if(e&&!e[r])t[r]=this.shape[r];else{let e=this.shape[r];for(;e instanceof Av;)e=e._def.innerType;t[r]=e}return new pv({...this._def,shape:()=>t})}keyof(){return Cv(sy.objectKeys(this.shape))}}pv.create=(e,t)=>new pv({shape:()=>e,unknownKeys:"strip",catchall:cv.create(),typeName:Dv.ZodObject,...Ry(t)}),pv.strictCreate=(e,t)=>new pv({shape:()=>e,unknownKeys:"strict",catchall:cv.create(),typeName:Dv.ZodObject,...Ry(t)}),pv.lazycreate=(e,t)=>new pv({shape:e,unknownKeys:"strip",catchall:cv.create(),typeName:Dv.ZodObject,...Ry(t)});class hv extends Ay{_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 dy(e.ctx.common.issues));return py(t,{code:cy.invalid_union,unionErrors:r}),fy});{let e;const s=[];for(const i of r){const r={...t,common:{...t.common,issues:[]},parent:null},n=i._parseSync({data:t.data,path:t.path,parent:r});if("valid"===n.status)return n;"dirty"!==n.status||e||(e={result:n,ctx:r}),r.common.issues.length&&s.push(r.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;const n=s.map(e=>new dy(e));return py(t,{code:cy.invalid_union,unionErrors:n}),fy}}get options(){return this._def.options}}function mv(e,t){const r=ay(e),s=ay(t);if(e===t)return{valid:!0,data:e};if(r===oy.object&&s===oy.object){const r=sy.objectKeys(t),s=sy.objectKeys(e).filter(e=>-1!==r.indexOf(e)),n={...e,...t};for(const i of s){const r=mv(e[i],t[i]);if(!r.valid)return{valid:!1};n[i]=r.data}return{valid:!0,data:n}}if(r===oy.array&&s===oy.array){if(e.length!==t.length)return{valid:!1};const r=[];for(let s=0;s<e.length;s++){const n=mv(e[s],t[s]);if(!n.valid)return{valid:!1};r.push(n.data)}return{valid:!0,data:r}}return r===oy.date&&s===oy.date&&+e===+t?{valid:!0,data:e}:{valid:!1}}hv.create=(e,t)=>new hv({options:e,typeName:Dv.ZodUnion,...Ry(t)});class fv extends Ay{_parse(e){const{status:t,ctx:r}=this._processInputParams(e),s=(e,s)=>{if(vy(e)||vy(s))return fy;const n=mv(e.value,s.value);return n.valid?((by(e)||by(s))&&t.dirty(),{status:t.value,value:n.data}):(py(r,{code:cy.invalid_intersection_types}),fy)};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}))}}fv.create=(e,t,r)=>new fv({left:e,right:t,typeName:Dv.ZodIntersection,...Ry(r)});class gv extends Ay{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==oy.array)return py(r,{code:cy.invalid_type,expected:oy.array,received:r.parsedType}),fy;if(r.data.length<this._def.items.length)return py(r,{code:cy.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),fy;!this._def.rest&&r.data.length>this._def.items.length&&(py(r,{code:cy.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 Ty(r,e,r.path,t)):null}).filter(e=>!!e);return r.common.async?Promise.all(s).then(e=>hy.mergeArray(t,e)):hy.mergeArray(t,s)}get items(){return this._def.items}rest(e){return new gv({...this._def,rest:e})}}gv.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new gv({items:e,typeName:Dv.ZodTuple,rest:null,...Ry(t)})};class yv extends Ay{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!==oy.object)return py(r,{code:cy.invalid_type,expected:oy.object,received:r.parsedType}),fy;const s=[],n=this._def.keyType,i=this._def.valueType;for(const o in r.data)s.push({key:n._parse(new Ty(r,o,r.path,o)),value:i._parse(new Ty(r,r.data[o],r.path,o)),alwaysSet:o in r.data});return r.common.async?hy.mergeObjectAsync(t,s):hy.mergeObjectSync(t,s)}get element(){return this._def.valueType}static create(e,t,r){return new yv(t instanceof Ay?{keyType:e,valueType:t,typeName:Dv.ZodRecord,...Ry(r)}:{keyType:Qy.create(),valueType:e,typeName:Dv.ZodRecord,...Ry(t)})}}class vv extends Ay{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!==oy.map)return py(r,{code:cy.invalid_type,expected:oy.map,received:r.parsedType}),fy;const s=this._def.keyType,n=this._def.valueType,i=[...r.data.entries()].map(([e,t],i)=>({key:s._parse(new Ty(r,e,r.path,[i,"key"])),value:n._parse(new Ty(r,t,r.path,[i,"value"]))}));if(r.common.async){const e=new Map;return Promise.resolve().then(async()=>{for(const r of i){const s=await r.key,n=await r.value;if("aborted"===s.status||"aborted"===n.status)return fy;"dirty"!==s.status&&"dirty"!==n.status||t.dirty(),e.set(s.value,n.value)}return{status:t.value,value:e}})}{const e=new Map;for(const r of i){const s=r.key,n=r.value;if("aborted"===s.status||"aborted"===n.status)return fy;"dirty"!==s.status&&"dirty"!==n.status||t.dirty(),e.set(s.value,n.value)}return{status:t.value,value:e}}}}vv.create=(e,t,r)=>new vv({valueType:t,keyType:e,typeName:Dv.ZodMap,...Ry(r)});class bv extends Ay{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==oy.set)return py(r,{code:cy.invalid_type,expected:oy.set,received:r.parsedType}),fy;const s=this._def;null!==s.minSize&&r.data.size<s.minSize.value&&(py(r,{code:cy.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&&(py(r,{code:cy.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),t.dirty());const n=this._def.valueType;function i(e){const r=new Set;for(const s of e){if("aborted"===s.status)return fy;"dirty"===s.status&&t.dirty(),r.add(s.value)}return{status:t.value,value:r}}const o=[...r.data.values()].map((e,t)=>n._parse(new Ty(r,e,r.path,t)));return r.common.async?Promise.all(o).then(e=>i(e)):i(o)}min(e,t){return new bv({...this._def,minSize:{value:e,message:Cy.toString(t)}})}max(e,t){return new bv({...this._def,maxSize:{value:e,message:Cy.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}bv.create=(e,t)=>new bv({valueType:e,minSize:null,maxSize:null,typeName:Dv.ZodSet,...Ry(t)});class Iv extends Ay{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})}}Iv.create=(e,t)=>new Iv({getter:e,typeName:Dv.ZodLazy,...Ry(t)});class wv extends Ay{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return py(t,{received:t.data,code:cy.invalid_literal,expected:this._def.value}),fy}return{status:"valid",value:e.data}}get value(){return this._def.value}}function Cv(e,t){return new Sv({values:e,typeName:Dv.ZodEnum,...Ry(t)})}wv.create=(e,t)=>new wv({value:e,typeName:Dv.ZodLiteral,...Ry(t)});class Sv extends Ay{_parse(e){if("string"!=typeof e.data){const t=this._getOrReturnCtx(e),r=this._def.values;return py(t,{expected:sy.joinValues(r),received:t.parsedType,code:cy.invalid_type}),fy}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 py(t,{received:t.data,code:cy.invalid_enum_value,options:r}),fy}return yy(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 Sv.create(e,{...this._def,...t})}exclude(e,t=this._def){return Sv.create(this.options.filter(t=>!e.includes(t)),{...this._def,...t})}}Sv.create=Cv;class Tv extends Ay{_parse(e){const t=sy.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==oy.string&&r.parsedType!==oy.number){const e=sy.objectValues(t);return py(r,{expected:sy.joinValues(e),received:r.parsedType,code:cy.invalid_type}),fy}if(this._cache||(this._cache=new Set(sy.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const e=sy.objectValues(t);return py(r,{received:r.data,code:cy.invalid_enum_value,options:e}),fy}return yy(e.data)}get enum(){return this._def.values}}Tv.create=(e,t)=>new Tv({values:e,typeName:Dv.ZodNativeEnum,...Ry(t)});class _v extends Ay{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==oy.promise&&!1===t.common.async)return py(t,{code:cy.invalid_type,expected:oy.promise,received:t.parsedType}),fy;const r=t.parsedType===oy.promise?t.data:Promise.resolve(t.data);return yy(r.then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}}_v.create=(e,t)=>new _v({type:e,typeName:Dv.ZodPromise,...Ry(t)});class Rv extends Ay{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Dv.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=>{py(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 fy;const s=await this._def.schema._parseAsync({data:e,path:r.path,parent:r});return"aborted"===s.status?fy:"dirty"===s.status||"dirty"===t.value?gy(s.value):s});{if("aborted"===t.value)return fy;const s=this._def.schema._parseSync({data:e,path:r.path,parent:r});return"aborted"===s.status?fy:"dirty"===s.status||"dirty"===t.value?gy(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?fy:("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?fy:("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(!Iy(e))return fy;const i=s.transform(e.value,n);if(i instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:i}}return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(e=>Iy(e)?Promise.resolve(s.transform(e.value,n)).then(e=>({status:t.value,value:e})):fy)}sy.assertNever(s)}}Rv.create=(e,t,r)=>new Rv({schema:e,typeName:Dv.ZodEffects,effect:t,...Ry(r)}),Rv.createWithPreprocess=(e,t,r)=>new Rv({schema:t,effect:{type:"preprocess",transform:e},typeName:Dv.ZodEffects,...Ry(r)});class Av extends Ay{_parse(e){return this._getType(e)===oy.undefined?yy(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Av.create=(e,t)=>new Av({innerType:e,typeName:Dv.ZodOptional,...Ry(t)});class Mv extends Ay{_parse(e){return this._getType(e)===oy.null?yy(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Mv.create=(e,t)=>new Mv({innerType:e,typeName:Dv.ZodNullable,...Ry(t)});class Ev extends Ay{_parse(e){const{ctx:t}=this._processInputParams(e);let r=t.data;return t.parsedType===oy.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}Ev.create=(e,t)=>new Ev({innerType:e,typeName:Dv.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...Ry(t)});class Uv extends Ay{_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 wy(s)?s.then(e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new dy(r.common.issues)},input:r.data})})):{status:"valid",value:"valid"===s.status?s.value:this._def.catchValue({get error(){return new dy(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}Uv.create=(e,t)=>new Uv({innerType:e,typeName:Dv.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...Ry(t)});class kv extends Ay{_parse(e){if(this._getType(e)!==oy.nan){const t=this._getOrReturnCtx(e);return py(t,{code:cy.invalid_type,expected:oy.nan,received:t.parsedType}),fy}return{status:"valid",value:e.data}}}kv.create=e=>new kv({typeName:Dv.ZodNaN,...Ry(e)});class Nv extends Ay{_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 Ov extends Ay{_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?fy:"dirty"===e.status?(t.dirty(),gy(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?fy:"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 Ov({in:e,out:t,typeName:Dv.ZodPipeline})}}class xv extends Ay{_parse(e){const t=this._def.innerType._parse(e),r=e=>(Iy(e)&&(e.value=Object.freeze(e.value)),e);return wy(t)?t.then(e=>r(e)):r(t)}unwrap(){return this._def.innerType}}function Lv(e,t){const r="function"==typeof e?e(t):"string"==typeof e?{message:e}:e;return"string"==typeof r?{message:r}:r}function Pv(e,t={},r){return e?ov.create().superRefine((s,n)=>{const i=e(s);if(i instanceof Promise)return i.then(e=>{if(!e){const e=Lv(t,s),i=e.fatal??r??!0;n.addIssue({code:"custom",...e,fatal:i})}});if(!i){const e=Lv(t,s),i=e.fatal??r??!0;n.addIssue({code:"custom",...e,fatal:i})}}):ov.create()}var Dv,qv;xv.create=(e,t)=>new xv({innerType:e,typeName:Dv.ZodReadonly,...Ry(t)}),(qv=Dv||(Dv={})).ZodString="ZodString",qv.ZodNumber="ZodNumber",qv.ZodNaN="ZodNaN",qv.ZodBigInt="ZodBigInt",qv.ZodBoolean="ZodBoolean",qv.ZodDate="ZodDate",qv.ZodSymbol="ZodSymbol",qv.ZodUndefined="ZodUndefined",qv.ZodNull="ZodNull",qv.ZodAny="ZodAny",qv.ZodUnknown="ZodUnknown",qv.ZodNever="ZodNever",qv.ZodVoid="ZodVoid",qv.ZodArray="ZodArray",qv.ZodObject="ZodObject",qv.ZodUnion="ZodUnion",qv.ZodDiscriminatedUnion="ZodDiscriminatedUnion",qv.ZodIntersection="ZodIntersection",qv.ZodTuple="ZodTuple",qv.ZodRecord="ZodRecord",qv.ZodMap="ZodMap",qv.ZodSet="ZodSet",qv.ZodFunction="ZodFunction",qv.ZodLazy="ZodLazy",qv.ZodLiteral="ZodLiteral",qv.ZodEnum="ZodEnum",qv.ZodEffects="ZodEffects",qv.ZodNativeEnum="ZodNativeEnum",qv.ZodOptional="ZodOptional",qv.ZodNullable="ZodNullable",qv.ZodDefault="ZodDefault",qv.ZodCatch="ZodCatch",qv.ZodPromise="ZodPromise",qv.ZodBranded="ZodBranded",qv.ZodPipeline="ZodPipeline",qv.ZodReadonly="ZodReadonly";const $v=Qy.create,Gv=Xy.create,Fv=tv.create;ov.create;const Bv=av.create,jv=cv.create,zv=uv.create,Kv=pv.create,Hv=hv.create;fv.create,gv.create;const Vv=yv.create,Wv=Sv.create;_v.create,Av.create,Mv.create;class Jv{static validate(e,t){try{return{success:!0,data:e.parse(t)}}catch(r){if(r instanceof dy){const e=r.errors.map(e=>({path:e.path.length>0?e.path.join("."):"root",message:e.message,rule:e.code})),t=`Validation failed: ${e.map(e=>`${e.path}: ${e.message}`).join("; ")}`,s=r.errors.some(e=>"invalid_type"===e.code&&"undefined"===e.received);return{success:!1,error:new Zr(t,{code:s?nt:it,details:{fields:e}})}}return{success:!1,error:new Zr("Unknown validation error",{code:ot,details:{fields:[]}})}}}static validateOrThrow(e,t){const r=this.validate(e,t);if(r.success&&void 0!==r.data)return r.data;if(r.error)throw r.error;throw new Zr("Unknown validation error",{code:ot,details:{fields:[]}})}static safeParse(e,t){return this.validate(e,t)}}const Zv=e=>$v().regex(/^https?:\/\/\S+$/i,e),Qv=e=>$v().regex(/^wss?:\/\/\S+$/i,e),Yv=Kv({appKey:$v().min(1,"appKey is required").optional(),appId:$v().min(1,"appId is required").optional(),enableUserInfoSync:Fv().optional(),enableSyncData:zv(Wv(["conversation","contact","group"])).optional(),enableDeliveryReceipt:Fv().optional(),deleteConversationOnGroupDestroyed:Fv().optional(),syncConversationListConfig:Kv({includeEmpty:Fv().optional()}).strict().optional(),useCustomAttachmentUpload:Fv().optional(),useFixedDeviceId:Fv().optional(),deviceId:$v().min(1,"deviceId is required").optional(),serviceConfig:Kv({dnsConfigUrls:zv(Zv("serviceConfig.dnsConfigUrls item must be a valid URL")).nonempty().optional(),serverUrls:Kv({restApiUrl:Zv("serviceConfig.serverUrls.restApiUrl must be a valid URL").optional(),wsUrl:Qv("serviceConfig.serverUrls.wsUrl must be a valid URL").optional(),syncRestApiUrl:Zv("serviceConfig.serverUrls.syncRestApiUrl must be a valid URL").optional(),syncWsUrl:Qv("serviceConfig.serverUrls.syncWsUrl must be a valid URL").optional()}).optional()}).optional(),useReplacedMessageContents:Fv().optional(),customDeviceName:$v().min(1,"customDeviceName is required").optional(),customOSPlatform:Gv().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:$v().min(1,"uiKitVersion is required").optional(),loginExtensionInfo:$v().max(1024,"loginExtensionInfo must be at most 1024 characters").optional(),managers:zv(Bv()).optional(),platformAdapterOptions:Kv({prefer:Wv(["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:Pv(e=>"object"==typeof e&&null!==e).optional(),overrides:Pv(e=>"object"==typeof e&&null!==e||"function"==typeof e).optional()}).strict().optional()}).passthrough().superRefine((e,t)=>{const r=Number(void 0!==e.appKey)+Number(void 0!==e.appId);0===r?t.addIssue({code:cy.custom,path:["appKey"],message:"appKey or appId is required"}):r>1&&t.addIssue({code:cy.custom,path:["appId"],message:"appKey and appId cannot be used together"}),"enableMd5Check"in e&&t.addIssue({code:cy.custom,path:["enableMd5Check"],message:"enableMd5Check is removed; attachment precheck is controlled by DNS_CONFIG"}),"enableHttpDns"in e&&t.addIssue({code:cy.custom,path:["enableHttpDns"],message:"enableHttpDns is removed; configure serviceConfig.serverUrls for fixed URLs"}),"dnsConfigUrls"in e&&t.addIssue({code:cy.custom,path:["dnsConfigUrls"],message:"dnsConfigUrls is moved to serviceConfig.dnsConfigUrls"}),"serverUrls"in e&&t.addIssue({code:cy.custom,path:["serverUrls"],message:"serverUrls is moved to serviceConfig.serverUrls"}),"profileSync"in e&&t.addIssue({code:cy.custom,path:["profileSync"],message:"profileSync is internal; profile sync scheduling uses SDK defaults"}),"cacheEncryptionMode"in e&&t.addIssue({code:cy.custom,path:["cacheEncryptionMode"],message:"cacheEncryptionMode is internal; cache encryption defaults to auto"}),"enableAutoSyncContacts"in e&&t.addIssue({code:cy.custom,path:["enableAutoSyncContacts"],message:"enableAutoSyncContacts is removed; use enableSyncData: ['contact']"});const s=e.serviceConfig&&"object"==typeof e.serviceConfig?e.serviceConfig:void 0,n=s?.serverUrls&&"object"==typeof s.serverUrls?s.serverUrls:void 0;s?.dnsConfigUrls&&n&&t.addIssue({code:cy.custom,path:["serviceConfig"],message:"serviceConfig.dnsConfigUrls and serviceConfig.serverUrls cannot be used together"}),n&&(void 0!==e.appId&&t.addIssue({code:cy.custom,path:["serviceConfig","serverUrls"],message:"serviceConfig.serverUrls cannot be used when initialized with appId"}),n?.restApiUrl||t.addIssue({code:cy.custom,path:["serviceConfig","serverUrls","restApiUrl"],message:"serviceConfig.serverUrls.restApiUrl is required when serverUrls is configured"}),n?.wsUrl||t.addIssue({code:cy.custom,path:["serviceConfig","serverUrls","wsUrl"],message:"serviceConfig.serverUrls.wsUrl is required when serverUrls is configured"}))}),Xv=Kv({userId:$v().min(1,"userId is required"),token:$v().min(1,"token is required")}),eb=$v().trim().min(1,"token is required"),tb=Kv({channelName:$v().trim().min(1,"channelName is required").optional()}).optional(),rb=zv(Gv({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))),sb=Kv({protocol:$v(),domain:$v().optional(),ip:$v().optional(),port:Hv([$v(),Gv()]).optional()}).passthrough(),nb=Kv({app_key:$v().optional(),rest:Kv({hosts:zv(sb).nonempty()}),"msync-wx":Kv({hosts:zv(sb).nonempty()}),"sync-ws":Kv({hosts:zv(sb).nonempty()}).optional(),enableReportLogs:Wv(["true","false"]).optional(),reportInterval:Gv().positive().finite().optional(),enableDataReport:Wv(["true","false"]).optional(),enableMd5Check:Wv(["true","false"]).optional(),uploadinparts_enable:Wv(["true","false"]).optional()}).passthrough(),ib=e=>encodeURIComponent(e).replace(/[!'()~]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`).replace(/%20/g,"+"),ob=e=>"function"==typeof URLSearchParams?new URLSearchParams(e):(e=>{const t=new Map;if(e)for(const[r,s]of Object.entries(e))t.set(r,s);return{set(e,r){t.set(e,r)},toString:()=>Array.from(t,([e,t])=>`${ib(e)}=${ib(t)}`).join("&")}})(e),ab="5.1.0",cb=["https://rs.chat.rtnsvc.com","https://rs.easemob.com","https://rs.chat.realtimemesh.com"],db=["msync-wx","msync-ws","msync","msync-web","websocket","websocket-im","im-websocket","im-ws","socket"],ub=["sync-ws","sync_ws","syncws","roster-ws","contact-sync-ws"];function lb(e){return"object"==typeof e&&null!==e}function pb(e){return Array.isArray(e)?{hosts:e}:function(e){return lb(e)&&"hosts"in e&&Array.isArray(e.hosts)}(e)?{hosts:e.hosts}:void 0}function hb(e,t,r){for(const s of t){const t=pb(e[s]);if(t)return{key:s,section:t}}for(const[s,n]of Object.entries(e)){if(!r(s))continue;const e=pb(n);if(e)return{key:s,section:e}}}function mb(e){if(!lb(e))return Jv.validateOrThrow(nb,e);const t=pb(e.rest),r=hb(e,db,e=>{const t=e.toLowerCase();return t.includes("msync")||t.includes("websocket")||"socket"===t||"im-ws"===t}),s=hb(e,ub,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&&!pb(n["sync-ws"])&&delete n["sync-ws"];const i="true"===(o=e.enableReportLogs)||!0===o?"true":"false"===o||!1===o?"false":void 0;var o;i&&(n.enableReportLogs=i);const a=function(e){if("number"!=typeof e&&"string"!=typeof e)return;if("string"==typeof e&&""===e.trim())return;const t=Number(e);return Number.isFinite(t)&&t>0?t:void 0}(e.reportInterval);void 0!==a?n.reportInterval=a:delete n.reportInterval;const c=function(e){if("true"===e||"false"===e)return e}(e.enableDataReport);c?n.enableDataReport=c:delete n.enableDataReport;const d=function(e){if("true"===e||"false"===e)return e}(e.enableMd5Check);d?n.enableMd5Check=d:delete n.enableMd5Check;const u=function(e){if("true"===e||"false"===e)return e}(e.uploadinparts_enable);return u?n.uploadinparts_enable=u:delete n.uploadinparts_enable,r&&"msync-wx"!==r.key&&Si("DNS config websocket section normalized",{sourceKey:r.key}),s&&"sync-ws"!==s.key&&Si("DNS config sync websocket section normalized",{sourceKey:s.key}),Jv.validateOrThrow(nb,n)}function fb(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 gb(e,t){return"https"===e?"https":"http"===e?"http":t}function yb(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 vb(e,t){const r=e.filter(e=>e.protocol===t);return r.length>0?r:"http"===t?e.filter(e=>"https"===e.protocol):[]}function bb(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 Ib(e,t,r){const s=new ty(e,{requestAdapter:r,includeRequestId:!0});let n="/easemob/server.json",i=!0;try{const t=new URL(e),r=""!==t.pathname&&"/"!==t.pathname,s=""!==t.search;(r||s)&&(n="",i=!1)}catch{n="/easemob/server.json",i=!0}if(i){n=`${n}?${(void 0!==t.appId?ob({app_id:t.appId,sdk_version:ab,file_version:"1"}):ob({app_key:t.appKey,_v:String(Date.now())})).toString()}`}return mb(await s.get(n))}function wb(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,gb(e.protocol,t))).filter(e=>"string"==typeof e&&e.length>0):[]}async function Cb(e){const t=e.baseUrls&&e.baseUrls.length>0?e.baseUrls:cb;if(0===t.length)throw new Zr("DNS_CONFIG list is empty",{code:nt,details:{fields:[{path:"serviceConfig.dnsConfigUrls",message:"DNS_CONFIG list is empty",rule:"required"}]}});const r=e.pageProtocol??("undefined"==typeof window||"https:"===window.location?.protocol?"https":"http");let s;for(const o of t)try{const t=void 0!==e.appId?{appId:e.appId}:{appKey:e.appKey},s=await Ib(o,t,e.requestAdapter),n=void 0!==e.appId?s.app_key:e.appKey;if("string"!=typeof n||0===n.length)throw new Zr("DNS app_key is required for appId initialization",{code:nt,details:{fields:[{path:"dns.app_key",message:"DNS app_key is required for appId initialization",rule:"required"}]}});const i=bb(vb(s["msync-wx"].hosts,r));if(0===i.length)throw new Zr("DNS msync-wx hosts resolution failed",{code:it,details:{fields:[{path:"dns.msync-wx.hosts",message:"DNS msync-wx hosts resolution failed",rule:"invalid_format"}]}});const a=i[0];if(!a)throw new Zr("DNS msync-wx hosts resolution failed",{code:it,details:{fields:[{path:"dns.msync-wx.hosts",message:"DNS msync-wx hosts resolution failed",rule:"invalid_format"}]}});const c=vb(s.rest.hosts,r);if(0===c.length)throw new Zr("DNS rest hosts resolution failed",{code:it,details:{fields:[{path:"dns.rest.hosts",message:"DNS rest hosts resolution failed",rule:"invalid_format"}]}});const d=c[0];if(!d)throw new Zr("DNS rest hosts resolution failed",{code:it,details:{fields:[{path:"dns.rest.hosts",message:"DNS rest hosts resolution failed",rule:"invalid_format"}]}});const u=i.map(e=>fb(e,gb(e.protocol,r))),l=fb(a,gb(a.protocol,r)),p=wb(s,r);return{appKey:n,websocketUrl:l,websocketUrls:u,syncWebsocketUrls:p,baseUrl:o,restBaseUrl:yb(d,gb(d.protocol,r)),dnsConfig:s}}catch(i){Si("DNS config candidate failed",{baseUrl:o,reason:i instanceof Error?i.message:String(i),error:i instanceof Error&&"function"==typeof i.toJSON?i.toJSON():i}),s=i}const n={stage:"dns"};throw s&&(n.reason=s.message,"code"in s&&"number"==typeof s.code&&(n.causeCode=s.code)),new Wr("DNS_CONFIG exhausted",{code:wt,details:n})}const Sb=e=>new Zr(e,{code:it,details:{reason:"invalid_rest_response"}}),Tb=e=>{if(!El(e))throw Sb("Invalid REST response");return El(e.data)?e.data:e},_b=(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}}},Rb=(e,t)=>{for(const r of t){const t=e[r];if("string"==typeof t)return t}},Ab=e=>{const{orgName:t,appName:r}=Qn(e.appKey);return`/${t}/${r}`},Mb=async(e,t)=>{const r=await e.get((e=>`${Ab(e)}/sdk/users/${encodeURIComponent(e.userId)}/token/expires`)(t),{operation:"getTokenExpireTimestamp"});return(e=>{const t=Tb(e),r=_b(t,["expire_timestamp","expireTimestamp","expireAt"]);if(void 0===r)throw Sb("Invalid token expires response");return r})(r)},Eb=async(e,t,r)=>{const s=await e.get(((e,t)=>{const r=ob({channelName:t?.channelName??"*"});return`${Ab(e)}/users/${encodeURIComponent(e.userId)}/token/rtc?${r.toString()}`})(t,r),{operation:"getRtcTokenInfo"});return(e=>{const t=Tb(e);return{appId:Rb(t,["app_id","appId"])??"",rtcToken:Rb(t,["rtc_token","rtcToken","RTCToken"])??"",channelName:Rb(t,["channel_name","channelName"])??"",rtcUid:_b(t,["rtcUid","RTCUId","rtc_uid"])??0,expireAt:_b(t,["expires_in","expire","expireAt"])??0}})(s)},Ub=async(e,t,r)=>{const s=await e.post((e=>`${Ab(e)}/rtc_mapper/batch/get`)(t),{data:r},{operation:"getUserIdsWithRtcUids"});return(e=>{const t=Tb(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)},kb=async(e,t)=>{const r=await e.get((e=>`${Ab(e)}/users/${encodeURIComponent(e.userId)}/resources`)(t),{operation:"getSelfIdsOnOtherPlatform"});return((e,t)=>{const r=El(e)&&Array.isArray(e.data)?e.data:[],s=[];for(const n of r){if(!El(n))continue;const e=Rb(n,["res","resource","clientResource"]);e&&e!==t.clientResource&&s.push(`${t.userId}/${e}`)}return s})(r,t)},Nb=(...e)=>{const t={},r={};for(const s of e)Object.assign(t,s.common),Object.assign(r,s.apis);return{common:t,apis:r}},Ob={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:{}},xb=e=>({userId:e}),Lb=e=>({userId:e.userId,nickname:e.nickname,avatarUrl:e.avatarUrl,sign:e.sign,ext:e.ext}),Pb=e=>e,Db=async(e,t)=>{const r=(e=>{const t=[],r=new Set;for(const s of e){const e=s.trim();e&&!r.has(e)&&(r.add(e),t.push(e))}return t})(e),s=new Map;if(0===r.length)return s;const n=t.cacheManager?.getUserInfoSummaries(r,!1)??[];for(const o of n)s.set(o.userId,Lb(o));const i=r.filter(e=>!s.has(e));if(i.length>0&&t.fetchUserInfos){const e=await t.fetchUserInfos({userIds:i});for(const t of e)s.set(t.userId,Pb(t))}for(const o of r)s.has(o)||s.set(o,xb(o));return s};class qb{constructor(e){this.options=e,this.pendingGroups=new Map,this.readyGroups=[],this.pendingOrder=[],this.activeGroups=new Set,this.timer=null,this.activeGroupCount=0}enqueue(e,t,r){if(!e||!t)return;const s=this.pendingGroups.get(e)??new Map;this.pendingGroups.has(e)||(this.pendingGroups.set(e,s),this.pendingOrder.push(e));const n=s.get(t);s.set(t,{userId:t,namecardUpdateTime:this.resolveMaxVersion(n?.namecardUpdateTime,r)}),this.schedule()}destroy(){this.timer&&(clearTimeout(this.timer),this.timer=null),this.pendingGroups.clear(),this.pendingOrder.length=0,this.readyGroups.length=0,this.activeGroups.clear(),this.activeGroupCount=0}getOptions(){return{windowMs:this.options.windowMs,minWindowMs:this.options.minWindowMs,maxBatchSize:this.options.maxBatchSize,maxConcurrency:this.options.maxConcurrency}}schedule(){this.timer||(this.timer=setTimeout(()=>{this.timer=null,this.flushWindow()},this.resolveWindowDelay()))}flushWindow(){if(0!==this.pendingOrder.length){for(const e of this.pendingOrder){const t=this.pendingGroups.get(e);if(!t||0===t.size)continue;const r=Array.from(t.values()),s=Math.max(1,this.options.maxBatchSize);for(let n=0;n<r.length;n+=s)this.readyGroups.push({groupId:e,targets:r.slice(n,n+s)})}this.pendingGroups.clear(),this.pendingOrder.length=0,this.runReadyGroups()}}runReadyGroups(){for(;this.activeGroupCount<this.options.maxConcurrency&&this.readyGroups.length>0;){const e=this.readyGroups.findIndex(e=>!this.activeGroups.has(e.groupId));if(e<0)return;const t=this.readyGroups.splice(e,1)[0];if(!t)return;this.activeGroupCount+=1,this.activeGroups.add(t.groupId),Promise.resolve(this.options.onFlushGroup(t)).catch(e=>{Si("Group namecard hydration queue flush failed",{groupId:t.groupId,userIds:t.targets.map(e=>e.userId),error:e instanceof Error?e.message:String(e)})}).finally(()=>{this.activeGroupCount-=1,this.activeGroups.delete(t.groupId),this.runReadyGroups()})}}resolveWindowDelay(){const e=Math.max(0,Math.min(this.options.minWindowMs,this.options.windowMs)),t=Math.max(e,this.options.windowMs),r=t-e;return r<=0?t:e+Math.floor(Math.random()*(r+1))}resolveMaxVersion(e,t){return"number"!=typeof e?t:"number"!=typeof t?e:Math.max(e,t)}}class $b{constructor(e){this.options=e,this.pendingTargets=new Map,this.readyBatches=[],this.timer=null,this.activeCount=0,this.generation=0}enqueue(e,t){e&&(this.mergeWaitingTarget({userId:e,userInfoUpdateTime:t,retryCount:0}),this.pendingTargets.size>=this.options.batchSize?this.flush():this.schedule())}destroy(){this.timer&&(clearTimeout(this.timer),this.timer=null),this.pendingTargets.clear(),this.readyBatches.length=0,this.generation+=1}getOptions(){return{windowMs:this.options.windowMs,batchSize:this.options.batchSize,maxConcurrency:this.options.maxConcurrency,maxRetries:this.options.maxRetries}}schedule(){this.timer||(this.timer=setTimeout(()=>{this.timer=null,this.flush()},this.options.windowMs))}flush(){if(this.timer&&(clearTimeout(this.timer),this.timer=null),0===this.pendingTargets.size)return;const e=Array.from(this.pendingTargets.values());this.pendingTargets.clear();const t=Math.max(1,this.options.batchSize);for(let r=0;r<e.length;r+=t)this.readyBatches.push(e.slice(r,r+t));this.runReadyBatches()}runReadyBatches(){const e=Math.max(1,this.options.maxConcurrency);for(;this.activeCount<e&&this.readyBatches.length>0;){const e=this.readyBatches.shift();if(!e)return;const r=this.generation;this.activeCount+=1;const s=e.map(({userId:e,userInfoUpdateTime:t})=>({userId:e,userInfoUpdateTime:t}));let n;try{n=Promise.resolve(this.options.onFlush(s))}catch(t){n=Promise.reject(t instanceof Error?t:new Error(String(t)))}n.catch(t=>{const s=e.filter(e=>e.retryCount<Math.max(0,this.options.maxRetries)).map(e=>({...e,retryCount:e.retryCount+1}));if(Si("User info hydration queue flush failed",{targets:e.map(e=>e.userId),retrying:s.length>0,error:t instanceof Error?t.message:String(t)}),r===this.generation&&0!==s.length){for(const e of s)this.mergeWaitingTarget(e);this.flush()}}).finally(()=>{this.activeCount-=1,this.runReadyBatches()})}}mergeWaitingTarget(e){for(const r of this.readyBatches){const t=r.findIndex(t=>t.userId===e.userId);if(t>=0){const s=r[t];return void(s&&(r[t]=this.mergeTarget(s,e)))}}const t=this.pendingTargets.get(e.userId);this.pendingTargets.set(e.userId,t?this.mergeTarget(t,e):e)}mergeTarget(e,t){return{userId:e.userId,userInfoUpdateTime:this.resolveMaxVersion(e.userInfoUpdateTime,t.userInfoUpdateTime),retryCount:Math.max(e.retryCount,t.retryCount)}}resolveMaxVersion(e,t){return"number"!=typeof e?t:"number"!=typeof t?e:Math.max(e,t)}}const Gb=0,Fb=1,Bb=2,jb=3,zb=4,Kb=5,Hb=0,Vb=0,Wb=1,Jb=1001,Zb=1002,Qb=1003,Yb=1004,Xb=1005,eI=1101,tI=Nb(Ob,{common:{},apis:{getSelfIdsOnOtherPlatform:{range:"202,300-303",errors:{}},getTokenExpireTimestamp:{range:"",errors:{}},getRtcTokenInfo:{range:"",errors:{}},getUserIdsWithRtcUids:{range:"",errors:{}}}}),rI=class e{constructor(e){this.core=null,this.cacheManager=null,this.cacheUserId=null,this.state=t,this.loginAttempt=0,this.currentUserId=null,this.activeAppKey=null,this.logReportEnabled=!1,this.restBaseUrl=null,this.authToken=null,this.clientResource=null,this.platformAdapter=null,this.contactSyncController=null,this.groupSyncController=null,this.syncConversationListConfigController=null,this.syncWebSocketSession=null,this.contactSyncWsUrls=[],this.syncConversationListConfigWsUrls=[],this.contactSyncDnsResolved=!1,this.conversationListVersion=0,this.conversationListSnapshot=[],this.activeIncomingStreamMessageIds=new Set,this.config={appKey:e.appKey,appId:e.appId,enableUserInfoSync:e.enableUserInfoSync,enableSyncData:[...e.enableSyncData],enableDeliveryReceipt:e.enableDeliveryReceipt,deleteConversationOnGroupDestroyed:e.deleteConversationOnGroupDestroyed,syncConversationListConfig:{...e.syncConversationListConfig},useCustomAttachmentUpload:e.useCustomAttachmentUpload,enableMd5Check:e.enableMd5Check,serviceConfig:{mode:e.serviceConfig.mode,dnsConfigUrls:[...e.serviceConfig.dnsConfigUrls],hasCustomDnsConfigUrls:e.serviceConfig.hasCustomDnsConfigUrls,serverUrls:e.serviceConfig.serverUrls},useFixedDeviceId:e.useFixedDeviceId,deviceId:e.deviceId,useReplacedMessageContents:e.useReplacedMessageContents,customDeviceName:e.customDeviceName,customOSPlatform:e.customOSPlatform,uiKitVersion:e.uiKitVersion,loginExtensionInfo:e.loginExtensionInfo,cacheEncryptionMode:e.cacheEncryptionMode,profileSync:{...e.profileSync},platformAdapterOptions:e.platformAdapterOptions},this.activeAppKey=this.config.appKey??null,this.config.platformAdapterOptions&&(this.platformAdapter=el(this.config.platformAdapterOptions)),this.managerRegistry=new Map,this.managerCapabilities=new Map,this.eventHub=new Wf,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 $b({windowMs:this.config.profileSync.userInfoWindowMs,batchSize:this.config.profileSync.userInfoBatchSize,maxConcurrency:3,maxRetries:1,onFlush:async e=>{await this.flushUserInfoHydrationTargets(e)}}),this.groupNamecardHydrationQueue=new qb({windowMs:this.config.profileSync.groupNamecardWindowMs,minWindowMs:1e3,maxBatchSize:50,maxConcurrency:this.config.profileSync.groupNamecardMaxConcurrency,onFlushGroup:async e=>{await this.flushGroupNamecardHydrationBatch(e)}}),this.eventHub.addEventHandler("__internal:chat-client",{[o]:e=>{this.updateState(e.state)},[a]:e=>{this.updateState(e.state)},[c]:e=>{this.updateState(e.state)},[d]:e=>{this.updateState(e.state)},[k]:e=>{this.handleIncomingConversationMessage(e),this.handleIncomingMessageProfileSync(e)},[N]:e=>{this.handleIncomingConversationStreamMessage(e)},[b]:e=>{this.handleOutgoingConversationMessage(e)},[G]:e=>{this.handleMultiDeviceContactEvent(e)},[F]:e=>{if("CONVERSATION_DELETED"===e.operation)return this.handleMultiDeviceConversationEvent(e)},[V]:e=>this.handleIncomingContactRosterEvent("add",e),[J]:e=>this.handleIncomingContactRosterEvent("add",e),[K]:e=>this.handleIncomingContactRosterEvent("none",e),[W]:e=>this.handleIncomingContactRosterEvent("none",e),[H]:e=>this.handleIncomingContactRosterEvent("remove",e),[f]:async e=>{await this.dispatchRawNotifyToCapability("rawNotify:group",{type:"group",payload:e}),e.eventName===ne&&await this.handleGroupDestroyedConversation(e.payload.groupId)},[g]:e=>this.dispatchRawNotifyToCapability("rawNotify:chatroom",{type:"chatroom",payload:e}),[y]:e=>this.dispatchRawNotifyToCapability("rawNotify:chatThread",{type:"chatThread",payload:e}),[v]:e=>this.dispatchRawNotifyToCapability("rawNotify:userInfo",{type:"userInfo",payload:e})})}static init(t){const r=Jv.validateOrThrow(Yv,t),s=r.customOSPlatform,n=e.normalizeServiceConfig(r.serviceConfig),i={appKey:r.appKey,appId:r.appId,enableUserInfoSync:r.enableUserInfoSync??!1,enableSyncData:e.normalizeSyncDataTypes(r.enableSyncData??["conversation"]),enableDeliveryReceipt:r.enableDeliveryReceipt??!1,deleteConversationOnGroupDestroyed:r.deleteConversationOnGroupDestroyed??!0,syncConversationListConfig:{includeEmpty:r.syncConversationListConfig?.includeEmpty??!1,includeMark:!0},useCustomAttachmentUpload:r.useCustomAttachmentUpload??!1,enableMd5Check:!1,serviceConfig:n,useFixedDeviceId:r.useFixedDeviceId??!0,deviceId:r.deviceId??"webim",useReplacedMessageContents:r.useReplacedMessageContents??!1,customDeviceName:void 0!==s?r.customDeviceName:void 0,customOSPlatform:s,uiKitVersion:r.uiKitVersion,loginExtensionInfo:r.loginExtensionInfo,cacheEncryptionMode:"auto",profileSync:{userInfoWindowMs:7e3,userInfoBatchSize:20,groupNamecardWindowMs:7e3,groupNamecardMaxConcurrency:5},platformAdapterOptions:r.platformAdapterOptions},o=t.managers??[];if(e.instance){if(!e.isSameConfig(e.instance.config,i))throw new Zr("ChatClient already initialized with different config",{code:it,details:{fields:[{path:"config",message:"ChatClient already initialized with different config",rule:"conflict"}],current:e.instance.config,next:i}});return o.length>0&&e.instance.registerManagers(o),e.instance.validateOptionalCapabilityDependencies(),e.instance}return e.instance=new e(i),o.length>0&&e.instance.registerManagers(o),e.instance.validateOptionalCapabilityDependencies(),e.instance}async login(n){if(e.instance!==this)throw new Zr("ChatClient is not initialized",{code:nt,details:{fields:[{path:"client",message:"ChatClient is not initialized",rule:"state"}]}});const i=Jv.validateOrThrow(Xv,n);if(this.state===r||this.state===s){const e=this.currentUserId&&this.currentUserId!==i.userId;throw new Wr(e?"Another user is already logged in":"ChatClient is already connecting or connected",{code:e?Jt:at,details:{stage:"auth",...e?{currentUserId:this.currentUserId,nextUserId:i.userId}:{}}})}const o=++this.loginAttempt;let a=this.config.appKey??null;this.activeAppKey=a,Si("Login started",{userId:i.userId,serviceConnectionMode:this.config.serviceConfig.mode,hasCustomDnsConfigUrls:this.config.serviceConfig.hasCustomDnsConfigUrls});const c=this.platformAdapter??el(this.config.platformAdapterOptions);var d;this.platformAdapter=c,d={requestAdapter:c.request,onDiagnostic:(e,t)=>{Si(e,t)}},zh?.reset(),zh=new jh(d);const u=(e=>zh?.startSession(e))({appKey:a??"default#appkey",uid:i.userId,sdkVersion:ab,platform:c.runtime.getPlatform(),deviceId:this.config.deviceId,os:this.config.customOSPlatform,uikitVersion:this.config.uiKitVersion,did:this.config.customDeviceName}),l=c.runtime.getNetworkType?.();l&&l.then(e=>{Vh(e)}).catch(()=>{Vh("unknown")});const p=Wh({operationName:"USER_LOGIN",operationType:"MANUALLOGIN",uid:i.userId});let h,m,f;this.updateState(r),this.logReportEnabled=!1,vi("unknown");let g,y=!1,v=!1,b=!0;if("dns"===this.config.serviceConfig.mode){const e=p?.startRequest({requestName:"REST_DNSLIST",method:"GET",url:this.config.serviceConfig.dnsConfigUrls[0]});try{const t=await Cb(void 0!==this.config.appId?{appId:this.config.appId,baseUrls:this.config.serviceConfig.dnsConfigUrls,requestAdapter:c.request}:{appKey:this.requireConfiguredAppKey(),baseUrls:this.config.serviceConfig.dnsConfigUrls,requestAdapter:c.request});a=t.appKey,this.activeAppKey=a,Kh({appKey:a}),Si("DNS resolved for login",{baseUrl:t.baseUrl,websocketUrl:t.websocketUrl,syncWsCount:t.syncWebsocketUrls.length,restBaseUrl:t.restBaseUrl}),h=t.websocketUrl,m=t.websocketUrls,this.contactSyncWsUrls=t.syncWebsocketUrls,this.syncConversationListConfigWsUrls=t.syncWebsocketUrls,this.contactSyncDnsResolved=!0,f=t.restBaseUrl,y="true"===t.dnsConfig.enableReportLogs,g=t.dnsConfig.reportInterval,v="true"===t.dnsConfig.enableMd5Check,b="false"!==t.dnsConfig.uploadinparts_enable,e?.finish({code:200,success:!0}),Hh(t.dnsConfig.enableDataReport),Ci("DNS report switch resolved",{enabled:y})}catch(C){const r=C instanceof Hr?C.code:-1,s=C instanceof Error?C.message:String(C);throw e?.finish({code:r,success:!1,description:s}),p?.finish({code:r,success:!1,description:s}),Hh(void 0),vi("disabled"),this.activeAppKey=this.config.appKey??null,this.updateState(t),C}}else{const e=this.config.serviceConfig.serverUrls;if(!e?.wsUrl||!e.restApiUrl){const e=new Zr("serviceConfig.serverUrls.restApiUrl and serviceConfig.serverUrls.wsUrl are required when serverUrls is configured",{code:nt,details:{fields:[{path:"serviceConfig.serverUrls.restApiUrl",message:"serviceConfig.serverUrls.restApiUrl is required when serverUrls is configured",rule:"required"},{path:"serviceConfig.serverUrls.wsUrl",message:"serviceConfig.serverUrls.wsUrl is required when serverUrls is configured",rule:"required"}]}});throw p?.finish({code:e.code,success:!1,description:e.message}),Hh(void 0),this.updateState(t),e}h=e.wsUrl,f=e.restApiUrl,v=this.config.enableMd5Check,this.contactSyncWsUrls=[],this.syncConversationListConfigWsUrls=e.syncWsUrl?[e.syncWsUrl]:[],this.contactSyncDnsResolved=!1,Hh(void 0)}if(!a){const e=new Zr("appKey is unavailable after service discovery",{code:nt,details:{fields:[{path:"appKey",message:"appKey is unavailable after service discovery",rule:"required"}]}});throw this.updateState(t),Jh(),e}var I;if(bi({restBaseUrl:f,appKey:a,userId:i.userId,token:i.token,requestAdapter:c.request}),I=g,di.updateReportInterval(I),this.logReportEnabled=y,vi(y?"enabled":"disabled"),this.resetCore(),o!==this.loginAttempt){const e=new Wr("Login cancelled",{code:yt,details:{stage:"auth"}});throw p?.finish({code:yt,success:!1,description:e.message}),this.updateState(t),this.activeAppKey=this.config.appKey??null,Jh(),e}this.core=new Wm({serverUrl:h,serverUrls:m,userId:i.userId,token:i.token,appKey:a,restBaseUrl:f,useReplacedMessageContents:this.config.useReplacedMessageContents,useCustomAttachmentUpload:this.config.useCustomAttachmentUpload,enableMd5Check:v,enableMultipartUpload:b,useFixedDeviceId:this.config.useFixedDeviceId,deviceId:this.config.deviceId,customDeviceName:this.config.customDeviceName,customOSPlatform:this.config.customOSPlatform,uiKitVersion:this.config.uiKitVersion,loginExtensionInfo:this.config.loginExtensionInfo,serviceId:u,platformAdapter:c,enableDeliveryReceipt:this.config.enableDeliveryReceipt},this.eventHub),bi({resource:this.core.getClientResource()});const w=p?.startRequest({requestName:"CONNECT_WEBSOCKET",method:"",url:h});try{if(Si("Connecting core websocket",{serverUrl:h,restBaseUrl:f,userId:i.userId}),await this.core.connect(),w?.finish({code:200,success:!0}),p?.finish({code:0,success:!0}),Si("Core websocket connected",{userId:i.userId,resource:this.core.getClientResource()}),this.currentUserId=i.userId,Kh({uid:i.userId}),this.restBaseUrl=f??null,this.authToken=i.token,this.clientResource=this.core.getClientResource(),await this.initCacheManager(i.userId),Si("Cache initialized after login",{userId:i.userId}),this.loadCachedConversations(),this.loadCachedUserInfo(),await this.syncSelfUserInfoAfterLogin(),this.config.enableSyncData.includes("conversation")&&await this.refreshSessionList(this.config.syncConversationListConfig),this.triggerConfiguredSyncDataAfterLogin(i.userId),this.logReportEnabled)try{await Ii()}catch(C){Si("Report logs on login failed",C)}}catch(C){const e=C instanceof Hr?C.code:-1,r=C instanceof Error?C.message:String(C);throw w?.finish({code:e,success:!1,description:r}),p?.finish({code:e,success:!1,description:r}),this.resetCore(),this.activeAppKey=this.config.appKey??null,this.updateState(t),Jh(),C}}async logout(){if(e.instance!==this)throw new Zr("ChatClient is not initialized",{code:nt,details:{fields:[{path:"client",message:"ChatClient is not initialized",rule:"state"}]}});if(this.loginAttempt+=1,!this.core)return this.contactSyncController?.cancel(),this.contactSyncController=null,this.groupSyncController?.cancel(),this.groupSyncController=null,this.syncWebSocketSession?.cancel("logout"),this.syncWebSocketSession=null,this.syncConversationListConfigController=null,this.userInfoHydrationQueue.destroy(),this.groupNamecardHydrationQueue.destroy(),this.activeIncomingStreamMessageIds.clear(),this.currentUserId=null,this.restBaseUrl=null,this.authToken=null,this.clientResource=null,this.platformAdapter=null,this.cacheManager=null,this.cacheUserId=null,this.contactSyncWsUrls=[],this.syncConversationListConfigWsUrls=[],this.contactSyncDnsResolved=!1,this.activeAppKey=this.config.appKey??null,this.resetManagerSessionRuntimes(),this.updateState(t),this.logReportEnabled=!1,vi("disabled"),wi(),void Jh();try{if(await(this.cacheManager?.flushPending()),this.logReportEnabled)try{await Ii()}catch(r){Si("Report logs on logout failed",r)}await this.core.disconnect()}finally{this.resetCore(),this.activeAppKey=this.config.appKey??null,this.updateState(t),this.logReportEnabled=!1,vi("disabled"),wi(),Jh()}}getConnectionState(){return this.state}getCurrentUserId(){return this.currentUserId}getClientResource(){return this.clientResource??this.core?.getClientResource()??null}getMessageCreationOptions(){return{useCustomAttachmentUpload:this.config.useCustomAttachmentUpload}}getRestContext(){if(!this.restBaseUrl)throw new Zr("restBaseUrl is required",{code:nt,details:{fields:[{path:"restBaseUrl",message:"restBaseUrl is required",rule:"required"}]}});if(!this.authToken)throw new Zr("token is required",{code:nt,details:{fields:[{path:"token",message:"token is required",rule:"required"}]}});if(!this.currentUserId)throw new Zr("userId is required",{code:nt,details:{fields:[{path:"userId",message:"userId is required",rule:"required"}]}});const e=this.clientResource??this.core?.getClientResource();if(!e)throw new Zr("clientResource is required",{code:nt,details:{fields:[{path:"clientResource",message:"clientResource is required",rule:"required"}]}});return{restBaseUrl:this.restBaseUrl,appKey:this.requireActiveAppKey(),userId:this.currentUserId,token:this.authToken,clientResource:e}}async renewToken(e){const t=Jv.validateOrThrow(eb,e);if(!this.core||!this.currentUserId||this.state!==s)throw new Wr("ChatClient is not connected",{code:ct,details:{stage:"token",state:this.state}});const r=this.getRestContext(),n={...r},i=new ty(n.restBaseUrl,{errorMap:tI,requestAdapter:this.platformAdapter?.request,includeRequestId:!0});i.setAuthToken(t),Si("Renew token started",{userId:r.userId});const o=await Mb(i,n);if(o<=Date.now())throw new Wr("Token is expired",{code:lt,details:{stage:"token"}});const a=this.core.renewToken(t,o);return this.authToken=t,bi({token:t}),Si("Renew token succeeded",{userId:r.userId,expireAt:o}),a}async getRTCTokenInfo(e){const t=Jv.validateOrThrow(tb,e),r=this.getRestContext(),s=new ty(r.restBaseUrl,{errorMap:tI,requestAdapter:this.platformAdapter?.request,includeRequestId:!0});return s.setAuthToken(r.token),Si("Get RTC token info started",{userId:r.userId,hasChannelName:Boolean(t?.channelName)}),Eb(s,r,t)}async getUserIdsWithRTCUids(e){const t=Jv.validateOrThrow(rb,e),r=this.getRestContext(),s=new ty(r.restBaseUrl,{errorMap:tI,requestAdapter:this.platformAdapter?.request,includeRequestId:!0});return s.setAuthToken(r.token),Si("Get userIds with RTC UIDs started",{userId:r.userId,count:t.length}),Ub(s,r,t)}async getSelfIdsOnOtherPlatform(){const e=this.getRestContext(),t=new ty(e.restBaseUrl,{errorMap:tI,requestAdapter:this.platformAdapter?.request,includeRequestId:!0});return t.setAuthToken(e.token),Si("Get self ids on other platform started",{userId:e.userId,clientResource:e.clientResource}),kb(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 Jg({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:hp(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 Db([e],t)).get(e),e))(t,{cacheManager:this.cacheManager,fetchUserInfos:r?async({userIds:e})=>await this.fetchContactEventUserInfos(e):void 0});e.userInfo=s}async fetchContactEventUserInfos(e){if(0===e.length)return[];const t=this.getUserInfoReadCapability();if(!t)return[];try{return await t.getUserInfoByUserId({userIds:e})}catch(r){return Si("Contact roster event user info fetch failed",{userIds:e,error:r}),[]}}isMessageProfileSyncEnabled(){return this.config.enableUserInfoSync}isUserInfoSyncEnabled(){return this.config.enableUserInfoSync}async syncSelfUserInfoAfterLogin(){if(!this.isMessageProfileSyncEnabled()||!this.currentUserId)return;const e=this.getUserInfoReadCapability();if(e)try{0===(await e.getUserInfoByUserId({userIds:[this.currentUserId]})).length&&Si("Self user info sync returned empty result after login",{userId:this.currentUserId})}catch(t){Si("Self user info sync failed after login",{userId:this.currentUserId,error:t})}}handleIncomingMessageProfileSync(e){if("RECEIVE"!==e.direct||!this.isMessageProfileSyncEnabled())return;const t=up(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=>{cp.delete(e)})(e);const t={userInfoUpdateTime:this.resolveCurrentUserInfoUpdateTime(),namecardUpdateTime:"groupChat"===e.conversationType?this.resolveCurrentGroupNamecardUpdateTime(e.conversationId):void 0};dp(e,t)}resolveCurrentUserInfoUpdateTime(){if(this.cacheManager&&this.currentUserId)return this.cacheManager.getUserInfoSummaries([this.currentUserId],!1)[0]?.userInfoUpdateTime}resolveCurrentGroupNamecardUpdateTime(e){if(this.cacheManager&&this.currentUserId)return this.cacheManager.getGroupNamecard(e,this.currentUserId,!1)?.namecardUpdateTime}shouldHydrateUserInfo(e,t){return"number"!=typeof e||e<t}shouldHydrateGroupNamecard(e,t){return"number"!=typeof e||e<t}async flushUserInfoHydrationTargets(e){const t=this.getUserInfoReadCapability();if(!t||0===e.length)return;const r=e.map(e=>e.userId);let s;try{s=await t.getUserInfoByUserId({userIds:r})}catch(d){throw Si("User info hydration failed",{userIds:r,error:d}),d}const n=this.currentUserId,i=n?s.find(e=>e.userId===n):void 0,o=s.filter(e=>e.userId!==n);i&&this.dispatchOwnInfoUpdated(i),o.length>0&&this.dispatchUserInfoUpdated(o),s.length>0&&this.refreshConversationDisplayFromUserInfos(s.map(e=>({userId:e.userId})),"profile");const a=new Set(s.map(e=>e.userId)),c=r.filter(e=>!a.has(e));c.length>0&&Si("User info hydration returned partial result",{requestedUserIds:r,missingUserIds:c})}async flushGroupNamecardHydrationBatch(e){const t=this.getGroupNamecardHydrationCapability();if(t&&0!==e.targets.length)try{await t.hydrateMessageProfileGroupNamecards(e.groupId,e.targets)}catch(r){Si("Group namecard hydration returned partial result",{groupId:e.groupId,requestedUserIds:e.targets.map(e=>e.userId),error:r})}}async refreshContactSnapshot(){if(!this.cacheManager||!this.currentUserId)return;const e=this.ensureContactSyncController();await e.sync()}addEventHandler(e,t){this.eventHub.addEventHandler(e,t)}removeEventHandler(e){this.eventHub.removeEventHandler(e)}use(t){if(e.instance!==this)throw new Zr("ChatClient is not initialized",{code:nt,details:{fields:[{path:"client",message:"ChatClient is not initialized",rule:"state"}]}});return this.registerManagerConstructor(t),this}async sendMessage(t,r){if(e.instance!==this)throw new Zr("ChatClient is not initialized",{code:nt,details:{fields:[{path:"client",message:"ChatClient is not initialized",rule:"state"}]}});if(!t?.sender?.userId)throw new Zr("sender.userId is required",{code:nt,details:{fields:[{path:"sender.userId",message:"sender.userId is required",rule:"required"}]}});if(this.currentUserId&&t.sender.userId!==this.currentUserId)throw new Zr("sender.userId does not match current user",{code:it,details:{fields:[{path:"sender.userId",message:"sender.userId does not match current user",rule:"conflict"}]}});if(st(t))throw new Qr("Stream message send is not supported",{code:ir,details:{msgLocalId:t.msgLocalId,retryable:!1}});if(!this.core||this.state!==s)throw new Qr("ChatClient is not connected",{code:St,details:{msgLocalId:t.msgLocalId,state:this.state,retryable:!0}});return this.attachOutgoingMessageProfileVersions(t),this.core.sendMessage(t,r)}dispatchOwnInfoUpdated(e){this.eventHub.dispatch("onOwnInfoUpdated",e)}dispatchUserInfoUpdated(e){0!==e.length&&this.eventHub.dispatch("onUserInfoUpdated",[...e])}refreshConversationDisplayFromUserInfos(e,t="profile"){if(!this.cacheManager||0===e.length)return;this.cacheManager.refreshSessionListDisplayFromUserInfos(e).changed&&this.emitConversationListUpdate(t)}refreshConversationDisplayFromJoinedGroups(e,t="profile",r){if(!this.cacheManager||0===e.length)return;this.cacheManager.refreshSessionListDisplayFromJoinedGroups(e.map(e=>({groupId:e.groupId,name:e.name,avatarUrl:e.avatarUrl,remindType:e.remindType})),r).changed&&this.emitConversationListUpdate(t)}enqueueMissingGroupSessionSenderUserInfos(e){if(!this.isMessageProfileSyncEnabled()||!this.cacheManager||0===e.length)return;const t=new Set;for(const n of e){const e="groupChat"===n.conversationType?n.lastMessage?.sender:null;!e?.userId||e.nickname&&e.avatarUrl||t.add(e.userId)}if(0===t.size)return;const r=this.cacheManager.getUserInfoSummaries([...t],!1),s=new Set(r.map(e=>e.userId));for(const n of t)s.has(n)||this.userInfoHydrationQueue.enqueue(n)}dispatchUserGroupNamecardUpdated(e,t,r){e&&t&&this.eventHub.dispatch(Ce,{groupId:e,userId:t,namecard:r})}async downloadAndParseCombinePayload(t){if(e.instance!==this)throw new Zr("ChatClient is not initialized",{code:nt,details:{fields:[{path:"client",message:"ChatClient is not initialized",rule:"state"}]}});if(!this.core)throw new Zr("ChatClient is not connected",{code:ct,details:{fields:[{path:"core",message:"ChatClient is not connected",rule:"state"}]}});return this.core.downloadAndParseCombineMessage(t)}async sendMessageAction(t,r){if(e.instance!==this)throw new Zr("ChatClient is not initialized",{code:nt});if(!this.core)throw new Zr("ChatClient is not connected",{code:ct});return this.core.sendMessageAction(t,r)}async sendChatRoomOperation(t,r){if(e.instance!==this)throw new Zr("ChatClient is not initialized",{code:nt});if(!this.core)throw new Zr("ChatClient is not connected",{code:ct});return this.core.sendChatRoomOperation(t,r)}async downloadAttachment(t){if(e.instance!==this)throw new Zr("ChatClient is not initialized",{code:nt});if(!this.core)throw new Zr("ChatClient is not connected",{code:ct});return this.core.downloadAttachment(t)}decodeServerMessageMeta(e){if(!this.core)throw new Zr("ChatClient is not connected",{code:ct});return this.core.decodeServerMessageMeta(e)}registerManagers(e){if(0===e.length)return;const t=new Set;for(const r of e){const e=this.resolveManagerKey(r);if(t.has(e))throw this.buildManagerValidationError(`Manager key duplicated: ${e}`,it,"managers.key","conflict",{managerKey:e});t.add(e)}for(const r of e)this.registerManagerInput(r)}registerManagerInput(t){return e.isManagerConstructor(t)?this.registerManagerConstructor(t):this.registerManagerInstance(t)}registerManagerConstructor(e){const t=this.getManagerKeyFromConstructor(e),r=this.managerRegistry.get(t);if(r){if(r.constructor===e)return r;throw this.buildManagerConflictError(t,this.getManagerNameFromInstance(r),this.getManagerNameFromConstructor(e),"constructor-mismatch")}const s=new e;return s.bind(this,this.managerEventContext),this.managerRegistry.set(t,s),this.registerManagerCapabilities(s),this.attachManager(t,s),s}registerManagerInstance(e){const t=this.getManagerKeyFromInstance(e),r=this.managerRegistry.get(t);if(r){if(r===e)return e;if(r.constructor===e.constructor)throw this.buildManagerConflictError(t,this.getManagerNameFromInstance(r),this.getManagerNameFromInstance(e),"instance-conflict");throw this.buildManagerConflictError(t,this.getManagerNameFromInstance(r),this.getManagerNameFromInstance(e),"constructor-mismatch")}return e.bind(this,this.managerEventContext),this.managerRegistry.set(t,e),this.registerManagerCapabilities(e),this.attachManager(t,e),e}registerManagerCapabilities(e){for(const t of e.capabilities??[])this.managerCapabilities.set(t,e)}dispatchRawNotifyToCapability(e,t){const r=this.getManagerByCapability(e);return r?.handleRawNotify?.(t)}getUserInfoReadCapability(){const e=this.getManagerByCapability("userInfo:read");return e&&this.hasUserInfoReadCapability(e)?e:null}getGroupNamecardHydrationCapability(){const e=this.getManagerByCapability("group:namecard");return e&&this.hasGroupNamecardHydrationCapability(e)?e:null}validateOptionalCapabilityDependencies(){if(this.config.enableUserInfoSync&&!this.getUserInfoReadCapability())throw this.buildMissingCapabilityError("enableUserInfoSync","userInfo:read",["UserInfoManager"]);if(this.config.enableUserInfoSync&&!this.getGroupNamecardHydrationCapability())throw this.buildMissingCapabilityError("enableUserInfoSync","group:namecard",["GroupManager"]);if(this.config.enableSyncData.includes("contact")&&!this.getUserInfoReadCapability())throw this.buildMissingCapabilityError("enableSyncData: ['contact']","userInfo:read",["UserInfoManager"]);if(this.config.enableSyncData.includes("group")&&!this.managerRegistry.has("groupManager"))throw this.buildMissingCapabilityError("enableSyncData: ['group']","rawNotify:group",["GroupManager"])}hasUserInfoReadCapability(e){return"function"==typeof e.getUserInfoByUserId}hasGroupNamecardHydrationCapability(e){return"function"==typeof e.hydrateMessageProfileGroupNamecards}buildMissingCapabilityError(e,t,r){return new Zr(`${e} requires explicit manager capability: ${t}`,{code:nt,details:{fields:[{path:e,message:`${e} requires explicit manager capability: ${t}`,rule:"dependency"}],capability:t,requiredManagers:r}})}resolveManagerKey(t){if(e.isManagerConstructor(t))return this.getManagerKeyFromConstructor(t);if("object"!=typeof t||null===t)throw this.buildManagerValidationError("Manager must be constructor or instance",it,"managers","type",{receivedType:typeof t});return this.getManagerKeyFromInstance(t)}getManagerKeyFromConstructor(e){const t=e.key;if(!this.isValidManagerKey(t))throw this.buildManagerValidationError("Manager key is required",nt,"managers.key","required",{managerType:"constructor",managerName:this.getManagerNameFromConstructor(e)});return t}getManagerKeyFromInstance(e){const t=e.constructor.key;if(!this.isValidManagerKey(t))throw this.buildManagerValidationError("Manager key is required",nt,"managers.key","required",{managerType:"instance",managerName:this.getManagerNameFromInstance(e)});return t}attachManager(e,t){Object.prototype.hasOwnProperty.call(this,e)||Object.defineProperty(this,e,{value:t,writable:!1,enumerable:!0})}isValidManagerKey(e){return"string"==typeof e&&e.trim().length>0}getManagerNameFromConstructor(e){return"string"==typeof e.name&&e.name.length>0?e.name:"AnonymousManager"}getManagerNameFromInstance(e){const t=e.constructor;return"string"==typeof t.name&&t.name.length>0?t.name:"AnonymousManager"}buildManagerValidationError(e,t,r,s,n){return new Zr(e,{code:t,details:{fields:[{path:r,message:e,rule:s}],...n}})}buildManagerConflictError(e,t,r,s){return this.buildManagerValidationError("Manager key conflict",it,"managers.key","conflict",{managerKey:e,existingName:t,incomingName:r,reason:s})}static isManagerConstructor(e){return"function"==typeof e}updateState(e){this.state!==e&&(this.state=e)}async initCacheManager(e){this.cacheManager&&this.cacheUserId===e||(this.cacheManager=new Vf({appKey:this.requireActiveAppKey(),userId:e,cacheEncryptionMode:this.config.cacheEncryptionMode,storageAdapter:this.platformAdapter?.storage}),this.cacheUserId=e),await this.cacheManager.prepare()}loadCachedConversations(){this.cacheManager&&this.emitConversationListUpdate("conversation",!0)}loadCachedUserInfo(){this.cacheManager&&this.cacheManager.loadUserInfoSummaries()}emitConversationListUpdate(e,t=!1){if(!this.cacheManager)return;const r=this.cacheManager.loadSessionList().map(xg),s=this.buildConversationListPatch(this.conversationListSnapshot,r,t);(s.reset||0!==s.upserted.length||0!==s.removed.length||s.orderChanged)&&(this.conversationListVersion+=1,this.conversationListSnapshot=r,this.eventHub.dispatch(O,{version:this.conversationListVersion,items:r,reason:e,patch:s}))}buildConversationListPatch(e,t,r){const s=new Map(e.map(e=>[this.buildConversationListKey(e),e])),n=new Map(t.map(e=>[this.buildConversationListKey(e),e])),i=new Set,o=[],a=[];for(const d of t){const e=this.buildConversationListKey(d),t=s.get(e);t&&this.isConversationListItemEqual(t,d)||(o.push(d),i.add(e))}for(const d of e){const e=this.buildConversationListKey(d);n.has(e)||(a.push({conversationId:d.conversationId,conversationType:d.conversationType}),i.add(e))}const c=e.map(e=>this.buildConversationListKey(e)).join("\n")!==t.map(e=>this.buildConversationListKey(e)).join("\n");if(c)for(const d of t)i.add(this.buildConversationListKey(d));return{reset:r,upserted:o,removed:a,affectedKeys:[...i],orderChanged:c}}buildConversationListKey(e){return`${e.conversationType}:${e.conversationId}`}isConversationListItemEqual(e,t){return e.conversationId===t.conversationId&&e.conversationType===t.conversationType&&e.unreadCount===t.unreadCount&&e.lastMessageAt===t.lastMessageAt&&e.isPinned===t.isPinned&&e.pinnedTimestamp===t.pinnedTimestamp&&e.readAt===t.readAt&&e.remindType===t.remindType&&e.conversationName===t.conversationName&&e.conversationAvatar===t.conversationAvatar&&e.marks.length===t.marks.length&&e.marks.every((e,r)=>e===t.marks[r])&&JSON.stringify(e.lastMessage)===JSON.stringify(t.lastMessage)}async triggerContactSync(){this.config.enableSyncData.includes("contact")&&await this.refreshContactSnapshot()}triggerConfiguredSyncDataAfterLogin(e){this.config.enableSyncData.includes("contact")&&(Si("Triggering automatic contact sync after login",{userId:e}),this.triggerContactSync()),this.config.enableSyncData.includes("group")&&(Si("Triggering automatic group sync after login",{userId:e}),this.triggerGroupSync())}async triggerGroupSync(){if(!this.config.enableSyncData.includes("group"))return;const e=this.ensureGroupSyncController();await e.sync()}ensureSessionListSyncController(){return this.syncConversationListConfigController||(this.syncConversationListConfigController=new jg(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 ry(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(B,{dataType:e})}emitSyncDataFinished(e){this.eventHub.dispatch(j,e)}requireCacheManager(){if(!this.cacheManager)throw new Zr("cacheManager is required",{code:nt,details:{fields:[{path:"cacheManager",message:"cacheManager is required",rule:"required"}]}});return this.cacheManager}async resolveContactSyncUrls(){const e=this.config.serviceConfig.serverUrls?.syncWsUrl;if(e)return this.buildAuthenticatedContactSyncUrls([e]);if(this.contactSyncWsUrls.length>0)return this.buildAuthenticatedContactSyncUrls(this.contactSyncWsUrls);if(this.contactSyncDnsResolved)throw Si("Automatic contact sync sync-ws is unavailable after DNS precheck",{userId:this.currentUserId,serviceConnectionMode:this.config.serviceConfig.mode}),new Hr("Contact sync websocket urls are unavailable",Cr,{details:{stage:"socket_connect"}});if("dns"!==this.config.serviceConfig.mode)throw Si("Automatic contact sync sync-ws is unavailable without dns service config",{userId:this.currentUserId,serviceConnectionMode:this.config.serviceConfig.mode}),new Hr("Contact sync websocket urls are unavailable",Cr,{details:{stage:"socket_connect"}});try{const e=await Cb(void 0!==this.config.appId?{appId:this.config.appId,baseUrls:this.config.serviceConfig.dnsConfigUrls,requestAdapter:this.platformAdapter?.request}:{appKey:this.requireConfiguredAppKey(),baseUrls:this.config.serviceConfig.dnsConfigUrls,requestAdapter:this.platformAdapter?.request});this.contactSyncWsUrls=e.syncWebsocketUrls,this.contactSyncDnsResolved=!0}catch(t){throw Si("Automatic contact sync sync-ws DNS resolve failed",{userId:this.currentUserId,reason:t instanceof Error?t.message:String(t)}),new Hr("Contact sync websocket dns resolve failed",Cr,{details:{stage:"socket_connect",cause:t instanceof Error?t.message:String(t)}})}if(0===this.contactSyncWsUrls.length)throw Si("Automatic contact sync sync-ws is unavailable after DNS resolve",{userId:this.currentUserId,serviceConnectionMode:"dns"}),new Hr("Contact sync websocket urls are unavailable",Cr,{details:{stage:"socket_connect"}});return this.buildAuthenticatedContactSyncUrls(this.contactSyncWsUrls)}buildAuthenticatedContactSyncUrls(e){const t=this.requireContactSyncToken();return this.shuffleContactSyncUrls(e.map(e=>this.buildContactSyncSocketUrl(e,t)))}buildAuthenticatedSessionListSyncUrls(e){if(0===e.length)return[];const t=this.requireContactSyncToken();return e.map(e=>this.buildContactSyncSocketUrl(e,t))}requireContactSyncToken(){if(this.authToken)return this.authToken;throw new Zr("token is required",{code:nt,details:{fields:[{path:"token",message:"token is required",rule:"required"}]}})}buildContactSyncSocketUrl(e,t){const r=e.trim();if(!/^wss?:\/\/[^/?#]+/i.test(r))throw new Zr("sync websocket URL must use ws or wss protocol");const s=r.indexOf("#"),n=s>=0?r.slice(s):"",i=s>=0?r.slice(0,s):r,o=i.indexOf("?"),a=o>=0?i.slice(0,o):i,c=o>=0?i.slice(o+1):"",d=a.indexOf("://")+3,u=a.indexOf("/",d),l=u<0||"/"===a.slice(u)?`${a}/ws`:a,p=c.split("&").filter(e=>e.length>0&&"token"!==e.split("=",1)[0]),h=encodeURIComponent(t).replace(/%20/g,"+");return p.push(`token=${h}`),`${l}?${p.join("&")}${n}`}shuffleContactSyncUrls(e){const t=[...e];for(let r=t.length-1;r>0;r-=1){const e=Math.floor(Math.random()*(r+1)),s=t[r],n=t[e];s&&n&&(t[r]=n,t[e]=s)}return t}buildContactRosterRequest(e){const t=this.getContactSyncRestContext(),{orgName:r,appName:s}=Qn(t.appKey);return{type:jb,header:{resource:t.clientResource,timestamp:Date.now(),requestId:`contact-sync-${Date.now()}`,protocolVersion:1},org:r,app:s,username:t.userId,version:e,cursor:0}}resetCore(){this.contactSyncController?.cancel(),this.contactSyncController=null,this.groupSyncController?.cancel(),this.groupSyncController=null,this.syncWebSocketSession?.cancel("reset-core"),this.syncWebSocketSession=null,this.syncConversationListConfigController=null,this.userInfoHydrationQueue.destroy(),this.groupNamecardHydrationQueue.destroy(),this.activeIncomingStreamMessageIds.clear(),this.core&&(this.core.destroy(),this.core=null,this.currentUserId=null,this.restBaseUrl=null,this.authToken=null,this.clientResource=null,this.platformAdapter=null,this.cacheManager=null,this.cacheUserId=null,this.contactSyncWsUrls=[],this.syncConversationListConfigWsUrls=[],this.contactSyncDnsResolved=!1,this.resetManagerSessionRuntimes())}requireConfiguredAppKey(){if(this.config.appKey)return this.config.appKey;throw new Zr("appKey is unavailable before DNSConfig resolution",{code:nt,details:{fields:[{path:"appKey",message:"appKey is unavailable before DNSConfig resolution",rule:"required"}]}})}requireActiveAppKey(){if(this.activeAppKey)return this.activeAppKey;throw new Zr("appKey is unavailable for the current session",{code:nt,details:{fields:[{path:"appKey",message:"appKey is unavailable for the current session",rule:"required"}]}})}resetManagerSessionRuntimes(){const e=this.managerRegistry.get("groupManager");e?.resetSessionRuntime?.()}getContactSyncRestContext(){const e=this.getRestContext(),t=this.config.serviceConfig.serverUrls?.syncRestApiUrl;return t?{...e,restBaseUrl:t}:e}static isSameConfig(t,r){return t.appKey===r.appKey&&(t.appId===r.appId&&(!!e.isSameStringArray(t.enableSyncData,r.enableSyncData)&&(t.useCustomAttachmentUpload===r.useCustomAttachmentUpload&&(t.enableMd5Check===r.enableMd5Check&&(!!e.isSameServiceConfig(t.serviceConfig,r.serviceConfig)&&(t.useFixedDeviceId===r.useFixedDeviceId&&(t.deviceId===r.deviceId&&(t.useReplacedMessageContents===r.useReplacedMessageContents&&(t.customDeviceName===r.customDeviceName&&(t.customOSPlatform===r.customOSPlatform&&(t.platformAdapterOptions?.prefer===r.platformAdapterOptions?.prefer&&(t.platformAdapterOptions?.runtimeInput===r.platformAdapterOptions?.runtimeInput&&(t.platformAdapterOptions?.overrides===r.platformAdapterOptions?.overrides&&(t.uiKitVersion===r.uiKitVersion&&(t.cacheEncryptionMode===r.cacheEncryptionMode&&(t.enableUserInfoSync===r.enableUserInfoSync&&(t.deleteConversationOnGroupDestroyed===r.deleteConversationOnGroupDestroyed&&(t.syncConversationListConfig.includeEmpty===r.syncConversationListConfig.includeEmpty&&(t.profileSync.userInfoWindowMs===r.profileSync.userInfoWindowMs&&t.profileSync.userInfoBatchSize===r.profileSync.userInfoBatchSize&&t.profileSync.groupNamecardWindowMs===r.profileSync.groupNamecardWindowMs&&t.profileSync.groupNamecardMaxConcurrency===r.profileSync.groupNamecardMaxConcurrency)))))))))))))))))))}static normalizeServiceConfig(e){return{mode:e?.serverUrls?"fixed":"dns",dnsConfigUrls:e?.dnsConfigUrls??cb,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)}};rI.instance=null;let sI=rI;const nI=(e,t)=>new Zr(t,{code:it,details:{fields:[{path:e,message:t,rule:"invalid_format"}]}}),iI=(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()},oI=e=>`mark_${String(e)}`,aI=(e,t)=>{if("singleChat"===e||"groupChat"===e||"chatRoom"===e)return e;throw nI(t,`${t} must be one of singleChat, groupChat, chatRoom`)},cI=e=>"singleChat"===e?"chat":"groupChat"===e?"groupchat":"chatroom",dI=e=>"string"==typeof e&&e.length>0?e:void 0,uI=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}},lI=e=>El(e)?e:void 0,pI=(e,t)=>{const r=lI(e);if(!r)return;const s=(e=>"string"==typeof e?Ul(e,{}):lI(e)??{})(r.payload),n=Array.isArray(s.bodies)?s.bodies:[],i=lI(n[0])??lI(s.body),o=(e=>"txt"===e||"text"===e?"text":"custom"===e?"custom":"cmd"===e?"cmd":"image"===e||"file"===e||"voice"===e||"video"===e||"location"===e||"combine"===e?e:null)(i?.type??s.type);if(!i||!o)return;const a=((e,t)=>{if("text"===e)return{content:dI(t.msg)??dI(t.content)??""};if("custom"===e){const e=lI(t.customExts)??lI(t.params)??{},r={};for(const[t,s]of Object.entries(e))"string"==typeof s&&(r[t]=s);return{event:dI(t.customEvent)??dI(t.event)??"",params:r}}if("cmd"===e)return{action:dI(t.action)??""};if("image"===e){const e=dI(t.url)??dI(t.remotePath)??"";return{localUrl:"",filename:dI(t.filename)??dI(t.displayName),filetype:dI(t.filetype)??"application/octet-stream",width:uI(t.width),height:uI(t.height),isGif:!0===t.isGif||1===t.subType,isOriginalImage:!0===t.isOriginalImage,originalImageUrl:e,bigImageUrl:dI(t.bigImageUrl),thumbnailUrl:dI(t.thumbnailUrl)??dI(t.thumbnailRemotePath),secret:dI(t.secret)??dI(t.secretKey),fileLength:uI(t.fileLength)}}return"file"===e?{url:dI(t.url)??dI(t.remotePath),filename:dI(t.filename)??dI(t.displayName),filetype:dI(t.filetype)??"application/octet-stream",fileSize:uI(t.fileSize),fileLength:uI(t.fileLength),secret:dI(t.secret)??dI(t.secretKey)}:"voice"===e?{url:dI(t.url)??dI(t.remotePath),filename:dI(t.filename)??dI(t.displayName),filetype:dI(t.filetype)??"application/octet-stream",duration:uI(t.duration)??0,fileLength:uI(t.fileLength),secret:dI(t.secret)??dI(t.secretKey)}:"video"===e?{url:dI(t.url)??dI(t.remotePath),filename:dI(t.filename)??dI(t.displayName),filetype:dI(t.filetype)??"application/octet-stream",duration:uI(t.duration)??0,width:uI(t.width),height:uI(t.height),fileLength:uI(t.fileLength),secret:dI(t.secret)??dI(t.secretKey),thumbnailUrl:dI(t.thumbnailUrl)??dI(t.thumbnailRemotePath)}:"location"===e?{latitude:uI(t.latitude)??0,longitude:uI(t.longitude)??0,address:dI(t.address),buildingName:dI(t.buildingName)}:null})(o,i);if(!a)return;const c=dI(s.from)??dI(r.from)??"",d=dI(s.to)??t.conversationId,u=lI(s.sender),l={userId:dI(u?.userId)??c,nickname:dI(u?.nickname),avatarUrl:dI(u?.avatarUrl)},p=lI(s.ext)??{},h=(e=>{const t=lI(e);if(!t)return;const r=dI(t.operatorId)??dI(t.operator),s=uI(t.operationCount)??uI(t.count),n=uI(t.operationTime)??uI(t.edit_time);return r&&void 0!==s&&void 0!==n?{operatorId:r,operationCount:s,operationTime:n}:void 0})(s.modifiedInfo??lI(s.meta)?.edit_msg);return{msgServerId:dI(r.id)??t.messageId,msgLocalId:dI(r.msgLocalId)??"",from:c,to:d,sender:l,conversationId:t.conversationId,conversationType:t.conversationType,type:o,sendStatus:"sent",ext:p,timestamp:uI(r.timestamp)??t.timestamp,body:a,direct:c===t.currentUserId?"SEND":"RECEIVE",...h?{modifiedInfo:h}:{}}},hI=e=>`${e.conversationType}:${e.conversationId}`,mI=e=>{const{orgName:t,appName:r}=Qn(e.appKey);return{orgName:t,appName:r,encodedUserId:encodeURIComponent(e.userId),encodedResource:encodeURIComponent(e.clientResource)}},fI=async(e,t,r,s)=>{const n=mI(t),i=(e=>{const t=e,r=t.conversations;if(void 0!==r){if(!Array.isArray(r)||0===r.length)throw nI("params.conversations","params.conversations must be a non-empty array");return r.map((e,t)=>{if(!El(e))throw nI(`params.conversations.${String(t)}`,`params.conversations.${String(t)} must be an object`);return{conversationId:iI(e.conversationId,`params.conversations.${String(t)}.conversationId`),conversationType:aI(e.conversationType,`params.conversations.${String(t)}.conversationType`)}})}return[{conversationId:iI(t.conversationId,"params.conversationId"),conversationType:aI(t.conversationType,"params.conversationType")}]})(r),o=((e,t)=>{if("number"!=typeof e||!Number.isInteger(e)||e<0||e>19)throw nI(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:oI(o),targets:i.map(e=>({to:e.conversationId,type:cI(e.conversationType)}))},operation:s?"addConversationMark":"removeConversationMark"}),c=(e=>{if(!Array.isArray(e))return new Set;const t=new Set;return e.forEach(e=>{if(!El(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(hI({conversationId:r,conversationType:s}))}),t})((El(a)&&El(a.data)?a.data:{}).ignore),d=[],u=[];for(const l of i){const e={conversationId:l.conversationId,conversationType:l.conversationType};c.has(hI(l))?u.push({...e,reason:"ignored_by_server"}):d.push(e)}return{succeeded:d,failed:u,mark:o,operation:s?"addMark":"removeMark"}},gI=async(e,t,r,s)=>{const n=mI(t),i=iI(r.conversationId,"params.conversationId"),o=aI(r.conversationType,"params.conversationType"),a=iI(r.messageId,"params.messageId");return await e.request(`/${n.orgName}/${n.appName}/sdk/user/${n.encodedUserId}/user_channel/pin?resource=${n.encodedResource}`,{method:s?"POST":"DELETE",body:{to:i,type:cI(o),pin_msg_id:a},operation:s?"pinMessage":"unpinMessage"}),{conversationId:i,conversationType:o,messageId:a,operation:s?"pin":"unpin"}},yI=["nickname","avatarUrl","mail","phone","gender","sign","birth","ext"],vI=(e,t)=>`${e}\0${t}`,bI=(e,t,r)=>{const s={userId:e};for(const n of yI){const e=r?.[n]??t?.[n];void 0!==e&&(s[n]=e)}return s},II=e=>bI(e.userId,void 0,{userId:e.userId,nickname:e.nickname,avatarUrl:e.avatarUrl,sign:e.sign,ext:e.ext}),wI=(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(vI(n.groupId,n.user.userId),t.namecard)}return s},CI=async(e,t)=>{if(0===e.length||!t)return[];try{return await t({userIds:e})}catch(r){return Si("Group user info hydration failed",{userIds:e,error:r}),[]}},SI=async(e,t)=>{t&&0!==e.size&&await Promise.all([...e.entries()].map(async([e,r])=>{try{await t(e,r)}catch(s){Si("Group namecard hydration failed",{groupId:e,userIds:r,error:s})}}))},TI=async e=>{const t=(e=>{const t=[],r=new Set;for(const s of e){const e=s.groupId.trim(),n=s.user.userId.trim();if(!e||!n)continue;const i=vI(e,n);r.has(i)||(r.add(i),t.push({groupId:e,user:{...s.user,userId:n}}))}return t})(e.contexts),r=(e=>{const t=[],r=new Set;for(const s of e)r.has(s.user.userId)||(r.add(s.user.userId),t.push(s.user.userId));return t})(t),s=((e,t)=>{const r=new Map;if(!e)return r;for(const n of t){const t=e.getRuntimeUserInfo?.(n,!1)??null;t&&r.set(n,t)}const s=t.filter(e=>!r.has(e));for(const n of e.getUserInfoSummaries?.(s,!1)??[])r.set(n.userId,II(n));return r})(e.cacheManager,r),n=r.filter(e=>!s.has(e)),i=new Set(n),o=wI(e.cacheManager,t,e.includeNameCard),a=e.includeNameCard?((e,t,r)=>{const s=new Map;for(const n of e){const e=n.user.userId,i=vI(n.groupId,e);if(!t.has(e)||r.has(i))continue;const o=s.get(n.groupId)??[];o.includes(e)||o.push(e),s.set(n.groupId,o)}return s})(t,i,o):new Map,[c]=await Promise.all([CI(n,e.fetchUserInfos),SI(a,e.hydrateGroupNamecards)]),d=new Map(c.map(e=>[e.userId,e])),u=wI(e.cacheManager,t,e.includeNameCard),l=new Map;for(const p of t){const e=p.user.userId,t=vI(p.groupId,e),r=bI(e,p.user,d.get(e)??s.get(e)),n=u.get(t)??o.get(t);l.set(t,void 0!==n?{...r,nameCard:n}:r)}return{usersByContextKey:l,fetchedUserInfos:c,missingUserIds:n.filter(e=>!d.has(e))}},_I=async e=>{const t=await TI({...e,contexts:e.users.map(t=>({groupId:e.groupId,user:t}))}),r=new Map;for(const s of e.users){const n=s.userId.trim();if(!n||r.has(n))continue;const i=t.usersByContextKey.get(vI(e.groupId.trim(),n));i&&r.set(n,i)}return{usersById:r,fetchedUserInfos:t.fetchedUserInfos,missingUserIds:t.missingUserIds}},RI=Wv(["singleChat","groupChat","chatRoom"]),AI=Vv(Bv()).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"),MI=Kv({path:$v().min(1,"data.path is required"),size:Gv().optional(),name:$v().optional(),type:$v().optional()}),EI=Kv({uri:$v().min(1,"data.uri is required"),size:Gv().optional(),name:$v().optional(),type:$v().optional()}),UI=Hv(["undefined"!=typeof File?((e,t={message:`Input not instance of ${e.name}`})=>Pv(t=>t instanceof e,t))(File):jv(),MI,EI]),kI=Kv({conversationId:$v().min(1,"conversationId is required"),conversationType:RI,ext:AI.optional(),timestamp:Gv().int().positive("timestamp must be a positive integer").optional(),receiverList:zv($v().min(1,"receiverList item is required")).nonempty("receiverList must not be empty").optional(),deliverOnlineOnly:Fv().optional(),webhookEnv:$v().optional(),priority:Wv(["high","normal","low"]).optional(),needReadReceipt:Fv().optional(),isChatThread:Fv().optional()}),NI=Kv({type:$v().min(1,"messageList.type is required"),sender:Kv({userId:$v().min(1,"messageList.sender.userId is required"),nickname:$v().optional(),avatarUrl:$v().optional()}),conversationId:$v().min(1,"messageList.conversationId is required"),conversationType:RI,timestamp:Gv().int().positive("messageList.timestamp must be positive"),body:Vv(Bv()),combineLevel:Gv().int().min(0).max(10).optional()}).passthrough(),OI=e=>e.superRefine((e,t)=>{e.receiverList&&"singleChat"===e.conversationType&&t.addIssue({code:cy.custom,message:"receiverList is only allowed for group or chat room conversation",path:["receiverList"]}),e.isChatThread&&"groupChat"!==e.conversationType&&t.addIssue({code:cy.custom,message:"isChatThread is only allowed for group conversation",path:["isChatThread"]}),e.needReadReceipt&&"chatRoom"===e.conversationType&&t.addIssue({code:cy.custom,message:"needReadReceipt is not allowed for chatRoom conversation",path:["needReadReceipt"]})}),xI=OI(kI.extend({content:$v().min(1,"content is required"),targetLanguages:zv($v().min(1)).optional()})),LI=OI(kI.extend({originalUrl:$v().min(1,"originalUrl is required").optional(),filename:$v().min(1,"filename is required").optional(),filetype:$v().min(1,"filetype is required").optional(),width:Gv().positive("width must be positive").optional(),height:Gv().positive("height must be positive").optional(),isGif:Fv().optional(),isOriginalImage:Fv().optional(),fileLength:Gv().positive("fileLength must be positive").optional(),data:UI.optional(),thumbnailUrl:$v().min(1).optional()}).refine(e=>Boolean(e.originalUrl||e.data),{message:"originalUrl or data is required",path:["originalUrl"]})),PI=OI(kI.extend({originalUrl:$v().min(1,"originalUrl is required").optional(),filename:$v().min(1,"filename is required").optional(),filetype:$v().min(1,"filetype is required").optional(),fileSize:Gv().positive("fileSize must be positive").optional(),fileLength:Gv().positive("fileLength must be positive").optional(),data:UI.optional()}).refine(e=>Boolean(e.originalUrl||e.data),{message:"originalUrl or data is required",path:["originalUrl"]})),DI=OI(kI.extend({originalUrl:$v().min(1,"originalUrl is required").optional(),filename:$v().min(1,"filename is required").optional(),filetype:$v().min(1,"filetype is required").optional(),duration:Gv().positive("duration must be positive"),fileLength:Gv().positive("fileLength must be positive").optional(),data:UI.optional()}).refine(e=>Boolean(e.originalUrl||e.data),{message:"originalUrl or data is required",path:["originalUrl"]})),qI=OI(kI.extend({originalUrl:$v().min(1,"originalUrl is required").optional(),filename:$v().min(1,"filename is required").optional(),filetype:$v().min(1,"filetype is required").optional(),duration:Gv().positive("duration must be positive"),width:Gv().positive("width must be positive").optional(),height:Gv().positive("height must be positive").optional(),fileLength:Gv().positive("fileLength must be positive").optional(),thumbnailUrl:$v().min(1).optional(),data:UI.optional()}).refine(e=>Boolean(e.originalUrl||e.data),{message:"originalUrl or data is required",path:["originalUrl"]})),$I=OI(kI.extend({latitude:Gv(),longitude:Gv(),address:$v().min(1).optional(),buildingName:$v().min(1).optional()})),GI=OI(kI.extend({action:$v().min(1,"action is required")})),FI=OI(kI.extend({event:$v().min(1,"event is required"),params:Vv($v()).optional()})),BI=OI(kI.extend({title:$v().min(1,"title is required"),summary:$v().min(1,"summary is required"),compatibleText:$v().min(1).optional(),messageList:zv(NI).min(1,"messageList must not be empty").max(300,"messageList max length is 300")})),jI=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}},zI=()=>Xh(),KI=(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=Yh(t);if(!r)throw new Zr("Failed to resolve local url",{code:it,details:{fields:[{path:"url",message:"Failed to resolve local url",rule:"invalid_format"}]}});return r},HI=e=>!!e.isGif||(e.isOriginalImage??!1),VI=(e,t,r,s,n)=>({msgServerId:"",msgLocalId:n??Xh(),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}),WI=(e,t)=>{const r=Jv.validateOrThrow(BI,e),s=r.messageList,n=jI(t);vm(s);const i=bm(s);Im(i);const o={title:r.title,summary:r.summary,messageList:s,filename:"combine",filetype:"application/octet-stream",combineLevel:i},a=VI(r,n,"combine",o);return((e,t)=>{t&&mp.set(e,t)})(a,r.compatibleText),a},JI=e=>{const{orgName:t,appName:r}=Qn(e.appKey);return`/${t}/${r}`},ZI=e=>{const t=new Uint8Array(Dc.util.base64.length(e));return Dc.util.base64.decode(e,t,0),t},QI=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),YI=async e=>{try{return await e()}catch(t){if(!(t instanceof ts))throw t;const e=(e=>{const t="string"==typeof e.details?.serverMessage?e.details.serverMessage:void 0;switch(e.code){case qt:case Ar:return"Translation service is not enabled";case Rr:return t?.includes("too long")?"Translation text is too long":t?.includes("target language")?"Invalid target language":"Invalid translation request";case Mr:return"Translation quota has been reached";case Er:return"Translation service error";default:return}})(t);if(!e)throw t;throw new ts(`REST business error: ${e}`,{code:t.code,details:t.details})}},XI=e=>"string"==typeof e?e:"number"==typeof e||"boolean"==typeof e||"bigint"==typeof e?String(e):"",ew=e=>{if("string"!=typeof e)return"";const t=e.trim();return t&&"undefined"!==t&&"null"!==t?t:""},tw=e=>({userId:e}),rw=(e,t)=>{if(!QI(e)||!QI(e.data))throw Qg({apiName:t,message:`${t} response data is invalid`,mapped:!1});return e.data},sw=(e,t)=>{if(!QI(e)||!Array.isArray(e.data))throw Qg({apiName:t,message:`${t} response data is invalid`,mapped:!1});return e.data},nw=(e,t)=>Array.isArray(e)?e:sw(e,t),iw={txt:"text",img:"image",video:"video",file:"file",loc:"location",custom:"custom",combine:"combine"},ow={text:"txt",image:"img",video:"video",file:"file",location:"loc",custom:"custom",combine:"combine"},aw={chat:"singleChat",chatroom:"chatRoom",groupchat:"groupChat",singleChat:"singleChat",chatRoom:"chatRoom",groupChat:"groupChat"},cw=(e,t,r)=>{if(!t)return"";if(t.includes("em-redirect"))return t;const{orgName:s,appName:n}=Qn(e.appKey),i=t.indexOf("/chatfiles/"),o=i>=0?t.slice(i):t,a=`${e.restBaseUrl}/${s}/${n}${o}`;return ri(a,r)},dw=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},uw=(e,t,r)=>{const s=XI(r.contentType??r.type),n=ow[s];if(!n)return null;const i=QI(r.content)?r.content:{},o=((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=aw[XI(r.conversationType)]??"singleChat",c={msgServerId:XI(r.messageId),msgLocalId:XI(r.messageId),from:XI(r.senderId),to:XI(r.receiverId),conversationId:o,conversationType:a,type:n,ext:QI(r.ext)?r.ext:{},timestamp:"number"==typeof r.sentTime?r.sentTime:new Date(XI(r.sentTime)).getTime(),sender:{userId:XI(r.senderId)},highlight:dw(r.highlight),text:"string"==typeof r.text?r.text:void 0};let d;const u=XI(i.remotePath??i.url),l=XI(i.secret??i.secretKey);switch(n){case"txt":d={type:"txt",content:XI(i.message??r.text)};break;case"img":{const t=cw(e,u,l);d={type:"img",url:t,thumb:i.thumb?cw(e,XI(i.thumb),XI(i.thumb_secret??i.thumbnailSecretKey)):`${t}&thumbnail=true`,secret:l,width:Number(i.width??(QI(i.size)?i.size.width:0))||0,height:Number(i.height??(QI(i.size)?i.size.height:0))||0,fileLength:Number(i.file_length??i.fileLength??0)};break}case"video":d={type:"video",url:cw(e,u,l),thumb:i.thumb||i.thumbnailRemotePath?cw(e,XI(i.thumb??i.thumbnailRemotePath),XI(i.thumb_secret??i.thumbnailSecretKey)):"",secret:l,filename:XI(i.filename??i.displayName),duration:Number(i.length??i.duration??0),fileLength:Number(i.file_length??i.fileLength??0)};break;case"file":d={type:"file",url:cw(e,u,l),secret:l,filename:XI(i.filename??i.displayName),fileLength:Number(i.file_length??i.fileLength??0)};break;case"loc":d={type:"loc",latitude:Number(i.lat??i.latitude??0),longitude:Number(i.lng??i.longitude??0),address:XI(i.addr??i.address),buildingName:XI(i.buildingName)};break;case"custom":d={type:"custom",customEvent:XI(i.customEvent),customExts:QI(i.customExts)?i.customExts:{}};break;default:return null}return{...c,body:d}},lw=async(e,t,r)=>{const s=`${JI(t)}/users/${t.userId}/messages/search/get`,n=((e,t)=>{const{option:r,pageNum:s=1,pageSize:n=20}=e,i=r.keywordList.map(e=>e.trim()).filter(e=>e.length>0),o={searchMode:"default",highlightEnable:!0,page:s,size:n};return 1===i.length?o.keyword=i[0]:(o.keywords=i,o.keywordMatch="and"===r.keywordListMatchType?"all":"any"),r.conversationId&&("singleChat"===r.conversationType?o.participantPairs=[{userId1:t,userId2:r.conversationId}]:"groupChat"===r.conversationType?o.groupIds=[r.conversationId]:"chatRoom"===r.conversationType&&(o.chatroomIds=[r.conversationId])),r.msgTypes&&r.msgTypes.length>0&&(o.contentType=r.msgTypes.map(e=>iw[e]??e).join(",")),void 0!==r.startTime&&(o.startTime=r.startTime),void 0!==r.endTime&&(o.endTime=r.endTime),r.searchScope&&(o.searchExt=r.searchScope),r.direction&&(o.sort="up"===r.direction?"sentTime:asc":"sentTime:desc"),{data:o}})(r,t.userId),i=await e.post(s,n,{operation:"searchMessages"}),o=QI(i)?i:{},a=QI(o.data)?o.data:o,c=QI(a.data)?a.data:a,d=Array.isArray(c.items)?c.items:Array.isArray(c.list)?c.list:[],u=QI(c.pagination)?c.pagination:c,l=Number(u.pageNum??u.page??r.pageNum??1),p=Number(u.pageSize??u.size??r.pageSize??20),h=Number(u.totalPages??0),m=1===u.isFinished||l>=h,f=[];for(const g of d){if(!QI(g))continue;const e=uw(t,t.userId,g);e&&f.push(e)}return{messages:f,pageNum:l,pageSize:p,totalPages:h,isLast:m}},pw=e=>{const{orgName:t,appName:r}=Qn(e.appKey);return`/api/sdk/v1/${t}/${r}`},hw=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),mw=e=>hw(e)&&"string"==typeof e.path&&e.path.trim().length>0,fw=e=>(e=>"undefined"!=typeof File&&e instanceof File)(e)||mw(e),gw=e=>{if(!hw(e))return;return{data:hw(e.data)?e.data:void 0,error:hw(e.error)?e.error:void 0}},yw=(e,t)=>{const r=gw(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},vw=(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}),bw=e=>!(void 0===e||hw(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))),Iw=e=>{if(!e)return;const t=(e.split("#")[0]?.split("?")[0]??"").split("/").filter(Boolean);return t.length>0?t[t.length-1]:void 0},ww=e=>{const{serviceCode:t,serviceMessage:r}=(e=>{const t=e instanceof Hr&&hw(e.details)?e.details:void 0,r=gw(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 vw("File upload failed",qr,{cause:e.details});if(e instanceof Hr&&!t)return e;if(t)switch(t){case"4041001":return vw("File not found",Or,{serviceCode:t,serviceMessage:r});case"4001002":return vw("Invalid file",Ur,{serviceCode:t,serviceMessage:r},"validation");case"5021001":return vw("File upload failed",qr,{serviceCode:t,serviceMessage:r});case"4001003":return vw("Voice duration exceeds 60 seconds",kr,{serviceCode:t,serviceMessage:r},"validation");case"4031001":return vw("Voice-to-text service is not enabled",qt,{serviceCode:t,serviceMessage:r});case"4031002":return vw("Beta service usage limit exceeded",Fr,{serviceCode:t,serviceMessage:r});case"4001001":return"string"==typeof(s=r)&&s.toLowerCase().includes("uploaded file exceeds")?vw("File too large",xr,{serviceCode:t,serviceMessage:r}):vw(r||"Missing or invalid request parameter",nt,{serviceCode:t,serviceMessage:r},"validation");case"5021003":case"5001003":return vw("Voice-to-text failed",Nr,{serviceCode:t,serviceMessage:r});case"4011001":return vw(r||"Unauthorized or invalid token",dt,{serviceCode:t,serviceMessage:r},"auth");default:return vw(r||(e instanceof Error?e.message:"Voice-to-text failed"),Nr,{serviceCode:t,serviceMessage:r})}var s;return e instanceof Hr?vw(e.message,e.code,e.details):vw(e instanceof Error?e.message:"Voice-to-text failed",Nr)},Cw=(e,t)=>{if(!hw(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 vw("Invalid file",Ur,{path:"voiceMessageBody"},"validation");var r;if(bw(t))throw vw("Invalid file",Ur,{path:"voiceParams"},"validation");if(!e.url)throw vw("File not found",Or,{path:"voiceMessageBody.url"});if(!Iw(e.url))throw vw("Invalid file",Ur,{path:"voiceMessageBody.url"},"validation");return e},Sw=(e,t)=>{if(bw(t))throw vw("Invalid file",Ur,{path:"voiceParams"},"validation");if(!fw(e))throw vw("Invalid file",Ur,{path:"file"},"validation");return e},Tw=async(e,t,r,s)=>{const n=Cw(r,s),i=Iw(n.url);if(!i)throw((e,t,r,s="invalid")=>new Zr(e,{code:t,details:{fields:[{path:r,message:e,rule:s}]}}))("File not found",Or,"voiceMessageBody.url");try{const r=await e.post(`${pw(t)}/speech/transcriptions`,{data:{fileId:i,username:t.userId,...s?{audio:s}:{}}},{operation:"voiceMessageToText"});return{text:yw(r,"voiceMessageToText")}}catch(o){throw ww(o)}},_w=Kv({keywordList:zv($v()).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:Wv(["or","and"]).optional(),conversationId:$v().min(1).optional(),conversationType:Wv(["singleChat","groupChat","chatRoom"]).optional(),msgTypes:zv(Wv(["txt","img","video","file","loc","custom","combine"])).optional(),startTime:Gv().optional(),endTime:Gv().optional(),searchScope:Wv(["none","with","only"]).optional(),direction:Wv(["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"}),Rw=Kv({option:_w,pageNum:Gv().int().min(1).default(1),pageSize:Gv().int().min(1).max(100).default(20)}),Aw=Nb(Ob,{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"]}}}}}),Mw=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=Jv.validateOrThrow(xI,e),s=jI(t),n=zI(),i={content:r.content};return r.targetLanguages&&(i.targetLanguages=r.targetLanguages),VI(r,s,"text",i,n)})(e,this.buildMessageSenderOrThrow())}createImageMessage(e){return((e,t,r)=>{const s=Jv.validateOrThrow(LI,e),n=jI(t),i=zI(),o=s.data?KI(void 0,s.data):"",a=s.originalUrl?ni(s.originalUrl,{deriveVariants:!r?.useCustomAttachmentUpload}):void 0;s.data&&Qh.set(i,s.data);const c=s.isGif??!1,d={localUrl:o,filename:s.filename,filetype:s.filetype,width:s.width,height:s.height,isGif:c,isOriginalImage:HI({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),VI(s,n,"image",d,i)})(e,this.buildMessageSenderOrThrow(),this.getClientOrThrow().getMessageCreationOptions())}createFileMessage(e){return((e,t)=>{const r=Jv.validateOrThrow(PI,e),s=jI(t),n=zI(),i=KI(r.originalUrl,r.data);r.data&&Qh.set(n,r.data);const o={url:i,filename:r.filename,filetype:r.filetype};return void 0!==r.fileSize&&(o.fileSize=r.fileSize),void 0!==r.fileLength&&(o.fileLength=r.fileLength),VI(r,s,"file",o,n)})(e,this.buildMessageSenderOrThrow())}createVoiceMessage(e){return((e,t)=>{const r=Jv.validateOrThrow(DI,e),s=jI(t),n=zI(),i=KI(r.originalUrl,r.data);r.data&&Qh.set(n,r.data);const o={url:i,filename:r.filename,filetype:r.filetype,duration:r.duration};return void 0!==r.fileLength&&(o.fileLength=r.fileLength),VI(r,s,"voice",o,n)})(e,this.buildMessageSenderOrThrow())}createVideoMessage(e){return((e,t)=>{const r=Jv.validateOrThrow(qI,e),s=jI(t),n=zI(),i=KI(r.originalUrl,r.data);r.data&&Qh.set(n,r.data);const o={url:i,filename:r.filename,filetype:r.filetype,duration:r.duration};return void 0!==r.width&&(o.width=r.width),void 0!==r.height&&(o.height=r.height),void 0!==r.fileLength&&(o.fileLength=r.fileLength),r.thumbnailUrl&&(o.thumbnailUrl=r.thumbnailUrl),VI(r,s,"video",o,n)})(e,this.buildMessageSenderOrThrow())}createLocationMessage(e){return((e,t)=>{const r=Jv.validateOrThrow($I,e),s=jI(t),n={latitude:r.latitude,longitude:r.longitude};return r.address&&(n.address=r.address),r.buildingName&&(n.buildingName=r.buildingName),VI(r,s,"location",n)})(e,this.buildMessageSenderOrThrow())}createCmdMessage(e){return((e,t)=>{const r=Jv.validateOrThrow(GI,e),s=jI(t),n={action:r.action};return void 0!==r.deliverOnlineOnly&&(n.deliverOnlineOnly=r.deliverOnlineOnly),VI(r,s,"cmd",n)})(e,this.buildMessageSenderOrThrow())}createCustomMessage(e){return((e,t)=>{const r=Jv.validateOrThrow(FI,e),s=jI(t),n={event:r.event};return r.params&&(n.params=r.params),VI(r,s,"custom",n)})(e,this.buildMessageSenderOrThrow())}createCombineMessage(e){return WI(e,this.buildMessageSenderOrThrow())}getConversationList(e){if(void 0!==e?.mark&&(!Number.isInteger(e.mark)||e.mark<0||e.mark>19))throw new Zr("filter.mark must be an integer between 0 and 19",{code:it,details:{fields:[{path:"filter.mark",message:"filter.mark must be an integer between 0 and 19",rule:"invalid_format"}]}});const t=(this.getClientOrThrow().getCacheManager()?.loadSessionList()??[]).filter(t=>null!==t.lastMessage&&((void 0===e?.isPinned||t.isPinned===e.isPinned)&&!(void 0!==e?.mark&&!((e,t)=>e.marks.includes(t))(t,e.mark)))).map(xg);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=mI(t),n=iI(r.conversationId,"params.conversationId"),i=aI(r.conversationType,"params.conversationType"),o=r.deleteRoamingMessages??!1;if("boolean"!=typeof o)throw nI("params.deleteRoamingMessages","params.deleteRoamingMessages must be a boolean");return await e.request(`/${s.orgName}/${s.appName}/user/${s.encodedUserId}/user_channel?resource=${s.encodedResource}`,{method:"DELETE",body:{channel:n,type:"groupChat"===i?"groupChat":cI(i),delete_roam:o},operation:"deleteConversation"}),{conversationId:n,conversationType:i,operation:"delete"}})(this.getRestClient(t),t,e),s=this.getClientOrThrow(),n=s.getCacheManager()?.deleteConversation({conversationId:r.conversationId,type:r.conversationType});return n?.changed&&s.emitConversationListUpdate("local"),r}async setConversationPinned(e){const t=this.getRestContextOrThrow(),r=await(async(e,t,r)=>{const s=mI(t),n=iI(r.conversationId,"params.conversationId"),i=aI(r.conversationType,"params.conversationType");if("boolean"!=typeof r.pinned)throw nI("params.pinned","params.pinned must be a boolean");const o="groupChat"===i?"groupChat":cI(i),a=r.pinned?await e.post(`/${s.orgName}/${s.appName}/sdk/user/${s.encodedUserId}/user_channel/top?resource=${s.encodedResource}`,{type:o,to:n},{operation:"setConversationPinned"}):await e.delete(`/${s.orgName}/${s.appName}/sdk/user/${s.encodedUserId}/user_channel/top?type=${encodeURIComponent(o)}&to=${encodeURIComponent(n)}&resource=${s.encodedResource}`,{operation:"setConversationPinned"}),c=El(a)&&El(a.data)?a.data:{};return{conversationId:n,conversationType:i,operation:"setPinned",isPinned:"boolean"==typeof c.is_top?c.is_top:r.pinned,pinnedTime:"number"==typeof c.update_top_status_time?c.update_top_status_time:r.pinned?Date.now():0}})(this.getRestClient(t),t,e),s=this.getClientOrThrow().getCacheManager(),n=s?.applyConversationPinnedMutation({conversationId:r.conversationId,type:r.conversationType,isPinned:r.isPinned??e.pinned,pinnedTime:r.pinnedTime});return n?.changed&&this.getClientOrThrow().emitConversationListUpdate("local"),r}async addConversationMark(e){const t=this.getRestContextOrThrow(),r=await(async(e,t,r)=>fI(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)=>fI(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=mI(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)=>gI(e,t,r,!0))(this.getRestClient(t),t,e))}async unpinMessage(e){const t=this.getRestContextOrThrow();await this.executeRestOperation(()=>(async(e,t,r)=>gI(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=mI(t),n=iI(r.conversationId,"params.conversationId"),i=aI(r.conversationType,"params.conversationType"),o=await e.get(`/${s.orgName}/${s.appName}/sdk/user/${s.encodedUserId}/user_channel/pin?to=${encodeURIComponent(n)}&type=${encodeURIComponent(cI(i))}&limit=${String(20)}`,{operation:"getPinnedMessageList"}),a=El(o)&&El(o.data)?o.data:{};return{items:(Array.isArray(a.msg_infos)?a.msg_infos:[]).reduce((e,r)=>{if(!El(r))return e;const s="string"==typeof r.pin_msg_id?r.pin_msg_id:El(r.message)&&"string"==typeof r.message.id?r.message.id:"";if(!s)return e;const o="number"==typeof r.pin_opt_at?r.pin_opt_at:0,a=pI(r.message,{messageId:s,conversationId:n,conversationType:i,currentUserId:t.userId,timestamp:o});return a?(e.push({messageId:s,conversationId:n,conversationType:i,operatorId:"string"==typeof r.pin_operator?r.pin_operator:void 0,pinnedAt:o,message:a}),e):e},[])}})(this.getRestClient(t),t,e))}addEventHandler(e,t){this.getEventContextOrThrow().addEventHandler(e,t)}removeEventHandler(e){this.getEventContextOrThrow().removeEventHandler(e)}async clearConversationUnreadMessageCount(e){this.validateUnreadConversationLocator(e);const t=this.getClientOrThrow(),r=t.getCacheManager()?.clearConversationUnreadMessageCount({conversationId:e.conversationId,type:e.conversationType});r?.changed&&t.emitConversationListUpdate("local");try{await this.requireConnectedClient().sendMessageAction({kind:"clearConversationUnreadMessageCount",conversationId:e.conversationId,conversationType:e.conversationType,sendToPeer:!1},(e,t)=>this.buildActionError(e,t))}catch(s){if(!r?.matched)throw s;Si("Conversation unread remote sync failed after local clear",{conversationId:e.conversationId,conversationType:e.conversationType,error:s})}}async sendMessageReadReceipts(e){this.validateSendMessageReadReceiptsParams(e),await this.requireConnectedClient().sendMessageAction({kind:"sendMessageReadReceipts",conversationId:e.conversationId,conversationType:e.conversationType,messageIds:e.messageIds},(e,t)=>this.buildActionError(e,t))}async clearAllConversationUnreadMessageCount(){await this.requireConnectedClient().sendMessageAction({kind:"clearAllConversationUnreadMessageCount",conversationId:this.getCurrentUserIdOrThrow(),conversationType:"singleChat",sendToPeer:!1,clearAllUnreadMessageCount:!0},(e,t)=>this.buildActionError(e,t));const e=this.getClientOrThrow(),t=e.getCacheManager()?.clearAllConversationUnreadMessageCount();t?.changed&&e.emitConversationListUpdate("local")}async recallMessage(e){this.validateConversationLocator(e),this.requireNonEmptyString(e.messageId,"messageId"),await this.requireConnectedClient().sendMessageAction({kind:"recall",conversationId:e.conversationId,conversationType:e.conversationType,messageId:e.messageId,ext:e.ext},(e,t)=>this.buildActionError(e,t));return{messageId:e.messageId,conversationId:e.conversationId,conversationType:e.conversationType,timestamp:Date.now()}}async modifyMessage(e){if(this.validateConversationLocator(e),this.requireNonEmptyString(e.messageId,"messageId"),"text"!==e.message.type&&"custom"!==e.message.type)throw new Zr("only text and custom messages are editable",{code:Ut});await this.requireConnectedClient().sendMessageAction({kind:"update",conversationId:e.conversationId,conversationType:e.conversationType,messageId:e.messageId,body:e.message.body,messageType:e.message.type,ext:e.message.ext},(e,t)=>this.buildActionError(e,t));const t=Date.now(),r=this.getCurrentUserIdOrThrow(),s={operatorId:r,operationCount:1,operationTime:t};return{msgServerId:e.messageId,msgLocalId:"",from:r,to:e.conversationId,sender:{userId:r},conversationId:e.conversationId,conversationType:e.conversationType,type:e.message.type,sendStatus:"sent",ext:e.message.ext,timestamp:t,body:e.message.body,direct:"SEND",modifiedInfo:s}}async getHistoryMessages(e){if(this.validateConversationLocator(e),void 0!==e.pageSize&&(!Number.isInteger(e.pageSize)||e.pageSize<=0))throw this.buildValidationError("pageSize must be a positive integer","pageSize");const t=this.getRestContextOrThrow();return this.executeRestOperation(()=>(async(e,t,r,s)=>{const n=`${JI(t)}/users/${t.userId}/messageroaming`,i=await e.post(n,{queue:"singleChat"===r.conversationType?`${r.conversationId}@easemob.com`:`${r.conversationId}@conference.easemob.com`,start:r.cursor&&r.cursor.length>0?r.cursor:-1,pull_number:r.pageSize??20,is_positive:"down"===r.searchDirection,msgType:(r.messageTypes??[]).join(","),end:-1,startTime:r.startTime??null,endTime:r.endTime??null,userIds:"singleChat"===r.conversationType?null:r.senderIds&&r.senderIds.length>0?r.senderIds:null},{operation:"getHistoryMessages"}),o=rw(i,"getHistoryMessages"),a=Array.isArray(o.msgs)?o.msgs:[],c=[];for(const d of a){if(!QI(d)||"string"!=typeof d.msg||0===d.msg.length)continue;const e=s(ZI(d.msg));e&&c.push(e)}return{items:c,cursor:ew(o.next_key),hasMore:!0!==o.is_last&&c.length>0}})(this.getRestClient(t),t,e,e=>this.getClientOrThrow().decodeServerMessageMeta(e)))}async searchMessages(e){const t=Jv.validateOrThrow(Rw,e),r=this.getRestContextOrThrow();return this.executeRestOperation(()=>lw(this.getRestClient(r),r,t))}async downloadAttachment(e){return this.getClientOrThrow().downloadAttachment(e.message)}async downloadAndParseCombineMessage(e){return this.getClientOrThrow().downloadAndParseCombinePayload(this.resolveDownloadCombineMessageParams(e))}async removeHistoryMessages(e){if(this.validateConversationLocator(e),!e.messageIds&&!e.beforeTimestamp)throw this.buildValidationError("messageIds or beforeTimestamp is required","removeHistoryMessages");if(e.messageIds&&0===e.messageIds.length)throw this.buildValidationError("messageIds cannot be empty","messageIds");if(void 0!==e.beforeTimestamp&&(!Number.isInteger(e.beforeTimestamp)||e.beforeTimestamp<=0))throw this.buildValidationError("beforeTimestamp must be a positive integer","beforeTimestamp");const t=this.getRestContextOrThrow();await this.executeRestOperation(()=>(async(e,t,r)=>{const s="singleChat"===r.conversationType?"userId":"groupId",n="singleChat"===r.conversationType?"chat":"group",i=encodeURIComponent(t.clientResource),o=r.messageIds?`${JI(t)}/sdk/message/roaming/${n}/user/${t.userId}?${s}=${encodeURIComponent(r.conversationId)}&msgIdList=${encodeURIComponent(r.messageIds.join(","))}&resource=${i}`:`${JI(t)}/sdk/message/roaming/${n}/user/${t.userId}/time?${s}=${encodeURIComponent(r.conversationId)}&delTime=${r.beforeTimestamp}&resource=${i}`;await e.delete(o,{operation:"removeHistoryMessages"})})(this.getRestClient(t),t,e))}async getGroupMessageReadUsers(e){if(this.requireNonEmptyString(e.groupId,"groupId"),this.requireNonEmptyString(e.messageId,"messageId"),void 0!==e.pageSize&&(!Number.isInteger(e.pageSize)||e.pageSize<=0))throw this.buildValidationError("pageSize must be a positive integer","pageSize");const t=this.getRestContextOrThrow(),r=await this.executeRestOperation(()=>(async(e,t,r)=>{const s=ob();s.set("limit",String(r.pageSize??10)),r.cursor&&s.set("key",r.cursor);const n=`${JI(t)}/chatgroups/${encodeURIComponent(r.groupId)}/acks/${encodeURIComponent(r.messageId)}?${s.toString()}`,i=await e.get(n,{operation:"getGroupMessageReadUsers"}),o=rw(i,"getGroupMessageReadUsers"),a=QI(o.group_ack)?o.group_ack:o,c=(Array.isArray(a.userlist)?a.userlist:[]).map(e=>QI(e)&&"string"==typeof e.username?{userId:e.username,user:tw(e.username),ackId:"string"==typeof e.meta_id?e.meta_id:void 0,timestamp:"number"==typeof e.timestamp?e.timestamp:void 0,ackContent:"string"==typeof e.ack_content?e.ack_content:void 0}:null).filter(e=>null!==e);return{groupId:r.groupId,messageId:"string"==typeof o.ackmid?o.ackmid:r.messageId,users:c,count:"number"==typeof a.total?a.total:c.length,cursor:ew(a.next_key),hasMore:!0!==a.is_last&&c.length>0}})(this.getRestClient(t),t,e));return await this.hydrateGroupMessageReadUsers(e.groupId,r)}async getGroupMessageReadReceipts(e){this.requireNonEmptyString(e.groupId,"groupId");const t=this.validateMessageIdList(e.messageIds,"messageIds"),r=this.getRestContextOrThrow();return this.executeRestOperation(()=>(async(e,t,r)=>{const s=`${JI(t)}/chatgroups/${encodeURIComponent(r.groupId)}/acks/batch`,n=await e.post(s,{messageIds:r.messageIds},{operation:"getGroupMessageReadReceipts"});return sw(n,"getGroupMessageReadReceipts").map(e=>QI(e)&&"string"==typeof e.ackmid&&"number"==typeof e.total?{messageId:e.ackmid,count:e.total}:null).filter(e=>null!==e)})(this.getRestClient(r),r,{groupId:e.groupId.trim(),messageIds:t}))}async addReaction(e){this.validateReactionParams(e);const t=this.getRestContextOrThrow();await this.executeRestOperation(()=>(async(e,t,r)=>{await e.post(`${JI(t)}/reaction/user/${t.userId}`,{msgId:r.messageId,message:r.reaction},{operation:"addReaction"})})(this.getRestClient(t),t,e))}async removeReaction(e){this.validateReactionParams(e);const t=this.getRestContextOrThrow();await this.executeRestOperation(()=>(async(e,t,r)=>{const s=`${JI(t)}/reaction/user/${t.userId}?msgId=${encodeURIComponent(r.messageId)}&message=${encodeURIComponent(r.reaction)}`;await e.delete(s,{operation:"removeReaction"})})(this.getRestClient(t),t,e))}async getReactionList(e){if(!e.messageId||Array.isArray(e.messageId)&&0===e.messageId.length)throw this.buildValidationError("messageId is required","messageId");"groupChat"===e.conversationType&&this.requireNonEmptyString(e.groupId??"","groupId");const t=this.getRestContextOrThrow();return this.executeRestOperation(()=>(async(e,t,r)=>{const s=ob(),n="string"==typeof r.messageId?r.messageId:[...r.messageId].join(",");s.set("msgIdList",n),s.set("msgType","groupChat"===r.conversationType?"group":"chat"),r.groupId&&s.set("groupId",r.groupId);const i=await e.get(`${JI(t)}/reaction/user/${t.userId}?${s.toString()}`,{operation:"getReactionList"});return sw(i,"getReactionList").map(e=>{if(!QI(e)||"string"!=typeof e.msgId)return null;const t=Array.isArray(e.reactionList)?e.reactionList:[];return{messageId:e.msgId,reactions:t.map(e=>QI(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=ob();s.set("msgId",r.messageId),s.set("message",r.reaction),s.set("cursor",r.cursor??""),s.set("limit",String(r.pageSize??20));const n=await e.get(`${JI(t)}/reaction/user/${t.userId}/detail?${s.toString()}`,{operation:"getReactionDetail"}),i=rw(n,"getReactionDetail"),o=Array.isArray(i.reactionUserList)?i.reactionUserList.map(e=>QI(e)&&"string"==typeof e.userId?{userId:e.userId,user:tw(e.userId),createdAt:"string"==typeof e.createdAt?e.createdAt:void 0}:null).filter(e=>null!==e):[],a=Array.isArray(i.userList)?i.userList.filter(e=>"string"==typeof e).map(e=>({userId:e,user:tw(e)})):[],c=o.length>0?o:a;return{reaction:"string"==typeof i.reaction?i.reaction:r.reaction,count:"number"==typeof i.count?i.count:c.length,isAddedBySelf:!0===i.state,reactionUsers:c,cursor:ew(i.cursor),hasMore:ew(i.cursor).length>0,createdAt:"string"==typeof i.createdAt?i.createdAt:void 0}})(this.getRestClient(t),t,e))}async getSupportedTranslationLanguages(){const e=this.getRestContextOrThrow();return this.executeRestOperation(()=>(async(e,t)=>{const r=await YI(()=>e.get(`${JI(t)}/users/${t.userId}/translate/support/language`,{operation:"getSupportedTranslationLanguages"}));return nw(r,"getSupportedTranslationLanguages").map(e=>QI(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 YI(()=>e.post(`${JI(t)}/users/${t.userId}/translate`,{text:r.text,to:[...r.targetLanguages]},{operation:"translateMessage"})),n=nw(s,"translateMessage"),i=QI(n[0])?n[0]:null;if(!i)throw Qg({apiName:"translateMessage",message:"translateMessage response data is invalid",mapped:!1});const o=Array.isArray(i.translations)?i.translations:[],a=QI(i.detectedLanguage)?i.detectedLanguage:void 0;return{detectedLanguage:a&&"string"==typeof a.language?{language:a.language,score:"number"==typeof a.score?a.score:Number(a.score??0)}:void 0,translations:o.map(e=>QI(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){Cw(e,t);const r=this.getRestContextOrThrow();return this.executeRestOperation(()=>Tw(this.getRestClient(r),r,e,t))}async voiceFileToText(e,t){Sw(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=Sw(r,s),i=Bn({file:n,fallbackName:mw(n)?"voice.amr":void 0,fallbackMimeType:"audio/amr"});try{const r=await e.upload({url:`${t.restBaseUrl}${pw(t)}/speech/recognitions`,headers:{Authorization:`Bearer ${t.token}`,Accept:"application/json",[vl]:yl()},source:i.source,fields:{username:t.userId,...s?.format?{format:s.format}:{},...void 0!==s?.sampleRate?{sampleRate:String(s.sampleRate)}:{},...void 0!==s?.bitsPerSample?{bitsPerSample:String(s.bitsPerSample)}:{},...void 0!==s?.channels?{channels:String(s.channels)}:{}}});let n=r.body;try{n=JSON.parse(r.body)}catch{n=r.body}if(r.status<200||r.status>=300)throw new Hr("Voice-to-text failed",Nr,{details:{httpStatus:r.status,rawResponse:n}});return{text:yw(n,"voiceFileToText")}}catch(o){if(o instanceof Hr)throw ww(o);throw ww(tl(o))}})(s,r,e,t))}validateConversationLocator(e){if(this.requireNonEmptyString(e.conversationId,"conversationId"),"singleChat"!==e.conversationType&&"groupChat"!==e.conversationType&&"chatRoom"!==e.conversationType)throw this.buildValidationError("conversationType is invalid","conversationType")}validateUnreadConversationLocator(e){if(this.requireNonEmptyString(e.conversationId,"conversationId"),"singleChat"!==e.conversationType&&"groupChat"!==e.conversationType)throw this.buildValidationError("conversationType must be singleChat or groupChat","conversationType")}validateSendMessageReadReceiptsParams(e){if(this.requireNonEmptyString(e.conversationId,"conversationId"),"singleChat"!==e.conversationType&&"groupChat"!==e.conversationType)throw this.buildValidationError("conversationType is invalid","conversationType");if(e.messageIds.length>50)throw this.buildValidationError("messageIds cannot contain more than 50 items","messageIds");return this.validateMessageIdList(e.messageIds,"messageIds")}validateMessageIdList(e,t){if(!Array.isArray(e)||0===e.length)throw this.buildValidationError(`${t} cannot be empty`,t);return e.map((e,r)=>{if("string"!=typeof e||0===e.trim().length)throw this.buildValidationError(`${t}.${r} is invalid`,`${t}.${r}`);return e.trim()})}resolveDownloadCombineMessageParams(e){if("message"in e){if("combine"!==e.message.type)throw new Zr("message must be a combine message",{code:it});const t=e.message.body;return{url:t.url??"",secret:t.secret,timeoutMs:e.timeoutMs,maxItems:e.maxItems}}return{url:e.url,secret:e.secret,timeoutMs:e.timeoutMs,maxItems:e.maxItems}}validateReactionParams(e){this.requireNonEmptyString(e.messageId,"messageId"),this.requireNonEmptyString(e.reaction,"reaction")}buildActionError(e,t){return e===ct||e===dt?new Jr(t??"authentication failed",{code:e}):e===gt||e===ft?new Wr(t??"connection unavailable",{code:e}):107===e||110===e||205===e||500===e||e===nt||e===it?new Zr(t??"invalid parameter",{code:e}):e===Dt?new Hr(t??"message recall time limit reached",e):e===zt?new Hr(t??"message update failed",e):e===Ut?new Zr(t??"operation unsupported",{code:e}):new Hr(t??"message action failed",e)}requireNonEmptyString(e,t){if("string"!=typeof e||0===e.trim().length)throw this.buildValidationError(`${t} is required`,t)}buildValidationError(e,t){return new Zr(e,{code:it,details:{fields:[{path:t,message:e,rule:"required"}]}})}getEventContextOrThrow(){if(!this.eventContext)throw new Zr("ChatManager is not bound to event context",{code:nt});return this.eventContext}getClientOrThrow(){if(!this.client)throw new Zr("ChatManager is not bound to client",{code:nt});return this.client}getRestContextOrThrow(){return this.getClientOrThrow().getRestContext()}getRestClient(e){return this.restClient&&this.restBaseUrl===e.restBaseUrl&&this.restToken===e.token||(this.restClient=new ty(e.restBaseUrl,{errorMap:Aw,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 _I({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),Br)}};Mw.key="chatManager";let Ew=Mw;class Uw{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 kw=e=>new Zr(`${e} is required`,{code:nt,details:{fields:[{path:e,message:`${e} is required`,rule:"required"}]}}),Nw=(e,t)=>new Zr(t,{code:it,details:{fields:[{path:e,message:t,rule:"invalid_format"}]}}),Ow=(e,t)=>{if("string"!=typeof e||0===e.trim().length)throw kw(t);return e.trim()},xw=(e,t)=>{if(void 0===e)return"";if("string"!=typeof e)throw Nw(t,`${t} must be a string`);return e},Lw=(e,t)=>{if(void 0===e)return 20;if("number"!=typeof e||!Number.isInteger(e)||e<=0||e>50)throw Nw(t,`${t} must be an integer between 1 and 50`);return e},Pw=e=>{const{orgName:t,appName:r}=Qn(e.appKey);return{orgName:t,appName:r,encodedUserId:encodeURIComponent(e.userId),encodedResource:encodeURIComponent(e.clientResource)}},Dw=e=>El(e)?e:null,qw=e=>{const t=Dw(e);return t?.data??e},$w=e=>{const t=Dw(e);if(Array.isArray(t?.entities))return t.entities;const r=qw(e);if(Array.isArray(r))return r;const s=Dw(r);return Array.isArray(s?.entities)?s.entities:Array.isArray(s?.affiliations)?s.affiliations:[]},Gw=e=>{const t=Dw(e),r=Dw(t?.data),s=Dw(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)??""},Fw=e=>{const t=Dw(e);if(!t)return null;const r=("string"==typeof t.id?t.id:void 0)??("string"==typeof t.msgId?t.msgId:void 0);if(!r)return null;const s="number"==typeof t.timestamp?t.timestamp:0,n=t.payload,i="string"==typeof n?Ul(n,{}):Dw(n)??{},o=Array.isArray(i.bodies)?i.bodies:[],a=Dw(o[0])??{};return{msgId:r,type:("string"==typeof a.type?a.type:void 0)??("string"==typeof i.type?i.type:void 0)??"",body:a,timestamp:s}},Bw=e=>{const t=Dw(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:Fw(t.lastMessage??t.last_message)}:null},jw=e=>({items:$w(e).map(e=>Bw(e)).filter(e=>null!==e),cursor:Gw(e)}),zw=async(e,t,r)=>{const s=Pw(t),n=Ow(r,"chatThreadId");return(e=>{const t=qw(e),r=Array.isArray(t)?t[0]:t,s=Bw(r);if(!s)throw Nw("response.data","response.data is invalid");return s})(await e.get(`/${s.orgName}/${s.appName}/thread/${encodeURIComponent(n)}`,{operation:"getChatThreadInfo"}))},Kw=async(e,t,r)=>{const s=Pw(t),n=Ow(r.chatThreadId,"params.chatThreadId"),i=Lw(r.pageSize,"params.pageSize"),o=xw(r.cursor,"params.cursor"),a=ob({limit:String(i),cursor:o}),c=await e.get(`/${s.orgName}/${s.appName}/thread/${encodeURIComponent(n)}/users?${a.toString()}`,{operation:"getChatThreadMemberList"});return{items:$w(d=c).map(e=>{if("string"==typeof e)return{memberId:e};const t=Dw(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:Gw(d)};var d},Hw=async(e,t,r)=>{const s=Pw(t);if(!Array.isArray(r.chatThreadIds)||0===r.chatThreadIds.length)throw kw("params.chatThreadIds");if(r.chatThreadIds.length>20)throw Nw("params.chatThreadIds","params.chatThreadIds must contain at most 20 items");const n=r.chatThreadIds.map((e,t)=>Ow(e,`params.chatThreadIds[${t}]`)),i=await e.post(`/${s.orgName}/${s.appName}/thread/message`,{threadIds:n},{operation:"getChatThreadLastMessageList"});return{items:$w(i).map(e=>{const t=Dw(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:Fw(t.lastMessage??t.last_message)}:null}).filter(e=>null!==e)}},Vw=Nb(Ob,{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"]}}}}}),Ww=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 Uw(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=Pw(t),n=Ow(r.parentId,"params.parentId"),i=Ow(r.name,"params.name"),o=Ow(r.messageId,"params.messageId"),a=await e.post(`/${s.orgName}/${s.appName}/thread?resource=${s.encodedResource}`,{name:i,msg_id:o,group_id:n,owner:t.userId},{operation:"createChatThread"}),c=Dw(qw(a)),d="string"==typeof c?.thread_id?c.thread_id:void 0;if(!d)throw Nw("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=Pw(t),n=Ow(r.parentId,"params.parentId"),i=Lw(r.pageSize,"params.pageSize"),o=xw(r.cursor,"params.cursor"),a=ob({limit:String(i),cursor:o}),c=await e.get(`/${s.orgName}/${s.appName}/threads/chatgroups/${encodeURIComponent(n)}?${a.toString()}`,{operation:"getChatThreadList"});return jw(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=Pw(t),n=Lw(r.pageSize,"params.pageSize"),i=xw(r.cursor,"params.cursor"),o=ob({limit:String(n),cursor:i}),a="string"==typeof r.parentId&&r.parentId.trim().length>0?`/${s.orgName}/${s.appName}/threads/chatgroups/${encodeURIComponent(r.parentId.trim())}/user/${s.encodedUserId}?${o.toString()}`:`/${s.orgName}/${s.appName}/threads/user/${s.encodedUserId}?${o.toString()}`,c=await e.get(a,{operation:"getJoinedChatThreadList"});return jw(c)})(this.getRestClient(t),t,e)})}async getChatThreadInfo(e){return this.runOperation("getChatThreadInfo",async()=>{const t=this.getRestContextOrThrow();return zw(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=Pw(t),n=Ow(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=Pw(t),n=Ow(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=Pw(t),n=Ow(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=Pw(t),n=Ow(r.chatThreadId,"params.chatThreadId"),i=Ow(r.name,"params.name");await e.put(`/${s.orgName}/${s.appName}/thread/${encodeURIComponent(n)}?resource=${s.encodedResource}`,{name:i},{operation:"updateChatThreadName"})})(this.getRestClient(t),t,e)})}async getChatThreadMemberList(e){return this.runOperation("getChatThreadMemberList",async()=>{const t=this.getRestContextOrThrow();return Kw(this.getRestClient(t),t,e)})}async removeChatThreadMember(e){return this.runOperation("removeChatThreadMember",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=Pw(t),n=Ow(r.chatThreadId,"params.chatThreadId"),i=Ow(r.memberId,"params.memberId");await e.delete(`/${s.orgName}/${s.appName}/thread/${encodeURIComponent(n)}/users/${encodeURIComponent(i)}?resource=${s.encodedResource}`,{operation:"removeChatThreadMember"})})(this.getRestClient(t),t,e)})}async getChatThreadLastMessageList(e){return this.runOperation("getChatThreadLastMessageList",async()=>{const t=this.getRestContextOrThrow();return Hw(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 ty(e.restBaseUrl,{errorMap:Vw,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}`,Br)}}buildChatThreadPublicEvent(e){const t=e.payload,r="string"==typeof t.id?t.id:"",s="string"==typeof t.muc_parent_id?t.muc_parent_id:"";if(!r||!s)return null;const n="string"==typeof t.msg_parent_id?t.msg_parent_id:void 0,i="string"==typeof t.name?t.name:void 0,o="number"==typeof t.message_count?t.message_count:void 0,a=t.last_message&&"object"==typeof t.last_message?this.tryBuildThreadMessageSnippet(t.last_message):void 0,c="number"==typeof t.timestamp?t.timestamp:0,d="string"==typeof t.from?t.from:void 0,u={chatThreadId:r,parentId:s,name:i??"",messageId:n,messageCount:o,lastMessage:a};switch(t.operation){case"create":return{eventName:"onChatThreadCreated",payload:{chatThreadId:r,parentId:s,operatorId:d,chatThreadName:i,messageId:n,thread:u,timestamp:c}};case"update":case"update_msg":return{eventName:"onChatThreadUpdated",payload:{chatThreadId:r,parentId:s,operatorId:d,chatThreadName:i,messageId:n,messageCount:o,lastMessage:a,thread:u,timestamp:c}};case"delete":return{eventName:"onChatThreadDestroyed",payload:{chatThreadId:r,parentId:s,operatorId:d,timestamp:c}};case"kick":return{eventName:"onChatThreadUserRemoved",payload:{chatThreadId:r,parentId:s,operatorId:d,memberId:t.userIds?.[0],timestamp:c}};default:return null}}tryBuildThreadMessageSnippet(e){const t=("string"==typeof e.id?e.id:void 0)??("string"==typeof e.msgId?e.msgId:void 0);if(!t)return null;const r=e.payload&&"object"==typeof e.payload?e.payload:{};return{msgId:t,type:"string"==typeof r.type?r.type:"",body:r,timestamp:"number"==typeof e.timestamp?e.timestamp:0}}};Ww.key="chatThreadManager";let Jw=Ww;class Zw{constructor(e,t){this.chatRoomId=e,this.manager=t}getInfo(){return this.manager.getChatRoomInfo({chatRoomId:this.chatRoomId})}refresh(){return this.getInfo()}updateInfo(e){return this.manager.updateChatRoomInfo({chatRoomId:this.chatRoomId,...e})}leaveChatRoom(){return this.manager.leaveChatRoom(this.toTarget())}getMembers(e={}){return this.manager.getMemberList({chatRoomId:this.chatRoomId,...e})}removeMembers(e){return this.manager.removeMembers(this.toUserBatchParams(e))}getAdminList(){return this.manager.getAdminList(this.toTarget())}addAdmin(e){return this.manager.addAdmin({chatRoomId:this.chatRoomId,userId:e.userId})}removeAdmin(e){return this.manager.removeAdmin({chatRoomId:this.chatRoomId,userId:e.userId})}getMuteList(e){return this.manager.getMuteList({...this.toTarget(),...e})}muteMembers(e){return this.manager.muteMembers({chatRoomId:this.chatRoomId,userIds:e.userIds,duration:e.duration})}unmuteMembers(e){return this.manager.unmuteMembers(this.toUserBatchParams(e))}muteAllMembers(){return this.manager.muteAllMembers(this.toTarget())}unmuteAllMembers(){return this.manager.unmuteAllMembers(this.toTarget())}checkIfInMuteList(){return this.manager.checkIfInMuteList(this.toTarget())}getBlocklist(e){return this.manager.getBlocklist({...this.toTarget(),...e})}blockMembers(e){return this.manager.blockMembers(this.toUserBatchParams(e))}unblockMembers(e){return this.manager.unblockMembers(this.toUserBatchParams(e))}getAllowlist(){return this.manager.getAllowlist(this.toTarget())}addUsersToAllowlist(e){return this.manager.addUsersToAllowlist(this.toUserBatchParams(e))}removeUsersFromAllowlist(e){return this.manager.removeUsersFromAllowlist(this.toUserBatchParams(e))}checkIfInAllowList(){return this.manager.checkIfInAllowList(this.toTarget())}getAnnouncement(){return this.manager.getAnnouncement(this.toTarget())}updateAnnouncement(e){return this.manager.updateAnnouncement({chatRoomId:this.chatRoomId,announcement:e.announcement})}getAttributes(e={}){return this.manager.getAttributes({chatRoomId:this.chatRoomId,keys:e.keys})}setAttributes(e){return this.manager.setAttributes({chatRoomId:this.chatRoomId,attributes:e.attributes,autoDelete:e.autoDelete,isForced:e.isForced})}removeAttributes(e){return this.manager.removeAttributes({chatRoomId:this.chatRoomId,keys:e.keys,isForced:e.isForced})}toTarget(){return{chatRoomId:this.chatRoomId}}toUserBatchParams(e){return{chatRoomId:this.chatRoomId,userIds:e.userIds}}}const Qw=["nickname","avatarUrl","mail","phone","gender","sign","birth","ext"],Yw=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}),eC=e=>({userId:e}),tC=(e,t,r)=>{const s={userId:r};for(const n of Qw){const r=t?.[n]??e?.[n];void 0!==r&&(s[n]=r)}return s},rC=async(e,t)=>{const r=Yw(e),s=new Map;if(0===r.length)return s;const n=t.cacheManager?.getUserInfoSummaries(r,!1)??[];for(const o of n)s.set(o.userId,Xw(o));const i=r.filter(e=>!s.has(e));if(i.length>0&&t.fetchUserInfos){const e=await t.fetchUserInfos({userIds:i});for(const t of e)s.set(t.userId,t)}for(const o of r)s.has(o)||s.set(o,eC(o));return s},sC=e=>El(e)?e:null,nC=e=>"string"==typeof e?e:void 0,iC=e=>{const t=nC(e)?.trim();return t||void 0},oC=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}},aC=e=>{if("boolean"==typeof e)return e;if("string"==typeof e){if("true"===e)return!0;if("false"===e)return!1}},cC=e=>{const t=sC(e);return t&&Array.isArray(t.data)?t.data:t&&Array.isArray(t.entities)?t.entities:Array.isArray(e)?e:[]},dC=e=>{const t=sC(e);return t?sC(t.data)?t.data:t:null},uC=(e,t)=>{const r=sC(e),s=r&&sC(r.params),n=s?.[t];if(Array.isArray(n)&&0!==n.length)return oC(n[0])},lC=e=>iC(e.chatRoomId)??iC(e.chatroomid)??iC(e.id)??"",pC=e=>nC(e.name)??nC(e.title)??nC(e.groupname)??"",hC=e=>eC(e),mC=(e,t)=>{const r=sC(e);if(!r)return null;const s=lC(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)})(iC(r.owner)):iC(r.owner);return{chatRoomId:s,name:pC(r),owner:n?hC(n):void 0,memberCount:oC(r.memberCount)??oC(r.affiliations_count),disabled:aC(r.disabled)}},fC=(e,t)=>{const r=(e=>{const t=sC(e);return t?oC(t.count):void 0})(e),s=cC(e).map(e=>mC(e,t)).filter(e=>null!==e),n=uC(e,"pagenum"),i=uC(e,"pagesize");return{items:s,pageNum:n,pageSize:i,total:r,hasMore:void 0!==r&&void 0!==n&&void 0!==i?n*i<r:void 0}},gC=(e,t)=>{const r=cC(e),s=sC(r[0])??dC(e)??{},n=mC(s)??{chatRoomId:lC(s),name:pC(s)},i=((e,t)=>{if(!t)return;if(iC(e.owner)===t)return"owner";const r=Array.isArray(e.affiliations)?e.affiliations:[];for(const s of r){const e=sC(s);if(e){if(iC(e.owner)===t)return"owner";if(iC(e.admin)===t)return"admin";if(iC(e.member)===t)return"member"}}})(s,t),o=oC(s.muteExpireAt)??oC(s.mute_expire)??oC(s.expire),a=aC(s.inAllowlist)??aC(s.white)??aC(s.in_whitelist),c=aC(s.muted);return{...n,description:nC(s.description),maxMembers:oC(s.maxMembers)??oC(s.maxusers)??oC(s.max_users),createdAt:oC(s.createdAt)??oC(s.created),ext:nC(s.ext)??nC(s.custom),announcement:nC(s.announcement),permissionType:i,currentUserStatus:void 0!==a||void 0!==c||void 0!==o||void 0!==i?{inAllowlist:a,muted:c,muteExpireAt:o,permissionType:i}:void 0}},yC=e=>cC(e).map(e=>iC(e)).filter(e=>Boolean(e)).map(e=>hC(e)),vC=(e,t)=>{const r=dC(e)??{},s=Array.isArray(r.successKeys)?r.successKeys.filter(e=>"string"==typeof e):[],n=sC(r.errorKeys)??{},i={};for(const[o,a]of Object.entries(n))"string"==typeof a&&(i[o]={code:IC(a),message:a});return{chatRoomId:t,appliedKeys:s,failedKeys:i}},bC=e=>{const t=sC(e),r=t?.data,s=Array.isArray(r)?r:void 0!==r?[r]:[],n=[],i=[];return s.forEach(e=>{const t=sC(e),r=(e=>{const t=sC(e);if(!t)return null;const r=iC(t.user),s=iC(t.chatRoomId)??iC(t.chatroomid)??iC(t.id),n=nC(t.action),i=aC(t.result);return r&&s&&void 0!==n&&void 0!==i?{chatRoomId:s,user:hC(r),action:n,reason:nC(t.reason),...i?{}:{reason:nC(t.reason)??"failed"}}:null})(e);if(!r||!t)return;aC(t.result)?n.push(r):i.push(r)}),{succeeded:n,failed:i}},IC=e=>e.includes("is exceeding maximum limit")||e.includes("size of metadata")&&e.includes("exceeds")?Fr:e.includes("is not part of you")?Ir:e.includes("is not Legal")||e.includes("is not exist")?nt:fr,wC=e=>{const{orgName:t,appName:r}=Qn(e.appKey);return{orgName:t,appName:r,encodedUserId:encodeURIComponent(e.userId),encodedResource:encodeURIComponent(e.clientResource)}},CC=e=>new Zr(`${e} is required`,{code:nt,details:{fields:[{path:e,message:`${e} is required`,rule:"required"}]}}),SC=(e,t)=>new Zr(t,{code:it,details:{fields:[{path:e,message:t,rule:"invalid_format"}]}}),TC=(e,t)=>`/${e.orgName}/${e.appName}${t}`,_C=(e,t)=>{if(void 0!==e){if("string"!=typeof e)throw SC(t,`${t} must be a string`);return e}},RC=(e,t)=>{if(void 0!==e){if("number"!=typeof e||Number.isNaN(e))throw SC(t,`${t} must be a number`);return e}},AC=(e,t)=>{const r=ob();"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}`:""},MC=(e,t)=>{if("string"!=typeof e||0===e.trim().length)throw CC(t);return e.trim()},EC=(e,t)=>{if(!Array.isArray(e)||0===e.length)throw CC(t);const r=[],s=new Set;if(e.forEach((e,n)=>{if("string"!=typeof e)throw SC(`${t}[${n}]`,`${t}[${n}] must be a string`);const i=e.trim();i&&!s.has(i)&&(s.add(i),r.push(i))}),0===r.length)throw CC(t);return r},UC=(e,t)=>EC(e,t),kC=async(e,t,r)=>{const s=wC(t),n=MC(r.chatRoomId,"params.chatRoomId"),i={},o=_C(r.name,"params.name"),a=_C(r.description,"params.description"),c=RC(r.maxMembers,"params.maxMembers");if(void 0!==o&&(i.groupname=o),void 0!==a&&(i.description=a),void 0!==c&&(i.maxusers=c),0===Object.keys(i).length)throw CC("params");const d=TC(s,`/chatrooms/${encodeURIComponent(n)}?resource=${s.encodedResource}`);return(e=>{const t=dC(e)??{};return{nameUpdated:aC(t.groupname),descriptionUpdated:aC(t.description),maxMembersUpdated:aC(t.maxusers)}})(await e.put(d,i,{operation:"updateChatRoomInfo"}))},NC=async(e,t,r)=>{const s=wC(t),n=MC(r.chatRoomId,"params.chatRoomId"),i=TC(s,`/chatrooms/${encodeURIComponent(n)}/users${(e=>{const t=ob();"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 cC(e)){const e=sC(n);if(!e)continue;const r=iC(e.owner),s=iC(e.admin),i=iC(e.member),o=r??s??i;o&&t.push({user:hC(o),role:r?"owner":s?"admin":"member",joinedAt:oC(e.joinedAt)??oC(e.joined_time)})}const r=sC(e),s=r?iC(r.cursor):void 0;return{items:t,cursor:s,hasMore:"string"==typeof s&&s.length>0}})(await e.get(i,{operation:"getChatRoomMemberList"}))},OC=async(e,t,r)=>{const s=wC(t),n=MC(r.chatRoomId,"params.chatRoomId"),i=TC(s,`/chatrooms/${encodeURIComponent(n)}/admin`),o=await e.get(i,{operation:"getChatRoomAdminList"});return yC(o)},xC=async(e,t,r)=>{const s=wC(t),n=MC(r.chatRoomId,"params.chatRoomId"),i=ob();i.set("version","v3"),"number"==typeof r.pageNum&&i.set("pagenum",String(r.pageNum)),"number"==typeof r.pageSize&&i.set("pagesize",String(r.pageSize));const o=TC(s,`/chatrooms/${encodeURIComponent(n)}/mute?${i.toString()}`);return(e=>{const t=cC(e);if(t.every(e=>"string"==typeof e))return yC(e).map(e=>({user:e}));const r=[];for(const s of t){const e=sC(s);if(!e)continue;const t=iC(e.user)??iC(e.member)??iC(e.owner)??iC(e.admin);t&&r.push({user:hC(t),muteExpire:oC(e.muteExpire)??oC(e.expire)??oC(e.expired)})}return r.map(e=>({user:e.user,muteExpire:e.muteExpire}))})(await e.get(o,{operation:"getChatRoomMuteList"}))},LC=async(e,t,r)=>{const s=wC(t),n=MC(r.chatRoomId,"params.chatRoomId"),i=TC(s,`/sdk/chatrooms/${encodeURIComponent(n)}/mute/${s.encodedUserId}?version=v3`);return(e=>{const t=dC(e)??{};return{muted:aC(t.muted)??aC(t.value)??Boolean(t.data),muteExpireAt:oC(t.muteExpireAt)??oC(t.expire)??oC(t.mute_expire)}})(await e.get(i,{operation:"isCurrentUserMutedInChatRoom"}))},PC=async(e,t,r)=>{const s=wC(t),n=MC(r.chatRoomId,"params.chatRoomId"),i=AC(r),o=i?"&":"",a=TC(s,`/chatrooms/${encodeURIComponent(n)}/blocks/users?version=v3${o}${i.replace("?","")}`),c=await e.get(a,{operation:"getChatRoomBlocklist"});return yC(c).map(e=>({user:e}))},DC=async(e,t,r)=>{const s=wC(t),n=MC(r.chatRoomId,"params.chatRoomId"),i=TC(s,`/chatrooms/${encodeURIComponent(n)}/white/users`),o=await e.get(i,{operation:"getChatRoomAllowlist"});return yC(o).map(e=>({user:e}))},qC=async(e,t,r)=>{const s=wC(t),n=MC(r.chatRoomId,"params.chatRoomId"),i=TC(s,`/chatrooms/${encodeURIComponent(n)}/white/users/${s.encodedUserId}?version=v3`);return(e=>{const t=dC(e)??{};return aC(t.value)??aC(t.white)??!1})(await e.get(i,{operation:"checkIfInChatRoomAllowList"}))},$C=async(e,t,r)=>{const s=wC(t),n=MC(r.chatRoomId,"params.chatRoomId"),i=TC(s,`/chatrooms/${encodeURIComponent(n)}/announcement`);return(e=>{const t=dC(e)??{};return{announcement:nC(t.announcement)??""}})(await e.get(i,{operation:"getChatRoomAnnouncement"}))},GC=async(e,t,r)=>{const s=wC(t),n=MC(r.chatRoomId,"params.chatRoomId"),i=TC(s,`/metadata/chatroom/${encodeURIComponent(n)}`);return((e,t)=>{const r=dC(e)??{};return{chatRoomId:t,attributes:Object.fromEntries(Object.entries(r).filter(e=>"string"==typeof e[1]))}})(await e.post(i,{keys:r.keys?UC(r.keys,"params.keys"):void 0},{operation:"getChatRoomAttributes"}),n)},FC=async(e,t,r)=>{const s=wC(t),n=MC(r.chatRoomId,"params.chatRoomId"),i=((e,t)=>{if(!e||"object"!=typeof e||Array.isArray(e))throw SC(t,`${t} must be an object`);const r=Object.entries(e);if(0===r.length)throw CC(t);return Object.fromEntries(r.map(([e,r])=>{if("string"!=typeof e||0===e.trim().length)throw SC(t,`${t} contains invalid key`);if("string"!=typeof r)throw SC(`${t}.${e}`,`${t}.${e} must be a string`);return[e,r]}))})(r.attributes,"params.attributes"),{autoDelete:o=!0,isForced:a=!1}=r,c=a?"/forced":"",d=TC(s,`/metadata/chatroom/${encodeURIComponent(n)}/user/${s.encodedUserId}${c}`),u=await e.put(d,{metaData:i,autoDelete:o?"DELETE":"NO_DELETE"},{operation:"setChatRoomAttributes"});return vC(u,n)},BC={nickname:"nickname",avatarUrl:"avatarurl",mail:"mail",phone:"phone",gender:"gender",sign:"sign",birth:"birth",ext:"ext"},jC=(e,t,r)=>new Zr(e,{code:"required"===r?nt:it,details:{fields:[{path:t,message:e,rule:r}]}}),zC=(e,t)=>{if("string"!=typeof e)throw jC(`${t} must be a string`,t,"invalid_format");return e},KC=(e,t)=>{if("string"==typeof e||"number"==typeof e||"boolean"==typeof e)return e;throw jC(`${t} must be a string, number, or boolean`,t,"invalid_format")},HC=(e,t="attribute")=>{const r=BC[e];if(!r)throw jC(`${t} is invalid`,t,"invalid_format");return r},VC=(e,t="params.userIds")=>{if(!Array.isArray(e)||0===e.length)throw jC(`${t} is required`,t,"required");const r=[],s=new Set;for(const[n,i]of e.entries()){const e=zC(i,`${t}[${n}]`).trim();e&&(s.has(e)||(s.add(e),r.push(e)))}if(0===r.length)throw jC(`${t} is required`,t,"required");return r},WC=(e,t="params.attributes")=>{if(!Array.isArray(e)||0===e.length)throw jC(`${t} is required`,t,"required");const r=[],s=new Set;for(const[n,i]of e.entries()){const e=zC(i,`${t}[${n}]`);if(!(e in BC))throw jC(`${t}[${n}] is invalid`,`${t}[${n}]`,"invalid_format");s.has(e)||(s.add(e),r.push(e))}if(0===r.length)throw jC(`${t} is required`,t,"required");return r},JC=e=>{const{orgName:t,appName:r}=Qn(e.appKey);return`/${t}/${r}/metadata/user/get`},ZC=e=>{const{orgName:t,appName:r}=Qn(e.appKey);return`/${t}/${r}/metadata/user/${encodeURIComponent(e.userId)}`},QC=e=>({targets:VC(e)}),YC=e=>!!El(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(!El(r))continue;const e="string"==typeof r.username?r.username:"";e&&t.set(e,r)}},eS=(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},tS=(e,t)=>{const r=(e=>{const t=new Map,r=El(e)?e:null;if(r?.data&&El(r.data))for(const[s,n]of Object.entries(r.data))YC(n)&&t.set(s,n);return XC(r?.entities,t),XC(r?.data&&El(r.data)?r.data.entities:void 0,t),t})(e),s=(e=>{const t=new Map,r=El(e)?e:null;if(!r?.lastModified||!El(r.lastModified))return t;for(const[s,n]of Object.entries(r.lastModified))"number"==typeof n&&t.set(s,n);return t})(e),n=[];for(const i of t){const e=r.get(i);e&&n.push({profile:eS(i,e),lastModified:s.get(i)})}return n},rS=(e,t)=>tS(e,t).map(e=>e.profile),sS=(e,t,r,s)=>{void 0!==r&&("gender"!==t?e.push([t,zC(r,s)]):e.push([t,String(KC(r,s))]))},nS=e=>e.map(([e,t])=>`${encodeURIComponent(e)}=${encodeURIComponent(t)}`).join("&"),iS={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:qe},oS=Nb(Ob,{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}}}}}),aS=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=iS[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=iS[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=wC(t),n=TC(s,`/chatrooms${AC(r)}`),i=await e.get(n,{operation:"getChatRoomList"});return fC(i)})(this.getRestClient(t),t,e);return{...r,items:await this.hydrateSummaryOwners(r.items)}})}getChatRoom(e){this.requireClient();const t=e.trim();if(0===t.length)throw new Zr("chatRoomId is required",{code:nt,details:{fields:[{path:"chatRoomId",message:"chatRoomId is required",rule:"required"}]}});const r=this.chatRoomRegistry.get(t);if(r)return r;const s=new Zw(t,this);return this.chatRoomRegistry.set(t,s),s}async getChatRoomInfo(e){return this.runOperation("getChatRoomInfo",async()=>{const t=this.getRestContextOrThrow(),r=await(async(e,t,r)=>{const s=wC(t),n=MC(r.chatRoomId,"params.chatRoomId"),i=TC(s,`/chatrooms/${encodeURIComponent(n)}?joined_time=true`),o=await e.get(i,{operation:"getChatRoomInfo"});return gC(o,t.userId)})(this.getRestClient(t),t,e);return this.hydrateChatRoomDetailUsers(r)})}async updateChatRoomInfo(e){return this.runOperation("updateChatRoomInfo",async()=>{const t=this.getRestContextOrThrow();return kC(this.getRestClient(t),t,e)})}async joinChatRoom(e){return this.runOperation("joinChatRoom",async()=>{const t=this.requireClient(),r=MC(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=MC(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 NC(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=wC(t),n=MC(r.chatRoomId,"params.chatRoomId"),i=EC(r.userIds,"params.userIds"),o=TC(s,`/chatrooms/${encodeURIComponent(n)}/users/${i.map(e=>encodeURIComponent(e)).join(",")}?resource=${s.encodedResource}`),a=await e.delete(o,{operation:"removeChatRoomMembers"});return bC(a)})(this.getRestClient(t),t,e);return this.hydrateActionListResult(r)})}async getAdminList(e){return this.runOperation("getAdminList",async()=>{const t=this.getRestContextOrThrow(),r=await OC(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=wC(t),n=MC(r.chatRoomId,"params.chatRoomId"),i=MC(r.userId,"params.userId"),o=TC(s,`/chatrooms/${encodeURIComponent(n)}/admin?resource=${s.encodedResource}`);await e.post(o,{newadmin:i},{operation:"setChatRoomAdmin"})})(this.getRestClient(t),t,e)})}async removeAdmin(e){return this.runOperation("removeAdmin",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=wC(t),n=MC(r.chatRoomId,"params.chatRoomId"),i=MC(r.userId,"params.userId"),o=TC(s,`/chatrooms/${encodeURIComponent(n)}/admin/${encodeURIComponent(i)}?resource=${s.encodedResource}`);await e.delete(o,{operation:"removeChatRoomAdmin"})})(this.getRestClient(t),t,e)})}async getMuteList(e){return this.runOperation("getMuteList",async()=>{const t=this.getRestContextOrThrow(),r=await xC(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=wC(t),n=MC(r.chatRoomId,"params.chatRoomId"),i=EC(r.userIds,"params.userIds"),o=RC(r.duration,"params.duration"),a=TC(s,`/chatrooms/${encodeURIComponent(n)}/mute?resource=${s.encodedResource}`);await e.post(a,{usernames:i,mute_duration:o},{operation:"muteChatRoomMembers"})})(this.getRestClient(t),t,e)})}async unmuteMembers(e){return this.runOperation("unmuteMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=wC(t),n=MC(r.chatRoomId,"params.chatRoomId"),i=EC(r.userIds,"params.userIds"),o=TC(s,`/chatrooms/${encodeURIComponent(n)}/mute/${i.map(e=>encodeURIComponent(e)).join(",")}?resource=${s.encodedResource}`);await e.delete(o,{operation:"unmuteChatRoomMembers"})})(this.getRestClient(t),t,e)})}async muteAllMembers(e){return this.runOperation("muteAllMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=wC(t),n=MC(r.chatRoomId,"params.chatRoomId"),i=TC(s,`/chatrooms/${encodeURIComponent(n)}/ban?resource=${s.encodedResource}`);await e.post(i,void 0,{operation:"muteAllChatRoomMembers"})})(this.getRestClient(t),t,e)})}async unmuteAllMembers(e){return this.runOperation("unmuteAllMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=wC(t),n=MC(r.chatRoomId,"params.chatRoomId"),i=TC(s,`/chatrooms/${encodeURIComponent(n)}/ban?resource=${s.encodedResource}`);await e.delete(i,{operation:"unmuteAllChatRoomMembers"})})(this.getRestClient(t),t,e)})}async checkIfInMuteList(e){return this.runOperation("checkIfInMuteList",async()=>{const t=this.getRestContextOrThrow();return LC(this.getRestClient(t),t,e)})}async getBlocklist(e){return this.runOperation("getBlocklist",async()=>{const t=this.getRestContextOrThrow(),r=await PC(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=wC(t),n=MC(r.chatRoomId,"params.chatRoomId"),i=EC(r.userIds,"params.userIds"),o=1===i.length,a=TC(s,o?`/chatrooms/${encodeURIComponent(n)}/blocks/users/${encodeURIComponent(i[0]??"")}?resource=${s.encodedResource}`:`/chatrooms/${encodeURIComponent(n)}/blocks/users?resource=${s.encodedResource}`),c=await e.post(a,o?void 0:{usernames:i},{operation:"blockChatRoomMembers"});return bC(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=wC(t),n=MC(r.chatRoomId,"params.chatRoomId"),i=EC(r.userIds,"params.userIds"),o=TC(s,`/chatrooms/${encodeURIComponent(n)}/blocks/users/${i.map(e=>encodeURIComponent(e)).join(",")}?resource=${s.encodedResource}`),a=await e.delete(o,{operation:"unblockChatRoomMembers"});return bC(a)})(this.getRestClient(t),t,e);return this.hydrateActionListResult(r)})}async getAllowlist(e){return this.runOperation("getAllowlist",async()=>{const t=this.getRestContextOrThrow(),r=await DC(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=wC(t),n=MC(r.chatRoomId,"params.chatRoomId"),i=EC(r.userIds,"params.userIds"),o=TC(s,`/chatrooms/${encodeURIComponent(n)}/white/users?resource=${s.encodedResource}`),a=await e.post(o,{usernames:i},{operation:"addUsersToChatRoomAllowlist"});return bC(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=wC(t),n=MC(r.chatRoomId,"params.chatRoomId"),i=EC(r.userIds,"params.userIds"),o=TC(s,`/chatrooms/${encodeURIComponent(n)}/white/users/${i.map(e=>encodeURIComponent(e)).join(",")}?resource=${s.encodedResource}`),a=await e.delete(o,{operation:"removeUsersFromChatRoomAllowlist"});return bC(a)})(this.getRestClient(t),t,e);return this.hydrateActionListResult(r)})}async checkIfInAllowList(e){return this.runOperation("checkIfInAllowList",async()=>{const t=this.getRestContextOrThrow();return qC(this.getRestClient(t),t,e)})}async getAnnouncement(e){return this.runOperation("getAnnouncement",async()=>{const t=this.getRestContextOrThrow();return $C(this.getRestClient(t),t,e)})}async updateAnnouncement(e){return this.runOperation("updateAnnouncement",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=wC(t),n=MC(r.chatRoomId,"params.chatRoomId"),i=_C(r.announcement,"params.announcement");if(void 0===i)throw CC("params.announcement");const o=TC(s,`/chatrooms/${encodeURIComponent(n)}/announcement?resource=${s.encodedResource}`);await e.post(o,{announcement:i},{operation:"updateChatRoomAnnouncement"})})(this.getRestClient(t),t,e)})}async getAttributes(e){return this.runOperation("getAttributes",async()=>{const t=this.getRestContextOrThrow();return GC(this.getRestClient(t),t,e)})}async setAttributes(e){return this.runOperation("setAttributes",async()=>{const t=this.getRestContextOrThrow(),r=await FC(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=wC(t),n=MC(r.chatRoomId,"params.chatRoomId"),i=UC(r.keys,"params.keys"),{isForced:o=!1}=r,a=o?"/forced":"",c=TC(s,`/metadata/chatroom/${encodeURIComponent(n)}/user/${s.encodedUserId}${a}`),d=await e.request(c,{method:"DELETE",body:{keys:i},operation:"removeChatRoomAttributes"});return vC(d,n)})(this.getRestClient(t),t,e);return this.checkAttributeMutationResult(r)})}async runOperation(e,t){try{return await t()}catch(r){const t=this.normalizeSdkError(e,r);throw Si(`ChatRoomManager ${e} failed`,{code:t.code,message:t.message,details:t.details}),t}}normalizeSdkError(e,t){return t instanceof Hr?t:t instanceof Error?new Hr(`ChatRoomManager ${e} failed: ${t.message}`,Br):new Hr(`ChatRoomManager ${e} failed`,Br)}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 ty(e.restBaseUrl,{errorMap:oS,requestAdapter:this.requireClient().getRequestAdapter?.(),includeRequestId:!0}),this.restClient.setAuthToken(e.token),this.restBaseUrl=e.restBaseUrl,this.restToken=e.token),this.restClient}requireClient(){if(!this.client)throw new Hr("ChatRoomManager is not bound to client",nt);return this.client}normalizeOptionalString(e,t){if(void 0!==e){if("string"!=typeof e)throw new Zr(`${t} must be a string`,{code:it,details:{fields:[{path:t,message:`${t} must be a string`,rule:"invalid_format"}]}});return e}}normalizeOptionalBoolean(e,t){if(void 0!==e){if("boolean"!=typeof e)throw new Zr(`${t} must be a boolean`,{code:it,details:{fields:[{path:t,message:`${t} must be a boolean`,rule:"invalid_format"}]}});return e}}getCacheManager(){return this.client?.getCacheManager()??null}getUserInfoManager(){const e=this.requireClient();if(!this.hasUserInfoCapabilityProvider(e))return null;const t=e.getManagerByCapability("userInfo:read");return t&&this.hasUserInfoReadCapability(t)?t:null}hasUserInfoCapabilityProvider(e){return"function"==typeof e.getManagerByCapability}hasUserInfoReadCapability(e){return"function"==typeof e.getUserInfoByUserId}async resolveUserInfoMap(e){return rC(e,{cacheManager:this.getCacheManager(),fetchUserInfos:async({userIds:e})=>{const t=this.getUserInfoManager();if(0===e.length)return[];if(!t)return await this.fetchUserInfosFromRest(e);try{return await t.getUserInfoByUserId({userIds:e})}catch(r){return Si("ChatRoomManager user info fetch failed",{userIds:e,error:r}),[]}}})}async hydrateUserInfos(e){return(async(e,t)=>{const r=Yw(e),s=await rC(r,t);return r.map(e=>tC(void 0,s.get(e),e))})(e.map(e=>e.userId),{cacheManager:this.getCacheManager(),fetchUserInfos:async({userIds:e})=>{const t=this.getUserInfoManager();if(0===e.length)return[];if(!t)return await this.fetchUserInfosFromRest(e);try{return await t.getUserInfoByUserId({userIds:e})}catch(r){return Si("ChatRoomManager hydrate users failed",{userIds:e,error:r}),[]}}})}async fetchUserInfosFromRest(e){const t=this.getRestContextOrThrow(),r=QC(e),s=await this.getRestClient(t).request(JC(t),{method:"POST",body:r,operation:"getUserInfoByUserId"});return rS(s,r.targets)}collectEventUserIds(e){const t=e.payload,r=[t.participantId,t.memberId,...t.memberIds??[],t.adminId,t.oldOwnerId,t.newOwnerId,t.from,...t.userIds??[]],s=[],n=new Set;for(const i of r){if("string"!=typeof i)continue;const e=i.trim();e&&!n.has(e)&&(n.add(e),s.push(e))}return s}pickEventUser(e,t){if(e)return tC(void 0,t.get(e),e)}pickEventUsers(e,t){return(e??[]).map(e=>tC(void 0,t.get(e),e))}pickEventMuteEntries(e,t,r){return this.pickEventUsers(e,r).map(e=>({user:e,muteExpire:t}))}async resolveChatRoomDetailForEvent(e){if(e.shouldFetchChatRoomDetail)try{return await this.getChatRoomInfo({chatRoomId:e.chatRoomId})}catch(t){Si("ChatRoomManager event detail fetch failed",{chatRoomId:e.chatRoomId,error:t})}return{chatRoomId:e.chatRoomId,name:e.chatRoomPatch?.name??e.chatRoomName??"",...e.chatRoomPatch??{}}}async hydrateEntriesWithUsers(e){const t=e.map(e=>e.user.userId),r=await this.resolveUserInfoMap(t);return e.map(e=>({...e,user:tC(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:tC(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:tC(e.owner,t.get(e.owner.userId),e.owner.userId)}}};aS.key="chatRoomManager";let cS=aS;const dS=e=>{const{orgName:t,appName:r}=Qn(e.appKey);return{orgName:t,appName:r,encodedUserId:encodeURIComponent(e.userId),encodedResource:encodeURIComponent(e.clientResource)}},uS=e=>El(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):[],lS=(e,t)=>{if(!Array.isArray(e.userIds)||0===e.userIds.length)throw new Zr(`${t} is required`,{code:nt,details:{fields:[{path:t,message:`${t} is required`,rule:"required"}]}});const r=e.userIds.map((e,r)=>{if("string"!=typeof e)throw new Zr(`${t}[${r}] must be a string`,{code:it,details:{fields:[{path:`${t}[${r}]`,message:"userId must be a string",rule:"invalid_format"}]}});return e.trim()}),s=(e=>{const t=[],r=new Set;for(const s of e)s&&!r.has(s)&&(r.add(s),t.push(s));return t})(r);if(0===s.length)throw new Zr(`${t} is required`,{code:nt,details:{fields:[{path:t,message:`${t} is required`,rule:"required"}]}});return s.length!==r.length&&El(e),s},pS=async(e,t)=>{const r=dS(t),s=`/${r.orgName}/${r.appName}/users/${r.encodedUserId}/blocks/users`,n=await e.get(s,{operation:"getBlocklist"});return uS(n).map(e=>({userId:e}))},hS=async(e,t,r)=>{const s=dS(t),n=`/${s.orgName}/${s.appName}/sdk/user/${s.encodedUserId}/blocks?resource=${s.encodedResource}`,i=await e.post(n,{usernames:r},{operation:"addUsersToBlocklist"});return{succeeded:uS(i).map(e=>({userId:e})),failed:[]}},mS={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 fS=!1,gS=null;const yS=()=>gS||(fS||(Dc.util.Long=mo,Dc.configure(),fS=!0),hd(),gS=Dc.Root.fromJSON(mS),pd(gS),gS),vS=e=>"number"==typeof e?e:mo.isLong(e)?e.toNumber():0,bS=e=>{if(!e||"object"!=typeof e)return;const t=e;return{resource:"string"==typeof t.resource?t.resource:"",timestamp:vS(t.timestamp),requestId:"string"==typeof t.requestId?t.requestId:"",protocolVersion:vS(t.protocolVersion)}};class IS{encodeRequest(e){const t=yS().lookupType("easemob.imfusion.gateway.v1.GetRosterRequest");return t.encode(t.create(e)).finish()}encodePong(e=Hb){const t=yS().lookupType("easemob.imfusion.gateway.v1.PongResponse");return t.encode(t.create({type:Bb,status:e})).finish()}decode(e){const t=yS(),r=t.lookupType("easemob.imfusion.gateway.v1.BaseMessage").decode(e);switch(r.type){case Fb:return{type:Fb};case Bb:{const r=t.lookupType("easemob.imfusion.gateway.v1.PongResponse").decode(e);return{type:Bb,status:vS(r.status)}}case zb:{const r=t.lookupType("easemob.imfusion.gateway.v1.GetRosterResponse").decode(e);return{type:zb,header:bS(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:vS(t.createdAt),updatedAt:vS(t.updatedAt),metadataUpdatedAt:vS(t.metadataUpdatedAt)}})(e)):[],cursor:vS(r.cursor),version:"string"==typeof r.version?r.version:"",responseType:vS(r.responseType)||Vb}}case Kb:{const r=t.lookupType("easemob.imfusion.gateway.v1.ErrorDetail").decode(e);return{type:Kb,header:bS(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:Gb}}}}class wS{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===Wb?"incremental":"full",version:this.version,pages:this.pages}}}const CS=e=>e.type===zb,SS=e=>"message"in e&&"code"in e;class TS{constructor(e){this.codec=new IS,this.sharedSession=e}async sync(e){const t=new wS(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:CS(t)||SS(t)?t.header?.requestId:void 0,frame:t}},onFrame:async(e,r)=>{try{if(e.type===Fb)return void(await r.send(this.codec.encodePong()));if(CS(e)){if(!t.push(e).done)return;return{done:!0,result:t.buildResult()}}if(SS(e))throw(e=>{const t=e.header?.requestId,r=r=>({stage:"sync_page",serverCode:e.code,requestId:t,retryable:r});switch(Number.parseInt(e.code,10)){case Zb:return new Jr(e.message,{code:dt,details:r(!1)});case Qb:return new Hr(e.message,Fr,{details:r(!0)});case Jb:return new Hr(e.message,nt,{details:r(!1)});case Yb:return new Hr(e.message,it,{details:r(!1)});case Xb:return new Hr(e.message,fr,{details:r(!0)});case eI: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 _S=e=>e.versionState.version?"incremental":"full",RS=e=>{const{metadata:t,metadataFailed:r,state:s}=e,n=s.versionState.version;return r||!t?{decision:"complete"===s.cacheMeta.cacheIntegrity?_S(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}},AS=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{}}},MS=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},ES=(e,t,r,s)=>({code:t,stage:e,message:`${e}: ${r}`,retryable:s}),US=e=>{Si("Contact sync duration",e)};class kS{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=RS({metadata:s,state:e}),"skip"===r.decision)return this.dependencies.onFinish(),void US({outcome:"skip",decision:r.decision,durationMs:Date.now()-t,version:r.version,hasUsableSnapshot:e.cachedSnapshot.complete})}catch(s){if(MS(s)){const r=RS({metadataFailed:!0,state:e}),n=s instanceof Hr?s:new Hr("Contact metadata request failed",wr,{details:{stage:"metadata"}});return this.dependencies.onFinish({error:ES("metadata",n.code,n.message,!1)}),void US({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=RS({metadataFailed:!0,state:e}),e.cachedSnapshot.complete)return this.dependencies.onFinish({error:ES("metadata",wr,s instanceof Error?s.message:String(s),!0)}),void US({outcome:"fail",decision:r.decision,durationMs:Date.now()-t,version:r.version,stage:"metadata",hasUsableSnapshot:!0,source:e.cachedSnapshot.source})}try{const s=await this.dependencies.getSyncUrls(),n=this.dependencies.buildRosterRequest({decision:r.decision,version:e.versionState.version}),i=await new TS(this.dependencies.getSharedSyncSession()).sync({urls:s,request:n}),o=(e=>{const t=[];for(const r of e)for(const e of r.data){const r=AS(e.metadata);t.push({relation:{userId:e.contact,remark:e.remark,sign:r.sign??"",addTs:e.createdAt,updatedAt:e.updatedAt,metadataUpdatedAt:e.metadataUpdatedAt},userInfo:{userId:e.contact,nickname:r.nickname,avatarUrl:r.avatarUrl,sign:r.sign,ext:r.ext}})}return t})(i.pages),a=this.dependencies.applySyncResult({mode:i.mode,relations:o.map(e=>e.relation),userInfos:o.map(e=>e.userInfo),version:i.version,lastSyncTs:Date.now()});this.dependencies.onFinish(),US({outcome:"finish",decision:r.decision,durationMs:Date.now()-t,version:i.version,source:"sync",changed:a.changed,hasUsableSnapshot:a.snapshot.complete})}catch(s){const n=s instanceof Hr?s:new Hr("Contact sync failed",Cr,{details:{stage:"sync_page",cause:s instanceof Error?s.message:String(s)}}),i=n.details??{},o="string"==typeof i.stage?i.stage:"sync_page";this.dependencies.onFinish({error:ES(o,n.code,n.message,!0)}),US({outcome:"fail",decision:r.decision,durationMs:Date.now()-t,version:r.version,stage:o,hasUsableSnapshot:e.cachedSnapshot.complete,source:e.cachedSnapshot.complete?e.cachedSnapshot.source:void 0})}}}const NS={items:[],loaded:!1,source:"server"},OS=Nb(Ob,{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:{}}}}),xS=class{constructor(){this.client=null,this.eventContext=null,this.restClient=null,this.restBaseUrl=null,this.restToken=null,this.blocklistSnapshot=NS,this.blocklistSessionKey=null}bind(e,t){this.client=e,this.eventContext=t??null,this.blocklistSnapshot=NS,this.blocklistSessionKey=null}getContacts(){return this.client?.getContactSnapshot()?.items??[]}async addContact(e){return this.runOperation("addContact",async()=>{const t=this.validateUserId(e.userId,"params.userId"),r=this.validateOptionalString(e.message,"params.message"),s=this.getRestContextOrThrow(),n=this.getRestClient(s);Ci("ContactManager addContact",{userId:t,hasMessage:"string"==typeof r&&r.length>0}),await(async(e,t,r)=>{const s=dS(t),n=`/${s.orgName}/${s.appName}/users/${s.encodedUserId}/contacts/apply?resource=${s.encodedResource}`;await e.post(n,{usernames:[r.userId],reason:r.message??""},{operation:"addContact"})})(n,s,{userId:t,message:r})})}async deleteContact(e){return this.runOperation("deleteContact",async()=>{const t=this.validateUserId(e.userId,"params.userId"),r=this.getRestContextOrThrow(),s=this.getRestClient(r);Ci("ContactManager deleteContact",{userId:t}),await(async(e,t,r)=>{const s=dS(t),n=`/${s.orgName}/${s.appName}/users/${s.encodedUserId}/contacts/users/${encodeURIComponent(r.userId)}?resource=${s.encodedResource}`;await e.delete(n,{operation:"deleteContact"})})(s,r,{userId:t});const n=this.client?.getCacheManager()?.removeContact(t);Ci("ContactManager deleteContact patched cache",{userId:t,changed:n?.changed??!1})})}async acceptContactInvite(e){return this.runOperation("acceptContactInvite",async()=>{const t=this.validateUserId(e.userId,"params.userId"),r=this.getRestContextOrThrow(),s=this.getRestClient(r);Ci("ContactManager acceptContactInvite",{userId:t}),await(async(e,t,r)=>{const s=dS(t),n=`/${s.orgName}/${s.appName}/users/${s.encodedUserId}/contacts/accept/users/${encodeURIComponent(r.userId)}?resource=${s.encodedResource}`;await e.post(n,void 0,{operation:"acceptContactInvite"})})(s,r,{userId:t}),await this.requireClient().refreshContactSnapshot()})}async declineContactInvite(e){return this.runOperation("declineContactInvite",async()=>{const t=this.validateUserId(e.userId,"params.userId"),r=this.getRestContextOrThrow(),s=this.getRestClient(r);Ci("ContactManager declineContactInvite",{userId:t}),await(async(e,t,r)=>{const s=dS(t),n=`/${s.orgName}/${s.appName}/users/${s.encodedUserId}/contacts/decline/users/${encodeURIComponent(r.userId)}?resource=${s.encodedResource}`;await e.post(n,void 0,{operation:"declineContactInvite"})})(s,r,{userId:t})})}async setContactRemark(e){return this.runOperation("setContactRemark",async()=>{const t=this.validateUserId(e.userId,"params.userId"),r=this.validateRemark(e.remark,"params.remark"),s=this.getRestContextOrThrow(),n=this.getRestClient(s);Ci("ContactManager setContactRemark",{userId:t,remarkLength:r.length}),await(async(e,t,r)=>{const s=dS(t),n=`/${s.orgName}/${s.appName}/users/${s.encodedUserId}/contacts/users/${encodeURIComponent(r.userId)}?resource=${s.encodedResource}`;await e.put(n,{remark:r.remark},{operation:"setContactRemark"})})(n,s,{userId:t,remark:r});const i=this.client?.getCacheManager()?.updateContactRemark(t,r);this.client?.refreshConversationDisplayFromUserInfos([{userId:t}],"profile"),Ci("ContactManager setContactRemark patched cache",{userId:t,changed:i?.changed??!1})})}async getBlocklist(){return this.runOperation("getBlocklist",async()=>{const e=this.getRestContextOrThrow();this.ensureBlocklistSession(e);const t=this.getRestClient(e);if(this.blocklistSnapshot.loaded)return this.blocklistSnapshot.items;const r=await this.enrichBlocklistUsers(await pS(t,e));return this.blocklistSnapshot={items:r,loaded:!0,source:"server"},Ci("ContactManager getBlocklist",{count:r.length}),r})}async addUsersToBlocklist(e){return this.runOperation("addUsersToBlocklist",async()=>{const t=this.getRestContextOrThrow();this.ensureBlocklistSession(t);const r=lS(e,"params.userIds"),s=this.getRestClient(t);Ci("ContactManager addUsersToBlocklist",{userIds:r,inputCount:e.userIds.length,normalizedCount:r.length});const n=await hS(s,t,r),i=await this.enrichBlocklistUsers(n.succeeded);return this.blocklistSnapshot=this.patchBlocklistSnapshotWithAdditions(i),{succeeded:i,failed:await this.enrichBlocklistUsers(n.failed)}})}async removeUserFromBlocklist(e){return this.runOperation("removeUserFromBlocklist",async()=>{const t=this.getRestContextOrThrow();this.ensureBlocklistSession(t);const r=lS(e,"params.userIds"),s=this.getRestClient(t);Ci("ContactManager removeUserFromBlocklist",{userIds:r,inputCount:e.userIds.length,normalizedCount:r.length}),await(async(e,t,r)=>{const s=dS(t),n=`/${s.orgName}/${s.appName}/sdk/user/${s.encodedUserId}/blocks?resource=${s.encodedResource}`;await e.request(n,{method:"DELETE",body:{usernames:r},operation:"removeUserFromBlocklist"})})(s,t,r),this.blocklistSnapshot=this.patchBlocklistSnapshotWithRemovals(r)})}addEventHandler(e,t){this.eventContext?.addEventHandler(e,t)}removeEventHandler(e){this.eventContext?.removeEventHandler(e)}async runOperation(e,t){try{return await t()}catch(r){const t=this.normalizeSdkError(e,r);throw Si(`ContactManager ${e} failed`,{code:t.code,message:t.message,details:t.details}),t}}normalizeSdkError(e,t){return t instanceof Hr?t:t instanceof Error?new Hr(`ContactManager ${e} failed: ${t.message}`,Br):new Hr(`ContactManager ${e} failed`,Br)}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 ty(e.restBaseUrl,{errorMap:OS,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=NS)}patchBlocklistSnapshotWithAdditions(e){const t=new Map(this.blocklistSnapshot.items.map(e=>[e.userId,e]));for(const r of e)t.set(r.userId,r);return{items:Array.from(t.values()),loaded:this.blocklistSnapshot.loaded,source:"mutation_patch"}}patchBlocklistSnapshotWithRemovals(e){const t=new Map(this.blocklistSnapshot.items.map(e=>[e.userId,e]));for(const r of e)t.delete(r);return{items:Array.from(t.values()),loaded:this.blocklistSnapshot.loaded,source:"mutation_patch"}}validateUserId(e,t){if("string"!=typeof e)throw this.buildValidationError("userId must be a string",[{path:t,message:"userId must be a string",rule:"invalid_format"}]);const r=e.trim();if(!r)throw this.buildValidationError("userId is required",[{path:t,message:"userId is required",rule:"required"}]);return r}validateOptionalString(e,t){if(void 0!==e){if("string"!=typeof e)throw this.buildValidationError(`${t} must be a string`,[{path:t,message:`${t} must be a string`,rule:"invalid_format"}]);return e}}validateRemark(e,t){if("string"!=typeof e)throw this.buildValidationError("remark must be a string",[{path:t,message:"remark must be a string",rule:"invalid_format"}]);return e}buildValidationError(e,t){const r=t.some(e=>"invalid_format"===e.rule)?it:nt;return new Zr(e,{code:r,details:{fields:t}})}async enrichBlocklistUsers(e){if(0===e.length||!this.requireClient().isUserInfoSyncEnabled())return e;const t=await Db(e.map(e=>e.userId),{cacheManager:this.requireClient().getCacheManager(),fetchUserInfos:async({userIds:e})=>await this.fetchUserInfos(e)});return e.map(e=>t.get(e.userId)??e)}async fetchUserInfos(e){if(0===e.length)return[];try{const t=this.getUserInfoManager();return t?await t.getUserInfoByUserId({userIds:e}):await this.fetchUserInfosFromRest(e)}catch(t){return Si("ContactManager user info fetch failed",{userIds:e,error:t}),[]}}async fetchUserInfosFromRest(e){const t=this.getRestContextOrThrow(),r=QC(e),s=await this.getRestClient(t).request(JC(t),{method:"POST",body:r,operation:"getUserInfoByUserId"});return rS(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 kS(e)}};xS.key="contactManager";let LS=xS;class PS{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 DS=e=>{const{orgName:t,appName:r}=Qn(e.appKey);return{orgName:t,appName:r,encodedUserId:encodeURIComponent(e.userId),encodedResource:encodeURIComponent(e.clientResource)}},qS=e=>new Zr(`${e} is required`,{code:nt,details:{fields:[{path:e,message:`${e} is required`,rule:"required"}]}}),$S=(e,t)=>new Zr(t,{code:it,details:{fields:[{path:e,message:t,rule:"invalid_format"}]}}),GS=(e,t)=>{if(!Array.isArray(e)||0===e.length)throw qS(t);const r=[],s=new Set;if(e.forEach((e,n)=>{if("string"!=typeof e)throw $S(`${t}[${n}]`,`${t}[${n}] must be a string`);const i=e.trim();i&&!s.has(i)&&(s.add(i),r.push(i))}),0===r.length)throw qS(t);return r},FS=(e,t)=>{if("string"!=typeof e||0===e.trim().length)throw qS(t);return e.trim()},BS=(e,t)=>{if(void 0!==e){if("string"!=typeof e)throw $S(t,`${t} must be a string`);return e}},jS=(e,t)=>{if(void 0!==e){if("boolean"!=typeof e)throw $S(t,`${t} must be a boolean`);return e}},zS=(e,t)=>`/${e.orgName}/${e.appName}${t}`,KS=new Set(["groupNamecard","group_namecard","group_name_card","namecard","nameCard"]),HS=e=>{const t=ob();"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}`:""},VS=async(e,t,r)=>{const s=DS(t),n=zS(s,`/chatgroups?resource=${s.encodedResource}`);return(e=>{const t=Fl(e),r=Pl(t[0]),s=Bl(e)??r;return{groupId:s&&Kl(s)||r&&Kl(r)||""}})(await e.post(n,{owner:t.userId,groupname:r.name,desc:r.description,members:r.memberIds?GS(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"}))},WS=async(e,t,r)=>{const s=DS(t),n=FS(r.groupId,"params.groupId"),i=zS(s,`/chatgroups/${encodeURIComponent(n)}?joined_time=true&version=v3`),o=await e.get(i,{operation:"getGroupInfo"});return Vl(o)},JS=async(e,t,r)=>{const s=DS(t),n=FS(r.groupId,"params.groupId"),i={},o=BS(r.name,"params.name"),a=BS(r.description,"params.description"),c=BS(r.avatar,"params.avatar"),d=BS(r.ext,"params.ext"),u=jS(r.public,"params.public"),l=jS(r.joinApprovalRequired,"params.joinApprovalRequired"),p=jS(r.allowInvites,"params.allowInvites"),h=jS(r.inviteNeedConfirm,"params.inviteNeedConfirm"),m=((e,t)=>{if(void 0!==e){if("number"!=typeof e||Number.isNaN(e))throw $S(t,`${t} must be a number`);return e}})(r.maxMembers,"params.maxMembers");if(void 0!==o&&(i.groupname=o),void 0!==a&&(i.description=a),void 0!==c&&(i.avatar=c),void 0!==d&&(i.custom=d),void 0!==u&&(i.public=u),void 0!==l&&(i.membersonly=l),void 0!==p&&(i.allowinvites=p),void 0!==h&&(i.invite_need_confirm=h),void 0!==m&&(i.maxusers=m),0===Object.keys(i).length)throw qS("params");const f=zS(s,`/chatgroups/${encodeURIComponent(n)}?resource=${s.encodedResource}&version=v3`);await e.put(f,i,{operation:"updateGroupInfo"})},ZS=async(e,t,r)=>{const s=DS(t),n=zS(s,`/chatgroups/${encodeURIComponent(FS(r.groupId,"params.groupId"))}/users${(e=>{const t=ob();return"number"==typeof e?.pageSize&&t.set("pagesize",String(e.pageSize)),"string"==typeof e?.cursor&&e.cursor.length>0&&t.set("cursor",e.cursor),t.set("version","v3"),`?${t.toString()}`})(r)}`);return(e=>{const t=[];for(const i of Fl(e)){const e=Pl(i);if(!e)continue;const r=ql(e.owner),s=ql(e.admin),n=ql(e.member),o=r??s??n;if(!o)continue;const a=$l(e.joinedAt)??$l(e.joined_time);t.push({user:Wl(o),role:r?"owner":s?"admin":"member",...void 0===a?{}:{joinedAt:a}})}const r=jl(e,"pagenum"),s=jl(e,"pagesize"),n=zl(e,s);return{items:t,pageNum:r,pageSize:s,...void 0===n?{}:{hasMore:n}}})(await e.get(n,{operation:"getGroupMemberList"}))},QS=async(e,t,r)=>{const s=DS(t),n=zS(s,`/chatgroups/${encodeURIComponent(FS(r.groupId,"params.groupId"))}/admin`),i=await e.get(n,{operation:"getGroupAdminList"});return Jl(i)},YS=async(e,t,r)=>{const s=DS(t),n=FS(r.groupId,"params.groupId"),i=HS(r),o=i?"&":"",a=zS(s,`/chatgroups/${encodeURIComponent(n)}/mute?version=v3${o}${i.replace("?","")}`);return(e=>{const t=[];for(const r of Fl(e)){const e=ql(r);if(e){t.push({user:Wl(e)});continue}const s=Pl(r);if(!s)continue;const n=ql(s.user);if(!n)continue;const i=$l(s.expire);t.push({user:Wl(n),...void 0===i?{}:{muteExpire:i}})}return t})(await e.get(a,{operation:"getGroupMuteList"}))},XS=async(e,t,r)=>{const s=DS(t),n=FS(r.groupId,"params.groupId"),i=HS(r),o=i?"&":"",a=zS(s,`/chatgroups/${encodeURIComponent(n)}/blocks/users?version=v3${o}${i.replace("?","")}`),c=await e.get(a,{operation:"getGroupBlocklist"});return Jl(c).map(e=>({user:e}))},eT=async(e,t,r)=>{const s=DS(t),n=zS(s,`/chatgroups/${encodeURIComponent(FS(r.groupId,"params.groupId"))}/white/users`),i=await e.get(n,{operation:"getGroupAllowlist"});return Jl(i).map(e=>({user:e}))},tT=async(e,t,r)=>{const s=DS(t),n=zS(s,`/chatgroups/${encodeURIComponent(FS(r.groupId,"params.groupId"))}/announcement`);return(e=>{const t=Bl(e)??{};return{announcement:Dl(t.announcement)??""}})(await e.get(n,{operation:"getGroupAnnouncement"}))},rT=async(e,t,r)=>{const s=DS(t),n=ob();n.set("pagenum",String(r.pageNum??1)),n.set("pagesize",String(r.pageSize??20));const i=zS(s,`/chatgroups/${encodeURIComponent(FS(r.groupId,"params.groupId"))}/share_files?${n.toString()}`);return(e=>{const t=jl(e,"pagenum"),r=jl(e,"pagesize"),s=zl(e,r);return{items:Fl(e).map(e=>Zl(e)).filter(e=>null!==e),pageNum:t,pageSize:r,...void 0===s?{}:{hasMore:s}}})(await e.get(i,{operation:"getGroupSharedFileList"}))},sT=(e,t)=>{const r=DS(e);return zS(r,`/chatgroups/${encodeURIComponent(FS(t.groupId,"params.groupId"))}/share_files/${encodeURIComponent(FS(t.fileId,"params.fileId"))}`)},nT=async(e,t,r)=>{const s=DS(t),n=FS(r.groupId,"params.groupId"),i=FS(r.userId,"params.userId"),o=((e,t,r)=>{if(t!==e.userId)return null;const s=Object.entries(r);if(0===s.length)return null;let n;for(const[i,o]of s){if(!KS.has(i)||"string"!=typeof o)return null;if(void 0!==n){if(n!==o)return null}else n=o}return void 0===n?null:{nameCard:n}})(t,i,r.memberAttributes);if(o){const t=zS(s,`/sdk/chatgroups/${encodeURIComponent(n)}/nameCard`);return await e.put(t,o,{operation:"setGroupMemberAttributes"})}const a=zS(s,`/sdk/metadata/chatgroup/${encodeURIComponent(n)}/user/${encodeURIComponent(i)}?resource=${s.encodedResource}`);return await e.put(a,{metaData:r.memberAttributes},{operation:"setGroupMemberAttributes"})},iT=async(e,t,r)=>{const s=DS(t),n=zS(s,`/sdk/metadata/chatgroup/${encodeURIComponent(FS(r.groupId,"params.groupId"))}/get`);return(e=>{const t=Bl(e)??{},r=Pl(t.data)??t,s={};for(const[n,i]of Object.entries(r)){const e=Pl(i);e&&(s[n]=Object.fromEntries(Object.entries(e).filter(e=>"string"==typeof e[1])))}return{items:s}})(await e.post(n,{targets:GS(r.userIds,"params.userIds"),properties:r.keys??[]},{operation:"getGroupMembersAttributes"}))},oT=e=>{const t=El(e)?e:{},r=t.data,s=El(r)?r.data:void 0,n=Array.isArray(r)?r:Array.isArray(s)?s:null;if(Array.isArray(n))return aT(n);const i=El(r)?r:t,o=El(i.namecards)?i.namecards:i,a={};for(const[c,d]of Object.entries(o)){if("string"==typeof d){a[c]={namecard:d};continue}if(!El(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:cT(d)})}return a},aT=e=>{const t={};return e.forEach(e=>{if(!El(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:cT(e)})}),t},cT=e=>Pp("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),dT=e=>{if(El(e))return Pp("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 uT{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 lT=e=>({...e}),pT=e=>({...e,owner:e.owner?{...e.owner}:void 0});class hT{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=lT({...this.summarySnapshot??{},...e,groupId:this.groupId}),this.loadedSummary=!0,this.lastPatchedAt=Date.now())}mergeDetail(e){e.groupId===this.groupId&&(this.detailSnapshot=pT({...this.detailSnapshot??this.summarySnapshot??{groupId:this.groupId,name:""},...e,groupId:this.groupId}),this.summarySnapshot=lT(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?lT(this.summarySnapshot):this.detailSnapshot?lT(this.toSummaryFromDetail(this.detailSnapshot)):null}getDetailSnapshot(){return this.detailSnapshot?pT(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 mT{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 fT{constructor(){this.groups=new Map,this.joinedGroupById=new Map,this.removedJoinedGroupIds=new Set,this.snapshotMapper=new mT,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 hT(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 gT=0,yT=5,vT=12,bT=13,IT=0,wT=1,CT=2,ST=0,TT=1,_T=2,RT=3,AT=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===IT?"owner":s===wT?"admin":s===CT?"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===ST?"DEFAULT":r===TT?"ALL":r===_T?"AT":r===RT?"NONE":void 0),createdAt:e.create_at,updatedAt:e.update_at,joinedAt:e.joined_timestamp}:null;var r,s},MT=e=>e.updatedAt??0,ET=(e,t)=>{if(!e)return!0;return MT(t)>=MT(e)},UT={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 kT=null,NT=!1;const OT=()=>kT||(NT||(Dc.util.Long=mo,Dc.configure(),NT=!0),hd(),kT=Dc.Root.fromJSON(UT),pd(kT),kT),xT=e=>OT().lookupType(e),LT=e=>{if("number"==typeof e&&Number.isFinite(e))return e;if("string"==typeof e&&e.length>0){const t=Number(e);return Number.isFinite(t)?t:void 0}if(mo.isLong(e))return e.toNumber();if(e&&"object"==typeof e&&"toString"in e&&"function"==typeof e.toString){const t=Number(e.toString());return Number.isFinite(t)?t:void 0}},PT=e=>{if(!e||"object"!=typeof e)return;const t=e;return{resource:"string"==typeof t.resource?t.resource:"",timestamp:LT(t.timestamp)??0,requestId:"string"==typeof t.request_id?t.request_id:"string"==typeof t.requestId?t.requestId:"",protocolVersion:LT(t.protocol_version)??LT(t.protocolVersion)??0}};class DT{constructor(){this.requestType=xT("easemob.joinedgroups.GetJoinedGroupsRequest"),this.responseType=xT("easemob.joinedgroups.GetJoinedGroupsResponse"),this.errorType=xT("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:gT}}tryDecodeRequest(e){try{const t=this.requestType.toObject(this.requestType.decode(e),{longs:String,bytes:Uint8Array}),r=LT(t.type);return r!==vT?null:{type:r,header:PT(t.header),org:"string"==typeof t.org?t.org:"",app:"string"==typeof t.app?t.app:"",username:"string"==typeof t.username?t.username:"",lastSyncTime:LT(t.last_sync_time)??LT(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=LT(t.type);return r!==bT?null:{type:r,header:PT(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:LT(t.members_count)??LT(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:LT(t.role),mute_expiration:LT(t.mute_expiration)??LT(t.muteExpiration),remind_type:LT(t.remind_type)??LT(t.remindType),create_at:LT(t.create_at)??LT(t.createAt),update_at:LT(t.update_at)??LT(t.updateAt),joined_timestamp:LT(t.joined_timestamp)??LT(t.joinedTimestamp)}})(e)):[],isLastBatch:!0===t.is_last_batch||!0===t.isLastBatch,lastSyncFinishedTs:LT(t.last_sync_finished_ts)??LT(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=LT(t.type);return r!==yT?null:{type:r,header:PT(t.header),code:LT(t.code)??0,message:"string"==typeof t.message?t.message:"Unknown joined groups sync error"}}catch{return null}}}class qT{constructor(e){this.batches=[],this.done=!1,this.requestId=e}getResumeCursor(){return this.latestCursor}push(e){if(e.type!==bT)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 $T=e=>e.type===bT,GT=e=>e.type===yT;class FT{constructor(e){this.codec=new DT,this.sharedSession=e}async sync(e){const t=e.request.header?.requestId??`group-sync-${Date.now()}`,r=new qT(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:$T(t)||GT(t)?t.header?.requestId:void 0,frame:t}},onFrame:e=>{try{if($T(e)){if(!r.push(e).done)return;return{done:!0,result:r.buildResult()}}if(GT(e))throw(e=>{const t=(t,r)=>({stage:t,serverCode:e.code,requestId:e.header?.requestId,retryable:r});switch(e.code){case 1601:return new Hr(e.message,nt,{details:t("request_send",!1)});case 1602:return new Hr(e.message,fr,{details:t("batch_merge",!0)});case 1002:return new Jr(e.message,{code:dt,details:t("auth",!1)});case 1003:return new Hr(e.message,Fr,{details:t("server_limit",!0)});default:return new Hr(e.message,fr,{details:t("response_decode",!0)})}})(e);return}catch(t){throw t instanceof Hr?t:new Hr("Joined groups frame decode failed",Tr,{details:{stage:"response_decode",cause:t instanceof Error?t.message:String(t)}})}}})}buildAttemptRequest(e,t,r){return{...e,cursor:r,lastSyncTime:0,header:{resource:e.header?.resource??"",timestamp:Date.now(),requestId:t,protocolVersion:e.header?.protocolVersion??1}}}}class BT{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 FT(this.dependencies.getSharedSyncSession()).sync({urls:r,request:s}),i=n.batches.flatMap(e=>(e=>{const t=[];for(const r of e){const e=AT(r);e&&t.push(e)}return t})(e.groups)),o=this.dependencies.getRuntimeSnapshot(),a=(e=>{const t=new Map(e.existingItems.map(e=>[e.groupId,e])),r=new Map;for(const n of e.incomingItems){const e=r.get(n.groupId)??t.get(n.groupId);ET(e,n)?r.set(n.groupId,{...e??{},...n,groupId:n.groupId}):e&&r.set(n.groupId,{...e})}const s=r.size>=Sf;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:Cf,serverLimit:Sf,source:"sync",lastSyncFinishedTs:e.lastSyncFinishedTs,lastSuccessfulAt:Date.now()}}})({existingItems:o?.items??[],incomingItems:i,lastSyncFinishedTs:n.lastSyncFinishedTs}),c=this.dependencies.getCacheManager();this.dependencies.applyRuntimeSnapshot(a);const d=this.dependencies.getRuntimeSnapshot()??a;try{await c.commitJoinedGroupPreviewSnapshot(d);const e=this.dependencies.getRuntimeSnapshot();e&&!this.hasSameMembership(d,e)&&await c.commitJoinedGroupPreviewSnapshot(e)}catch(t){throw o&&this.dependencies.applyRuntimeSnapshot(o),new Xr("Joined-group preview persistence failed",{details:{stage:"preview_persist",cause:t instanceof Error?t.message:String(t)}})}Si("Group sync finished",{durationMs:Date.now()-e,itemCount:a.items.length,limited:a.meta.limited}),this.dependencies.onFinish({status:"success"})}catch(t){const r=(e=>{const t=e instanceof Hr?e:new Hr("Group sync failed",fr,{details:{stage:"socket_connect",cause:e instanceof Error?e.message:String(e)}}),r=t.details??{},s=r.serverCode;return{dataType:"group",code:t.code,stage:(n=r.stage,"config"===n||"socket_connect"===n||"request_send"===n||"response_decode"===n||"batch_merge"===n||"preview_persist"===n||"completion_meta"===n||"auth"===n||"server_limit"===n||"cancelled"===n?n:"socket_connect"),message:t.message,retryable:!0===r.retryable,serverCode:"number"==typeof s||"string"==typeof s?s:void 0};var n})(t);Si("Group sync failed",{durationMs:Date.now()-e,stage:r.stage,code:r.code,serverCode:r.serverCode}),this.dependencies.onFinish({status:"failed",error:r})}}hasSameMembership(e,t){if(e.items.length!==t.items.length)return!1;const r=new Set(t.items.map(e=>e.groupId));return e.items.every(e=>r.has(e.groupId))}buildRequest(){const e=this.dependencies.getRestContext(),{orgName:t,appName:r}=Qn(e.appKey);return{type:vT,header:{resource:e.clientResource,timestamp:Date.now(),requestId:`group-sync-${Date.now()}`,protocolVersion:1},org:t,app:r,username:e.userId,lastSyncTime:0}}}const jT=Nb(Ob,{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:{}}}}),zT=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 fT,this.groupEventSync=new uT(this.groupRepository),this.ensureRepositorySession()}addEventHandler(e,t){this.eventContext?.addEventHandler(e,t)}removeEventHandler(e){this.eventContext?.removeEventHandler(e)}async handleRawNotify(e){if("group"!==e.type)return;const t=e.payload,r=t.eventName,s=await this.buildIncomingEventPayload(r,t);if(!s)return;if(this.eventContext?.dispatch?.(r,s),r!==we)return;if(!("attribute"in s)||!("user"in s))return;const n=this.extractGroupNamecard(s.attribute);if(void 0===n||!s.user?.userId)return;const i=this.client?.getCurrentUserId();s.user.userId!==i&&(this.getCacheManager()?.setGroupNamecards([{groupId:s.groupId,userId:s.user.userId,namecard:n,lastAccess:Date.now(),lastUpdate:Date.now()}]),this.eventContext?.dispatch?.(Ce,{groupId:s.groupId,userId:s.user.userId,namecard:n}))}async createGroup(e){return this.runOperation("createGroup",async()=>{const t=this.getRestContextOrThrow(),r=await VS(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 PS(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 WS(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=DS(t),n=GS(r.groupIds,"params.groupIds"),i=zS(s,`/chatgroups/${n.map(e=>encodeURIComponent(e)).join(",")}?joined_time=true&version=v3`),o=await e.get(i,{operation:"getGroupInfoList"});return(El(o)&&Array.isArray(o.data)?o.data:[]).map(e=>Vl({data:[e]}))})(this.getRestClient(t),t,e),s=await this.hydrateGroupDetailsUsers(r);return this.getGroupRepository().mergeDetails(s)})}async getGroupDetailForHandle(e){this.ensureRepositorySession();const t=this.getGroupRepository();if(t.getOrCreate(e),t.hasFreshDetail(e)){const r=t.getDetailSnapshot(e);if(r)return r}return this.getGroupInfo({groupId:e})}async refreshGroupDetailForHandle(e){return this.ensureRepositorySession(),this.getGroupRepository().getOrCreate(e),this.getGroupInfo({groupId:e})}resetSessionRuntime(){this.groupRegistry.clear(),this.getGroupRepository().ensureSession(null)}async buildIncomingEventPayload(e,t){this.ensureRepositorySession();const r=t.payload,s=e===ne?this.resolveLocalGroupName(r.groupId):void 0,n=await this.resolveUserInfoMap(this.collectEventUserIds(t));switch(await this.syncRuntimeForEvent(e,r,n),e){case Q:return{groupId:r.groupId,groupName:r.groupName,inviter:this.pickEventUser(r.inviterId,n),reason:r.reason};case Y:return{groupId:r.groupId,groupName:r.groupName,applicant:this.pickEventUser(r.applicantId,n),reason:r.reason};case X:return{groupId:r.groupId,groupName:r.groupName,accepter:this.pickEventUser(r.accepterId,n)};case ee:return{groupId:r.groupId,groupName:r.groupName,decliner:this.pickEventUser(r.declinerId,n),applicant:this.pickEventUser(r.applicantId,n),reason:r.reason};case te:case re:return{groupId:r.groupId,invitee:this.pickEventUser(r.inviteeId,n),reason:r.reason};case se:return{groupId:r.groupId,groupName:r.groupName};case ne:return{groupId:r.groupId,groupName:r.groupName??s};case ie:return{groupId:r.groupId,inviter:this.pickEventUser(r.inviterId,n),inviteMessage:r.reason};case oe:return{groupId:r.groupId,mutes:this.pickEventUsers(r.userIds,n),muteExpire:r.muteExpire};case ae:return{groupId:r.groupId,mutes:this.pickEventUsers(r.userIds,n)};case ce:case de:return{groupId:r.groupId,allowlist:this.pickEventUsers(r.userIds,n)};case ue:return{groupId:r.groupId,isMuted:Boolean(r.isMuted)};case le:case pe:return{groupId:r.groupId,administrator:this.pickEventUser(r.administratorId,n)};case he:return{groupId:r.groupId,newOwner:this.pickEventUser(r.newOwnerId,n),oldOwner:this.pickEventUser(r.oldOwnerId,n)};case me:return{groupId:r.groupId,groupName:await this.resolveMembersJoinedGroupName(r),members:this.pickEventUsers(r.memberIds,n)};case fe:return{groupId:r.groupId,members:this.pickEventUsers(r.memberIds,n)};case ge:return{groupId:r.groupId,announcement:r.announcement??""};case ye:return{groupId:r.groupId,sharedFile:this.hydrateEventSharedFile(r.sharedFile,n)};case ve:return{groupId:r.groupId,fileId:r.fileId??""};case be:return{groupId:r.groupId,groupInfo:await this.resolveGroupDetailForEvent(r)};case Ie:{const e=await this.resolveGroupDetailForEvent(r),t=void 0===r.isDisabled?Boolean(e.disabled):Boolean(r.isDisabled);return{groupId:r.groupId,groupInfo:e,disabled:t}}case we:return{groupId:r.groupId,user:this.pickEventUser(r.userId,n),attribute:r.attribute??{},from:r.from,source:r.source};default:return null}}async resolveGroupDetailForEvent(e){this.ensureRepositorySession();const t=void 0===e.isDisabled?e.groupPatch:{...e.groupPatch??{},disabled:e.isDisabled},r=this.getGroupEventSync().applyPatch({groupId:e.groupId,groupName:e.groupName,groupPatch:t,shouldMarkStale:e.shouldFetchGroupDetail});if(e.shouldFetchGroupDetail)try{return await this.getGroupInfo({groupId:e.groupId})}catch(n){Si("GroupManager resolveGroupDetailForEvent fallback to snapshot",{groupId:e.groupId,error:n})}if(r)return r;const s=this.getGroupRepository().getDetailSnapshot(e.groupId);return s||{groupId:e.groupId,name:t?.name??e.groupName??"",...t??{}}}async updateGroupInfo(e){return this.runOperation("updateGroupInfo",async()=>{const t=this.getRestContextOrThrow();await JS(this.getRestClient(t),t,e)})}async changeGroupOwner(e){return this.runOperation("changeGroupOwner",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=DS(t),n=zS(s,`/chatgroups/${encodeURIComponent(FS(r.groupId,"params.groupId"))}?resource=${s.encodedResource}`);await e.put(n,{newowner:FS(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=DS(t),n=zS(s,`/chatgroups/${encodeURIComponent(FS(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=DS(t),n=zS(s,`/chatgroups/${encodeURIComponent(FS(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=DS(t),n=zS(s,`/chatgroups/${encodeURIComponent(FS(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=DS(t),n=zS(s,`/chatgroups/${encodeURIComponent(FS(r.groupId,"params.groupId"))}/invite?resource=${s.encodedResource}`);await e.post(n,{usernames:GS(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=DS(t),n=zS(s,`/chatgroups/${encodeURIComponent(FS(r.groupId,"params.groupId"))}/apply_verify?resource=${s.encodedResource}`);await e.post(n,{applicant:FS(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=DS(t),n=zS(s,`/chatgroups/${encodeURIComponent(FS(r.groupId,"params.groupId"))}/apply_verify?resource=${s.encodedResource}`);await e.post(n,{applicant:FS(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=DS(t),n=zS(s,`/chatgroups/${encodeURIComponent(FS(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=DS(t),n=zS(s,`/chatgroups/${encodeURIComponent(FS(r.groupId,"params.groupId"))}/invite_verify?resource=${s.encodedResource}`);await e.post(n,{invitee:t.userId,verifyResult:!1},{operation:"rejectInvitation"})})(this.getRestClient(t),t,e)})}async getGroupMemberList(e){return this.runOperation("getGroupMemberList",async()=>{const t=this.getRestContextOrThrow(),r=await ZS(this.getRestClient(t),t,e);return{...r,items:await this.hydrateEntriesWithUsers(e.groupId,r.items)}})}async removeGroupMembers(e){return this.runOperation("removeGroupMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=DS(t),n=GS(r.userIds,"params.userIds"),i=zS(s,`/chatgroups/${encodeURIComponent(FS(r.groupId,"params.groupId"))}/users/${n.map(e=>encodeURIComponent(e)).join(",")}?resource=${s.encodedResource}`);await e.delete(i,{operation:"removeGroupMembers"})})(this.getRestClient(t),t,e)})}async getGroupAdminList(e){return this.runOperation("getGroupAdminList",async()=>{const t=this.getRestContextOrThrow(),r=await QS(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=DS(t),n=zS(s,`/chatgroups/${encodeURIComponent(FS(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=DS(t),n=zS(s,`/chatgroups/${encodeURIComponent(FS(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 YS(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=DS(t),n=zS(s,`/chatgroups/${encodeURIComponent(FS(r.groupId,"params.groupId"))}/mute?resource=${s.encodedResource}`);await e.post(n,{usernames:GS(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=DS(t),n=GS(r.userIds,"params.userIds"),i=zS(s,`/chatgroups/${encodeURIComponent(FS(r.groupId,"params.groupId"))}/mute/${n.map(e=>encodeURIComponent(e)).join(",")}?resource=${s.encodedResource}`);await e.delete(i,{operation:"unmuteGroupMembers"})})(this.getRestClient(t),t,e)})}async muteAllGroupMembers(e){return this.runOperation("muteAllGroupMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=DS(t),n=zS(s,`/chatgroups/${encodeURIComponent(FS(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=DS(t),n=zS(s,`/chatgroups/${encodeURIComponent(FS(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=DS(t),n=zS(s,`/chatgroups/${encodeURIComponent(FS(r.groupId,"params.groupId"))}/blocks/users?resource=${s.encodedResource}`);await e.post(n,{usernames:GS(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=DS(t),n=GS(r.userIds,"params.userIds"),i=zS(s,`/chatgroups/${encodeURIComponent(FS(r.groupId,"params.groupId"))}/blocks/users/${n.map(e=>encodeURIComponent(e)).join(",")}?resource=${s.encodedResource}`);await e.delete(i,{operation:"unblockGroupMembers"})})(this.getRestClient(t),t,e)})}async getGroupAllowlist(e){return this.runOperation("getGroupAllowlist",async()=>{const t=this.getRestContextOrThrow(),r=await eT(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=DS(t),n=zS(s,`/chatgroups/${encodeURIComponent(FS(r.groupId,"params.groupId"))}/white/users?resource=${s.encodedResource}`);await e.post(n,{usernames:GS(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=DS(t),n=GS(r.userIds,"params.userIds"),i=zS(s,`/chatgroups/${encodeURIComponent(FS(r.groupId,"params.groupId"))}/white/users/${n.map(e=>encodeURIComponent(e)).join(",")}?resource=${s.encodedResource}`);await e.delete(i,{operation:"removeUsersFromGroupAllowlist"})})(this.getRestClient(t),t,e)})}async checkIfInGroupAllowList(e){return this.runOperation("checkIfInGroupAllowList",async()=>{const t=this.getRestContextOrThrow();return(async(e,t,r)=>{const s=DS(t),n=zS(s,`/chatgroups/${encodeURIComponent(FS(r.groupId,"params.groupId"))}/white/users/${s.encodedUserId}?version=v3`),i=await e.get(n,{operation:"checkIfInGroupAllowList"});return"boolean"==typeof i?i:El(i)&&"boolean"==typeof i.data?i.data:Boolean(i)})(this.getRestClient(t),t,e)})}async checkIfInGroupMuteList(e){return this.runOperation("checkIfInGroupMuteList",async()=>{const t=this.getRestContextOrThrow();return(async(e,t,r)=>{const s=DS(t),n=zS(s,`/sdk/chatgroups/${encodeURIComponent(FS(r.groupId,"params.groupId"))}/mute/${s.encodedUserId}?version=v3`),i=await e.get(n,{operation:"checkIfInGroupMuteList"});return"boolean"==typeof i?i:El(i)&&"boolean"==typeof i.data?i.data:Boolean(i)})(this.getRestClient(t),t,e)})}async getGroupAnnouncement(e){return this.runOperation("getGroupAnnouncement",async()=>{const t=this.getRestContextOrThrow();return tT(this.getRestClient(t),t,e)})}async updateGroupAnnouncement(e){return this.runOperation("updateGroupAnnouncement",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=DS(t),n=zS(s,`/chatgroups/${encodeURIComponent(FS(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 rT(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=sT(t,{groupId:e.groupId,fileId:"__upload__"}).replace(/\/share_files\/__upload__$/,"/share_files"),s=Bn({file:e.file}),n=Wh({operationName:"GROUP_UPLOAD_SHAREDFILE",operationType:"GROUP"}),i=n?.startRequest({requestName:"GROUP_UPLOAD_SHAREDFILE",method:"POST",url:`${t.restBaseUrl}${r}`});try{const o=await(this.requireClient().getUploadAdapter()?.upload({url:`${t.restBaseUrl}${r}?resource=${encodeURIComponent(t.clientResource)}`,headers:{Authorization:`Bearer ${t.token}`,[vl]:yl()},source:s.source,timeoutMs:3e5,onProgress:e.onFileUploadProgress}));if(!o)throw new Error("platform upload adapter is unavailable");if(o.status<200||o.status>=300)throw new Hr("uploadGroupSharedFile failed",mr,{details:{status:o.status}});i?.finish({code:o.status,success:!0}),n?.finish({code:0,success:!0}),e.onFileUploadComplete?.(o.body)}catch(o){const t=tl(o);throw i?.finish({code:t.code,success:!1,description:t.message}),n?.finish({code:t.code,success:!1,description:t.message}),t.code===Gr&&e.onFileUploadCanceled?.(),e.onFileUploadError?.(t),t}})}async deleteGroupSharedFile(e){return this.runOperation("deleteGroupSharedFile",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=DS(t),n=zS(s,`/chatgroups/${encodeURIComponent(FS(r.groupId,"params.groupId"))}/share_files/${encodeURIComponent(FS(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}${sT(s,e)}`;t=Wh({operationName:"GROUP_DOWNLOAD_SHAREDFILE",operationType:"GROUP"}),r=t?.startRequest({requestName:"GROUP_DOWNLOAD_SHAREDFILE",method:"GET",url:n});const i=this.requireClient().getRequestAdapter();if(!i)throw new Hr("downloadGroupSharedFile request adapter is unavailable",pr);const o=await i.request({url:n,method:"GET",headers:{Authorization:`Bearer ${s.token}`,...e.secret?{"Share-Secret":e.secret}:{},[vl]:yl()},responseType:"arraybuffer",timeoutMs:6e4});if(o.status<200||o.status>=300)throw r?.finish({code:o.status,success:!1,description:"downloadGroupSharedFile failed"}),t?.finish({code:o.status,success:!1,description:"downloadGroupSharedFile failed"}),new Hr("downloadGroupSharedFile failed",mr);r?.finish({code:o.status,success:!0}),t?.finish({code:0,success:!0});const a="undefined"!=typeof Blob?new Blob([o.data]):o.data;e.onFileDownloadComplete?.(a)}catch(s){const n=s instanceof Hr?s.code:pr,i=s instanceof Error?s.message:String(s);throw r?.finish({code:n,success:!1,description:i}),t?.finish({code:n,success:!1,description:i}),e.onFileDownloadError?.(s),s}})}async setGroupMemberAttributes(e){return this.runOperation("setGroupMemberAttributes",async()=>{const t=this.getRestContextOrThrow(),r=await nT(this.getRestClient(t),t,e);this.writeSelfGroupNamecardCache(t.userId,e,r)})}async getGroupMembersAttributes(e){return this.runOperation("getGroupMembersAttributes",async()=>{const t=this.getRestContextOrThrow();return iT(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=DS(t),n=zS(s,`/sdk/chatgroups/${encodeURIComponent(FS(r.groupId,"params.groupId"))}/nameCard/batch/get`),i=await e.post(n,{members:GS(r.userIds,"params.userIds")},{operation:"getGroupNamecards"});return{items:oT(i),responseTimestamp:dT(i)}})(this.getRestClient(r),r,{groupId:e,userIds:s}),i=new Map(t.map(e=>[e.userId,e.namecardUpdateTime])),o=[],a=new Set;for(const[t,d]of Object.entries(n.items))a.add(t),o.push({groupId:e,userId:t,namecard:d.namecard,namecardUpdateTime:i.get(t)??d.namecardUpdateTime,lastSyncAt:Date.now(),lastAccess:Date.now(),lastUpdate:Date.now()});const c=s.filter(e=>!a.has(e));c.length>0&&"number"==typeof n.responseTimestamp&&o.push(...c.map(t=>({groupId:e,userId:t,namecard:"",namecardUpdateTime:n.responseTimestamp,lastSyncAt:Date.now(),lastAccess:Date.now(),lastUpdate:Date.now()}))),this.getCacheManager()?.setGroupNamecards(o);for(const e of o)e.userId!==r.userId&&""!==e.namecard&&this.eventContext?.dispatch?.(Ce,{groupId:e.groupId,userId:e.userId,namecard:e.namecard});c.length>0&&"number"!=typeof n.responseTimestamp&&Si("Group namecard hydration returned partial result",{groupId:e,requestedUserIds:s,missingUserIds:c})})}async runOperation(e,t){try{return await t()}catch(r){const t=this.normalizeSdkError(e,r);throw Si(`GroupManager ${e} failed`,{code:t.code,message:t.message,details:t.details}),t}}normalizeSdkError(e,t){return t instanceof Hr?t:t instanceof Error?new Hr(`GroupManager ${e} failed: ${t.message}`,Br):new Hr(`GroupManager ${e} failed`,Br)}getRestContextOrThrow(){return this.requireClient().getRestContext()}getRestClient(e){return this.restClient&&this.restBaseUrl===e.restBaseUrl&&this.restToken===e.token||(this.restClient=new ty(e.restBaseUrl,{errorMap:jT,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 fT),this.groupRepository}getGroupEventSync(){return this.groupEventSync||(this.groupEventSync=new uT(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 WS(this.getRestClient(t),t,{groupId:e.groupId}),n=this.getGroupRepository();if(n.getSessionKey()!==s)return;return n.mergeDetail(r),this.resolveUsableGroupName(r.name,e.groupId)}catch(n){return void Si("Members joined group detail enrichment failed",{groupId:e.groupId,error:n})}}resolveUsableGroupName(e,t){const r=e?.trim();return r&&r!==t?r:void 0}writeSelfGroupNamecardCache(e,t,r){if(t.userId!==e)return;const s=this.extractGroupNamecard(t.memberAttributes);if("string"!=typeof s)return;const n=this.resolveGroupMemberAttributesUpdateTime(r,t.userId);"number"!=typeof n&&Si("Group member attributes update response missing server update time",{groupId:t.groupId,userId:t.userId}),this.getCacheManager()?.setGroupNamecards([{groupId:t.groupId,userId:t.userId,namecard:s,namecardUpdateTime:n,lastSyncAt:Date.now(),lastAccess:Date.now(),lastUpdate:Date.now()}])}resolveGroupMemberAttributesUpdateTime(e,t){const r=[];this.collectUpdateTimeCandidates(e,t,r);for(const s of r){const e=Pp("number"==typeof s?s:Number(s));if("number"==typeof e)return e}}collectUpdateTimeCandidates(e,t,r){if(!El(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(El(s)){this.collectUpdateTimeCandidates(s,t,r);const e=s[t];El(e)&&this.collectUpdateTimeCandidates(e,t,r)}const n=e.lastModified??e.last_modified;El(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 Ll(e,{cacheManager:this.getCacheManager(),fetchUserInfos:async({userIds:e})=>{const t=this.getUserInfoManager();if(0===e.length)return[];if(!t)return await this.fetchUserInfosFromRest(e);try{return await t.getUserInfoByUserId({userIds:e})}catch(r){return Si("GroupManager user info fetch failed",{userIds:e,error:r}),[]}}})}collectEventUserIds(e){const t=e.payload,r=[t.inviterId,t.applicantId,t.accepterId,t.declinerId,t.inviteeId,t.administratorId,t.oldOwnerId,t.newOwnerId,t.userId,t.sharedFile?.fileOwner?.userId,...t.memberIds??[],...t.userIds??[]],s=[],n=new Set;for(const i of r){if("string"!=typeof i)continue;const e=i.trim();e&&!n.has(e)&&(n.add(e),s.push(e))}return s}pickEventUser(e,t){if(e)return xl(void 0,t.get(e),e)}pickEventUsers(e,t){return(e??[]).map(e=>xl(void 0,t.get(e),e))}hydrateEventSharedFile(e,t){return e?.fileOwner?.userId?{...e,fileOwner:xl(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 he:return void this.getGroupEventSync().applyPatch({groupId:t.groupId,groupName:t.groupName,groupPatch:{owner:this.pickEventUser(t.newOwnerId,r)}});case X:case ie:return void this.addCurrentUserJoinedGroupFromEvent(t);case me:{let r=!1;if(t.memberIds?.includes(this.requireClient().getCurrentUserId()??"")&&(r=await this.addCurrentUserJoinedGroupFromEvent(t)),r)return;if(this.applyMemberCountDeltaPatch(t.groupId,t.groupName,this.getMemberEventDeltaCount(e,t)))return;return void this.getGroupEventSync().applyPatch({groupId:t.groupId,groupName:t.groupName,shouldMarkStale:!0})}case fe:if(this.applyMemberCountDeltaPatch(t.groupId,t.groupName,-this.getMemberEventDeltaCount(e,t)))return;return void this.getGroupEventSync().applyPatch({groupId:t.groupId,groupName:t.groupName,shouldMarkStale:!0});case se:case ne:return void(await this.removeJoinedGroupLocal(t.groupId));case oe:case ae:case ce:case de:case le:case pe:return void this.getGroupEventSync().applyPatch({groupId:t.groupId,groupName:t.groupName,shouldMarkStale:!0});default:return}}getMemberEventDeltaCount(e,t){switch(e){case me:case fe:return t.memberIds?.length??0;default:return 0}}applyMemberCountDeltaPatch(e,t,r){if(0===r)return!1;const s=this.getGroupRepository().getDetailSnapshot(e);return!(!s||"number"!=typeof s.memberCount)&&(this.getGroupEventSync().applyPatch({groupId:e,groupName:t,groupPatch:{memberCount:Math.max(0,s.memberCount+r)}}),!0)}async removeJoinedGroupLocal(e){this.getGroupRepository().markJoinedGroupRemoved(e);const t=this.getCacheManager();t&&"function"==typeof t.removeJoinedGroupPreview&&await t.removeJoinedGroupPreview(e)}async addCurrentUserJoinedGroupFromEvent(e){if(!this.addJoinedGroupIfAbsent({groupId:e.groupId,name:e.groupName??"",role:"member"}))return!1;const t=this.getGroupRepository().getSessionKey();let r;try{r=this.getRestContextOrThrow()}catch(s){return Si("Joined group detail enrichment skipped",{groupId:e.groupId,error:s}),!1}try{return await this.enrichJoinedGroupFromDetail(e.groupId,t,r)}catch(s){return Si("Joined group detail enrichment failed",{groupId:e.groupId,error:s}),!1}}addJoinedGroupIfAbsent(e){const t=this.getGroupRepository().addJoinedGroupIfAbsent(e,this.loadJoinedGroupPreviewSnapshot());return!!t&&(this.persistJoinedGroupSnapshot(t),!0)}async enrichJoinedGroupFromDetail(e,t,r){const s=await WS(this.getRestClient(r),r,{groupId:e}),n=this.getGroupRepository();if(n.getSessionKey()!==t)return!1;n.mergeDetail(s);const i=n.getJoinedGroupSummarySnapshot(e);if(!i)return!1;const o=n.mergeJoinedGroupSummary(e,{...i.name||!s.name?{}:{name:s.name},...void 0!==i.description||void 0===s.description?{}:{description:s.description},...void 0!==i.memberCount||void 0===s.memberCount?{}:{memberCount:s.memberCount},...void 0!==i.role||void 0===s.role?{}:{role:s.role},...void 0!==i.disabled||void 0===s.disabled?{}:{disabled:s.disabled},...i.ownerId||!s.owner?.userId?{}:{ownerId:s.owner.userId},...void 0!==i.avatarUrl||void 0===s.avatarUrl?{}:{avatarUrl:s.avatarUrl},...void 0!==i.muteAllMembers||void 0===s.muteAllMembers?{}:{muteAllMembers:s.muteAllMembers},...void 0!==i.createdAt||void 0===s.createdAt?{}:{createdAt:s.createdAt},...void 0!==i.joinedAt||void 0===s.joinedAt?{}:{joinedAt:s.joinedAt}});if(o){this.persistJoinedGroupSnapshot(o);const t=n.getJoinedGroupSummarySnapshot(e);t&&this.requireClient().refreshConversationDisplayFromJoinedGroups([{...t,name:s.name||t.name,avatarUrl:s.avatarUrl??t.avatarUrl}],"profile",{onlyWhenNameMissing:!0})}return!0}persistJoinedGroupSnapshot(e){const t=this.getCacheManager();if(t&&"function"==typeof t.applyJoinedGroupPreviewSnapshot){try{t.applyJoinedGroupPreviewSnapshot(e)}catch(r){return void Si("Joined group preview persistence failed",{error:r})}"function"==typeof t.flushPending&&t.flushPending().catch(e=>{Si("Joined group preview flush failed",{error:e})})}}async hydrateUserInfos(e,t){const r=await this.resolveGroupContextUserInfoMap(e,t);return t.map(e=>r.get(e.userId)??e)}async fetchUserInfosFromRest(e){const t=this.getRestContextOrThrow(),r=QC(e),s=await this.getRestClient(t).request(JC(t),{method:"POST",body:r,operation:"getUserInfoByUserId"});return rS(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(vI(e.groupId,e.owner.userId))??e.owner}:e)}async resolveGroupContextUserInfoMap(e,t){const r=this.isGroupNamecardEnhancementEnabled(),s=await _I({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 TI({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 BT(e)}};zT.key="groupManager";let KT=zT;const HT=Nb(Ob,{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}}}}}),VT=class{constructor(){this.client=null,this.eventContext=null,this.restClient=null,this.restBaseUrl=null,this.restToken=null}bind(e,t){this.client=e,this.eventContext=t??null}addEventHandler(e,t){this.getEventContextOrThrow().addEventHandler(e,t)}removeEventHandler(e){this.getEventContextOrThrow().removeEventHandler(e)}async publishPresence(e){return this.runOperation("publishPresence",async()=>{this.validateDescription(e.customStatus);const t=this.getRestContextOrThrow(),r=this.getRestClient(t),{orgName:s,appName:n}=this.parseAppKey(t.appKey),i=`/${s}/${n}/users/${t.userId}/presence/${t.clientResource}/1`,o={ext:e.customStatus};Ci("Call publishPresence",{customStatus:e.customStatus}),await r.request(i,{method:"POST",body:o,operation:"publishPresence"})})}async subscribePresence(e){return this.runOperation("subscribePresence",async()=>{this.validateUserIds(e.userIds),this.validateExpiry(e.expiry);const t=this.getRestContextOrThrow(),r=this.getRestClient(t),{orgName:s,appName:n}=this.parseAppKey(t.appKey),i=`/${s}/${n}/users/${t.userId}/presence/${e.expiry}`,o={usernames:e.userIds};Ci("Call subscribePresence",{userIds:e.userIds,expiry:e.expiry});const a=await r.request(i,{method:"POST",body:o,operation:"subscribePresences"});return this.normalizeSubscribeResponse(a)})}async unsubscribePresence(e){return this.runOperation("unsubscribePresence",async()=>{this.validateUserIds(e.userIds);const t=this.getRestContextOrThrow(),r=this.getRestClient(t),{orgName:s,appName:n}=this.parseAppKey(t.appKey),i=`/${s}/${n}/users/${t.userId}/presence`;Ci("Call unsubscribePresence",{userIds:e.userIds}),await r.request(i,{method:"DELETE",body:e.userIds,operation:"unsubscribePresence"})})}async getSubscribedPresenceList(e){return this.runOperation("getSubscribedPresenceList",async()=>{this.validatePage(e.pageNum,e.pageSize);const t=this.getRestContextOrThrow(),r=this.getRestClient(t),{orgName:s,appName:n}=this.parseAppKey(t.appKey),i=`/${s}/${n}/users/${t.userId}/presence/sublist?pageNum=${e.pageNum}&pageSize=${e.pageSize}`;Ci("Call getSubscribedPresenceList",{pageNum:e.pageNum,pageSize:e.pageSize});const o=await r.request(i,{method:"GET",operation:"getSubscribedPresenceList"});return this.normalizeSubscribedListResponse(o)})}async getPresenceStatus(e){return this.runOperation("getPresenceStatus",async()=>{this.validateUserIds(e.userIds);const t=this.getRestContextOrThrow(),r=this.getRestClient(t),{orgName:s,appName:n}=this.parseAppKey(t.appKey),i=`/${s}/${n}/users/${t.userId}/presence`,o={usernames:e.userIds};Ci("Call getPresenceStatus",{userIds:e.userIds});const a=await r.request(i,{method:"POST",body:o,operation:"getPresenceStatus"});return this.normalizeSubscribeResponse(a)})}async runOperation(e,t){try{return await t()}catch(r){const t=this.normalizeSdkError(e,r);throw Si(`PresenceManager ${e} failed`,{code:t.code,message:t.message,details:t.details}),t}}normalizeSdkError(e,t){return t instanceof Hr?t:t instanceof Error?new Hr(`PresenceManager ${e} failed: ${t.message}`,Br):new Hr(`PresenceManager ${e} failed`,Br)}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 ty(e.restBaseUrl,{errorMap:HT,requestAdapter:this.client?.getRequestAdapter?.(),includeRequestId:!0}),this.restClient.setAuthToken(e.token),this.restBaseUrl=e.restBaseUrl,this.restToken=e.token),this.restClient}parseAppKey(e){const t=e.split("#");if(2!==t.length||!t[0]||!t[1])throw this.buildValidationError([{path:"appKey",message:"appKey is invalid",rule:"invalid_format"}]);return{orgName:t[0],appName:t[1]}}validateDescription(e){if("string"!=typeof e)throw this.buildValidationError([{path:"description",message:"description must be a string",rule:"invalid_format"}])}validateUserIds(e){if(!Array.isArray(e))throw this.buildValidationError([{path:"userIds",message:"userIds must be an array",rule:"invalid_format"}]);if(0===e.length)throw this.buildValidationError([{path:"userIds",message:"userIds is required",rule:"required"}]);for(const t of e)if("string"!=typeof t||0===t.trim().length)throw this.buildValidationError([{path:"userIds",message:"userIds contains invalid userId",rule:"invalid_format"}])}validateExpiry(e){if("number"!=typeof e||Number.isNaN(e))throw this.buildValidationError([{path:"expiry",message:"expiry must be a number",rule:"invalid_format"}]);if(e<0)throw this.buildValidationError([{path:"expiry",message:"expiry must be greater than or equal to 0",rule:"range"}])}validatePage(e,t){if("number"!=typeof e||Number.isNaN(e))throw this.buildValidationError([{path:"pageNum",message:"pageNum must be a number",rule:"invalid_format"}]);if("number"!=typeof t||Number.isNaN(t))throw this.buildValidationError([{path:"pageSize",message:"pageSize must be a number",rule:"invalid_format"}]);if(e<0||t<0)throw this.buildValidationError([{path:"pageNum",message:"pageNum must be greater than or equal to 0",rule:"range"},{path:"pageSize",message:"pageSize must be greater than or equal to 0",rule:"range"}])}normalizeSubscribeResponse(e){return(e.result??[]).map(e=>e&&"string"==typeof e.uid&&0!==e.uid.length?{publisher:e.uid,statusList:this.normalizeStatusList(e.status),ext:"string"==typeof e.ext?e.ext:"",latestTime:"number"==typeof e.last_time?e.last_time:0,expiryTime:"number"==typeof e.expiry?e.expiry:0}:null).filter(e=>null!==e)}normalizeSubscribedListResponse(e){const t=e.result;return(t?.sublist??[]).map(e=>e&&"string"==typeof e.uid&&0!==e.uid.trim().length?e.uid:null).filter(e=>null!==e)}normalizeStatusList(e){if("object"!=typeof(t=e)||null===t||Array.isArray(t))return{};var t;const r={};for(const[s,n]of Object.entries(e))if("number"==typeof n&&Number.isFinite(n))r[s]=Math.trunc(n);else if("string"==typeof n&&n.trim().length>0){const e=Number(n);Number.isFinite(e)&&(r[s]=Math.trunc(e))}return r}buildValidationError(e){return new Zr("Invalid parameters",{code:it,details:{fields:e}})}};VT.key="presenceManager";let WT=VT;const JT=Nb(Ob,{common:{},apis:{setGlobalSilentMode:{range:"110,1501",localErrors:{setGlobalSilentMode:{validation_invalid:{code:110,retryable:!1}}},errors:{SILENT_MODE_OPERATION_FAILED:{code:1501,httpStatus:400,retryable:!1}}},setConversationSilentMode:{range:"110,1501",localErrors:{setConversationSilentMode:{validation_invalid:{code:110,retryable:!1}}},errors:{SILENT_MODE_OPERATION_FAILED:{code:1501,httpStatus:400,retryable:!1}}},setPushLanguage:{range:"110,1502",localErrors:{setPushLanguage:{validation_invalid:{code:110,retryable:!1}}},errors:{PUSH_LANGUAGE_OPERATION_FAILED:{code:1502,httpStatus:400,retryable:!1}}},uploadPushToken:{range:"110,1500",localErrors:{uploadPushToken:{validation_invalid:{code:110,retryable:!1}}},errors:{TOKEN_UPLOAD_FAILED:{code:1500,httpStatus:400,retryable:!0}}},getGlobalSilentMode:{range:"1501",errors:{SILENT_MODE_OPERATION_FAILED:{code:1501,retryable:!1}}},getConversationSilentMode:{range:"110,1501",localErrors:{getConversationSilentMode:{validation_invalid:{code:110,retryable:!1}}},errors:{SILENT_MODE_OPERATION_FAILED:{code:1501,retryable:!1}}},clearConversationRemindType:{range:"110,1501",localErrors:{clearConversationRemindType:{validation_invalid:{code:110,retryable:!1}}},errors:{SILENT_MODE_OPERATION_FAILED:{code:1501,retryable:!1}}},getConversationSilentModes:{range:"110,1501",localErrors:{getConversationSilentModes:{validation_invalid:{code:110,retryable:!1}}},errors:{SILENT_MODE_OPERATION_FAILED:{code:1501,retryable:!1}}},getConversationListByRemindType:{range:"110",localErrors:{getConversationListByRemindType:{validation_invalid:{code:110,retryable:!1}}},errors:{}},getPushLanguage:{range:"1502",errors:{PUSH_LANGUAGE_OPERATION_FAILED:{code:1502,retryable:!1}}}}}),ZT=["singleChat","groupChat"],QT=["ALL","AT","NONE","DEFAULT"],YT=["ALL","AT","NONE"],XT=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),e_=class{constructor(){this.client=null,this.restClient=null,this.restBaseUrl=null,this.restToken=null}bind(e,t){this.client=e}async uploadPushToken(e){return this.runOperation(async()=>{this.validateUploadPushTokenParams(e);const t=this.getRestContextOrThrow(),r=this.getRestClient(t),{orgName:s,appName:n}=this.parseAppKey(t.appKey),i=`/${s}/${n}/users/${t.userId}`;Ci("Call uploadPushToken",{deviceId:e.deviceId,notifierName:e.notifierName}),await r.request(i,{method:"PUT",body:{device_id:e.deviceId,device_token:e.deviceToken,notifier_name:e.notifierName},operation:"uploadPushToken"})})}async setGlobalSilentMode(e){return this.runOperation(async()=>{this.validateRuleInput(e.rule,"rule");const t=this.getRestContextOrThrow(),r=this.getRestClient(t),{orgName:s,appName:n}=this.parseAppKey(t.appKey),i=`/${s}/${n}/users/${t.userId}/notification/user/${t.userId}?resource=${encodeURIComponent(t.clientResource)}`,o=this.buildSilentModePayload(e.rule);Ci("Call setGlobalSilentMode",{mode:e.rule.mode});const a=await r.request(i,{method:"PUT",body:o,operation:"setGlobalSilentMode"});return{scope:"global",rule:this.normalizeRuleView(this.resolveSilentModeRuleSource(a),e.rule)}})}async getGlobalSilentMode(e={}){return this.runOperation(async()=>{const e=this.getRestContextOrThrow(),t=this.getRestClient(e),{orgName:r,appName:s}=this.parseAppKey(e.appKey),n=`/${r}/${s}/users/${e.userId}/notification/user/${e.userId}`;Ci("Call getGlobalSilentMode");const i=await t.request(n,{method:"GET",operation:"getGlobalSilentMode"});return{scope:"global",rule:this.normalizeRuleView(this.resolveSilentModeRuleSource(i))}})}async setConversationSilentMode(e){return this.runOperation(async()=>{this.validateConversationId(e.conversationId,"conversationId"),this.validateConversationType(e.conversationType,"conversationType"),this.validateRuleInput(e.rule,"rule");const t=this.getRestContextOrThrow(),r=this.getRestClient(t),{orgName:s,appName:n}=this.parseAppKey(t.appKey),i=this.mapConversationTypeToPath(e.conversationType),o=`/${s}/${n}/users/${t.userId}/notification/${i}/${encodeURIComponent(e.conversationId)}?resource=${encodeURIComponent(t.clientResource)}`,a=this.buildSilentModePayload(e.rule);Ci("Call setConversationSilentMode",{conversationId:e.conversationId,conversationType:e.conversationType,mode:e.rule.mode});const c=await r.request(o,{method:"PUT",body:a,operation:"setConversationSilentMode"});return{conversationId:e.conversationId,conversationType:e.conversationType,rule:this.normalizeRuleView(this.resolveSilentModeRuleSource(c),e.rule)}})}async getConversationSilentMode(e){return this.runOperation(async()=>{this.validateConversationId(e.conversationId,"conversationId"),this.validateConversationType(e.conversationType,"conversationType");const t=this.getRestContextOrThrow(),r=this.getRestClient(t),{orgName:s,appName:n}=this.parseAppKey(t.appKey),i=this.mapConversationTypeToPath(e.conversationType),o=`/${s}/${n}/users/${t.userId}/notification/${i}/${encodeURIComponent(e.conversationId)}`;Ci("Call getConversationSilentMode",{conversationId:e.conversationId,conversationType:e.conversationType});const a=await r.request(o,{method:"GET",operation:"getConversationSilentMode"});return{conversationId:e.conversationId,conversationType:e.conversationType,rule:this.normalizeRuleView(this.resolveSilentModeRuleSource(a))}})}async clearConversationRemindType(e){return this.runOperation(async()=>{this.validateConversationId(e.conversationId,"conversationId"),this.validateConversationType(e.conversationType,"conversationType");const t=this.getRestContextOrThrow(),r=this.getRestClient(t),{orgName:s,appName:n}=this.parseAppKey(t.appKey),i=this.mapConversationTypeToPath(e.conversationType),o=`/${s}/${n}/users/${t.userId}/notification/${i}/${encodeURIComponent(e.conversationId)}?resource=${encodeURIComponent(t.clientResource)}`;Ci("Call clearConversationRemindType",{conversationId:e.conversationId,conversationType:e.conversationType});const a=await r.request(o,{method:"PUT",body:{type:"DEFAULT"},operation:"clearConversationRemindType"});return{conversationId:e.conversationId,conversationType:e.conversationType,rule:this.normalizeRuleView(this.resolveSilentModeRuleSource(a),{remindType:"DEFAULT"})}})}async getConversationSilentModes(e){return this.runOperation(async()=>{this.validateConversationList(e.conversationList,"conversationList");const t=this.getRestContextOrThrow(),r=this.getRestClient(t),{orgName:s,appName:n}=this.parseAppKey(t.appKey),i=e.conversationList.filter(e=>"singleChat"===e.conversationType).map(e=>encodeURIComponent(e.conversationId)).join(","),o=e.conversationList.filter(e=>"groupChat"===e.conversationType).map(e=>encodeURIComponent(e.conversationId)).join(","),a=`/${s}/${n}/users/${t.userId}/notification?user=${i}&group=${o}`;Ci("Call getConversationSilentModes",{count:e.conversationList.length});const c=await r.request(a,{method:"GET",operation:"getConversationSilentModes"}),d=this.resolveConversationRuleMap(c,"user"),u=this.resolveConversationRuleMap(c,"group");return{conversations:e.conversationList.map(e=>{const t="singleChat"===e.conversationType?d[e.conversationId]:u[e.conversationId];return{conversationId:e.conversationId,conversationType:e.conversationType,rule:this.normalizeRuleView(t)}})}})}async setPushLanguage(e){await this.runOperation(async()=>{this.validateLanguage(e.language,"language");const t=this.getRestContextOrThrow(),r=this.getRestClient(t),{orgName:s,appName:n}=this.parseAppKey(t.appKey),i=`/${s}/${n}/users/${t.userId}/notification/language`;Ci("Call setPushLanguage",{language:e.language}),await r.request(i,{method:"PUT",body:{translationLanguage:e.language},operation:"setPushLanguage"})})}async getPushLanguage(e={}){return this.runOperation(async()=>{const e=this.getRestContextOrThrow(),t=this.getRestClient(e),{orgName:r,appName:s}=this.parseAppKey(e.appKey),n=`/${r}/${s}/users/${e.userId}/notification/language`;Ci("Call getPushLanguage");const i=await t.request(n,{method:"GET",operation:"getPushLanguage"});return{language:this.resolvePushLanguage(i,"")}})}getConversationListByRemindType(e){return this.runOperation(()=>{Ci("Call getConversationListByRemindType",{pageSize:e.pageSize,hasCursor:Boolean(e.cursor)});const t=this.getClientOrThrow(),r=Dg({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}`,Br):new Hr("PushManager operation failed",Br)}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 ty(e.restBaseUrl,{errorMap:JT,requestAdapter:this.getClientOrThrow().getRequestAdapter?.(),includeRequestId:!0}),this.restClient.setAuthToken(e.token),this.restBaseUrl=e.restBaseUrl,this.restToken=e.token),this.restClient}getClientOrThrow(){if(!this.client)throw new Hr("PushManager is not bound to client",nt);return this.client}parseAppKey(e){const t=e.split("#");if(2!==t.length||!t[0]||!t[1])throw this.buildValidationError("Invalid appKey format",[{path:"appKey",message:'appKey must be in format "org#app"',rule:"invalid_format"}]);return{orgName:t[0],appName:t[1]}}validateUploadPushTokenParams(e){this.validateNonEmptyString(e.deviceId,"deviceId"),this.validateNonEmptyString(e.deviceToken,"deviceToken"),this.validateNonEmptyString(e.notifierName,"notifierName")}validateConversationId(e,t){this.validateNonEmptyString(e,t)}validateConversationType(e,t){if("string"!=typeof e||!ZT.includes(e))throw this.buildValidationError("Conversation type is not supported",[{path:t,message:"Only singleChat and groupChat are supported",rule:"invalid_format"}])}validateConversationList(e,t){if(!Array.isArray(e)||0===e.length)throw this.buildValidationError("conversationList must be a non-empty array",[{path:t,message:"conversationList must be a non-empty array",rule:"required"}]);if(e.length>20)throw this.buildValidationError("conversationList length must be <= 20",[{path:t,message:"conversationList length exceeds 20",rule:"range"}]);e.forEach((e,r)=>{this.validateConversationId(e.conversationId,`${t}[${r}].conversationId`),this.validateConversationType(e.conversationType,`${t}[${r}].conversationType`)})}validateLanguage(e,t){this.validateNonEmptyString(e,t)}validateNonEmptyString(e,t){if("string"!=typeof e||0===e.trim().length)throw this.buildValidationError(`${t} must be a non-empty string`,[{path:t,message:`${t} must be a non-empty string`,rule:"invalid_format"}])}validateRuleInput(e,t){if(!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(!YT.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]),i=Number(t[4]);return Number.isInteger(r)&&Number.isInteger(s)&&Number.isInteger(n)&&Number.isInteger(i)?r<0||r>23||n<0||n>23||s<0||s>59||i<0||i>59?null:{startTime:{hours:r,minutes:s},endTime:{hours:n,minutes:i}}:null}toRuleViewFromFallback(e){if("mode"in e)switch(e.mode){case"REMIND_TYPE":return{remindType:e.remindType};case"DURATION":return{};case"INTERVAL":return{silentModeStartTime:e.startTime,silentModeEndTime:e.endTime}}return e}formatIntervalSegment(e){return`${String(e.hours).padStart(2,"0")}:${String(e.minutes).padStart(2,"0")}`}resolveConversationRuleMap(e,t){if(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":QT.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:it,details:{fields:t}})}};e_.key="pushManager";let t_=e_;const r_=e=>{const{orgName:t,appName:r}=Qn(e.appKey);return`/${t}/${r}/user/${encodeURIComponent(e.userId)}/metadata/subscription`},s_=(e,t="params.userIds")=>VC(e,t),n_=e=>{const t=s_(e);if(t.length>100)throw((e,t,r,s=it)=>new Zr(e,{code:s,details:{fields:[{path:t,message:e,rule:r}]}}))("params.userIds must contain at most 100 unique users","params.userIds","range",Fr);return{usernames:t}},i_=(e,t)=>{const r=(e=>s_(e))(t);return`${r_(e)}?usernames=${r.map(e=>encodeURIComponent(e)).join(",")}`},o_=(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}},a_=["nickname","avatarUrl","mail","phone","gender","sign","birth","ext"],c_=Nb(Ob,{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}}}}}),d_=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=o_(r,s);e&&Object.assign(t,e)}return{userId:e.userId,attributes:t,lastModified:e.lastModified,source:"subscribe_metadata_updated"===e.notifyType?"subscription":"contact_metadata_updated"===e.notifyType?"contact":"own"}})(s);if(!n)return;const i=r.applyUserInfoNotifyPatch(n);if(!i.applied)return void Ci("User-info notify ignored",{userId:n.userId,notifyType:s.notifyType,reason:i.reason,lastModified:n.lastModified});if(r.updateUserInfoSummaryFromRuntime(n.userId),t.refreshConversationDisplayFromUserInfos?.([{userId:n.userId,lastModified:n.lastModified}]),"subscription"===n.source)return void this.eventContext?.dispatch?.("onUserInfoUpdated",[i.record.profile]);if("own"===n.source)return void this.eventContext?.dispatch?.("onOwnInfoUpdated",i.record.profile);const o=t.getContactSnapshot()?.items.find(e=>e.userId===n.userId);this.eventContext?.dispatch?.(Z,{userInfo:i.record.profile,contact:o})}async getUserInfoByUserId(e){return this.runOperation("getUserInfoByUserId",async()=>{const t=this.getRestContextOrThrow(),r=this.getRestClient(t),s=QC(VC(e.userIds,"params.userIds")),n=JC(t);Ci("UserInfoManager getUserInfoByUserId",{userIds:s.targets});const i=await r.request(n,{method:"POST",body:s,operation:"getUserInfoByUserId"}),o=this.normalizeFetchEnvelope(i,s.targets);return this.writeCache(o),o.map(e=>e.profile)})}async getUserInfoByAttribute(e){return this.runOperation("getUserInfoByAttribute",async()=>{const t=this.getRestContextOrThrow(),r=this.getRestClient(t),s=(n=VC(e.userIds,"params.userIds"),i=WC(e.attributes,"params.attributes"),{targets:VC(n),properties:WC(i).map(e=>HC(e,"params.attributes"))});var n,i;const o=JC(t);Ci("UserInfoManager getUserInfoByAttribute",{userIds:s.targets,attributes:s.properties});const a=await r.request(o,{method:"POST",body:s,operation:"getUserInfoByAttribute"}),c=this.normalizeFetchEnvelope(a,s.targets);return this.writeCache(c),c.map(e=>e.profile)})}async subscribeUsersInfo(e){return this.runOperation("subscribeUsersInfo",async()=>{const t=this.getRestContextOrThrow(),r=this.getRestClient(t),s=(e=>r_(e))(t),n=n_(e.userIds);Ci("UserInfoManager subscribeUsersInfo",{userIds:n.usernames}),await r.request(s,{method:"POST",body:n,operation:"subscribeUsersInfo"})})}async unsubscribeUsersInfo(e){return this.runOperation("unsubscribeUsersInfo",async()=>{const t=this.getRestContextOrThrow(),r=this.getRestClient(t),s=i_(t,e.userIds);Ci("UserInfoManager unsubscribeUsersInfo",{userIds:VC(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=>r_(e))(e);Ci("UserInfoManager getSubscribedUsers",{userId:e.userId});const s=(e=>{const t=e&&"object"==typeof e?e:null;if(!t||!Array.isArray(t.data))return[];const r=[],s=new Set;for(const n of t.data){if("string"!=typeof n)continue;const e=n.trim();e&&!s.has(e)&&(s.add(e),r.push(e))}return r})(await t.request(r,{method:"GET",operation:"getSubscribedUsers"}));return 0===s.length?[]:await this.getUserInfoByUserId({userIds:s})})}async updateOwnInfo(e){return this.runOperation("updateOwnInfo",async()=>{const t=this.getRestContextOrThrow(),r=this.getRestClient(t),s=(e=>{const t=[];if(sS(t,"nickname",e.nickname,"params.nickname"),sS(t,"avatarurl",e.avatarUrl,"params.avatarUrl"),sS(t,"mail",e.mail,"params.mail"),sS(t,"phone",e.phone,"params.phone"),sS(t,"gender",e.gender,"params.gender"),sS(t,"sign",e.sign,"params.sign"),sS(t,"birth",e.birth,"params.birth"),sS(t,"ext",e.ext,"params.ext"),0===t.length)throw jC("params must include at least one updatable field","params","required");return nS(t)})(e),n=ZC(t);Ci("UserInfoManager updateOwnInfo",{userId:t.userId,fields:this.getUpdatedFieldNames(e)});const i=await r.request(n,{method:"PUT",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s,operation:"updateOwnInfo"}),o=this.normalizeUpdateEnvelope(i,t.userId,this.buildFallbackProfile(t.userId,e));return this.writeCache([o]),this.dispatchSelfUpdate(o.profile),o.profile})}async updateOwnInfoByAttribute(e,t){return this.runOperation("updateOwnInfoByAttribute",async()=>{const r=this.getRestContextOrThrow(),s=this.getRestClient(r),n=((e,t)=>{const r=HC(e,"attribute"),s=KC(t,"value");if("gender"!==r&&"string"!=typeof s)throw jC("value must be a string","value","invalid_format");return nS([[r,String(s)]])})(e,t),i=ZC(r);Ci("UserInfoManager updateOwnInfoByAttribute",{userId:r.userId,attribute:e});const o=await s.request(i,{method:"PUT",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:n,operation:"updateOwnInfoByAttribute"}),a=this.normalizeUpdateEnvelope(o,r.userId,{userId:r.userId,[e]:t});return this.writeCache([a]),this.dispatchSelfUpdate(a.profile),a.profile})}async runOperation(e,t){try{return await t()}catch(r){throw this.normalizeOperationError(e,r)}}normalizeOperationError(e,t){return t instanceof Hr?t:(Si("UserInfoManager operation failed",{operation:e,message:t instanceof Error?t.message:String(t)}),new Hr(`${e} failed`))}getRestContextOrThrow(){if(this.client)return this.client.getRestContext();throw new Zr("UserInfoManager is not bound to client",{code:nt,details:{fields:[{path:"userInfoManager.client",message:"client is required",rule:"required"}]}})}getRestClient(e){return this.restClient&&this.restBaseUrl===e.restBaseUrl&&this.restToken===e.token||(this.restClient=new ty(e.restBaseUrl,{errorMap:c_,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 tS(e,t)}normalizeUpdateEnvelope(e,t,r){const s=El(e)?e:null,n=(s&&El(s.data)?s.data:null)??(s&&this.looksLikeUserInfoAttributes(s)?s:null),i=s&&"number"==typeof s.lastModified?s.lastModified:void 0;return{profile:n?this.toUserInfo(t,n):{userId:t,...r??{}},lastModified:i}}toUserInfo(e,t){const r={userId:e};return"string"==typeof t.nickname&&(r.nickname=t.nickname),"string"==typeof t.avatarurl?r.avatarUrl=t.avatarurl:"string"==typeof t.avatarUrl&&(r.avatarUrl=t.avatarUrl),"string"==typeof t.mail&&(r.mail=t.mail),"string"==typeof t.phone&&(r.phone=t.phone),"string"!=typeof t.gender&&"number"!=typeof t.gender&&"boolean"!=typeof t.gender||(r.gender=t.gender),"string"==typeof t.sign&&(r.sign=t.sign),"string"==typeof t.birth&&(r.birth=t.birth),"string"==typeof t.ext&&(r.ext=t.ext),r}looksLikeUserInfoAttributes(e){return!!El(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 a_)n in t&&(s[n]=t[n]);return r}getUpdatedFieldNames(e){return a_.filter(t=>t in e)}projectToSummary(e){const t=Date.now(),r=Pp(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)}};d_.key="userInfoManager";let u_=d_;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=Vf,e.ChatClient=sI,e.ChatManager=Ew,e.ChatRoom=Zw,e.ChatRoomManager=cS,e.ChatThread=Uw,e.ChatThreadManager=Jw,e.ConnectionError=Wr,e.ContactManager=LS,e.Group=PS,e.GroupManager=KT,e.ImageType={ORIGINAL:"original",LARGE:"large"},e.MessageReceiveError=Yr,e.MessageSendError=Qr,e.NetworkError=Vr,e.PresenceManager=WT,e.PushManager=t_,e.RUNTIME_PLATFORMS=Mi,e.RestBusinessError=ts,e.RestTransportError=es,e.SDKError=Hr,e.StorageError=Xr,e.StreamMessageStatus=rt,e.UploadError=rs,e.UserInfoManager=u_,e.ValidationError=Zr,e.createPlatformAdapter=el,e.detectRuntimePlatform=(e,t)=>co(t,e).platform,e.isSDKError=function(e){if(e instanceof Hr)return!0;if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.name&&"string"==typeof t.message&&"number"==typeof t.code&&"function"==typeof t.toJSON},e.setLogLevel=function(e){yi instanceof gi&&yi.setLevel(e)},Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),e}({});
1
+ var IMSDK=function(e){"use strict";const t="disconnected",r="connecting",s="connected",n="reconnecting",i="reconnectFailed",o="onConnecting",a="onConnected",c="onDisconnected",d="onReconnectFailed",u="onTokenWillExpire",l="onTokenExpired",h="onOfflineMessageSyncStart",p="onOfflineMessageSyncFinish",m="onSendTimeout",f="onGroupNotify",g="onChatRoomNotify",y="onChatThreadNotify",v="onUserInfoNotify",I="__internal:onMessageSent",b="login",_="reconnect",T="online",C="offline-recover",S="heartbeat-failed",E="send-timeout",w="close",R="error",A="limit",N="offline",O="token-expired",M="onMessage",U="onStreamMessage",L="onConversationListUpdate",k="onMessageReadReceipts",D="onMessageDelivered",P="onMessageRecalled",x="onMessageUpdated",F="onReactionChanged",B="onPinnedMessageChanged",G="onMultiDeviceContact",q="onMultiDeviceConversation",$="onSyncDataStart",j="onSyncDataFinished",V={LOG:"onLog"},K="onPresenceStatusChange",z="onContactInvited",H="onContactDeleted",W="onContactAdded",J="onContactRefuse",Q="onContactAgreed",Z="onContactInfoUpdated",Y="onInvitationReceived",X="onRequestToJoinReceived",ee="onRequestToJoinAccepted",te="onRequestToJoinDeclined",re="onInvitationAccepted",se="onInvitationDeclined",ne="onUserRemoved",ie="onGroupDestroyed",oe="onAutoAcceptInvitationFromGroup",ae="onMuteListAdded",ce="onMuteListRemoved",de="onAllowListAdded",ue="onAllowListRemoved",le="onAllMemberMuteStateChanged",he="onAdminAdded",pe="onAdminRemoved",me="onOwnerChanged",fe="onMembersJoined",ge="onMembersExited",ye="onAnnouncementChanged",ve="onSharedFileAdded",Ie="onSharedFileDeleted",be="onGroupInfoChanged",_e="onGroupDisabledChanged",Te="onGroupMemberAttributeChanged",Ce="onUserGroupNamecardUpdated",Se="__chatroom:onChatRoomDestroyed",Ee="__chatroom:onMembersJoined",we="__chatroom:onMembersExited",Re="__chatroom:onRemovedFromChatRoom",Ae="__chatroom:onMuteListAdded",Ne="__chatroom:onMuteListRemoved",Oe="__chatroom:onAllowListAdded",Me="__chatroom:onAllowListRemoved",Ue="__chatroom:onAllMemberMuteStateChanged",Le="__chatroom:onAdminAdded",ke="__chatroom:onAdminRemoved",De="__chatroom:onOwnerChanged",Pe="__chatroom:onAnnouncementChanged",xe="__chatroom:onChatRoomInfoChanged",Fe="__chatroom:onAttributesUpdate",Be="__chatroom:onAttributesRemoved",Ge={TOKEN_BOUND:"onPushTokenBound",TOKEN_BIND_FAILED:"onPushTokenBindFailed",TOKEN_REMOVE_FAILED:"onPushTokenRemoveFailed"},qe="onChatRoomDestroyed",$e="onMembersJoined",je="onMembersExited",Ve="onRemovedFromChatRoom",Ke="onMuteListAdded",ze="onMuteListRemoved",He="onAllowListAdded",We="onAllowListRemoved",Je="onAllMemberMuteStateChanged",Qe="onAdminAdded",Ze="onAdminRemoved",Ye="onOwnerChanged",Xe="onAnnouncementChanged",et="onChatRoomInfoChanged",rt="onAttributesUpdate",st="onAttributesRemoved",nt={START:"STREAM_START",START_COMPLETED:"STREAM_START_COMPLETED",IN_PROGRESS:"STREAM_IN_PROGRESS",COMPLETED:"STREAM_COMPLETED",FULL:"STREAM_FULL",ERROR:"STREAM_ERROR"};function it(e){return"object"==typeof e.stream&&null!==e.stream}const ot={VALIDATION_REQUIRED:110,VALIDATION_INVALID_FORMAT:110,VALIDATION_UNKNOWN:110,AUTH_ALREADY_LOGIN:200,AUTH_NOT_LOGIN:201,AUTH_UNAUTHORIZED:202,AUTH_FORBIDDEN:210,AUTH_TOKEN_EXPIRED:108,AUTH_BIND_ANOTHER_DEVICE:213,AUTH_LOGIN_TOO_MANY_DEVICES:214,AUTH_USER_MUTED:215,CONNECTION_TIMEOUT:301,CONNECTION_LOGIN_TIMEOUT:301,CONNECTION_WEBSOCKET_ERROR:300,CONNECTION_NOT_CREATED:1,CONNECTION_CLOSED_BEFORE_READY:300,CONNECTION_CANCELLED:1,CONNECTION_PROVISION_TIMEOUT:301,CONNECTION_PROVISION_REJECTED:202,CONNECTION_PROVISION_CLOSED:300,CONNECTION_DNSLIST_FAILED:304,STORAGE_OPERATION_FAILED:3,MESSAGE_NOT_CONNECTED:300,MESSAGE_ACK_TIMEOUT:301,MESSAGE_SEND_FAILED:303,MESSAGE_SENDER_DESTROYED:1,MESSAGE_ENCODE_FAILED:500,MESSAGE_DECODE_FAILED:500,MESSAGE_ACK_MISSING:301,MESSAGE_BLOCKED_BY_RECIPIENT:222,OPERATION_UNSUPPORTED:111,SERVER_BUSY:302,ATTACHMENT_NOT_FOUND:400,ATTACHMENT_INVALID:401,ATTACHMENT_EXPIRED:407,MESSAGE_INCLUDE_ILLEGAL_CONTENT:501,MESSAGE_SEND_TRAFFIC_LIMIT:502,MESSAGE_RECALL_TIME_LIMIT:504,SERVICE_NOT_ENABLED:505,MESSAGE_EXPIRED:506,MESSAGE_ILLEGAL_WHITELIST:507,MESSAGE_EXTERNAL_LOGIC_BLOCKED:508,MESSAGE_CURRENT_LIMITING:509,MESSAGE_SIZE_LIMIT:510,MESSAGE_EDIT_FAILED:511,INVALID_CONVERSATION:107,USER_LOGIN_ANOTHER_DEVICE:206,USER_REMOVED:207,USER_KICKED_BY_CHANGE_PASSWORD:216,USER_KICKED_BY_OTHER_DEVICE:217,USER_ALREADY_LOGIN_ANOTHER:218,USER_MUTED_BY_ADMIN:219,USER_DEVICE_CHANGED:220,USER_NOT_ON_ROSTER:221,SERVER_SERVING_DISABLED:305,FILE_DOWNLOAD_FAILED:403,FILE_TOO_LARGE:405,FILE_CONTENT_IMPROPER:406,THIRD_MODERATION_FAILED:1200,THIRD_DEFAULT_FAILED:1299,STREAM_SEND_NOT_SUPPORTED:303,STREAM_CHUNK_INVALID:500,STREAM_TIMEOUT_BY_SERVER:500,STREAM_STATE_CONFLICT:500,COMBINE_INVALID_INPUT:110,COMBINE_LEVEL_EXCEEDED:4,COMBINE_ITEM_LIMIT_EXCEEDED:4,COMBINE_ENCODE_FAILED:500,COMBINE_UPLOAD_FAILED:402,COMBINE_DOWNLOAD_FAILED:2,COMBINE_PARSE_FAILED:500,REST_NETWORK_ERROR:2,REST_TIMEOUT:301,REST_HTTP_ERROR:303,REST_BUSINESS_UNKNOWN:303,PUSH_TOKEN_UPLOAD_FAILED:1500,PUSH_SILENT_MODE_OPERATION_FAILED:1501,PUSH_LANGUAGE_OPERATION_FAILED:1502,USER_INFO_SUBSCRIPTION_LIMIT_EXCEEDED:1600,USER_INFO_SUBSCRIPTION_TARGET_LIMIT_EXCEEDED:1601,USERINFO_USERCOUNT_EXCEED:900,USERINFO_DATALENGTH_EXCEED:901,CONTACT_ADD_USER_NOT_FOUND:204,CONTACT_ADD_ALREADY_FRIEND:1e3,CONTACT_ADD_BLOCKED_BY_USER:210,CONTACT_SET_REMARK_NOT_FRIEND:223,CONTACT_REACH_LIMIT:1001,CONTACT_REACH_LIMIT_PEER:1002,CONTACT_BLOCKLIST_USER_NOT_FOUND:204,GROUP_INVALID_ID:600,GROUP_ALREADY_JOINED:601,GROUP_NOT_JOINED:602,GROUP_PERMISSION_DENIED:603,GROUP_MEMBERS_FULL:604,GROUP_SHARED_FILE_INVALID_ID:605,GROUP_NOT_EXIST:606,GROUP_DISABLED:607,GROUP_NAME_VIOLATION:608,GROUP_MEMBER_ATTRIBUTES_REACH_LIMIT:609,GROUP_MEMBER_ATTRIBUTES_UPDATE_FAILED:610,GROUP_MEMBER_ATTRIBUTES_KEY_REACH_LIMIT:611,GROUP_MEMBER_ATTRIBUTES_VALUE_REACH_LIMIT:612,GROUP_USER_IN_BLOCKLIST:613,CHATROOM_INVALID_ID:700,CHATROOM_NOT_JOINED:702,CHATROOM_PERMISSION_DENIED:703,CHATROOM_MEMBERS_FULL:704,CHATROOM_NOT_EXIST:705,CHATROOM_OWNER_NOT_ALLOW_LEAVE:706,CHATROOM_USER_IN_BLOCKLIST:707,CONTACT_SYNC_METADATA_FAILED:1700,CONTACT_SYNC_SOCKET_FAILED:1701,CONTACT_SYNC_CURSOR_INVALID:1702,CONTACT_SYNC_PROTO_DECODE_FAILED:1703,CONTACT_SYNC_CANCELLED:1704,SESSION_LIST_SOCKET_FAILED:300,SESSION_LIST_PROTO_DECODE_FAILED:500,SESSION_LIST_REQUEST_INVALID:110,SESSION_LIST_FETCH_FAILED:303,SESSION_LIST_SERVICE_DISABLED:305,SESSION_LIST_CANCELLED:1,PRESENCE_PARAM_LENGTH_EXCEED:1100,PRESENCE_CANNOT_SUBSCRIBE_YOURSELF:1101,TRANSLATE_PARAM_INVALID:1110,TRANSLATE_SERVICE_NOT_ENABLED:1111,TRANSLATE_USAGE_LIMIT:1112,TRANSLATE_FAILED:1113,VOICE_TO_TEXT_FILE_INVALID:407,VOICE_TO_TEXT_FILE_DURATION_TOO_LONG:408,VOICE_TO_TEXT_FAILED:409,VOICE_TO_TEXT_FILE_NOT_FOUND:410,VOICE_TO_TEXT_FILE_TOO_LARGE:411,REACTION_REACH_LIMIT:1300,REACTION_ALREADY_OPERATED:1301,REACTION_OPERATION_ILLEGAL:1302,UPLOAD_REQUIRED_FIELD_MISSING:110,UPLOAD_INVALID_APPKEY:100,UPLOAD_SIZE_EXCEEDED:405,UPLOAD_REQUEST_FAILED:402,UPLOAD_TIMEOUT:301,UPLOAD_ABORTED:1,SERVICE_LIMIT_EXCEEDED:4,UNKNOWN:1},at="[REDACTED]",ct=e=>{if(!e)return"";const t=e.includes("?"),r=e.includes("#");try{return((e,t,r)=>(e.username&&(e.username=at),e.password&&(e.password=at),e.search=t?`?${at}`:"",e.hash=r?`#${at}`:"",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)}?${at}`}},dt=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>"url"===e.toLowerCase()&&"string"==typeof t?[e,ct(t)]:[e,t]));class ut extends Error{constructor(e,t=ot.UNKNOWN,r){super(e),this.name="SDKError",this.code=t,this.details=r?.details?dt(r.details):void 0,Error.captureStackTrace&&Error.captureStackTrace(this,ut)}toJSON(){return{name:this.name,message:this.message,code:this.code,details:this.details,stack:this.stack}}}class lt extends ut{constructor(e,t){super(e,t?.code??ot.REST_NETWORK_ERROR,t),this.name="NetworkError"}}class ht extends ut{constructor(e,t){super(e,t?.code??ot.CONNECTION_WEBSOCKET_ERROR,t),this.name="ConnectionError"}}class pt extends ut{constructor(e,t){super(e,t?.code??ot.AUTH_UNAUTHORIZED,t),this.name="AuthenticationError"}}class mt extends ut{constructor(e,t){super(e,t?.code??ot.VALIDATION_UNKNOWN,t),this.name="ValidationError"}}class ft extends ut{constructor(e,t){super(e,t?.code??ot.MESSAGE_SEND_FAILED,t),this.name="MessageSendError"}}class gt extends ut{constructor(e,t){super(e,t?.code??ot.MESSAGE_DECODE_FAILED,t),this.name="MessageReceiveError"}}class yt extends ut{constructor(e,t){super(e,t?.code??ot.STORAGE_OPERATION_FAILED,t),this.name="StorageError"}}class vt extends ut{constructor(e,t){super(e,t?.code??ot.REST_NETWORK_ERROR,t),this.name="RestTransportError"}}class It extends ut{constructor(e,t){super(e,t?.code??ot.REST_BUSINESS_UNKNOWN,t),this.name="RestBusinessError"}}class bt extends ut{constructor(e,t){super(e,t?.code??ot.UPLOAD_REQUEST_FAILED,t),this.name="UploadError"}}const _t=0,Tt=1,Ct=2,St=3,Et=4,wt=0,Rt=1,At=2,Nt=3,Ot=4,Mt=5,Ut=6,Lt=7,kt=8,Dt=0,Pt=1,xt=2,Ft=3,Bt=4,Gt=5,qt=6,$t=7,jt=8,Vt=0,Kt=1,zt=2,Ht=3,Wt=4,Jt=0,Qt=1,Zt=2,Yt=3,Xt=5,er=0,tr=1,rr=2,sr=0,nr=0,ir=2,or=0,ar=1,cr=2,dr=3,ur=4,lr=5,hr=6,pr=7,mr=8,fr=9,gr=10,yr=11,vr=12,Ir=13,br=14,_r=15,Tr=16,Cr=17,Sr=18,Er=19,wr=20,Rr=1,Ar=2,Nr=3,Or=4,Mr=5,Ur=6,Lr=7,kr=8,Dr="Sorry, user register limit",Pr="Sorry, user register rate limit",xr="Sorry, token expired",Fr="Sorry, token or password does not match login info",Br="Sorry, user not found",Gr="Sorry, the app month live count limit",qr="Sorry, the app day live count limit",$r="Sorry, the app online count limit",jr={[ar]:ot.AUTH_UNAUTHORIZED,[cr]:ot.AUTH_UNAUTHORIZED,[dr]:ot.VALIDATION_REQUIRED,[ur]:ot.VALIDATION_INVALID_FORMAT,[lr]:ot.CONNECTION_WEBSOCKET_ERROR,[hr]:ot.AUTH_TOKEN_EXPIRED,[pr]:ot.AUTH_FORBIDDEN,[Er]:ot.AUTH_FORBIDDEN,[mr]:ot.CONNECTION_WEBSOCKET_ERROR,[fr]:ot.UNKNOWN,[gr]:ot.UNKNOWN,[yr]:ot.AUTH_BIND_ANOTHER_DEVICE,[vr]:ot.AUTH_FORBIDDEN,[Ir]:ot.AUTH_LOGIN_TOO_MANY_DEVICES,[br]:ot.SERVICE_LIMIT_EXCEEDED,[_r]:ot.AUTH_USER_MUTED,[Tr]:ot.UNKNOWN,[Cr]:ot.UNKNOWN,[Sr]:ot.MESSAGE_DECODE_FAILED,[wr]:ot.USER_DEVICE_CHANGED},Vr=new Set([ar,cr,dr,ur,hr,pr,Er,fr,gr,yr,vr,Ir,br,_r,Tr,Cr,Sr,wr]),Kr={[Dr]:ot.SERVICE_LIMIT_EXCEEDED,[Pr]:ot.SERVICE_LIMIT_EXCEEDED,[xr]:ot.AUTH_TOKEN_EXPIRED,[Fr]:ot.AUTH_UNAUTHORIZED,[Br]:ot.AUTH_UNAUTHORIZED,blocked:ot.MESSAGE_BLOCKED_BY_RECIPIENT,"group not found":ot.GROUP_NOT_EXIST,"illegal chatroom tag":ot.VALIDATION_REQUIRED,"not in group or chatroom":ot.GROUP_NOT_JOINED,"exceed recall time limit":ot.MESSAGE_RECALL_TIME_LIMIT,"message recall disabled":ot.SERVICE_NOT_ENABLED,"group ack not open":ot.SERVICE_NOT_ENABLED,"group ack msg permission denied":ot.GROUP_PERMISSION_DENIED,"the message has expired":ot.MESSAGE_EXPIRED,"limit send group ack msg":ot.SERVICE_LIMIT_EXCEEDED,"not in group or chatroom white list":ot.MESSAGE_ILLEGAL_WHITELIST,nonroster:ot.USER_NOT_ON_ROSTER,"group is disabled":ot.GROUP_DISABLED,"roaming is not open":ot.SERVICE_NOT_ENABLED,"Sorry, message does not exist":ot.VALIDATION_REQUIRED,"Sorry, edit limit reached":ot.SERVICE_LIMIT_EXCEEDED,"Sorry, You do not have permission":ot.AUTH_FORBIDDEN,"Sorry, format is incorrect":ot.VALIDATION_REQUIRED,"Sorry, edit is not available":ot.SERVER_SERVING_DISABLED,"Sorry, edit fail":ot.MESSAGE_EDIT_FAILED},zr=[["limit directed users",ot.SERVICE_LIMIT_EXCEEDED],["no permission to recall message",ot.AUTH_FORBIDDEN]],Hr={[Gr]:ot.SERVICE_LIMIT_EXCEEDED,[qr]:ot.SERVICE_LIMIT_EXCEEDED,[$r]:ot.SERVICE_LIMIT_EXCEEDED,"sensitive words":ot.MESSAGE_INCLUDE_ILLEGAL_CONTENT,"blocked by mod_antispam":ot.MESSAGE_INCLUDE_ILLEGAL_CONTENT,"user is mute":ot.USER_MUTED_BY_ADMIN,"traffic limit":ot.MESSAGE_CURRENT_LIMITING,"Sorry, data is too large":ot.MESSAGE_SIZE_LIMIT},Wr=(e,t)=>{if("number"!=typeof e)return{code:ot.UNKNOWN,retryable:!0};const r=((e,t)=>{if(t){if(e===ar){const e=Kr[t];if(void 0!==e)return e;for(const[r,s]of zr)if(t.includes(r))return s;try{const e=JSON.parse(t);if("moderation"===e.error_type)return ot.THIRD_MODERATION_FAILED;if("string"==typeof e.error_type)return ot.THIRD_DEFAULT_FAILED}catch{}return}return e===pr?Hr[t]:e===Er?ot.MESSAGE_EXTERNAL_LOGIC_BLOCKED:e===_r?ot.AUTH_USER_MUTED:void 0}})(e,t),s=jr[e]??ot.UNKNOWN;return{code:r??s,retryable:!Vr.has(e)}},Jr={[ot.SERVICE_LIMIT_EXCEEDED]:"Message operation exceeded a service limit",[ot.AUTH_TOKEN_EXPIRED]:"Message cannot be sent because the authentication token expired",[ot.VALIDATION_REQUIRED]:"Message cannot be sent because the request is invalid",[ot.AUTH_UNAUTHORIZED]:"Message cannot be sent because authentication failed",[ot.AUTH_FORBIDDEN]:"Message operation is forbidden",[ot.AUTH_BIND_ANOTHER_DEVICE]:"Message cannot be sent because the account is bound to another device",[ot.AUTH_LOGIN_TOO_MANY_DEVICES]:"Message cannot be sent because the account is logged in on too many devices",[ot.AUTH_USER_MUTED]:"Message cannot be sent because the user is muted in the group or chat room",[ot.MESSAGE_BLOCKED_BY_RECIPIENT]:"Message cannot be sent because you are blocked by the recipient",[ot.USER_MUTED_BY_ADMIN]:"Message cannot be sent because the user is globally muted",[ot.USER_DEVICE_CHANGED]:"Message cannot be sent because the current device has changed",[ot.USER_NOT_ON_ROSTER]:"Message cannot be sent because the recipient is not in your contact list",[ot.CONNECTION_WEBSOCKET_ERROR]:"Message cannot be sent because the server is unreachable",[ot.SERVER_SERVING_DISABLED]:"Message editing is not available",[ot.MESSAGE_DECODE_FAILED]:"Message processing failed",[ot.MESSAGE_INCLUDE_ILLEGAL_CONTENT]:"Message contains prohibited content",[ot.MESSAGE_SEND_TRAFFIC_LIMIT]:"Message sending traffic limit exceeded",[ot.MESSAGE_RECALL_TIME_LIMIT]:"The message recall time limit has been exceeded",[ot.SERVICE_NOT_ENABLED]:"The required messaging service is not enabled",[ot.MESSAGE_EXPIRED]:"The message has expired",[ot.MESSAGE_ILLEGAL_WHITELIST]:"The user is not in the group or chat room allowlist",[ot.MESSAGE_EXTERNAL_LOGIC_BLOCKED]:"The message was blocked by external logic",[ot.MESSAGE_CURRENT_LIMITING]:"Message sending rate limit exceeded",[ot.MESSAGE_SIZE_LIMIT]:"Message size exceeds the limit",[ot.MESSAGE_EDIT_FAILED]:"Message editing failed",[ot.GROUP_NOT_JOINED]:"The user is not in the group or chat room",[ot.GROUP_PERMISSION_DENIED]:"The user does not have permission to perform this group message operation",[ot.GROUP_NOT_EXIST]:"The group does not exist",[ot.GROUP_DISABLED]:"The group is disabled",[ot.THIRD_MODERATION_FAILED]:"The message was rejected by content moderation",[ot.THIRD_DEFAULT_FAILED]:"The message was rejected by a third-party service"},Qr=3e5,Zr=12e4,Yr=[1e3,2e3],Xr={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"},es=e=>"undefined"!=typeof Blob&&e instanceof Blob,ts=e=>{const t=e.replace(/[?#].*$/,"").split(/[\\/]/).filter(Boolean),r=t.length>0?t[t.length-1]:void 0;if(r)return r},rs=e=>{if(!e)return;const t=e.lastIndexOf(".");if(t<0||t===e.length-1)return;const r=e.slice(t+1).toLowerCase();return Xr[r]},ss=(e,t)=>{for(const r of t){const t=e[r];if("string"==typeof t&&t.length>0)return t}},ns=e=>{const t=e.file,r=e.sourceMeta,s=t.name||(r?ss(r,["name","fileName","filename"]):void 0),n=e.file.type||(r?ss(r,["type","mimeType","filetype"]):void 0),i=e.file.size||(r?((e,t)=>{for(const r of t){const t=e[r];if("number"==typeof t&&Number.isFinite(t))return t}})(r,["size","fileSize","fileLength"]):void 0),o=is({fileName:s,fileType:n,fileSize:i,fallbackName:e.fallbackName,fallbackMimeType:e.fallbackMimeType,fallbackSize:e.fallbackSize});return{source:{sourceType:"web-file",file:e.file,name:o.fileName,mimeType:o.fileType,size:o.fileSize},fileName:o.fileName,fileType:o.fileType,fileSize:o.fileSize,webFile:e.file}},is=e=>({fileName:e.fileName??e.fallbackName??"file",fileType:e.fileType??e.fallbackMimeType??"application/octet-stream",fileSize:e.fileSize??e.fallbackSize??0}),os=e=>{const{file:t,fallbackName:r,fallbackMimeType:s,fallbackSize:n}=e,i=(e=>{if(es(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(es(e))return e}})(t);if(i)return ns({file:i,fallbackName:r,fallbackMimeType:s,fallbackSize:n,sourceMeta:"object"==typeof t&&null!==t?t:void 0});if((e=>"object"==typeof e&&null!==e&&"path"in e)(t)){const e=ts(t.path),i=is({fileName:t.name??e,fileType:t.type??rs(t.name??e),fileSize:t.size,fallbackName:r,fallbackMimeType:s,fallbackSize:n});return{source:{sourceType:"miniapp-path",path:t.path,name:i.fileName,mimeType:i.fileType,size:i.fileSize},fileName:i.fileName,fileType:i.fileType,fileSize:i.fileSize}}if((e=>"object"==typeof e&&null!==e&&"uri"in e)(t)){const e=ts(t.uri),i=is({fileName:t.name??e,fileType:t.type??rs(t.name??e),fileSize:t.size,fallbackName:r,fallbackMimeType:s,fallbackSize:n});return{source:{sourceType:"rn-uri",uri:t.uri,name:i.fileName,mimeType:i.fileType,size:i.fileSize},fileName:i.fileName,fileType:i.fileType,fileSize:i.fileSize}}const o=is({fallbackName:r,fallbackMimeType:s,fallbackSize:n});return{source:{sourceType:"web-file",name:o.fileName,mimeType:o.fileType,size:o.fileSize},fileName:o.fileName,fileType:o.fileType,fileSize:o.fileSize}},as=5242880,cs=5242880,ds="CHAT",us="GROUP",ls="ROOM",hs="original",ps="large",ms=e=>/^https?:\/\//i.test(e),fs=e=>{const t=e.split("#");if(2!==t.length||!t[0]||!t[1])throw new bt("Invalid appKey for upload",{code:ot.UPLOAD_INVALID_APPKEY,details:{appKey:e}});return{orgName:t[0],appName:t[1]}},gs=e=>"singleChat"===e?ds:"groupChat"===e?us:ls,ys=(e,t)=>Is(e,{size:t}),vs=e=>{try{return decodeURIComponent(e)}catch{return e}},Is=(e,t)=>{const[r="",s]=e.split("#",2),[n,i=""]=r.split("?",2),o=i.split("&").filter(Boolean);return Object.entries(t).forEach(([e,t])=>{const r=encodeURIComponent(e),s=o.filter(t=>{const[s=""]=t.split("=",2);return s!==r&&vs(s)!==e});o.length=0,o.push(...s),void 0!==t&&o.push(`${r}=${encodeURIComponent(String(t))}`)}),`${n}${o.length>0?`?${o.join("&")}`:""}${s?`#${s}`:""}`},bs=(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:Is(e,r)},_s=e=>{const t=(r=e.messageType,s=e.imageType,"image"!==r?"attachment":s===hs?"image-origin":"image-big");var r,s;const n=(e=>"image-origin"===e?204800:1048576)(t),i=e.fileSize>n;return{shouldPrecheck:i,thresholdType:t,thresholdBytes:n,actualBytes:e.fileSize,reason:i?"threshold-exceeded":"below-threshold"}},Ts=(e,t)=>{if(!e)return{};if(!1===t?.deriveVariants)return{originalImageUrl:e};const r=(e=>{const[t="",r]=e.split("#",2),[s,n=""]=t.split("?",2),i=n.split("&").filter(Boolean).filter(e=>{const[t="",r=""]=e.split("=",2),s=vs(t),n=vs(r);return"size"!==s||!["big","large","thumbnail","small"].includes(n)}).join("&");return`${s}${i?`?${i}`:""}${r?`#${r}`:""}`})(e);return{originalImageUrl:r,bigImageUrl:ys(r,"large"),thumbnailUrl:ys(r,"small")}},Cs=e=>e===hs?"origin":"large",Ss=e=>2===e?ps:hs,Es=e=>{const t=e.response.entities?.[0];if(!t?.uuid)throw new bt("Upload response missing uuid",{code:ot.UPLOAD_REQUEST_FAILED,details:{response:e.response}});const r=t["share-secret"],s=t["file-metadata"]??{},n="number"==typeof s["content-length"]?s["content-length"]:e.fallbackSize,i="string"==typeof s["content-type"]?s["content-type"]:e.fileType,o=`${e.restBaseUrl}/${e.orgName}/${e.appName}/chatfiles/${t.uuid}`;if("image"===e.messageType){const t=(e.imageType??ps)===hs;return{...Ts(o,{deriveVariants:!e.useCustomAttachmentUpload}),isOriginalImage:t,secret:r,fileLength:n,filetype:i,filename:e.fileName,width:e.width,height:e.height}}const a="video"===e.messageType?`${o}?vframe=true`:void 0;return{url:o,secret:r,fileLength:n,filetype:i,filename:e.fileName,thumbnailUrl:a}},ws=e=>new Promise(t=>{setTimeout(t,e)});const Rs=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 ws(this.chunkDelayMs)}}finally{this.reporting=!1}}}async reportChunk(e){if(!this.canReport())return!1;const{restBaseUrl:t,appKey:r,userId:s,token:n,resource:i,requestAdapter:o}=this.context;if(!(t&&r&&s&&n&&o))return!1;let a="",c="";try{const e=fs(r);a=e.orgName,c=e.appName}catch{return!1}const d=`${t}/${a}/${c}/sdk/users/${s}/client/logs`,u={resource:i??"webim",logContent:e};try{const e=await o.request({url:d,method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json",Accept:"application/json"},body:u,responseType:"json",timeoutMs:this.reportTimeoutMs});if(e.status<200||e.status>=300)return!1;const t="string"==typeof e.data?(e=>{try{return JSON.parse(e)}catch{return}})(e.data):e.data;return!t||!t.status||"ok"===t.status}catch{return!1}}},As="[MASKED]",Ns=new Set(["token","password","authorization","appkey","userid","deviceid","accesstoken","refreshtoken","secret","authtoken","sessionid","clientresource"]),Os=e=>!!e&&Ns.has((e=>e.toLowerCase())(e)),Ms=(e,t,r)=>{const s=r??new WeakSet;if("string"==typeof e)return((e,t)=>Os(t)?As: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=>Ms(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))Os(r)?t[r]=As:t[r]=Ms(n,r,s);return t}return Object.prototype.toString.call(e)}return"[Unsupported]"},Us="undefined"!=typeof document;let Ls=null,Ds=!1;const Ps={DEBUG:0,WARN:1,ERROR:2};class xs{constructor(e="WARN"){this.consoleEnabled=!0,this.level=e}setLevel(e){this.level=e}setConsoleEnabled(e){this.consoleEnabled=e}shouldLog(e){return Ps[e]>=Ps[this.level]}emit(e,t,r){const s=(e=>{const t=new WeakSet;return e.map(e=>Ms(e,void 0,t))})(r),n=((e,t,r)=>({timestamp:(new Date).toISOString(),level:e,message:t,args:r}))(e,t,s);if(Rs.append(n),this.consoleEnabled){const r=new Date,n=`[Chat][${e}][${`${String(r.getHours()).padStart(2,"0")}:${String(r.getMinutes()).padStart(2,"0")}:${String(r.getSeconds()).padStart(2,"0")}.${String(r.getMilliseconds()).padStart(3,"0")}`}]`;Us?console.log(`%c${n}`,"color: rgb(0, 157, 255); font-weight: bold",t,...s):console.log(n,t,...s)}const i=Ls;i&&!Ds&&Promise.resolve().then(()=>{if(i===Ls){Ds=!0;try{i(n)}catch{}finally{Ds=!1}}})}debug(e,...t){this.shouldLog("DEBUG")&&this.emit("DEBUG",e,t)}warn(e,...t){this.shouldLog("WARN")&&this.emit("WARN",e,t)}error(e,...t){this.shouldLog("ERROR")&&this.emit("ERROR",e,t)}}let Fs=new xs;function Bs(e){Rs.setState(e)}function Gs(e){Rs.updateContext(e)}async function qs(){await Rs.reportNow()}function $s(){Rs.stop()}const js=(e,...t)=>Fs.debug(e,...t),Vs=(e,...t)=>Fs.warn(e,...t),Ks=(e,...t)=>Fs.error(e,...t),zs=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)},Hs=e=>{if("function"==typeof TextDecoder)return(new TextDecoder).decode(e);let t="";for(let r=0;r<e.length;r+=1){const s=e[r]??0;if(s<128){t+=String.fromCharCode(s);continue}if(s>=192&&s<224){const n=e[r+1]??0;t+=String.fromCharCode((31&s)<<6|63&n),r+=1;continue}if(s>=224&&s<240){const n=e[r+1]??0,i=e[r+2]??0;t+=String.fromCharCode((15&s)<<12|(63&n)<<6|63&i),r+=2;continue}const n=((7&s)<<18|(63&(e[r+1]??0))<<12|(63&(e[r+2]??0))<<6|63&(e[r+3]??0))-65536;t+=String.fromCharCode(55296+(n>>10),56320+(1023&n)),r+=3}return t};class Ws{constructor(){this.lastEventKey=null}normalize(e,u){const l=(e=>{switch(e){case r:case n:return o;case s:return a;case t:return c;case i:return d;default:return null}})(e);if(!l)return null;const h=((e,t)=>[e,t.state,t.reason,String(t.attempt),String(t.maxAttempts),String(t.isLoginPhase),String(t.isOnline),String(t.errorCode??""),t.errorMessage??""].join("|"))(l,u);return this.lastEventKey===h?null:(this.lastEventKey=h,{eventName:l,payload:u})}reset(){this.lastEventKey=null}}const Js={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"},Qs="init",Zs="request",Ys="upload",Xs="socket",en="proto",tn="runtime",rn="PLATFORM_INIT_FAILED",sn="PLATFORM_MISSING_CAPABILITY",nn="PLATFORM_REQUEST_FAILED",on="PLATFORM_UPLOAD_FAILED",an="PLATFORM_SOCKET_FAILED",cn="PLATFORM_PROTO_FAILED",dn=(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=dt(t.details)),r},un=0,ln=1,hn=2,pn=3,mn=["__uniConfig","skipWaiting","registration","navigator","process","window","document","localStorage","fetch","WebSocket","XMLHttpRequest","FormData","TextEncoder","TextDecoder","crypto"],fn=e=>{if(e)return e;return((e,t)=>{if(!e)return t;if(0===Object.keys(t).length)return e;const r={},s=e;for(const n of mn)try{const e=s[n];void 0!==e&&(r[n]=e)}catch{}for(const n of Object.keys(t))r[n]=t[n];return r})("undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:"undefined"!=typeof global?global:void 0,{..."undefined"!=typeof wx?{wx:wx}:{},..."undefined"!=typeof qq?{qq:qq}:{},..."undefined"!=typeof tt?{tt:tt}:{},..."undefined"!=typeof swan?{swan:swan}:{},..."undefined"!=typeof my?{my:my}:{},..."undefined"!=typeof dd?{dd:dd}:{},..."undefined"!=typeof jd?{jd:jd}:{},..."undefined"!=typeof ks?{ks:ks}:{},..."undefined"!=typeof uni?{uni:uni}:{}})},gn={web:Js.WEB,"mp-weixin":Js.WECHAT_MINIAPP,"mp-alipay":Js.ALIPAY_MINIAPP,"mp-baidu":Js.BAIDU_MINIAPP,"mp-toutiao":Js.TOUTIAO_MINIAPP,"mp-lark":Js.LARK_MINIAPP,"mp-qq":Js.QQ_MINIAPP,"mp-kuaishou":Js.KUAISHOU_MINIAPP,"mp-jd":Js.JD_MINIAPP,"mp-360":Js.MINIAPP_360,"mp-harmony":Js.HARMONY_MINIAPP,"quickapp-webview":Js.QUICKAPP,"quickapp-webview-union":Js.QUICKAPP,"quickapp-webview-huawei":Js.QUICKAPP},yn=(e,t)=>{if("object"!=typeof e&&"function"!=typeof e||null===e)return!1;return"function"==typeof e[t]},vn=e=>(e=>yn(e,"canIUse")&&yn(e,"getSystemInfo"))(e)||(e=>yn(e,"request")&&yn(e,"connectSocket"))(e),In=e=>yn(e,"request")&&yn(e,"connectSocket")&&yn(e,"uploadFile"),bn=(e,t)=>t===Js.WECHAT_MINIAPP?e.wx:t===Js.QQ_MINIAPP?e.qq:t===Js.TOUTIAO_MINIAPP?e.tt:t===Js.BAIDU_MINIAPP?e.swan:t===Js.ALIPAY_MINIAPP?e.my:t===Js.DINGTALK_MINIAPP?e.dd:t===Js.JD_MINIAPP?e.jd:t===Js.KUAISHOU_MINIAPP?e.ks:t===Js.UNIAPP?e.uni:void 0,_n=e=>{const t=e?.miniGlobal;return vn(t)?t:e},Tn=e=>{const t=_n(e);return In(t)?t:void 0},Cn=e=>void 0!==e.window&&void 0!==e.document,Sn=e=>!(void 0!==e.window||void 0!==e.document)&&"function"==typeof e.fetch&&("function"==typeof e.skipWaiting||void 0!==e.registration),En=e=>{const t=e.uni;if(void 0!==e.__uniConfig)return!0;if(vn(t))return!0;try{if(!yn(t,"getSystemInfoSync"))return!1;const e=t.getSystemInfoSync();return"object"==typeof e&&null!==e&&"string"==typeof e.uniPlatform}catch{return!1}},wn=e=>In(e.wx)?Js.WECHAT_MINIAPP:In(e.my)?Js.ALIPAY_MINIAPP:In(e.dd)?Js.DINGTALK_MINIAPP:In(e.swan)?Js.BAIDU_MINIAPP:In(e.tt)?Js.TOUTIAO_MINIAPP:In(e.qq)?Js.QQ_MINIAPP:In(e.jd)?Js.JD_MINIAPP:In(e.ks)?Js.KUAISHOU_MINIAPP:void 0,Rn=e=>void 0!==wn(e),An=e=>{const t=wn(e);if(t)return t;try{const t=e.uni?.getSystemInfoSync?.(),r=t?.uniPlatform;if("string"==typeof r)return gn[r]??Js.UNIAPP}catch{return Js.UNIAPP}return Cn(e)?Js.WEB:Js.UNIAPP},Nn=(e,t)=>{const r=Tn(bn(e,t));if(r)return r;const s=Tn(e.uni);return s||(e.uni??e)},On=(e,t)=>{const r=e??fn();if(t){const e=t===Js.UNIAPP||En(r),s=e?An(r):t;return{platform:t,hostPlatform:s,framework:e?"uniapp":Cn(r)?"web":"native",global:e?Nn(r,s):_n(bn(r,t))??r}}if(En(r)){const e=An(r);return{platform:Js.UNIAPP,hostPlatform:e,framework:"uniapp",global:Nn(r,e)}}return vn(r.swan)?{platform:Js.BAIDU_MINIAPP,hostPlatform:Js.BAIDU_MINIAPP,framework:"native",global:_n(r.swan)??r.swan}:vn(r.tt)?{platform:Js.TOUTIAO_MINIAPP,hostPlatform:Js.TOUTIAO_MINIAPP,framework:"native",global:_n(r.tt)??r.tt}:vn(r.dd)?{platform:Js.DINGTALK_MINIAPP,hostPlatform:Js.DINGTALK_MINIAPP,framework:"native",global:_n(r.dd)??r.dd}:vn(r.my)?{platform:Js.ALIPAY_MINIAPP,hostPlatform:Js.ALIPAY_MINIAPP,framework:"native",global:_n(r.my)??r.my}:vn(r.wx)?{platform:Js.WECHAT_MINIAPP,hostPlatform:Js.WECHAT_MINIAPP,framework:"native",global:_n(r.wx)??r.wx}:vn(r.qq)?{platform:Js.QQ_MINIAPP,hostPlatform:Js.QQ_MINIAPP,framework:"native",global:_n(r.qq)??r.qq}:vn(r.jd)?{platform:Js.JD_MINIAPP,hostPlatform:Js.JD_MINIAPP,framework:"native",global:_n(r.jd)??r.jd}:vn(r.ks)?{platform:Js.KUAISHOU_MINIAPP,hostPlatform:Js.KUAISHOU_MINIAPP,framework:"native",global:_n(r.ks)??r.ks}:(e=>"ReactNative"===e.navigator?.product)(r)?{platform:Js.REACT_NATIVE,hostPlatform:Js.REACT_NATIVE,framework:"react-native",global:r}:(e=>"string"==typeof e.process?.versions?.electron)(r)?{platform:Cn(r)?Js.ELECTRON_RENDERER:Js.ELECTRON_MAIN,hostPlatform:Cn(r)?Js.ELECTRON_RENDERER:Js.ELECTRON_MAIN,framework:"electron",global:r}:Sn(r)||Cn(r)?{platform:Js.WEB,hostPlatform:Js.WEB,framework:Sn(r)?"worker":"web",global:r}:{platform:Js.UNKNOWN,hostPlatform:Js.UNKNOWN,framework:"native",global:r}},Mn=e=>e===Js.WECHAT_MINIAPP||e===Js.QQ_MINIAPP||e===Js.TOUTIAO_MINIAPP||e===Js.BAIDU_MINIAPP||e===Js.ALIPAY_MINIAPP||e===Js.DINGTALK_MINIAPP||e===Js.LARK_MINIAPP||e===Js.KUAISHOU_MINIAPP||e===Js.JD_MINIAPP||e===Js.MINIAPP_360||e===Js.HARMONY_MINIAPP||e===Js.QUICKAPP||e===Js.UNIAPP,Un=["request","upload","socket","proto"],Ln=(e,t=Un)=>{const r=((e,t=Un)=>t.filter(t=>!e[t]))(e,t);if(0!==r.length)throw dn("Platform missing required capabilities.",{code:sn,stage:Qs,retryable:!1,details:{required:[...t],missing:r}})};var kn=null;try{kn=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 Dn(e,t,r){this.low=0|e,this.high=0|t,this.unsigned=!!r}function Pn(e){return!0===(e&&e.__isLong__)}function xn(e){var t=Math.clz32(e&-e);return e?31-t:t}Dn.prototype.__isLong__,Object.defineProperty(Dn.prototype,"__isLong__",{value:!0}),Dn.isLong=Pn;var Fn={},Bn={};function Gn(e,t){var r,s,n;return t?(n=0<=(e>>>=0)&&e<256)&&(s=Bn[e])?s:(r=$n(e,0,!0),n&&(Bn[e]=r),r):(n=-128<=(e|=0)&&e<128)&&(s=Fn[e])?s:(r=$n(e,e<0?-1:0,!1),n&&(Fn[e]=r),r)}function qn(e,t){if(isNaN(e))return t?Zn:Qn;if(t){if(e<0)return Zn;if(e>=Hn)return ri}else{if(e<=-Wn)return si;if(e+1>=Wn)return ti}return e<0?qn(-e,t).neg():$n(e%zn|0,e/zn|0,t)}function $n(e,t,r){return new Dn(e,t,r)}Dn.fromInt=Gn,Dn.fromNumber=qn,Dn.fromBits=$n;var jn=Math.pow;function Vn(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?Zn:Qn;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 Vn(e.substring(1),t,r).neg();for(var n=qn(jn(r,8)),i=Qn,o=0;o<e.length;o+=8){var a=Math.min(8,e.length-o),c=parseInt(e.substring(o,o+a),r);if(a<8){var d=qn(jn(r,a));i=i.mul(d).add(qn(c))}else i=(i=i.mul(n)).add(qn(c))}return i.unsigned=t,i}function Kn(e,t){return"number"==typeof e?qn(e,t):"string"==typeof e?Vn(e,t):$n(e.low,e.high,"boolean"==typeof t?t:e.unsigned)}Dn.fromString=Vn,Dn.fromValue=Kn;var zn=4294967296,Hn=zn*zn,Wn=Hn/2,Jn=Gn(1<<24),Qn=Gn(0);Dn.ZERO=Qn;var Zn=Gn(0,!0);Dn.UZERO=Zn;var Yn=Gn(1);Dn.ONE=Yn;var Xn=Gn(1,!0);Dn.UONE=Xn;var ei=Gn(-1);Dn.NEG_ONE=ei;var ti=$n(-1,2147483647,!1);Dn.MAX_VALUE=ti;var ri=$n(-1,-1,!0);Dn.MAX_UNSIGNED_VALUE=ri;var si=$n(0,-2147483648,!1);Dn.MIN_VALUE=si;var ni=Dn.prototype;ni.toInt=function(){return this.unsigned?this.low>>>0:this.low},ni.toNumber=function(){return this.unsigned?(this.high>>>0)*zn+(this.low>>>0):this.high*zn+(this.low>>>0)},ni.toString=function(e){if((e=e||10)<2||36<e)throw RangeError("radix");if(this.isZero())return"0";if(this.isNegative()){if(this.eq(si)){var t=qn(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=qn(jn(e,6),this.unsigned),i=this,o="";;){var a=i.div(n),c=(i.sub(a.mul(n)).toInt()>>>0).toString(e);if((i=a).isZero())return c+o;for(;c.length<6;)c="0"+c;o=""+c+o}},ni.getHighBits=function(){return this.high},ni.getHighBitsUnsigned=function(){return this.high>>>0},ni.getLowBits=function(){return this.low},ni.getLowBitsUnsigned=function(){return this.low>>>0},ni.getNumBitsAbs=function(){if(this.isNegative())return this.eq(si)?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},ni.isSafeInteger=function(){var e=this.high>>21;return!e||!this.unsigned&&(-1===e&&!(0===this.low&&-2097152===this.high))},ni.isZero=function(){return 0===this.high&&0===this.low},ni.eqz=ni.isZero,ni.isNegative=function(){return!this.unsigned&&this.high<0},ni.isPositive=function(){return this.unsigned||this.high>=0},ni.isOdd=function(){return!(1&~this.low)},ni.isEven=function(){return!(1&this.low)},ni.equals=function(e){return Pn(e)||(e=Kn(e)),(this.unsigned===e.unsigned||this.high>>>31!=1||e.high>>>31!=1)&&(this.high===e.high&&this.low===e.low)},ni.eq=ni.equals,ni.notEquals=function(e){return!this.eq(e)},ni.neq=ni.notEquals,ni.ne=ni.notEquals,ni.lessThan=function(e){return this.comp(e)<0},ni.lt=ni.lessThan,ni.lessThanOrEqual=function(e){return this.comp(e)<=0},ni.lte=ni.lessThanOrEqual,ni.le=ni.lessThanOrEqual,ni.greaterThan=function(e){return this.comp(e)>0},ni.gt=ni.greaterThan,ni.greaterThanOrEqual=function(e){return this.comp(e)>=0},ni.gte=ni.greaterThanOrEqual,ni.ge=ni.greaterThanOrEqual,ni.compare=function(e){if(Pn(e)||(e=Kn(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},ni.comp=ni.compare,ni.negate=function(){return!this.unsigned&&this.eq(si)?si:this.not().add(Yn)},ni.neg=ni.negate,ni.add=function(e){Pn(e)||(e=Kn(e));var t=this.high>>>16,r=65535&this.high,s=this.low>>>16,n=65535&this.low,i=e.high>>>16,o=65535&e.high,a=e.low>>>16,c=0,d=0,u=0,l=0;return u+=(l+=n+(65535&e.low))>>>16,d+=(u+=s+a)>>>16,c+=(d+=r+o)>>>16,c+=t+i,$n((u&=65535)<<16|(l&=65535),(c&=65535)<<16|(d&=65535),this.unsigned)},ni.subtract=function(e){return Pn(e)||(e=Kn(e)),this.add(e.neg())},ni.sub=ni.subtract,ni.multiply=function(e){if(this.isZero())return this;if(Pn(e)||(e=Kn(e)),kn)return $n(kn.mul(this.low,this.high,e.low,e.high),kn.get_high(),this.unsigned);if(e.isZero())return this.unsigned?Zn:Qn;if(this.eq(si))return e.isOdd()?si:Qn;if(e.eq(si))return this.isOdd()?si:Qn;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(Jn)&&e.lt(Jn))return qn(this.toNumber()*e.toNumber(),this.unsigned);var t=this.high>>>16,r=65535&this.high,s=this.low>>>16,n=65535&this.low,i=e.high>>>16,o=65535&e.high,a=e.low>>>16,c=65535&e.low,d=0,u=0,l=0,h=0;return l+=(h+=n*c)>>>16,u+=(l+=s*c)>>>16,l&=65535,u+=(l+=n*a)>>>16,d+=(u+=r*c)>>>16,u&=65535,d+=(u+=s*a)>>>16,u&=65535,d+=(u+=n*o)>>>16,d+=t*c+r*a+s*o+n*i,$n((l&=65535)<<16|(h&=65535),(d&=65535)<<16|(u&=65535),this.unsigned)},ni.mul=ni.multiply,ni.divide=function(e){if(Pn(e)||(e=Kn(e)),e.isZero())throw Error("division by zero");var t,r,s;if(kn)return this.unsigned||-2147483648!==this.high||-1!==e.low||-1!==e.high?$n((this.unsigned?kn.div_u:kn.div_s)(this.low,this.high,e.low,e.high),kn.get_high(),this.unsigned):this;if(this.isZero())return this.unsigned?Zn:Qn;if(this.unsigned){if(e.unsigned||(e=e.toUnsigned()),e.gt(this))return Zn;if(e.gt(this.shru(1)))return Xn;s=Zn}else{if(this.eq(si))return e.eq(Yn)||e.eq(ei)?si:e.eq(si)?Yn:(t=this.shr(1).div(e).shl(1)).eq(Qn)?e.isNegative()?Yn:ei:(r=this.sub(e.mul(t)),s=t.add(r.div(e)));if(e.eq(si))return this.unsigned?Zn:Qn;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=Qn}for(r=this;r.gte(e);){t=Math.max(1,Math.floor(r.toNumber()/e.toNumber()));for(var n=Math.ceil(Math.log(t)/Math.LN2),i=n<=48?1:jn(2,n-48),o=qn(t),a=o.mul(e);a.isNegative()||a.gt(r);)a=(o=qn(t-=i,this.unsigned)).mul(e);o.isZero()&&(o=Yn),s=s.add(o),r=r.sub(a)}return s},ni.div=ni.divide,ni.modulo=function(e){return Pn(e)||(e=Kn(e)),kn?$n((this.unsigned?kn.rem_u:kn.rem_s)(this.low,this.high,e.low,e.high),kn.get_high(),this.unsigned):this.sub(this.div(e).mul(e))},ni.mod=ni.modulo,ni.rem=ni.modulo,ni.not=function(){return $n(~this.low,~this.high,this.unsigned)},ni.countLeadingZeros=function(){return this.high?Math.clz32(this.high):Math.clz32(this.low)+32},ni.clz=ni.countLeadingZeros,ni.countTrailingZeros=function(){return this.low?xn(this.low):xn(this.high)+32},ni.ctz=ni.countTrailingZeros,ni.and=function(e){return Pn(e)||(e=Kn(e)),$n(this.low&e.low,this.high&e.high,this.unsigned)},ni.or=function(e){return Pn(e)||(e=Kn(e)),$n(this.low|e.low,this.high|e.high,this.unsigned)},ni.xor=function(e){return Pn(e)||(e=Kn(e)),$n(this.low^e.low,this.high^e.high,this.unsigned)},ni.shiftLeft=function(e){return Pn(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?$n(this.low<<e,this.high<<e|this.low>>>32-e,this.unsigned):$n(0,this.low<<e-32,this.unsigned)},ni.shl=ni.shiftLeft,ni.shiftRight=function(e){return Pn(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?$n(this.low>>>e|this.high<<32-e,this.high>>e,this.unsigned):$n(this.high>>e-32,this.high>=0?0:-1,this.unsigned)},ni.shr=ni.shiftRight,ni.shiftRightUnsigned=function(e){return Pn(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?$n(this.low>>>e|this.high<<32-e,this.high>>>e,this.unsigned):$n(32===e?this.high:this.high>>>e-32,0,this.unsigned)},ni.shru=ni.shiftRightUnsigned,ni.shr_u=ni.shiftRightUnsigned,ni.rotateLeft=function(e){var t;return Pn(e)&&(e=e.toInt()),0==(e&=63)?this:32===e?$n(this.high,this.low,this.unsigned):e<32?(t=32-e,$n(this.low<<e|this.high>>>t,this.high<<e|this.low>>>t,this.unsigned)):(t=32-(e-=32),$n(this.high<<e|this.low>>>t,this.low<<e|this.high>>>t,this.unsigned))},ni.rotl=ni.rotateLeft,ni.rotateRight=function(e){var t;return Pn(e)&&(e=e.toInt()),0==(e&=63)?this:32===e?$n(this.high,this.low,this.unsigned):e<32?(t=32-e,$n(this.high<<t|this.low>>>e,this.low<<t|this.high>>>e,this.unsigned)):(t=32-(e-=32),$n(this.low<<t|this.high>>>e,this.high<<t|this.low>>>e,this.unsigned))},ni.rotr=ni.rotateRight,ni.toSigned=function(){return this.unsigned?$n(this.low,this.high,!1):this},ni.toUnsigned=function(){return this.unsigned?this:$n(this.low,this.high,!0)},ni.toBytes=function(e){return e?this.toBytesLE():this.toBytesBE()},ni.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]},ni.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]},Dn.fromBytes=function(e,t,r){return r?Dn.fromBytesLE(e,t):Dn.fromBytesBE(e,t)},Dn.fromBytesLE=function(e,t){return new Dn(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24,t)},Dn.fromBytesBE=function(e,t){return new Dn(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&&(Dn.fromBigInt=function(e,t){return $n(Number(BigInt.asIntN(32,e)),Number(BigInt.asIntN(32,e>>BigInt(32))),t)},Dn.fromValue=function(e,t){return"bigint"==typeof e?Dn.fromBigInt(e,t):Kn(e,t)},ni.toBigInt=function(){var e=BigInt(this.low>>>0);return BigInt(this.unsigned?this.high>>>0:this.high)<<BigInt(32)|e});var ii="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function oi(e){if(Object.prototype.hasOwnProperty.call(e,"__esModule"))return e;var t=e.default;if("function"==typeof t){var r=function e(){var r=!1;try{r=this instanceof e}catch{}return r?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};r.prototype=t.prototype}else r={};return Object.defineProperty(r,"__esModule",{value:!0}),Object.keys(e).forEach(function(t){var s=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(r,t,s.get?s:{enumerable:!0,get:function(){return e[t]}})}),r}var ai,ci,di={exports:{}},ui={},li={};function hi(){if(ci)return ai;return ci=1,ai=function(e,t){var r=new Array(arguments.length-1),s=0,n=2,i=!0;for(;n<arguments.length;)r[s++]=arguments[n++];return new Promise(function(n,o){r[s]=function(e){if(i)if(i=!1,e)o(e);else{for(var t=new Array(arguments.length-1),r=0;r<t.length;)t[r++]=arguments[r];n.apply(null,t)}};try{e.apply(t||null,r)}catch(a){i&&(i=!1,o(a))}})},ai}var pi,mi,fi,gi,yi,vi={};var Ii,bi,_i,Ti,Ci,Si={};var Ei,wi,Ri,Ai,Ni,Oi,Mi,Ui,Li,ki,Di={exports:{}};Di.exports;function Pi(){return Ei||(Ei=1,e=Di,t=Di.exports,"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self&&self,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var t=null;try{t=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch{}function r(e,t,r){this.low=0|e,this.high=0|t,this.unsigned=!!r}function s(e){return!0===(e&&e.__isLong__)}function n(e){var t=Math.clz32(e&-e);return e?31-t:t}r.prototype.__isLong__,Object.defineProperty(r.prototype,"__isLong__",{value:!0}),r.isLong=s;var i={},o={};function a(e,t){var r,s,n;return t?(n=0<=(e>>>=0)&&e<256)&&(s=o[e])?s:(r=d(e,0,!0),n&&(o[e]=r),r):(n=-128<=(e|=0)&&e<128)&&(s=i[e])?s:(r=d(e,e<0?-1:0,!1),n&&(i[e]=r),r)}function c(e,t){if(isNaN(e))return t?I:v;if(t){if(e<0)return I;if(e>=f)return S}else{if(e<=-g)return E;if(e+1>=g)return C}return e<0?c(-e,t).neg():d(e%m|0,e/m|0,t)}function d(e,t,s){return new r(e,t,s)}r.fromInt=a,r.fromNumber=c,r.fromBits=d;var u=Math.pow;function l(e,t,r){if(0===e.length)throw Error("empty string");if("number"==typeof t?(r=t,t=!1):t=!!t,"NaN"===e||"Infinity"===e||"+Infinity"===e||"-Infinity"===e)return t?I:v;if((r=r||10)<2||36<r)throw RangeError("radix");var s;if((s=e.indexOf("-"))>0)throw Error("interior hyphen");if(0===s)return l(e.substring(1),t,r).neg();for(var n=c(u(r,8)),i=v,o=0;o<e.length;o+=8){var a=Math.min(8,e.length-o),d=parseInt(e.substring(o,o+a),r);if(a<8){var h=c(u(r,a));i=i.mul(h).add(c(d))}else i=(i=i.mul(n)).add(c(d))}return i.unsigned=t,i}function h(e,t){return"number"==typeof e?c(e,t):"string"==typeof e?l(e,t):d(e.low,e.high,"boolean"==typeof t?t:e.unsigned)}r.fromString=l,r.fromValue=h;var p=65536,m=p*p,f=m*m,g=f/2,y=a(1<<24),v=a(0);r.ZERO=v;var I=a(0,!0);r.UZERO=I;var b=a(1);r.ONE=b;var _=a(1,!0);r.UONE=_;var T=a(-1);r.NEG_ONE=T;var C=d(-1,2147483647,!1);r.MAX_VALUE=C;var S=d(-1,-1,!0);r.MAX_UNSIGNED_VALUE=S;var E=d(0,-2147483648,!1);r.MIN_VALUE=E;var w=r.prototype;w.toInt=function(){return this.unsigned?this.low>>>0:this.low},w.toNumber=function(){return this.unsigned?(this.high>>>0)*m+(this.low>>>0):this.high*m+(this.low>>>0)},w.toString=function(e){if((e=e||10)<2||36<e)throw RangeError("radix");if(this.isZero())return"0";if(this.isNegative()){if(this.eq(E)){var t=c(e),r=this.div(t),s=r.mul(t).sub(this);return r.toString(e)+s.toInt().toString(e)}return"-"+this.neg().toString(e)}for(var n=c(u(e,6),this.unsigned),i=this,o="";;){var a=i.div(n),d=(i.sub(a.mul(n)).toInt()>>>0).toString(e);if((i=a).isZero())return d+o;for(;d.length<6;)d="0"+d;o=""+d+o}},w.getHighBits=function(){return this.high},w.getHighBitsUnsigned=function(){return this.high>>>0},w.getLowBits=function(){return this.low},w.getLowBitsUnsigned=function(){return this.low>>>0},w.getNumBitsAbs=function(){if(this.isNegative())return this.eq(E)?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},w.isSafeInteger=function(){var e=this.high>>21;return!e||!this.unsigned&&-1===e&&!(0===this.low&&-2097152===this.high)},w.isZero=function(){return 0===this.high&&0===this.low},w.eqz=w.isZero,w.isNegative=function(){return!this.unsigned&&this.high<0},w.isPositive=function(){return this.unsigned||this.high>=0},w.isOdd=function(){return!(1&~this.low)},w.isEven=function(){return!(1&this.low)},w.equals=function(e){return s(e)||(e=h(e)),(this.unsigned===e.unsigned||this.high>>>31!=1||e.high>>>31!=1)&&this.high===e.high&&this.low===e.low},w.eq=w.equals,w.notEquals=function(e){return!this.eq(e)},w.neq=w.notEquals,w.ne=w.notEquals,w.lessThan=function(e){return this.comp(e)<0},w.lt=w.lessThan,w.lessThanOrEqual=function(e){return this.comp(e)<=0},w.lte=w.lessThanOrEqual,w.le=w.lessThanOrEqual,w.greaterThan=function(e){return this.comp(e)>0},w.gt=w.greaterThan,w.greaterThanOrEqual=function(e){return this.comp(e)>=0},w.gte=w.greaterThanOrEqual,w.ge=w.greaterThanOrEqual,w.compare=function(e){if(s(e)||(e=h(e)),this.eq(e))return 0;var t=this.isNegative(),r=e.isNegative();return t&&!r?-1:!t&&r?1:this.unsigned?e.high>>>0>this.high>>>0||e.high===this.high&&e.low>>>0>this.low>>>0?-1:1:this.sub(e).isNegative()?-1:1},w.comp=w.compare,w.negate=function(){return!this.unsigned&&this.eq(E)?E:this.not().add(b)},w.neg=w.negate,w.add=function(e){s(e)||(e=h(e));var t=this.high>>>16,r=65535&this.high,n=this.low>>>16,i=65535&this.low,o=e.high>>>16,a=65535&e.high,c=e.low>>>16,u=0,l=0,p=0,m=0;return p+=(m+=i+(65535&e.low))>>>16,l+=(p+=n+c)>>>16,u+=(l+=r+a)>>>16,u+=t+o,d((p&=65535)<<16|(m&=65535),(u&=65535)<<16|(l&=65535),this.unsigned)},w.subtract=function(e){return s(e)||(e=h(e)),this.add(e.neg())},w.sub=w.subtract,w.multiply=function(e){if(this.isZero())return this;if(s(e)||(e=h(e)),t)return d(t.mul(this.low,this.high,e.low,e.high),t.get_high(),this.unsigned);if(e.isZero())return this.unsigned?I:v;if(this.eq(E))return e.isOdd()?E:v;if(e.eq(E))return this.isOdd()?E:v;if(this.isNegative())return e.isNegative()?this.neg().mul(e.neg()):this.neg().mul(e).neg();if(e.isNegative())return this.mul(e.neg()).neg();if(this.lt(y)&&e.lt(y))return c(this.toNumber()*e.toNumber(),this.unsigned);var r=this.high>>>16,n=65535&this.high,i=this.low>>>16,o=65535&this.low,a=e.high>>>16,u=65535&e.high,l=e.low>>>16,p=65535&e.low,m=0,f=0,g=0,b=0;return g+=(b+=o*p)>>>16,f+=(g+=i*p)>>>16,g&=65535,f+=(g+=o*l)>>>16,m+=(f+=n*p)>>>16,f&=65535,m+=(f+=i*l)>>>16,f&=65535,m+=(f+=o*u)>>>16,m+=r*p+n*l+i*u+o*a,d((g&=65535)<<16|(b&=65535),(m&=65535)<<16|(f&=65535),this.unsigned)},w.mul=w.multiply,w.divide=function(e){if(s(e)||(e=h(e)),e.isZero())throw Error("division by zero");var r,n,i;if(t)return this.unsigned||-2147483648!==this.high||-1!==e.low||-1!==e.high?d((this.unsigned?t.div_u:t.div_s)(this.low,this.high,e.low,e.high),t.get_high(),this.unsigned):this;if(this.isZero())return this.unsigned?I:v;if(this.unsigned){if(e.unsigned||(e=e.toUnsigned()),e.gt(this))return I;if(e.gt(this.shru(1)))return _;i=I}else{if(this.eq(E))return e.eq(b)||e.eq(T)?E:e.eq(E)?b:(r=this.shr(1).div(e).shl(1)).eq(v)?e.isNegative()?b:T:(n=this.sub(e.mul(r)),i=r.add(n.div(e)));if(e.eq(E))return this.unsigned?I:v;if(this.isNegative())return e.isNegative()?this.neg().div(e.neg()):this.neg().div(e).neg();if(e.isNegative())return this.div(e.neg()).neg();i=v}for(n=this;n.gte(e);){r=Math.max(1,Math.floor(n.toNumber()/e.toNumber()));for(var o=Math.ceil(Math.log(r)/Math.LN2),a=o<=48?1:u(2,o-48),l=c(r),p=l.mul(e);p.isNegative()||p.gt(n);)p=(l=c(r-=a,this.unsigned)).mul(e);l.isZero()&&(l=b),i=i.add(l),n=n.sub(p)}return i},w.div=w.divide,w.modulo=function(e){return s(e)||(e=h(e)),t?d((this.unsigned?t.rem_u:t.rem_s)(this.low,this.high,e.low,e.high),t.get_high(),this.unsigned):this.sub(this.div(e).mul(e))},w.mod=w.modulo,w.rem=w.modulo,w.not=function(){return d(~this.low,~this.high,this.unsigned)},w.countLeadingZeros=function(){return this.high?Math.clz32(this.high):Math.clz32(this.low)+32},w.clz=w.countLeadingZeros,w.countTrailingZeros=function(){return this.low?n(this.low):n(this.high)+32},w.ctz=w.countTrailingZeros,w.and=function(e){return s(e)||(e=h(e)),d(this.low&e.low,this.high&e.high,this.unsigned)},w.or=function(e){return s(e)||(e=h(e)),d(this.low|e.low,this.high|e.high,this.unsigned)},w.xor=function(e){return s(e)||(e=h(e)),d(this.low^e.low,this.high^e.high,this.unsigned)},w.shiftLeft=function(e){return s(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?d(this.low<<e,this.high<<e|this.low>>>32-e,this.unsigned):d(0,this.low<<e-32,this.unsigned)},w.shl=w.shiftLeft,w.shiftRight=function(e){return s(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?d(this.low>>>e|this.high<<32-e,this.high>>e,this.unsigned):d(this.high>>e-32,this.high>=0?0:-1,this.unsigned)},w.shr=w.shiftRight,w.shiftRightUnsigned=function(e){return s(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?d(this.low>>>e|this.high<<32-e,this.high>>>e,this.unsigned):d(32===e?this.high:this.high>>>e-32,0,this.unsigned)},w.shru=w.shiftRightUnsigned,w.shr_u=w.shiftRightUnsigned,w.rotateLeft=function(e){var t;return s(e)&&(e=e.toInt()),0==(e&=63)?this:32===e?d(this.high,this.low,this.unsigned):e<32?(t=32-e,d(this.low<<e|this.high>>>t,this.high<<e|this.low>>>t,this.unsigned)):(t=32-(e-=32),d(this.high<<e|this.low>>>t,this.low<<e|this.high>>>t,this.unsigned))},w.rotl=w.rotateLeft,w.rotateRight=function(e){var t;return s(e)&&(e=e.toInt()),0==(e&=63)?this:32===e?d(this.high,this.low,this.unsigned):e<32?(t=32-e,d(this.high<<t|this.low>>>e,this.low<<t|this.high>>>e,this.unsigned)):(t=32-(e-=32),d(this.low<<t|this.high>>>e,this.high<<t|this.low>>>e,this.unsigned))},w.rotr=w.rotateRight,w.toSigned=function(){return this.unsigned?d(this.low,this.high,!1):this},w.toUnsigned=function(){return this.unsigned?this:d(this.low,this.high,!0)},w.toBytes=function(e){return e?this.toBytesLE():this.toBytesBE()},w.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]},w.toBytesBE=function(){var e=this.high,t=this.low;return[e>>>24,e>>>16&255,e>>>8&255,255&e,t>>>24,t>>>16&255,t>>>8&255,255&t]},r.fromBytes=function(e,t,s){return s?r.fromBytesLE(e,t):r.fromBytesBE(e,t)},r.fromBytesLE=function(e,t){return new r(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24,t)},r.fromBytesBE=function(e,t){return new r(e[4]<<24|e[5]<<16|e[6]<<8|e[7],e[0]<<24|e[1]<<16|e[2]<<8|e[3],t)},"function"==typeof BigInt&&(r.fromBigInt=function(e,t){return d(Number(BigInt.asIntN(32,e)),Number(BigInt.asIntN(32,e>>BigInt(32))),t)},r.fromValue=function(e,t){return"bigint"==typeof e?r.fromBigInt(e,t):h(e,t)},w.toBigInt=function(){var e=BigInt(this.low>>>0);return BigInt(this.unsigned?this.high>>>0:this.high)<<BigInt(32)|e}),e.default=r}(t),e.exports=(r=t).default||r),Di.exports;var e,t,r}function xi(){return wi||(wi=1,function(e){var t,r,s=e;function n(e){return"__proto__"===e||"prototype"===e||"constructor"===e}function i(e){var t="boolean"==typeof arguments[arguments.length-1],r=t?arguments.length-1:arguments.length;t=t&&arguments[arguments.length-1];for(var s=1;s<r;++s){var i=arguments[s];if(i)for(var o=Object.keys(i),a=0;a<o.length;++a)n(o[a])||void 0!==e[o[a]]&&t||(e[o[a]]=i[o[a]])}return e}function o(e){function t(e,r){if(!(this instanceof t))return new t(e,r);Object.defineProperty(this,"message",{get:function(){return e}}),Error.captureStackTrace?Error.captureStackTrace(this,t):Object.defineProperty(this,"stack",{value:(new Error).stack||""}),r&&i(this,r)}return t.prototype=Object.create(Error.prototype,{constructor:{value:t,writable:!0,enumerable:!1,configurable:!0},name:{get:function(){return e},set:void 0,enumerable:!1,configurable:!0},toString:{value:function(){return this.name+": "+this.message},writable:!0,enumerable:!1,configurable:!0}}),t}s.asPromise=hi(),s.base64=(pi||(pi=1,function(e){var t=e;t.length=function(e){var t=e.length;if(!t)return 0;for(var r=0;--t%4>1&&"="===e.charAt(t);)++r;return Math.ceil(3*e.length)/4-r};for(var r=new Array(64),s=new Array(123),n=0;n<64;)s[r[n]=n<26?n+65:n<52?n+71:n<62?n-4:n-59|43]=n++;t.encode=function(e,t,s){for(var n,i=null,o=[],a=0,c=0;t<s;){var d=e[t++];switch(c){case 0:o[a++]=r[d>>2],n=(3&d)<<4,c=1;break;case 1:o[a++]=r[n|d>>4],n=(15&d)<<2,c=2;break;case 2:o[a++]=r[n|d>>6],o[a++]=r[63&d],c=0}a>8191&&((i||(i=[])).push(String.fromCharCode.apply(String,o)),a=0)}return c&&(o[a++]=r[n],o[a++]=61,1===c&&(o[a++]=61)),i?(a&&i.push(String.fromCharCode.apply(String,o.slice(0,a))),i.join("")):String.fromCharCode.apply(String,o.slice(0,a))};var i="invalid encoding";t.decode=function(e,t,r){for(var n,o=r,a=0,c=0;c<e.length;){var d=e.charCodeAt(c++);if(61===d&&a>1)break;if(void 0===(d=s[d]))throw Error(i);switch(a){case 0:n=d,a=1;break;case 1:t[r++]=n<<2|(48&d)>>4,n=d,a=2;break;case 2:t[r++]=(15&n)<<4|(60&d)>>2,n=d,a=3;break;case 3:t[r++]=(3&n)<<6|d,a=0}}if(1===a)throw Error(i);return r-o},t.test=function(e){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e)}}(vi)),vi),s.EventEmitter=function(){if(fi)return mi;function e(){this._listeners=Object.create(null)}return fi=1,mi=e,e.prototype.on=function(e,t,r){return(this._listeners[e]||(this._listeners[e]=[])).push({fn:t,ctx:r||this}),this},e.prototype.off=function(e,t){if(void 0===e)this._listeners=Object.create(null);else if(void 0===t)this._listeners[e]=[];else{var r=this._listeners[e];if(!r)return this;for(var s=0;s<r.length;)r[s].fn===t?r.splice(s,1):++s}return this},e.prototype.emit=function(e){var t=this._listeners[e];if(t){for(var r=[],s=1;s<arguments.length;)r.push(arguments[s++]);for(s=0;s<t.length;)t[s].fn.apply(t[s++].ctx,r)}return this},mi}(),s.float=function(){if(yi)return gi;function e(e){return"undefined"!=typeof Float32Array?function(){var t=new Float32Array([-0]),r=new Uint8Array(t.buffer),s=128===r[3];function n(e,s,n){t[0]=e,s[n]=r[0],s[n+1]=r[1],s[n+2]=r[2],s[n+3]=r[3]}function i(e,s,n){t[0]=e,s[n]=r[3],s[n+1]=r[2],s[n+2]=r[1],s[n+3]=r[0]}function o(e,s){return r[0]=e[s],r[1]=e[s+1],r[2]=e[s+2],r[3]=e[s+3],t[0]}function a(e,s){return r[3]=e[s],r[2]=e[s+1],r[1]=e[s+2],r[0]=e[s+3],t[0]}e.writeFloatLE=s?n:i,e.writeFloatBE=s?i:n,e.readFloatLE=s?o:a,e.readFloatBE=s?a:o}():function(){function i(e,t,r,s){var n=t<0?1:0;if(n&&(t=-t),0===t)e(1/t>0?0:2147483648,r,s);else if(isNaN(t))e(2143289344,r,s);else if(t>34028234663852886e22)e((n<<31|2139095040)>>>0,r,s);else if(t<11754943508222875e-54)e((n<<31|Math.round(t/1401298464324817e-60))>>>0,r,s);else{var i=Math.floor(Math.log(t)/Math.LN2);e((n<<31|i+127<<23|8388607&Math.round(t*Math.pow(2,-i)*8388608))>>>0,r,s)}}function o(e,t,r){var s=e(t,r),n=2*(s>>31)+1,i=s>>>23&255,o=8388607&s;return 255===i?o?NaN:n*(1/0):0===i?1401298464324817e-60*n*o:n*Math.pow(2,i-150)*(o+8388608)}e.writeFloatLE=i.bind(null,t),e.writeFloatBE=i.bind(null,r),e.readFloatLE=o.bind(null,s),e.readFloatBE=o.bind(null,n)}(),"undefined"!=typeof Float64Array?function(){var t=new Float64Array([-0]),r=new Uint8Array(t.buffer),s=128===r[7];function n(e,s,n){t[0]=e,s[n]=r[0],s[n+1]=r[1],s[n+2]=r[2],s[n+3]=r[3],s[n+4]=r[4],s[n+5]=r[5],s[n+6]=r[6],s[n+7]=r[7]}function i(e,s,n){t[0]=e,s[n]=r[7],s[n+1]=r[6],s[n+2]=r[5],s[n+3]=r[4],s[n+4]=r[3],s[n+5]=r[2],s[n+6]=r[1],s[n+7]=r[0]}function o(e,s){return r[0]=e[s],r[1]=e[s+1],r[2]=e[s+2],r[3]=e[s+3],r[4]=e[s+4],r[5]=e[s+5],r[6]=e[s+6],r[7]=e[s+7],t[0]}function a(e,s){return r[7]=e[s],r[6]=e[s+1],r[5]=e[s+2],r[4]=e[s+3],r[3]=e[s+4],r[2]=e[s+5],r[1]=e[s+6],r[0]=e[s+7],t[0]}e.writeDoubleLE=s?n:i,e.writeDoubleBE=s?i:n,e.readDoubleLE=s?o:a,e.readDoubleBE=s?a:o}():function(){function i(e,t,r,s,n,i){var o=s<0?1:0;if(o&&(s=-s),0===s)e(0,n,i+t),e(1/s>0?0:2147483648,n,i+r);else if(isNaN(s))e(0,n,i+t),e(2146959360,n,i+r);else if(s>17976931348623157e292)e(0,n,i+t),e((o<<31|2146435072)>>>0,n,i+r);else{var a;if(s<22250738585072014e-324)e((a=s/5e-324)>>>0,n,i+t),e((o<<31|a/4294967296)>>>0,n,i+r);else{var c=Math.floor(Math.log(s)/Math.LN2);1024===c&&(c=1023),e(4503599627370496*(a=s*Math.pow(2,-c))>>>0,n,i+t),e((o<<31|c+1023<<20|1048576*a&1048575)>>>0,n,i+r)}}}function o(e,t,r,s,n){var i=e(s,n+t),o=e(s,n+r),a=2*(o>>31)+1,c=o>>>20&2047,d=4294967296*(1048575&o)+i;return 2047===c?d?NaN:a*(1/0):0===c?5e-324*a*d:a*Math.pow(2,c-1075)*(d+4503599627370496)}e.writeDoubleLE=i.bind(null,t,0,4),e.writeDoubleBE=i.bind(null,r,4,0),e.readDoubleLE=o.bind(null,s,0,4),e.readDoubleBE=o.bind(null,n,4,0)}(),e}function t(e,t,r){t[r]=255&e,t[r+1]=e>>>8&255,t[r+2]=e>>>16&255,t[r+3]=e>>>24}function r(e,t,r){t[r]=e>>>24,t[r+1]=e>>>16&255,t[r+2]=e>>>8&255,t[r+3]=255&e}function s(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0}function n(e,t){return(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0}return yi=1,gi=e(e)}(),s.utf8=(Ii||(Ii=1,r=65533,(t=Si).length=function(e){for(var t=0,r=0,s=0;s<e.length;++s)(r=e.charCodeAt(s))<128?t+=1:r<2048?t+=2:55296==(64512&r)&&56320==(64512&e.charCodeAt(s+1))?(++s,t+=4):t+=3;return t},t.read=function(e,t,s){if(s-t<1)return"";for(var n,i,o,a,c=null,d=[],u=0;t<s;)(n=e[t++])<=127?d[u++]=n:n>=192&&n<224?(o=(31&n)<<6|63&e[t++],d[u++]=o>=128?o:r):n>=224&&n<240?(a=(15&n)<<12|(63&e[t++])<<6|63&e[t++],d[u++]=a>=2048?a:r):n>=240&&((i=(7&n)<<18|(63&e[t++])<<12|(63&e[t++])<<6|63&e[t++])<65536||i>1114111?d[u++]=r:(i-=65536,d[u++]=55296+(i>>10),d[u++]=56320+(1023&i))),u>8191&&((c||(c=[])).push(String.fromCharCode.apply(String,d.slice(0,u))),u=0);return c?(u&&c.push(String.fromCharCode.apply(String,d.slice(0,u))),c.join("")):String.fromCharCode.apply(String,d.slice(0,u))},t.write=function(e,t,r){for(var s,n,i=r,o=0;o<e.length;++o)(s=e.charCodeAt(o))<128?t[r++]=s:s<2048?(t[r++]=s>>6|192,t[r++]=63&s|128):55296==(64512&s)&&56320==(64512&(n=e.charCodeAt(o+1)))?(s=65536+((1023&s)<<10)+(1023&n),++o,t[r++]=s>>18|240,t[r++]=s>>12&63|128,t[r++]=s>>6&63|128,t[r++]=63&s|128):(t[r++]=s>>12|224,t[r++]=s>>6&63|128,t[r++]=63&s|128);return r-i}),Si),s.pool=_i?bi:(_i=1,bi=function(e,t,r){var s=r||8192,n=s>>>1,i=null,o=s;return function(r){if(r<1||r>n)return e(r);o+r>s&&(i=e(s),o=0);var a=t.call(i,o,o+=r);return 7&o&&(o=1+(7|o)),a}}),s.LongBits=function(){if(Ci)return Ti;Ci=1,Ti=t;var e=xi();function t(e,t){this.lo=e>>>0,this.hi=t>>>0}var r=t.zero=new t(0,0);r.toNumber=function(){return 0},r.zzEncode=r.zzDecode=function(){return this},r.length=function(){return 1};var s=t.zeroHash="\0\0\0\0\0\0\0\0";t.fromNumber=function(e){if(0===e)return r;var s=e<0;s&&(e=-e);var n=e>>>0,i=(e-n)/4294967296>>>0;return s&&(i=~i>>>0,n=~n>>>0,++n>4294967295&&(n=0,++i>4294967295&&(i=0))),new t(n,i)},t.from=function(s){if("number"==typeof s)return t.fromNumber(s);if(e.isString(s)){if(!e.Long)return t.fromNumber(parseInt(s,10));s=e.Long.fromString(s)}return s.low||s.high?new t(s.low>>>0,s.high>>>0):r},t.prototype.toNumber=function(e){if(!e&&this.hi>>>31){var t=1+~this.lo>>>0,r=~this.hi>>>0;return t||(r=r+1>>>0),-(t+4294967296*r)}return this.lo+4294967296*this.hi},t.prototype.toLong=function(t){return e.Long?new e.Long(0|this.lo,0|this.hi,Boolean(t)):{low:0|this.lo,high:0|this.hi,unsigned:Boolean(t)}};var n=String.prototype.charCodeAt;return t.fromHash=function(e){return e===s?r:new t((n.call(e,0)|n.call(e,1)<<8|n.call(e,2)<<16|n.call(e,3)<<24)>>>0,(n.call(e,4)|n.call(e,5)<<8|n.call(e,6)<<16|n.call(e,7)<<24)>>>0)},t.prototype.toHash=function(){return String.fromCharCode(255&this.lo,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,255&this.hi,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)},t.prototype.zzEncode=function(){var e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this},t.prototype.zzDecode=function(){var e=-(1&this.lo);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this},t.prototype.length=function(){var e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,r=this.hi>>>24;return 0===r?0===t?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:r<128?9:10},Ti}(),s.isUnsafeProperty=n,s.isNode=Boolean(void 0!==ii&&ii&&ii.process&&ii.process.versions&&ii.process.versions.node),s.global=s.isNode&&ii||"undefined"!=typeof window&&window||"undefined"!=typeof self&&self||li,s.emptyArray=Object.freeze?Object.freeze([]):[],s.emptyObject=Object.freeze?Object.freeze({}):{},s.isInteger=Number.isInteger||function(e){return"number"==typeof e&&isFinite(e)&&Math.floor(e)===e},s.isString=function(e){return"string"==typeof e||e instanceof String},s.isObject=function(e){return e&&"object"==typeof e},s.isset=s.isSet=function(e,t){var r=e[t];return!(null==r||!Object.hasOwnProperty.call(e,t))&&("object"!=typeof r||(Array.isArray(r)?r.length:Object.keys(r).length)>0)},s.Buffer=function(){try{var e=s.global.Buffer;return e.prototype.utf8Write?e:null}catch(t){return null}}(),s._Buffer_from=null,s._Buffer_allocUnsafe=null,s.newBuffer=function(e){return"number"==typeof e?s.Buffer?s._Buffer_allocUnsafe(e):new s.Array(e):s.Buffer?s._Buffer_from(e):"undefined"==typeof Uint8Array?e:new Uint8Array(e)},s.Array="undefined"!=typeof Uint8Array?Uint8Array:Array,s.Long=s.global.dcodeIO&&s.global.dcodeIO.Long||s.global.Long||function(){try{var e=Pi();return e&&e.isLong?e:null}catch(t){return null}}(),s.key2Re=/^true|false|0|1$/,s.key32Re=/^-?(?:0|[1-9][0-9]*)$/,s.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/,s.longToHash=function(e){return e?s.LongBits.from(e).toHash():s.LongBits.zeroHash},s.longFromHash=function(e,t){var r=s.LongBits.fromHash(e);return s.Long?s.Long.fromBits(r.lo,r.hi,t):r.toNumber(Boolean(t))},s.merge=i,s.nestingLimit=32,s.recursionLimit=100,s.makeProp=function(e,t){Object.defineProperty(e,t,{enumerable:!0,configurable:!0,writable:!0})},s.lcFirst=function(e){return e.charAt(0).toLowerCase()+e.substring(1)},s.newError=o,s.ProtocolError=o("ProtocolError"),s.oneOfGetter=function(e){for(var t={},r=0;r<e.length;++r)t[e[r]]=1;return function(){for(var e=Object.keys(this),r=e.length-1;r>-1;--r)if(1===t[e[r]]&&void 0!==this[e[r]]&&null!==this[e[r]])return e[r]}},s.oneOfSetter=function(e){return function(t){for(var r=0;r<e.length;++r)e[r]!==t&&delete this[e[r]]}},s.toJSONOptions={longs:String,enums:String,bytes:String,json:!0},s._configure=function(){var e=s.Buffer;e?(s._Buffer_from=e.from!==Uint8Array.from&&e.from||function(t,r){return new e(t,r)},s._Buffer_allocUnsafe=e.allocUnsafe||function(t){return new e(t)}):s._Buffer_from=s._Buffer_allocUnsafe=null}}(li)),li}function Fi(){if(Ai)return Ri;Ai=1,Ri=c;var e,t=xi(),r=t.LongBits,s=t.base64,n=t.utf8;function i(e,t,r){this.fn=e,this.len=t,this.next=void 0,this.val=r}function o(){}function a(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}function c(){this.len=0,this.head=new i(o,0,0),this.tail=this.head,this.states=null}var d=function(){return t.Buffer?function(){return(c.create=function(){return new e})()}:function(){return new c}};function u(e,t,r){t[r]=255&e}function l(e,t){this.len=e,this.next=void 0,this.val=t}function h(e,t,r){for(var s=e.lo,n=e.hi;n;)t[r++]=127&s|128,s=(s>>>7|n<<25)>>>0,n>>>=7;for(;s>127;)t[r++]=127&s|128,s>>>=7;t[r++]=s}function p(e,t,r){t[r]=255&e,t[r+1]=e>>>8&255,t[r+2]=e>>>16&255,t[r+3]=e>>>24}c.create=d(),c.alloc=function(e){return new t.Array(e)},t.Array!==Array&&(c.alloc=t.pool(c.alloc,t.Array.prototype.subarray)),c.prototype._push=function(e,t,r){return this.tail=this.tail.next=new i(e,t,r),this.len+=t,this},l.prototype=Object.create(i.prototype),l.prototype.fn=function(e,t,r){for(;e>127;)t[r++]=127&e|128,e>>>=7;t[r]=e},c.prototype.uint32=function(e){return this.len+=(this.tail=this.tail.next=new l((e>>>=0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this},c.prototype.int32=function(e){return(e|=0)<0?this._push(h,10,r.fromNumber(e)):this.uint32(e)},c.prototype.sint32=function(e){return this.uint32((e<<1^e>>31)>>>0)},c.prototype.uint64=function(e){var t=r.from(e);return this._push(h,t.length(),t)},c.prototype.int64=c.prototype.uint64,c.prototype.sint64=function(e){var t=r.from(e).zzEncode();return this._push(h,t.length(),t)},c.prototype.bool=function(e){return this._push(u,1,e?1:0)},c.prototype.fixed32=function(e){return this._push(p,4,e>>>0)},c.prototype.sfixed32=c.prototype.fixed32,c.prototype.fixed64=function(e){var t=r.from(e);return this._push(p,4,t.lo)._push(p,4,t.hi)},c.prototype.sfixed64=c.prototype.fixed64,c.prototype.float=function(e){return this._push(t.float.writeFloatLE,4,e)},c.prototype.double=function(e){return this._push(t.float.writeDoubleLE,8,e)};var m=t.Array.prototype.set?function(e,t,r){t.set(e,r)}:function(e,t,r){for(var s=0;s<e.length;++s)t[r+s]=e[s]};return c.prototype.bytes=function(e){var r=e.length>>>0;if(!r)return this._push(u,1,0);if(t.isString(e)){var n=c.alloc(r=s.length(e));s.decode(e,n,0),e=n}return this.uint32(r)._push(m,r,e)},c.prototype.string=function(e){var t=n.length(e);return t?this.uint32(t)._push(n.write,t,e):this._push(u,1,0)},c.prototype.fork=function(){return this.states=new a(this),this.head=this.tail=new i(o,0,0),this.len=0,this},c.prototype.reset=function(){return this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new i(o,0,0),this.len=0),this},c.prototype.ldelim=function(){var e=this.head,t=this.tail,r=this.len;return this.reset().uint32(r),r&&(this.tail.next=e.next,this.tail=t,this.len+=r),this},c.prototype.finish=function(){for(var e=this.head.next,t=this.constructor.alloc(this.len),r=0;e;)e.fn(e.val,t,r),r+=e.len,e=e.next;return t},c._configure=function(t){e=t,c.create=d(),e._configure()},Ri}function Bi(){if(Ui)return Mi;Ui=1,Mi=i;var e,t=xi(),r=t.LongBits,s=t.utf8;function n(e,t){return RangeError("index out of range: "+e.pos+" + "+(t||1)+" > "+e.len)}function i(e){this.buf=e,this.pos=0,this.len=e.length}var o="undefined"!=typeof Uint8Array?function(e){if(e instanceof Uint8Array||Array.isArray(e))return new i(e);throw Error("illegal buffer")}:function(e){if(Array.isArray(e))return new i(e);throw Error("illegal buffer")},a=function(){return t.Buffer?function(r){return(i.create=function(r){return t.Buffer.isBuffer(r)?new e(r):o(r)})(r)}:o};function c(){var e=new r(0,0),t=0;if(!(this.len-this.pos>4)){for(;t<3;++t){if(this.pos>=this.len)throw n(this);if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(127&this.buf[this.pos++])<<7*t)>>>0,e}for(;t<4;++t)if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(127&this.buf[this.pos])<<28)>>>0,e.hi=(e.hi|(127&this.buf[this.pos])>>4)>>>0,this.buf[this.pos++]<128)return e;if(t=0,this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw n(this);if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}function d(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}function u(){if(this.pos+8>this.len)throw n(this,8);return new r(d(this.buf,this.pos+=4),d(this.buf,this.pos+=4))}return i.create=a(),i.prototype._slice=t.Array.prototype.subarray||t.Array.prototype.slice,i.prototype.uint32=function(){var e=4294967295;return function(){if(e=(127&this.buf[this.pos])>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<7)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<14)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<21)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(15&this.buf[this.pos])<<28)>>>0,this.buf[this.pos++]<128)return e;if((this.pos+=5)>this.len)throw this.pos=this.len,n(this,10);return e}}(),i.prototype.int32=function(){return 0|this.uint32()},i.prototype.sint32=function(){var e=this.uint32();return e>>>1^-(1&e)},i.prototype.bool=function(){return 0!==this.uint32()},i.prototype.fixed32=function(){if(this.pos+4>this.len)throw n(this,4);return d(this.buf,this.pos+=4)},i.prototype.sfixed32=function(){if(this.pos+4>this.len)throw n(this,4);return 0|d(this.buf,this.pos+=4)},i.prototype.float=function(){if(this.pos+4>this.len)throw n(this,4);var e=t.float.readFloatLE(this.buf,this.pos);return this.pos+=4,e},i.prototype.double=function(){if(this.pos+8>this.len)throw n(this,4);var e=t.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,e},i.prototype.bytes=function(){var e=this.uint32(),r=this.pos,s=this.pos+e;if(s>this.len)throw n(this,e);if(this.pos+=e,Array.isArray(this.buf))return this.buf.slice(r,s);if(r===s){var i=t.Buffer;return i?i.alloc(0):new this.buf.constructor(0)}return this._slice.call(this.buf,r,s)},i.prototype.string=function(){var e=this.bytes();return s.read(e,0,e.length)},i.prototype.skip=function(e){if("number"==typeof e){if(this.pos+e>this.len)throw n(this,e);this.pos+=e}else do{if(this.pos>=this.len)throw n(this)}while(128&this.buf[this.pos++]);return this},i.recursionLimit=t.recursionLimit,i.prototype.skipType=function(e,t){if(void 0===t&&(t=0),t>i.recursionLimit)throw Error("maximum nesting depth exceeded");switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;4!=(e=7&this.uint32());)this.skipType(e,t+1);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+e+" at offset "+this.pos)}return this},i._configure=function(r){e=r,i.create=a(),e._configure();var s=t.Long?"toLong":"toNumber";t.merge(i.prototype,{int64:function(){return c.call(this)[s](!1)},uint64:function(){return c.call(this)[s](!0)},sint64:function(){return c.call(this).zzDecode()[s](!1)},fixed64:function(){return u.call(this)[s](!0)},sfixed64:function(){return u.call(this)[s](!1)}})},Mi}var Gi,qi,$i,ji,Vi,Ki,zi={};function Hi(){return $i||($i=1,zi.Service=function(){if(qi)return Gi;qi=1,Gi=t;var e=xi();function t(t,r,s){if("function"!=typeof t)throw TypeError("rpcImpl must be a function");e.EventEmitter.call(this),this.rpcImpl=t,this.requestDelimited=Boolean(r),this.responseDelimited=Boolean(s)}return(t.prototype=Object.create(e.EventEmitter.prototype)).constructor=t,t.prototype.rpcCall=function t(r,s,n,i,o){if(!i)throw TypeError("request must be specified");var a=this;if(!o)return e.asPromise(t,a,r,s,n,i);if(a.rpcImpl)try{return a.rpcImpl(r,s[a.requestDelimited?"encodeDelimited":"encode"](i).finish(),function(e,t){if(e)return a.emit("error",e,r),o(e);if(null!==t){if(!(t instanceof n))try{t=n[a.responseDelimited?"decodeDelimited":"decode"](t)}catch(s){return a.emit("error",s,r),o(s)}return a.emit("data",t,r),o(null,t)}a.end(!0)})}catch(c){return a.emit("error",c,r),void setTimeout(function(){o(c)},0)}else setTimeout(function(){o(Error("already ended"))},0)},t.prototype.end=function(e){return this.rpcImpl&&(e||this.rpcImpl(null,null,null),this.rpcImpl=null,this.emit("end").off()),this},Gi}()),zi}function Wi(){return Vi?ji:(Vi=1,ji=Object.create(null))}function Ji(){return Ki||(Ki=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=Fi(),t.BufferWriter=function(){if(Oi)return Ni;Oi=1,Ni=r;var e=Fi();(r.prototype=Object.create(e.prototype)).constructor=r;var t=xi();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(),Ni}(),t.Reader=Bi(),t.BufferReader=function(){if(ki)return Li;ki=1,Li=r;var e=Bi();(r.prototype=Object.create(e.prototype)).constructor=r;var t=xi();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(),Li}(),t.util=xi(),t.rpc=Hi(),t.roots=Wi(),t.configure=r,r()}(ui)),ui}var Qi,Zi,Yi={},Xi={exports:{}};function eo(){if(Zi)return Qi;Zi=1,Qi=t;var e=/^(?:do|if|in|for|let|new|try|var|case|else|enum|eval|false|null|this|true|void|with|break|catch|class|const|super|throw|while|yield|delete|export|import|public|return|static|switch|typeof|default|extends|finally|package|private|continue|debugger|function|arguments|interface|protected|implements|instanceof)$/;function t(r,s){"string"==typeof r&&(s=r,r=void 0);var n=[];function i(e){if("string"!=typeof e){var r=o();if(t.verbose&&console.log("codegen: "+r),r="return "+r,e){for(var s=Object.keys(e),a=new Array(s.length+1),c=new Array(s.length),d=0;d<s.length;)a[d]=s[d],c[d]=e[s[d++]];return a[d]=r,Function.apply(null,a).apply(null,c)}return Function(r)()}for(var u=new Array(arguments.length-1),l=0;l<u.length;)u[l]=arguments[++l];if(l=0,e=e.replace(/%([%dfijs])/g,function(e,t){var r=u[l++];switch(t){case"d":case"f":return String(Number(r));case"i":return String(Math.floor(r));case"j":return JSON.stringify(r);case"s":return String(r)}return"%"}),l!==u.length)throw Error("parameter count mismatch");return n.push(e),i}function o(t){return"function "+function(t){if(!t)return"";if(!(t=String(t).replace(/[^\w$]/g,"")))return"";/^\d/.test(t)&&(t="_"+t);return e.test(t)?t+"_":t}(t||s)+"("+(r&&r.join(",")||"")+"){\n "+n.join("\n ")+"\n}"}return i.toString=o,i}return t.verbose=!1,Qi}const to=oi(Object.freeze(Object.defineProperty({__proto__:null,default:{}},Symbol.toStringTag,{value:"Module"})));var ro,so,no,io;function oo(){if(io)return no;io=1,no=r;var e=hi(),t=function(){if(so)return ro;so=1;var e=null;try{(e=to)&&e.readFile&&e.readFileSync||(e=null)}catch(t){}return ro=e}();function r(s,n,i){return"function"==typeof n?(i=n,n={}):n||(n={}),i?!n.xhr&&t&&t.readFile?t.readFile(s,function(e,t){return e&&"undefined"!=typeof XMLHttpRequest?r.xhr(s,n,i):e?i(e):i(null,n.binary?t:t.toString("utf8"))}):r.xhr(s,n,i):e(r,this,s,n)}return r.xhr=function(e,t,r){var s=new XMLHttpRequest;s.onreadystatechange=function(){if(4===s.readyState){if(0!==s.status&&200!==s.status)return r(Error("status "+s.status));if(t.binary){var e=s.response;if(!e){e=[];for(var n=0;n<s.responseText.length;++n)e.push(255&s.responseText.charCodeAt(n))}return r(null,"undefined"!=typeof Uint8Array?new Uint8Array(e):e)}return r(null,s.responseText)}},t.binary&&("overrideMimeType"in s&&s.overrideMimeType("text/plain; charset=x-user-defined"),s.responseType="arraybuffer"),s.open("GET",e),s.send()},no}var ao,co={};var uo,lo,ho,po,mo,fo,go,yo,vo,Io,bo,_o,To,Co,So,Eo,wo,Ro={};function Ao(){if(mo)return po;mo=1,po=c;var e=ha();((c.prototype=Object.create(e.prototype)).constructor=c).className="Namespace";var t,r,s,n=ua(),i=ca(),o=la();function a(e,t){if(e&&e.length){for(var r={},s=0;s<e.length;++s)r[e[s].name]=e[s].toJSON(t);return r}}function c(t,r){e.call(this,t,r),this.nested=void 0,this._nestedArray=null,this._lookupCache=Object.create(null),this._needsRecursiveFeatureResolution=!0,this._needsRecursiveResolve=!0}function d(e){e._nestedArray=null,e._lookupCache=Object.create(null);for(var t=e;t=t.parent;)t._lookupCache=Object.create(null);return e}return c.fromJSON=function(e,t,r){return r=i.checkDepth(r),new c(e,t.options).addJSON(t.nested,r)},c.arrayToJSON=a,c.isReservedId=function(e,t){if(e)for(var r=0;r<e.length;++r)if("string"!=typeof e[r]&&e[r][0]<=t&&e[r][1]>t)return!0;return!1},c.isReservedName=function(e,t){if(e)for(var r=0;r<e.length;++r)if(e[r]===t)return!0;return!1},Object.defineProperty(c.prototype,"nestedArray",{get:function(){return this._nestedArray||(this._nestedArray=i.toArray(this.nested))}}),c.prototype.toJSON=function(e){return i.toObject(["options",this.options,"nested",a(this.nestedArray,e)])},c.prototype.addJSON=function(e,o){o=i.checkDepth(o);if(e)for(var a,d=Object.keys(e),u=0;u<d.length;++u)a=e[d[u]],this.add((void 0!==a.fields?t.fromJSON:void 0!==a.values?s.fromJSON:void 0!==a.methods?r.fromJSON:void 0!==a.id?n.fromJSON:c.fromJSON)(d[u],a,o+1));return this},c.prototype.get=function(e){return this.nested&&Object.prototype.hasOwnProperty.call(this.nested,e)?this.nested[e]:null},c.prototype.getEnum=function(e){if(this.nested&&Object.prototype.hasOwnProperty.call(this.nested,e)&&this.nested[e]instanceof s)return this.nested[e].values;throw Error("no such enum: "+e)},c.prototype.add=function(e){if(!(e instanceof n&&void 0!==e.extend||e instanceof t||e instanceof o||e instanceof s||e instanceof r||e instanceof c))throw TypeError("object must be a valid nested object");if("__proto__"===e.name)return this;if(this.nested){var i=this.get(e.name);if(i){if(!(i instanceof c&&e instanceof c)||i instanceof t||i instanceof r)throw Error("duplicate name '"+e.name+"' in "+this);for(var a=i.nestedArray,u=0;u<a.length;++u)e.add(a[u]);this.remove(i),this.nested||(this.nested={}),e.setOptions(i.options,!0)}}else this.nested={};this.nested[e.name]=e,this instanceof t||this instanceof r||this instanceof s||this instanceof n||e._edition||(e._edition=e._defaultEdition),this._needsRecursiveFeatureResolution=!0,this._needsRecursiveResolve=!0;for(var l=this;l=l.parent;)l._needsRecursiveFeatureResolution=!0,l._needsRecursiveResolve=!0;return e.onAdd(this),d(this)},c.prototype.remove=function(t){if(!(t instanceof e))throw TypeError("object must be a ReflectionObject");if(t.parent!==this)throw Error(t+" is not a member of "+this);return delete this.nested[t.name],Object.keys(this.nested).length||(this.nested=void 0),t.onRemove(this),d(this)},c.prototype.define=function(e,t){if(i.isString(e))e=e.split(".");else if(!Array.isArray(e))throw TypeError("illegal path");if(e&&e.length&&""===e[0])throw Error("path must be relative");if(e.length>i.recursionLimit)throw Error("max depth exceeded");for(var r=this;e.length>0;){var s=e.shift();if(r.nested&&r.nested[s]){if(!((r=r.nested[s])instanceof c))throw Error("path conflicts with non-namespace objects")}else r.add(r=new c(s))}return t&&r.addJSON(t),r},c.prototype.resolveAll=function(){if(!this._needsRecursiveResolve)return this;this._resolveFeaturesRecursive(this._edition);var e=this.nestedArray,t=0;for(this.resolve();t<e.length;)e[t]instanceof c?e[t++].resolveAll():e[t++].resolve();return this._needsRecursiveResolve=!1,this},c.prototype._resolveFeaturesRecursive=function(t){return this._needsRecursiveFeatureResolution?(this._needsRecursiveFeatureResolution=!1,t=this._edition||t,e.prototype._resolveFeaturesRecursive.call(this,t),this.nestedArray.forEach(e=>{e._resolveFeaturesRecursive(t)}),this):this},c.prototype.lookup=function(e,t,r){if("boolean"==typeof t?(r=t,t=void 0):t&&!Array.isArray(t)&&(t=[t]),i.isString(e)&&e.length){if("."===e)return this.root;e=e.split(".")}else if(!e.length)return this;var s=e.join(".");if(""===e[0])return this.root.lookup(e.slice(1),t);var n=this.root._fullyQualifiedObjects&&this.root._fullyQualifiedObjects["."+s];if(n&&(!t||t.indexOf(n.constructor)>-1))return n;if((n=this._lookupImpl(e,s))&&(!t||t.indexOf(n.constructor)>-1))return n;if(r)return null;for(var o=this;o.parent;){if((n=o.parent._lookupImpl(e,s))&&(!t||t.indexOf(n.constructor)>-1))return n;o=o.parent}return null},c.prototype._lookupImpl=function(e,t){if(Object.prototype.hasOwnProperty.call(this._lookupCache,t))return this._lookupCache[t];var r=this.get(e[0]),s=null;if(r)1===e.length?s=r:r instanceof c&&(e=e.slice(1),s=r._lookupImpl(e,e.join(".")));else for(var n=0;n<this.nestedArray.length;++n)if(this._nestedArray[n]instanceof c&&(r=this._nestedArray[n]._lookupImpl(e,t))){s=r;break}return this._lookupCache[t]=s,s},c.prototype.lookupType=function(e){var r=this.lookup(e,[t]);if(!r)throw Error("no such type: "+e);return r},c.prototype.lookupEnum=function(e){var t=this.lookup(e,[s]);if(!t)throw Error("no such Enum '"+e+"' in "+this);return t},c.prototype.lookupTypeOrEnum=function(e){var r=this.lookup(e,[t,s]);if(!r)throw Error("no such Type or Enum '"+e+"' in "+this);return r},c.prototype.lookupService=function(e){var t=this.lookup(e,[r]);if(!t)throw Error("no such Service '"+e+"' in "+this);return t},c._configure=function(e,n,i){t=e,r=n,s=i},po}function No(){if(go)return fo;go=1,fo=s;var e=ua();((s.prototype=Object.create(e.prototype)).constructor=s).className="MapField";var t=da(),r=ca();function s(t,s,n,i,o,a){if(e.call(this,t,s,i,void 0,void 0,o,a),!r.isString(n))throw TypeError("keyType must be a string");this.keyType=n,this.resolvedKeyType=null,this.map=!0}return s.fromJSON=function(e,t){return new s(e,t.id,t.keyType,t.type,t.options,t.comment)},s.prototype.toJSON=function(e){var t=!!e&&Boolean(e.keepComments);return r.toObject(["keyType",this.keyType,"type",this.type,"id",this.id,"extend",this.extend,"options",this.options,"comment",t?this.comment:void 0])},s.prototype.resolve=function(){if(this.resolved)return this;if(void 0===t.mapKey[this.keyType])throw Error("invalid key type: "+this.keyType);return e.prototype.resolve.call(this)},s.d=function(e,t,n){return"function"==typeof n?n=r.decorateType(n).name:n&&"object"==typeof n&&(n=r.decorateEnum(n).name),function(i,o){r.decorateType(i.constructor).add(new s(o,e,t,n))}},fo}function Oo(){if(vo)return yo;vo=1,yo=r;var e=ha();((r.prototype=Object.create(e.prototype)).constructor=r).className="Method";var t=ca();function r(r,s,n,i,o,a,c,d,u){if(t.isObject(o)?(c=o,o=a=void 0):t.isObject(a)&&(c=a,a=void 0),void 0!==s&&!t.isString(s))throw TypeError("type must be a string");if(!t.isString(n))throw TypeError("requestType must be a string");if(!t.isString(i))throw TypeError("responseType must be a string");e.call(this,r,c),this.type=s||"rpc",this.requestType=n,this.requestStream=!!o||void 0,this.responseType=i,this.responseStream=!!a||void 0,this.resolvedRequestType=null,this.resolvedResponseType=null,this.comment=d,this.parsedOptions=u}return r.fromJSON=function(e,t){return new r(e,t.type,t.requestType,t.responseType,t.requestStream,t.responseStream,t.options,t.comment,t.parsedOptions)},r.prototype.toJSON=function(e){var r=!!e&&Boolean(e.keepComments);return t.toObject(["type","rpc"!==this.type&&this.type||void 0,"requestType",this.requestType,"requestStream",this.requestStream,"responseType",this.responseType,"responseStream",this.responseStream,"options",this.options,"comment",r?this.comment:void 0,"parsedOptions",this.parsedOptions])},r.prototype.resolve=function(){return this.resolved?this:(this.resolvedRequestType=this.parent.lookupType(this.requestType),this.resolvedResponseType=this.parent.lookupType(this.responseType),e.prototype.resolve.call(this))},yo}function Mo(){if(bo)return Io;bo=1,Io=n;var e=Ao();((n.prototype=Object.create(e.prototype)).constructor=n).className="Service";var t=Oo(),r=ca(),s=Hi();function n(t,r){e.call(this,t,r),this.methods={},this._methodsArray=null}function i(e){return e._methodsArray=null,e}return n.fromJSON=function(e,s,i){i=r.checkDepth(i);var o=new n(e,s.options);if(s.methods)for(var a=Object.keys(s.methods),c=0;c<a.length;++c)o.add(t.fromJSON(a[c],s.methods[a[c]]));return s.nested&&o.addJSON(s.nested,i),s.edition&&(o._edition=s.edition),o.comment=s.comment,o._defaultEdition="proto3",o},n.prototype.toJSON=function(t){var s=e.prototype.toJSON.call(this,t),n=!!t&&Boolean(t.keepComments);return r.toObject(["edition",this._editionToJSON(),"options",s&&s.options||void 0,"methods",e.arrayToJSON(this.methodsArray,t)||{},"nested",s&&s.nested||void 0,"comment",n?this.comment:void 0])},Object.defineProperty(n.prototype,"methodsArray",{get:function(){return this._methodsArray||(this._methodsArray=r.toArray(this.methods))}}),n.prototype.get=function(t){return Object.prototype.hasOwnProperty.call(this.methods,t)?this.methods[t]:e.prototype.get.call(this,t)},n.prototype.resolveAll=function(){if(!this._needsRecursiveResolve)return this;e.prototype.resolve.call(this);for(var t=this.methodsArray,r=0;r<t.length;++r)t[r].resolve();return this},n.prototype._resolveFeaturesRecursive=function(t){return this._needsRecursiveFeatureResolution?(t=this._edition||t,e.prototype._resolveFeaturesRecursive.call(this,t),this.methodsArray.forEach(e=>{e._resolveFeaturesRecursive(t)}),this):this},n.prototype.add=function(r){if(this.get(r.name))throw Error("duplicate name '"+r.name+"' in "+this);return r instanceof t?"__proto__"===r.name?this:(this.methods[r.name]=r,r.parent=this,i(this)):e.prototype.add.call(this,r)},n.prototype.remove=function(r){if(r instanceof t){if(this.methods[r.name]!==r)throw Error(r+" is not a member of "+this);return delete this.methods[r.name],r.parent=null,i(this)}return e.prototype.remove.call(this,r)},n.prototype.create=function(e,t,n){for(var i,o=new s.Service(e,t,n),a=0;a<this.methodsArray.length;++a){o[r.lcFirst((i=this._methodsArray[a]).resolve().name).replace(/[^$\w_]/g,"")]=function(e,t,r){return function(n,i){return s.Service.prototype.rpcCall.call(this,e,t,r,n,i)}}(i,i.resolvedRequestType.ctor,i.resolvedResponseType.ctor)}return o},Io}function Uo(){if(To)return _o;To=1,_o=t;var e=xi();function t(e){if(e)for(var t=Object.keys(e),r=0;r<t.length;++r){var s=t[r];"__proto__"!==s&&(this[s]=e[s])}}return t.create=function(e){return this.$type.create(e)},t.encode=function(e,t){return this.$type.encode(e,t)},t.encodeDelimited=function(e,t){return this.$type.encodeDelimited(e,t)},t.decode=function(e){return this.$type.decode(e)},t.decodeDelimited=function(e){return this.$type.decodeDelimited(e)},t.verify=function(e){return this.$type.verify(e)},t.fromObject=function(e){return this.$type.fromObject(e)},t.toObject=function(e,t){return this.$type.toObject(e,t)},t.prototype.toJSON=function(){return this.$type.toObject(this,e.toJSONOptions)},_o}function Lo(){if(So)return Co;So=1,Co=function(n){for(var i=r.codegen(["r","l","e","n"],n.name+"$decode")("if(!(r instanceof Reader))")("r=Reader.create(r)")("if(n===undefined)n=0")("if(n>Reader.recursionLimit)")('throw Error("maximum nesting depth exceeded")')("var c=l===undefined?r.len:r.pos+l,m=new this.ctor"+(n.fieldsArray.filter(function(e){return e.map}).length?",k,value":""))("while(r.pos<c){")("var t=r.uint32()")("if(t===e)")("break")("switch(t>>>3){"),o=0;o<n.fieldsArray.length;++o){var a=n._fieldsArray[o].resolve(),c=a.resolvedType instanceof e?"int32":a.type,d="m"+r.safeProp(a.name);i("case %i: {",a.id),a.map?(i("if(%s===util.emptyObject)",d)("%s={}",d)("var c2 = r.uint32()+r.pos"),void 0!==t.defaults[a.keyType]?i("k=%j",t.defaults[a.keyType]):i("k=null"),void 0!==t.defaults[c]?i("value=%j",t.defaults[c]):i("value=null"),i("while(r.pos<c2){")("var tag2=r.uint32()")("switch(tag2>>>3){")("case 1: k=r.%s(); break",a.keyType)("case 2:"),void 0===t.basic[c]?i("value=types[%i].decode(r,r.uint32(),undefined,n+1)",o):i("value=r.%s()",c),i("break")("default:")("r.skipType(tag2&7,n)")("break")("}")("}"),void 0!==t.long[a.keyType]?i('%s[typeof k==="object"?util.longToHash(k):k]=value',d):("string"===a.keyType&&i('if(k==="__proto__")')("util.makeProp(%s,k)",d),i("%s[k]=value",d))):a.repeated?(i("if(!(%s&&%s.length))",d,d)("%s=[]",d),void 0!==t.packed[c]&&i("if((t&7)===2){")("var c2=r.uint32()+r.pos")("while(r.pos<c2)")("%s.push(r.%s())",d,c)("}else"),void 0===t.basic[c]?i(a.delimited?"%s.push(types[%i].decode(r,undefined,((t&~7)|4),n+1))":"%s.push(types[%i].decode(r,r.uint32(),undefined,n+1))",d,o):i("%s.push(r.%s())",d,c)):void 0===t.basic[c]?i(a.delimited?"%s=types[%i].decode(r,undefined,((t&~7)|4),n+1)":"%s=types[%i].decode(r,r.uint32(),undefined,n+1)",d,o):i("%s=r.%s()",d,c),i("break")("}")}for(i("default:")("r.skipType(t&7,n)")("break")("}")("}"),o=0;o<n._fieldsArray.length;++o){var u=n._fieldsArray[o];u.required&&i("if(!Object.hasOwnProperty.call(m,%j))",u.name)("throw util.ProtocolError(%j,{instance:m})",s(u))}return i("return m")};var e=pa(),t=da(),r=ca();function s(e){return"missing required '"+e.name+"'"}return Co}function ko(){if(wo)return Eo;wo=1,Eo=function(e){var i=t.codegen(["m","n"],e.name+"$verify")('if(typeof m!=="object"||m===null)')("return%j","object expected")("if(n===undefined)n=0")("if(n>util.recursionLimit)")("return%j","maximum nesting depth exceeded"),o=e.oneofsArray,a={};o.length&&i("var p={}");for(var c=0;c<e.fieldsArray.length;++c){var d=e._fieldsArray[c].resolve(),u="m"+t.safeProp(d.name);if(d.optional&&i("if(%s!=null&&Object.hasOwnProperty.call(m,%j)){",u,d.name),d.map)i("if(!util.isObject(%s))",u)("return%j",r(d,"object"))("var k=Object.keys(%s)",u)("for(var i=0;i<k.length;++i){"),n(i,d,"k[i]"),s(i,d,c,u+"[k[i]]")("}");else if(d.repeated)i("if(!Array.isArray(%s))",u)("return%j",r(d,"array"))("for(var i=0;i<%s.length;++i){",u),s(i,d,c,u+"[i]")("}");else{if(d.partOf){var l=t.safeProp(d.partOf.name);1===a[d.partOf.name]&&i("if(p%s===1)",l)("return%j",d.partOf.name+": multiple values"),a[d.partOf.name]=1,i("p%s=1",l)}s(i,d,c,u)}d.optional&&i("}")}return i("return null")};var e=pa(),t=ca();function r(e,t){return e.name+": "+t+(e.repeated&&"array"!==t?"[]":e.map&&"object"!==t?"{k:"+e.keyType+"}":"")+" expected"}function s(t,s,n,i){if(s.resolvedType)if(s.resolvedType instanceof e){t("switch(%s){",i)("default:")("return%j",r(s,"enum value"));for(var o=Object.keys(s.resolvedType.values),a=0;a<o.length;++a)t("case %i:",s.resolvedType.values[o[a]]);t("break")("}")}else t("{")("var e=types[%i].verify(%s,n+1);",n,i)("if(e)")("return%j+e",s.name+".")("}");else switch(s.type){case"int32":case"uint32":case"sint32":case"fixed32":case"sfixed32":t("if(!util.isInteger(%s))",i)("return%j",r(s,"integer"));break;case"int64":case"uint64":case"sint64":case"fixed64":case"sfixed64":t("if(!util.isInteger(%s)&&!(%s&&util.isInteger(%s.low)&&util.isInteger(%s.high)))",i,i,i,i)("return%j",r(s,"integer|Long"));break;case"float":case"double":t('if(typeof %s!=="number")',i)("return%j",r(s,"number"));break;case"bool":t('if(typeof %s!=="boolean")',i)("return%j",r(s,"boolean"));break;case"string":t("if(!util.isString(%s))",i)("return%j",r(s,"string"));break;case"bytes":t('if(!(%s&&typeof %s.length==="number"||util.isString(%s)))',i,i,i)("return%j",r(s,"buffer"))}return t}function n(e,t,s){switch(t.keyType){case"int32":case"uint32":case"sint32":case"fixed32":case"sfixed32":e("if(!util.key32Re.test(%s))",s)("return%j",r(t,"integer key"));break;case"int64":case"uint64":case"sint64":case"fixed64":case"sfixed64":e("if(!util.key64Re.test(%s))",s)("return%j",r(t,"integer|Long key"));break;case"bool":e("if(!util.key2Re.test(%s))",s)("return%j",r(t,"boolean key"))}return e}return Eo}var Do,Po={};function xo(){return Do||(Do=1,function(e){var t=e,r=pa(),s=ca();function n(e,t,s,n){var i=!1;if(t.resolvedType)if(t.resolvedType instanceof r){e("switch(d%s){",n);for(var o=t.resolvedType.values,a=Object.keys(o),c=0;c<a.length;++c)o[a[c]]!==t.typeDefault||i||(e("default:")('if(typeof(d%s)==="number"){m%s=d%s;break}',n,n,n),t.repeated||e("break"),i=!0),e("case%j:",a[c])("case %i:",o[a[c]])("m%s=%j",n,o[a[c]])("break");e("}")}else e("if(!util.isObject(d%s))",n)("throw TypeError(%j)",t.fullName+": object expected")("m%s=types[%i].fromObject(d%s,n+1)",n,s,n);else{var d=!1;switch(t.type){case"double":case"float":e("m%s=Number(d%s)",n,n);break;case"uint32":case"fixed32":e("m%s=d%s>>>0",n,n);break;case"int32":case"sint32":case"sfixed32":e("m%s=d%s|0",n,n);break;case"uint64":case"fixed64":d=!0;case"int64":case"sint64":case"sfixed64":e("if(util.Long)")("m%s=util.Long.fromValue(d%s,%j)",n,n,d)('else if(typeof d%s==="string")',n)("m%s=parseInt(d%s,10)",n,n)('else if(typeof d%s==="number")',n)("m%s=d%s",n,n)('else if(typeof d%s==="object")',n)("m%s=new util.LongBits(d%s.low>>>0,d%s.high>>>0).toNumber(%s)",n,n,n,d?"true":"");break;case"bytes":e('if(typeof d%s==="string")',n)("util.base64.decode(d%s,m%s=util.newBuffer(util.base64.length(d%s)),0)",n,n,n)("else if(d%s.length >= 0)",n)("m%s=d%s",n,n);break;case"string":e("m%s=String(d%s)",n,n);break;case"bool":e("m%s=Boolean(d%s)",n,n)}}return e}function i(e,t,s,n){if(t.resolvedType)t.resolvedType instanceof r?e("d%s=o.enums===String?(types[%i].values[m%s]===undefined?m%s:types[%i].values[m%s]):m%s",n,s,n,n,s,n,n):e("d%s=types[%i].toObject(m%s,o,q+1)",n,s,n);else{var i=!1;switch(t.type){case"double":case"float":e("d%s=o.json&&!isFinite(m%s)?String(m%s):m%s",n,n,n,n);break;case"uint64":case"fixed64":i=!0;case"int64":case"sint64":case"sfixed64":e('if(typeof BigInt!=="undefined"&&o.longs===BigInt)')('d%s=typeof m%s==="number"?BigInt(m%s):util.Long.fromBits(m%s.low>>>0,m%s.high>>>0,%j).toBigInt()',n,n,n,n,n,i)('else if(typeof m%s==="number")',n)("d%s=o.longs===String?String(m%s):m%s",n,n,n)("else")("d%s=o.longs===String?util.Long.prototype.toString.call(m%s):o.longs===Number?new util.LongBits(m%s.low>>>0,m%s.high>>>0).toNumber(%s):m%s",n,n,n,n,i?"true":"",n);break;case"bytes":e("d%s=o.bytes===String?util.base64.encode(m%s,0,m%s.length):o.bytes===Array?Array.prototype.slice.call(m%s):m%s",n,n,n,n,n);break;default:e("d%s=m%s",n,n)}}return e}t.fromObject=function(e){var t=e.fieldsArray,i=s.codegen(["d","n"],e.name+"$fromObject")("if(d instanceof this.ctor)")("return d");if(!t.length)return i("return new this.ctor");i("if(!util.isObject(d))")("throw TypeError(%j)",e.fullName+": object expected")("if(n===undefined)n=0")("if(n>util.recursionLimit)")('throw Error("maximum nesting depth exceeded")'),i("var m=new this.ctor");for(var o=0;o<t.length;++o){var a=t[o].resolve(),c=s.safeProp(a.name);a.map?(i("if(d%s){",c)("if(!util.isObject(d%s))",c)("throw TypeError(%j)",a.fullName+": object expected")("m%s={}",c)("for(var ks=Object.keys(d%s),i=0;i<ks.length;++i){",c),i('if(ks[i]==="__proto__")')("util.makeProp(m%s,ks[i])",c),n(i,a,o,c+"[ks[i]]")("}")("}")):a.repeated?(i("if(d%s){",c)("if(!Array.isArray(d%s))",c)("throw TypeError(%j)",a.fullName+": array expected")("m%s=[]",c)("for(var i=0;i<d%s.length;++i){",c),n(i,a,o,c+"[i]")("}")("}")):(a.resolvedType instanceof r||i("if(d%s!=null){",c),n(i,a,o,c),a.resolvedType instanceof r||i("}"))}return i("return m")},t.toObject=function(e){var t=e.fieldsArray.slice().sort(s.compareFieldsById);if(!t.length)return s.codegen()("return {}");for(var n=s.codegen(["m","o","q"],e.name+"$toObject")("if(!o)")("o={}")("if(q===undefined)q=0")("if(q>util.recursionLimit)")('throw Error("max depth exceeded")')("var d={}"),o=[],a=[],c=[],d=0;d<t.length;++d)t[d].partOf||(t[d].resolve().repeated?o:t[d].map?a:c).push(t[d]);if(o.length){for(n("if(o.arrays||o.defaults){"),d=0;d<o.length;++d)n("d%s=[]",s.safeProp(o[d].name));n("}")}if(a.length){for(n("if(o.objects||o.defaults){"),d=0;d<a.length;++d)n("d%s={}",s.safeProp(a[d].name));n("}")}if(c.length){for(n("if(o.defaults){"),d=0;d<c.length;++d){var u=c[d],l=s.safeProp(u.name);if(u.resolvedType instanceof r)n("d%s=o.enums===String?%j:%j",l,u.resolvedType.valuesById[u.typeDefault],u.typeDefault);else if(u.long)n("if(util.Long){")("var n=new util.Long(%i,%i,%j)",u.typeDefault.low,u.typeDefault.high,u.typeDefault.unsigned)('d%s=o.longs===String?n.toString():o.longs===Number?n.toNumber():typeof BigInt!=="undefined"&&o.longs===BigInt?n.toBigInt():n',l)("}else")('d%s=o.longs===String?%j:typeof BigInt!=="undefined"&&o.longs===BigInt?BigInt(%j):%i',l,u.typeDefault.toString(),u.typeDefault.toString(),u.typeDefault.toNumber());else if(u.bytes){var h=Array.prototype.slice.call(u.typeDefault);n("if(o.bytes===String)d%s=%j",l,String.fromCharCode.apply(String,u.typeDefault))("else{")("d%s=%j",l,h)("if(o.bytes!==Array)d%s=util.newBuffer(d%s)",l,l)("}")}else n("d%s=%j",l,u.typeDefault)}n("}")}var p=!1;for(d=0;d<t.length;++d){u=t[d];var m=e._fieldsArray.indexOf(u);l=s.safeProp(u.name);u.map?(p||(p=!0,n("var ks2")),n("if(m%s&&(ks2=Object.keys(m%s)).length){",l,l)("d%s={}",l)("for(var j=0;j<ks2.length;++j){"),n('if(ks2[j]==="__proto__")')("util.makeProp(d%s,ks2[j])",l),i(n,u,m,l+"[ks2[j]]")("}")):u.repeated?(n("if(m%s&&m%s.length){",l,l)("d%s=[]",l)("for(var j=0;j<m%s.length;++j){",l),i(n,u,m,l+"[j]")("}")):(n("if(m%s!=null&&Object.hasOwnProperty.call(m,%j)){",l,u.name),i(n,u,m,l),u.partOf&&n("if(o.oneofs)")("d%s=%j",s.safeProp(u.partOf.name),u.name)),n("}")}return n("return d")}}(Po)),Po}var Fo,Bo,Go,qo,$o,jo,Vo,Ko,zo,Ho,Wo,Jo,Qo,Zo,Yo,Xo,ea,ta,ra,sa,na={};function ia(){return Fo||(Fo=1,e=na,t=Uo(),r=xi(),e[".google.protobuf.Any"]={fromObject:function(e,t){if(e&&e["@type"]){var r=e["@type"].substring(e["@type"].lastIndexOf("/")+1),s=this.lookup(r);if(s){var n="."===e["@type"].charAt(0)?e["@type"].slice(1):e["@type"];return-1===n.indexOf("/")&&(n="/"+n),this.create({type_url:n,value:s.encode(s.fromObject(e,void 0===t?1:t+1)).finish()})}}return this.fromObject(e,t)},toObject:function(e,s,n){if(void 0===n&&(n=0),n>r.recursionLimit)throw Error("max depth exceeded");var i="",o="";if(s&&s.json&&e.type_url&&e.value){o=e.type_url.substring(e.type_url.lastIndexOf("/")+1),i=e.type_url.substring(0,e.type_url.lastIndexOf("/")+1);var a=this.lookup(o);a&&(e=a.decode(e.value,void 0,void 0,n+1))}if(!(e instanceof this.ctor)&&e instanceof t){var c=e.$type.toObject(e,s,n+1);return""===i&&(i="type.googleapis.com/"),o=i+("."===e.$type.fullName[0]?e.$type.fullName.slice(1):e.$type.fullName),c["@type"]=o,c}return this.toObject(e,s,n)}}),na;var e,t,r}function oa(){if(Go)return Bo;Go=1,Bo=f;var e=Ao();((f.prototype=Object.create(e.prototype)).constructor=f).className="Type";var t=pa(),r=la(),s=ua(),n=No(),i=Mo(),o=Uo(),a=Bi(),c=Fi(),d=ca(),u=ma(),l=Lo(),h=ko(),p=xo(),m=ia();function f(t,r){t=t.replace(/\W/g,""),e.call(this,t,r),this.fields={},this.oneofs=void 0,this.extensions=void 0,this.reserved=void 0,this.group=void 0,this._fieldsById=null,this._fieldsArray=null,this._oneofsArray=null,this._ctor=null}function g(e){return e._fieldsById=e._fieldsArray=e._oneofsArray=null,delete e.encode,delete e.decode,delete e.verify,e}return Object.defineProperties(f.prototype,{fieldsById:{get:function(){if(this._fieldsById)return this._fieldsById;this._fieldsById={};for(var e=Object.keys(this.fields),t=0;t<e.length;++t){var r=this.fields[e[t]],s=r.id;if(this._fieldsById[s])throw Error("duplicate id "+s+" in "+this);this._fieldsById[s]=r}return this._fieldsById}},fieldsArray:{get:function(){return this._fieldsArray||(this._fieldsArray=d.toArray(this.fields))}},oneofsArray:{get:function(){return this._oneofsArray||(this._oneofsArray=d.toArray(this.oneofs))}},ctor:{get:function(){return this._ctor||(this.ctor=f.generateConstructor(this)())},set:function(e){var t=e.prototype;t instanceof o||((e.prototype=new o).constructor=e,d.merge(e.prototype,t)),e.$type=e.prototype.$type=this,d.merge(e,o,!0),this._ctor=e;for(var r=0;r<this.fieldsArray.length;++r)this._fieldsArray[r].resolve();var s={};for(r=0;r<this.oneofsArray.length;++r)s[this._oneofsArray[r].resolve().name]={get:d.oneOfGetter(this._oneofsArray[r].oneof),set:d.oneOfSetter(this._oneofsArray[r].oneof)};r&&Object.defineProperties(e.prototype,s)}}}),f.generateConstructor=function(e){for(var t,r=d.codegen(["p"],e.name),s=0;s<e.fieldsArray.length;++s)(t=e._fieldsArray[s]).map?r("this%s={}",d.safeProp(t.name)):t.repeated&&r("this%s=[]",d.safeProp(t.name));return r('if(p)for(var ks=Object.keys(p),i=0;i<ks.length;++i)if(p[ks[i]]!=null&&ks[i]!=="__proto__")')("this[ks[i]]=p[ks[i]]")},f.fromJSON=function(o,a,c){if(void 0===c&&(c=0),c>d.nestingLimit)throw Error("max depth exceeded");var u=new f(o,a.options);u.extensions=a.extensions,u.reserved=a.reserved;for(var l=Object.keys(a.fields),h=0;h<l.length;++h)u.add((void 0!==a.fields[l[h]].keyType?n.fromJSON:s.fromJSON)(l[h],a.fields[l[h]]));if(a.oneofs)for(l=Object.keys(a.oneofs),h=0;h<l.length;++h)u.add(r.fromJSON(l[h],a.oneofs[l[h]]));if(a.nested)for(l=Object.keys(a.nested),h=0;h<l.length;++h){var p=a.nested[l[h]];u.add((void 0!==p.id?s.fromJSON:void 0!==p.fields?f.fromJSON:void 0!==p.values?t.fromJSON:void 0!==p.methods?i.fromJSON:e.fromJSON)(l[h],p,c+1))}return a.extensions&&a.extensions.length&&(u.extensions=a.extensions),a.reserved&&a.reserved.length&&(u.reserved=a.reserved),a.group&&(u.group=!0),a.comment&&(u.comment=a.comment),a.edition&&(u._edition=a.edition),u._defaultEdition="proto3",u},f.prototype.toJSON=function(t){var r=e.prototype.toJSON.call(this,t),s=!!t&&Boolean(t.keepComments);return d.toObject(["edition",this._editionToJSON(),"options",r&&r.options||void 0,"oneofs",e.arrayToJSON(this.oneofsArray,t),"fields",e.arrayToJSON(this.fieldsArray.filter(function(e){return!e.declaringField}),t)||{},"extensions",this.extensions&&this.extensions.length?this.extensions:void 0,"reserved",this.reserved&&this.reserved.length?this.reserved:void 0,"group",this.group||void 0,"nested",r&&r.nested||void 0,"comment",s?this.comment:void 0])},f.prototype.resolveAll=function(){if(!this._needsRecursiveResolve)return this;e.prototype.resolveAll.call(this);var t=this.oneofsArray;for(s=0;s<t.length;)t[s++].resolve();for(var r=this.fieldsArray,s=0;s<r.length;)r[s++].resolve();return this},f.prototype._resolveFeaturesRecursive=function(t){return this._needsRecursiveFeatureResolution?(t=this._edition||t,e.prototype._resolveFeaturesRecursive.call(this,t),this.oneofsArray.forEach(e=>{e._resolveFeatures(t)}),this.fieldsArray.forEach(e=>{e._resolveFeatures(t)}),this):this},f.prototype.get=function(e){return Object.prototype.hasOwnProperty.call(this.fields,e)?this.fields[e]:this.oneofs&&Object.prototype.hasOwnProperty.call(this.oneofs,e)?this.oneofs[e]:this.nested&&Object.prototype.hasOwnProperty.call(this.nested,e)?this.nested[e]:null},f.prototype.add=function(t){if(this.get(t.name))throw Error("duplicate name '"+t.name+"' in "+this);if(t instanceof s&&void 0===t.extend){if(this._fieldsById?this._fieldsById[t.id]:this.fieldsById[t.id])throw Error("duplicate id "+t.id+" in "+this);if(this.isReservedId(t.id))throw Error("id "+t.id+" is reserved in "+this);if(this.isReservedName(t.name)||"$"===t.name.charAt(0))throw Error("name '"+t.name+"' is reserved in "+this);return"__proto__"===t.name?this:(t.parent&&t.parent.remove(t),this.fields[t.name]=t,t.message=this,t.onAdd(this),g(this))}if(t instanceof r){if("$"===t.name.charAt(0))throw Error("name '"+t.name+"' is reserved in "+this);return"__proto__"===t.name?this:(this.oneofs||(this.oneofs={}),this.oneofs[t.name]=t,t.onAdd(this),g(this))}return e.prototype.add.call(this,t)},f.prototype.remove=function(t){if(t instanceof s&&void 0===t.extend){if(!this.fields||this.fields[t.name]!==t)throw Error(t+" is not a member of "+this);return delete this.fields[t.name],t.parent=null,t.onRemove(this),g(this)}if(t instanceof r){if(!this.oneofs||this.oneofs[t.name]!==t)throw Error(t+" is not a member of "+this);return delete this.oneofs[t.name],t.parent=null,t.onRemove(this),g(this)}return e.prototype.remove.call(this,t)},f.prototype.isReservedId=function(t){return e.isReservedId(this.reserved,t)},f.prototype.isReservedName=function(t){return e.isReservedName(this.reserved,t)},f.prototype.create=function(e){return new this.ctor(e)},f.prototype.setup=function(){for(var e=this.fullName,t=[],r=0;r<this.fieldsArray.length;++r)t.push(this._fieldsArray[r].resolve().resolvedType);this.encode=u(this)({Writer:c,types:t,util:d}),this.decode=l(this)({Reader:a,types:t,util:d}),this.verify=h(this)({types:t,util:d}),this.fromObject=p.fromObject(this)({types:t,util:d}),this.toObject=p.toObject(this)({types:t,util:d});var s=m[e];if(s){var n=Object.create(this);n.fromObject=this.fromObject,this.fromObject=s.fromObject.bind(n),n.toObject=this.toObject,this.toObject=s.toObject.bind(n)}return this},f.prototype.encode=function(e,t){return this.setup().encode.apply(this,arguments)},f.prototype.encodeDelimited=function(e,t){return this.encode(e,t&&t.len?t.fork():t).ldelim()},f.prototype.decode=function(e,t,r,s){return this.setup().decode(e,t,r,s)},f.prototype.decodeDelimited=function(e){return e instanceof a||(e=a.create(e)),this.decode(e,e.uint32())},f.prototype.verify=function(e,t){return this.setup().verify(e,t)},f.prototype.fromObject=function(e,t){return this.setup().fromObject(e,t)},f.prototype.toObject=function(e,t){return this.setup().toObject.apply(this,arguments)},f.d=function(e){return function(t){d.decorateType(t,e)}},Bo}function aa(){if($o)return qo;$o=1,qo=c;var e=Ao();((c.prototype=Object.create(e.prototype)).constructor=c).className="Root";var t,r,s,n=ua(),i=pa(),o=la(),a=ca();function c(t){e.call(this,"",t),this.deferred=[],this.files=[],this._edition="proto2",this._fullyQualifiedObjects={}}function d(){}c.fromJSON=function(e,t,r){return r=a.checkDepth(r),t||(t=new c),e.options&&t.setOptions(e.options),t.addJSON(e.nested,r).resolveAll()},c.prototype.resolvePath=a.path.resolve,c.prototype.fetch=a.fetch,c.prototype.load=function e(t,n,i){"function"==typeof n&&(i=n,n=void 0);var o=this;if(!i)return a.asPromise(e,o,t,n);var c=i===d;function u(e,t){if(i){if(c)throw e;t&&t.resolveAll();var r=i;i=null,r(e,t)}}function l(e){var t=e.lastIndexOf("google/protobuf/");if(t>-1){var r=e.substring(t);if(r in s)return r}return null}function h(e,t,s){void 0===s&&(s=0);try{if(s>a.recursionLimit)throw Error("max depth exceeded");if(a.isString(t)&&"{"===t.charAt(0)&&(t=JSON.parse(t)),a.isString(t)){r.filename=e;var i,d=r(t,o,n),h=0;if(d.imports)for(;h<d.imports.length;++h)(i=l(d.imports[h])||o.resolvePath(e,d.imports[h]))&&p(i,!1,s+1);if(d.weakImports)for(h=0;h<d.weakImports.length;++h)(i=l(d.weakImports[h])||o.resolvePath(e,d.weakImports[h]))&&p(i,!0,s+1)}else o.setOptions(t.options).addJSON(t.nested)}catch(f){u(f)}c||m||u(null,o)}function p(e,t,r){if(void 0===r&&(r=0),e=l(e)||e,!(o.files.indexOf(e)>-1))if(o.files.push(e),e in s)c?h(e,s[e],r):(++m,setTimeout(function(){--m,h(e,s[e],r)}));else if(c){var n;try{n=a.fs.readFileSync(e).toString("utf8")}catch(d){return void(t||u(d))}h(e,n,r)}else++m,o.fetch(e,function(s,n){--m,i&&(s?t?m||u(null,o):u(s):h(e,n,r))})}var m=0;a.isString(t)&&(t=[t]);for(var f,g=0;g<t.length;++g)(f=o.resolvePath("",t[g]))&&p(f);return c?(o.resolveAll(),o):(m||u(null,o),o)},c.prototype.loadSync=function(e,t){if(!a.isNode)throw Error("not supported");return this.load(e,t,d)},c.prototype.resolveAll=function(){if(!this._needsRecursiveResolve)return this;if(this.deferred.length)throw Error("unresolvable extensions: "+this.deferred.map(function(e){return"'extend "+e.extend+"' in "+e.parent.fullName}).join(", "));return e.prototype.resolveAll.call(this)};var u=/^[A-Z]/;function l(e,t){var r=t.parent.lookup(t.extend);if(r){var s=new n(t.fullName,t.id,t.type,t.rule,void 0,t.options);return r.get(s.name)||(s.declaringField=t,t.extensionField=s,r.add(s)),!0}return!1}return c.prototype._handleAdd=function(e){if(e instanceof n)void 0===e.extend||e.extensionField||l(0,e)||this.deferred.push(e);else if(e instanceof i)u.test(e.name)&&(e.parent[e.name]=e.values);else if(!(e instanceof o)){if(e instanceof t)for(var r=0;r<this.deferred.length;)l(0,this.deferred[r])?this.deferred.splice(r,1):++r;for(var s=0;s<e.nestedArray.length;++s)this._handleAdd(e._nestedArray[s]);u.test(e.name)&&(e.parent[e.name]=e)}(e instanceof t||e instanceof i||e instanceof n)&&(this._fullyQualifiedObjects[e.fullName]=e)},c.prototype._handleRemove=function(t){if(t instanceof n){if(void 0!==t.extend)if(t.extensionField)t.extensionField.parent.remove(t.extensionField),t.extensionField=null;else{var r=this.deferred.indexOf(t);r>-1&&this.deferred.splice(r,1)}}else if(t instanceof i)u.test(t.name)&&delete t.parent[t.name];else if(t instanceof e){for(var s=0;s<t.nestedArray.length;++s)this._handleRemove(t._nestedArray[s]);u.test(t.name)&&delete t.parent[t.name]}delete this._fullyQualifiedObjects[t.fullName]},c._configure=function(e,n,i){t=e,r=n,s=i},qo}function ca(){if(jo)return Xi.exports;jo=1;var e,t,r,s,n,i,o=Xi.exports=xi(),a=Wi();o.codegen=eo(),o.fetch=oo(),o.path=(ao||(ao=1,s=(r=co).isAbsolute=function(e){return/^(?:\/|\w+:)/.test(e)},n=r.normalize=function(e){var t=(e=e.replace(/\\/g,"/").replace(/\/{2,}/g,"/")).split("/"),r=s(e),n="";r&&(n=t.shift()+"/");for(var i=0;i<t.length;)".."===t[i]?i>0&&".."!==t[i-1]?t.splice(--i,2):r?t.splice(i,1):++i:"."===t[i]?t.splice(i,1):++i;return n+t.join("/")},r.resolve=function(e,t,r){return r||(t=n(t)),s(t)?t:(r||(e=n(e)),(e=e.replace(/(?:\/|^)[^/]+$/,"")).length?n(e+"/"+t):t)}),co),o.patterns=(uo||(uo=1,(i=Ro).numberRe=/^(?![eE])[0-9]*(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?$/,i.typeRefRe=/^(?:\.?[a-zA-Z_][a-zA-Z_0-9]*)(?:\.[a-zA-Z_][a-zA-Z_0-9]*)*$/,i.reservedRe=/^(?:do|if|in|for|let|new|try|var|case|else|enum|eval|false|null|this|true|void|with|break|catch|class|const|super|throw|while|yield|delete|export|import|public|return|static|switch|typeof|default|extends|finally|package|private|continue|debugger|function|arguments|interface|protected|implements|instanceof)$/),Ro);var c=o.patterns.reservedRe;o.fs=function(){if(ho)return lo;ho=1;var e=null;try{(e=to)&&e.readFile&&e.readFileSync||(e=null)}catch(t){}return lo=e}(),o.checkDepth=function(e){if(void 0===e&&(e=0),e>o.recursionLimit)throw Error("max depth exceeded");return e},o.toArray=function(e){if(e){for(var t=Object.keys(e),r=new Array(t.length),s=0;s<t.length;)r[s]=e[t[s++]];return r}return[]},o.toObject=function(e){for(var t={},r=0;r<e.length;){var s=e[r++],n=e[r++];void 0!==n&&(t[s]=n)}return t},o.isReserved=function(e){return c.test(e)},o.safeProp=function(e){return!/^[$\w_]+$/.test(e)||c.test(e)?"["+JSON.stringify(e)+"]":"."+e},o.ucFirst=function(e){return e.charAt(0).toUpperCase()+e.substring(1)};var d=/_([a-z])/g;o.camelCase=function(e){return e.substring(0,1)+e.substring(1).replace(d,function(e,t){return t.toUpperCase()})},o.compareFieldsById=function(e,t){return e.id-t.id},o.decorateType=function(t,r){if(t.$type)return r&&t.$type.name!==r&&(o.decorateRoot.remove(t.$type),t.$type.name=r,o.decorateRoot.add(t.$type)),t.$type;e||(e=oa());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=pa());var r=new t("Enum"+u++,e);return o.decorateRoot.add(r),Object.defineProperty(e,"$type",{value:r,enumerable:!1}),r},o.setProperty=function(e,t,r,s){if("object"!=typeof e)throw TypeError("dst must be an object");if(!t)throw TypeError("path must be specified");if((t=t.split(".")).length>o.recursionLimit)throw Error("max depth exceeded");return function e(t,r,n){var i=r.shift();if(o.isUnsafeProperty(i))return t;if(r.length>0)t[i]=e(t[i]||{},r,n);else{var a=t[i];if(a&&s)return t;a&&(n=[].concat(a).concat(n)),t[i]=n}return t}(e,t,r)},Object.defineProperty(o,"decorateRoot",{get:function(){return a.decorated||(a.decorated=new(aa()))}}),Xi.exports}function da(){return Vo||(Vo=1,function(e){var t=e,r=ca(),s=["double","float","int32","uint32","sint32","fixed32","sfixed32","int64","uint64","sint64","fixed64","sfixed64","bool","string","bytes"];function n(e,t){var r=0,n=Object.create(null);for(t|=0;r<e.length;)n[s[r+t]]=e[r++];return n}t.basic=n([1,5,0,0,0,5,5,0,0,0,1,1,0,2,2]),t.defaults=n([0,0,0,0,0,0,0,0,0,0,0,0,!1,"",r.emptyArray,null]),t.long=n([0,0,0,1,1],7),t.mapKey=n([0,0,0,5,5,0,0,0,1,1,0,2],2),t.packed=n([1,5,0,0,0,5,5,0,0,0,1,1,0])}(Yi)),Yi}function ua(){if(zo)return Ko;zo=1,Ko=o;var e=ha();((o.prototype=Object.create(e.prototype)).constructor=o).className="Field";var t,r=pa(),s=da(),n=ca(),i=/^required|optional|repeated$/;function o(t,r,o,a,c,d,u){if(n.isObject(a)?(u=c,d=a,a=c=void 0):n.isObject(c)&&(u=d,d=c,c=void 0),e.call(this,t,d),!n.isInteger(r)||r<0)throw TypeError("id must be a non-negative integer");if(!n.isString(o))throw TypeError("type must be a string");if(void 0!==a&&!i.test(a=a.toString().toLowerCase()))throw TypeError("rule must be a string rule");if(void 0!==c&&!n.isString(c))throw TypeError("extend must be a string");"proto3_optional"===a&&(a="optional"),this.rule=a&&"optional"!==a?a:void 0,this.type=o,this.id=r,this.extend=c||void 0,this.repeated="repeated"===a,this.map=!1,this.message=null,this.partOf=null,this.typeDefault=null,this.defaultValue=null,this.long=!!n.Long&&void 0!==s.long[o],this.bytes="bytes"===o,this.resolvedType=null,this.extensionField=null,this.declaringField=null,this.comment=u}return o.fromJSON=function(e,t){var r=new o(e,t.id,t.type,t.rule,t.extend,t.options,t.comment);return t.edition&&(r._edition=t.edition),r._defaultEdition="proto3",r},Object.defineProperty(o.prototype,"required",{get:function(){return"LEGACY_REQUIRED"===this._features.field_presence}}),Object.defineProperty(o.prototype,"optional",{get:function(){return!this.required}}),Object.defineProperty(o.prototype,"delimited",{get:function(){return this.resolvedType instanceof t&&"DELIMITED"===this._features.message_encoding}}),Object.defineProperty(o.prototype,"packed",{get:function(){return"PACKED"===this._features.repeated_field_encoding}}),Object.defineProperty(o.prototype,"hasPresence",{get:function(){return!this.repeated&&!this.map&&(this.partOf||this.declaringField||this.extensionField||"IMPLICIT"!==this._features.field_presence)}}),o.prototype.setOption=function(t,r,s){return e.prototype.setOption.call(this,t,r,s)},o.prototype.toJSON=function(e){var t=!!e&&Boolean(e.keepComments);return n.toObject(["edition",this._editionToJSON(),"rule","optional"!==this.rule&&this.rule||void 0,"type",this.type,"id",this.id,"extend",this.extend,"options",this.options,"comment",t?this.comment:void 0])},o.prototype.resolve=function(){if(this.resolved)return this;if(void 0===(this.typeDefault=s.defaults[this.type])?(this.resolvedType=(this.declaringField?this.declaringField.parent:this.parent).lookupTypeOrEnum(this.type),this.resolvedType instanceof t?this.typeDefault=null:this.typeDefault=this.resolvedType.values[Object.keys(this.resolvedType.values)[0]]):this.options&&this.options.proto3_optional&&(this.typeDefault=null),this.options&&null!=this.options.default&&(this.typeDefault=this.options.default,this.resolvedType instanceof r&&"string"==typeof this.typeDefault&&(this.typeDefault=this.resolvedType.values[this.typeDefault])),this.options&&(void 0===this.options.packed||!this.resolvedType||this.resolvedType instanceof r||delete this.options.packed,Object.keys(this.options).length||(this.options=void 0)),this.long)this.typeDefault=n.Long.fromNumber(this.typeDefault,"uint64"===this.type||"fixed64"===this.type),Object.freeze&&Object.freeze(this.typeDefault);else if(this.bytes&&"string"==typeof this.typeDefault){var i;n.base64.test(this.typeDefault)?n.base64.decode(this.typeDefault,i=n.newBuffer(n.base64.length(this.typeDefault)),0):n.utf8.write(this.typeDefault,i=n.newBuffer(n.utf8.length(this.typeDefault)),0),this.typeDefault=i}return this.map?this.defaultValue=n.emptyObject:this.repeated?this.defaultValue=n.emptyArray:this.defaultValue=this.typeDefault,this.parent instanceof t&&(this.parent.ctor.prototype[this.name]=this.defaultValue),e.prototype.resolve.call(this)},o.prototype._inferLegacyProtoFeatures=function(e){if("proto2"!==e&&"proto3"!==e)return{};var r={};if("required"===this.rule&&(r.field_presence="LEGACY_REQUIRED"),this.parent&&void 0===s.defaults[this.type]){var n=this.parent.get(this.type.split(".").pop());n&&n instanceof t&&n.group&&(r.message_encoding="DELIMITED")}return!0===this.getOption("packed")?r.repeated_field_encoding="PACKED":!1===this.getOption("packed")&&(r.repeated_field_encoding="EXPANDED"),r},o.prototype._resolveFeatures=function(t){return e.prototype._resolveFeatures.call(this,this._edition||t)},o.d=function(e,t,r,s){return"function"==typeof t?t=n.decorateType(t).name:t&&"object"==typeof t&&(t=n.decorateEnum(t).name),function(i,a){n.decorateType(i.constructor).add(new o(a,e,t,r,{default:s}))}},o._configure=function(e){t=e},Ko}function la(){if(Wo)return Ho;Wo=1,Ho=s;var e=ha();((s.prototype=Object.create(e.prototype)).constructor=s).className="OneOf";var t=ua(),r=ca();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)})}},Ho}function ha(){if(Qo)return Jo;Qo=1,Jo=o,o.className="ReflectionObject";const e=la();var t,r=ca(),s={enum_type:"OPEN",field_presence:"EXPLICIT",json_format:"ALLOW",message_encoding:"LENGTH_PREFIXED",repeated_field_encoding:"PACKED",utf8_validation:"VERIFY"},n={enum_type:"CLOSED",field_presence:"EXPLICIT",json_format:"LEGACY_BEST_EFFORT",message_encoding:"LENGTH_PREFIXED",repeated_field_encoding:"EXPANDED",utf8_validation:"NONE"},i={enum_type:"OPEN",field_presence:"IMPLICIT",json_format:"ALLOW",message_encoding:"LENGTH_PREFIXED",repeated_field_encoding:"PACKED",utf8_validation:"VERIFY"};function o(e,t){if(!r.isString(e))throw TypeError("name must be a string");if(t&&!r.isObject(t))throw TypeError("options must be an object");this.options=t,this.parsedOptions=null,this.name=e,this._edition=null,this._defaultEdition="proto2",this._features={},this._featuresResolved=!1,this.parent=null,this.resolved=!1,this.comment=null,this.filename=null}return Object.defineProperties(o.prototype,{root:{get:function(){for(var e=this;null!==e.parent;)e=e.parent;return e}},fullName:{get:function(){for(var e=[this.name],t=this.parent;t;)e.unshift(t.name),t=t.parent;return e.join(".")}}}),o.prototype.toJSON=function(){throw Error()},o.prototype.onAdd=function(e){this.parent&&this.parent!==e&&this.parent.remove(this),this.parent=e,this.resolved=!1;var r=e.root;r instanceof t&&r._handleAdd(this)},o.prototype.onRemove=function(e){var r=e.root;r instanceof t&&r._handleRemove(this),this.parent=null,this.resolved=!1},o.prototype.resolve=function(){return this.resolved||this.root instanceof t&&(this.resolved=!0),this},o.prototype._resolveFeaturesRecursive=function(e){return this._resolveFeatures(this._edition||e)},o.prototype._resolveFeatures=function(t){if(!this._featuresResolved){var o={};if(!t)throw new Error("Unknown edition for "+this.fullName);var a=r.merge({},this.options&&this.options.features,this._inferLegacyProtoFeatures(t));if(this._edition){if("proto2"===t)o=Object.assign({},n);else if("proto3"===t)o=Object.assign({},i);else{if("2023"!==t)throw new Error("Unknown edition: "+t);o=Object.assign({},s)}return this._features=r.merge(o,a),void(this._featuresResolved=!0)}if(this.partOf instanceof e){var c=r.merge({},this.partOf._features);this._features=r.merge(c,a)}else if(this.declaringField);else{if(!this.parent)throw new Error("Unable to find a parent for "+this.fullName);var d=r.merge({},this.parent._features);this._features=r.merge(d,a)}this.extensionField&&(this.extensionField._features=this._features),this._featuresResolved=!0}},o.prototype._inferLegacyProtoFeatures=function(){return{}},o.prototype.getOption=function(e){if(this.options)return this.options[e]},o.prototype.setOption=function(e,t,s){return"__proto__"===e||(this.options||(this.options={}),/^features\./.test(e)?r.setProperty(this.options,e,t,s):s&&void 0!==this.options[e]||(this.getOption(e)!==t&&(this.resolved=!1),this.options[e]=t)),this},o.prototype.setParsedOption=function(e,t,s){if("__proto__"===e)return this;this.parsedOptions||(this.parsedOptions=[]);var n=this.parsedOptions;if(s){var i=n.find(function(t){return Object.prototype.hasOwnProperty.call(t,e)});if(i){var o=i[e];r.setProperty(o,s,t)}else(i={})[e]=r.setProperty({},s,t),n.push(i)}else{var a={};a[e]=t,n.push(a)}return this},o.prototype.setOptions=function(e,t){if(e)for(var r=Object.keys(e),s=0;s<r.length;++s)this.setOption(r[s],e[r[s]],t);return this},o.prototype.toString=function(){var e=this.constructor.className,t=this.fullName;return t.length?e+" "+t:e},o.prototype._editionToJSON=function(){if(this._edition&&"proto3"!==this._edition)return this._edition},o._configure=function(e){t=e},Jo}function pa(){if(Yo)return Zo;Yo=1,Zo=s;var e=ha();((s.prototype=Object.create(e.prototype)).constructor=s).className="Enum";var t=Ao(),r=ca();function s(t,r,s,n,i,o){if(e.call(this,t,s),r&&"object"!=typeof r)throw TypeError("values must be an object");if(this.valuesById={},this.values=Object.create(this.valuesById),this.comment=n,this.comments=i||{},this.valuesOptions=o,this._valuesFeatures={},this.reserved=void 0,r)for(var a=Object.keys(r),c=0;c<a.length;++c)"__proto__"!==a[c]&&"number"==typeof r[a[c]]&&(this.valuesById[this.values[a[c]]=r[a[c]]]=a[c])}return s.prototype._resolveFeatures=function(t){return t=this._edition||t,e.prototype._resolveFeatures.call(this,t),Object.keys(this.values).forEach(e=>{var t=r.merge({},this._features);this._valuesFeatures[e]=r.merge(t,this.valuesOptions&&this.valuesOptions[e]&&this.valuesOptions[e].features||{})}),this},s.fromJSON=function(e,t){var r=new s(e,t.values,t.options,t.comment,t.comments);return r.reserved=t.reserved,t.edition&&(r._edition=t.edition),r._defaultEdition="proto3",r},s.prototype.toJSON=function(e){var t=!!e&&Boolean(e.keepComments);return r.toObject(["edition",this._editionToJSON(),"options",this.options,"valuesOptions",this.valuesOptions,"values",this.values,"reserved",this.reserved&&this.reserved.length?this.reserved:void 0,"comment",t?this.comment:void 0,"comments",t?this.comments:void 0])},s.prototype.add=function(e,t,s,n){if(!r.isString(e))throw TypeError("name must be a string");if(!r.isInteger(t))throw TypeError("id must be an integer");if("__proto__"===e)return this;if(void 0!==this.values[e])throw Error("duplicate name '"+e+"' in "+this);if(this.isReservedId(t))throw Error("id "+t+" is reserved in "+this);if(this.isReservedName(e))throw Error("name '"+e+"' is reserved in "+this);if(void 0!==this.valuesById[t]){if(!this.options||!this.options.allow_alias)throw Error("duplicate id "+t+" in "+this);this.values[e]=t}else this.valuesById[this.values[e]=t]=e;return n&&(void 0===this.valuesOptions&&(this.valuesOptions={}),this.valuesOptions[e]=n||null),this.comments[e]=s||null,this},s.prototype.remove=function(e){if(!r.isString(e))throw TypeError("name must be a string");var t=this.values[e];if(null==t)throw Error("name '"+e+"' does not exist in "+this);return delete this.valuesById[t],delete this.values[e],delete this.comments[e],this.valuesOptions&&delete this.valuesOptions[e],this},s.prototype.isReservedId=function(e){return t.isReservedId(this.reserved,e)},s.prototype.isReservedName=function(e){return t.isReservedName(this.reserved,e)},Zo}function ma(){if(ea)return Xo;ea=1,Xo=function(n){for(var i,o=r.codegen(["m","w","q"],n.name+"$encode")("if(!w)")("w=Writer.create()")("if(q===undefined)q=0")("if(q>util.recursionLimit)")('throw Error("max depth exceeded")'),a=n.fieldsArray.slice().sort(r.compareFieldsById),c=0;c<a.length;++c){var d=a[c].resolve(),u=n._fieldsArray.indexOf(d),l=d.resolvedType instanceof e?"int32":d.type,h=t.basic[l];i="m"+r.safeProp(d.name),d.map?(o("if(%s!=null&&Object.hasOwnProperty.call(m,%j)){",i,d.name)("for(var ks=Object.keys(%s),i=0;i<ks.length;++i){",i)("w.uint32(%i).fork().uint32(%i).%s(ks[i])",(d.id<<3|2)>>>0,8|t.mapKey[d.keyType],d.keyType),void 0===h?o("types[%i].encode(%s[ks[i]],w.uint32(18).fork(),q+1).ldelim().ldelim()",u,i):o(".uint32(%i).%s(%s[ks[i]]).ldelim()",16|h,l,i),o("}")("}")):d.repeated?(o("if(%s!=null&&%s.length){",i,i),d.packed&&void 0!==t.packed[l]?o("w.uint32(%i).fork()",(d.id<<3|2)>>>0)("for(var i=0;i<%s.length;++i)",i)("w.%s(%s[i])",l,i)("w.ldelim()"):(o("for(var i=0;i<%s.length;++i)",i),void 0===h?s(o,d,u,i+"[i]"):o("w.uint32(%i).%s(%s[i])",(d.id<<3|h)>>>0,l,i)),o("}")):(d.optional&&o("if(%s!=null&&Object.hasOwnProperty.call(m,%j))",i,d.name),void 0===h?s(o,d,u,i):o("w.uint32(%i).%s(%s)",(d.id<<3|h)>>>0,l,i))}return o("return w")};var e=pa(),t=da(),r=ca();function s(e,t,r,s){return t.delimited?e("types[%i].encode(%s,w.uint32(%i),q+1).uint32(%i)",r,s,(t.id<<3|3)>>>0,(t.id<<3|4)>>>0):e("types[%i].encode(%s,w.uint32(%i).fork(),q+1).ldelim()",r,s,(t.id<<3|2)>>>0)}return Xo}var fa=sa?ra:(sa=1,ra=function(){if(ta)return di.exports;ta=1;var e=di.exports=Ji();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=ma(),e.decoder=Lo(),e.verifier=ko(),e.converter=xo(),e.ReflectionObject=ha(),e.Namespace=Ao(),e.Root=aa(),e.Enum=pa(),e.Type=oa(),e.Field=ua(),e.OneOf=la(),e.MapField=No(),e.Service=Mo(),e.Method=Oo(),e.Message=Uo(),e.wrappers=ia(),e.types=da(),e.util=ca(),e.ReflectionObject._configure(e.Root),e.Namespace._configure(e.Type,e.Service,e.Enum),e.Root._configure(e.Type),e.Field._configure(e.Type),di.exports}());const ga={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}}}}}}}}}},ya=e=>{if(!e||0===e.trim().length)throw dn("Proto type name is required.",{code:cn,stage:en,retryable:!1,details:{typeName:e}})};class va{constructor(){this.codecMap=new Map}register(e,t){ya(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 dn("Proto payload must be an object.",{code:cn,stage:en,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 ya(e),this.codecMap.get(e)}getOrThrow(e){const t=this.get(e);if(t)return t;throw dn("Proto codec not found.",{code:cn,stage:en,retryable:!1,details:{typeName:e}})}}const Ia=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),ba=e=>{class t extends fa.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},_a=e=>Dn.isLong(e),Ta=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&"number"==typeof e.byteLength,Ca=e=>Object.prototype.hasOwnProperty.call(fa.types.packed,e),Sa=e=>{const t=e.resolve();return t.resolvedType instanceof fa.Enum||Ca(t.type)},Ea=(e,t)=>t in e?e[t]:void 0,wa=e=>{const t=e.resolve();return t.resolvedType instanceof fa.Enum?0:(r=t.type,Object.prototype.hasOwnProperty.call(fa.types.basic,r)?fa.types.basic[t.type]:2);var r},Ra=(e,t)=>_a(e)||"number"==typeof e||"string"==typeof e?e:Ia(e)&&"number"==typeof e.low&&"number"==typeof e.high?new Dn(e.low,e.high,t):t?Dn.UZERO:Dn.ZERO,Aa=(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(Ra(r,!1));case"uint64":return e.uint64(Ra(r,!0));case"sint64":return e.sint64(Ra(r,!1));case"fixed64":return e.fixed64(Ra(r,!0));case"sfixed64":return e.sfixed64(Ra(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:Ta(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}`)}},Na=(e,t,r)=>{if(t<0||e.pos+t>r)throw RangeError(`index out of range: ${e.pos} + ${t} > ${r}`)},Oa=(e,t)=>{const r=e.uint32();return Na(e,r,t),r},Ma=(e,t,r)=>{const s=e.len;e.len=r;try{switch(t){case 0:return void e.skip();case 1:return Na(e,8,r),void e.skip(8);case 2:{const t=Oa(e,r);return void e.skip(t)}case 5:return Na(e,4,r),void e.skip(4);default:throw new Error(`Unsupported protobuf wire type: ${String(t)}`)}}finally{e.len=s}},Ua=(e,t,r)=>{const s=t.resolve(),n=s.resolvedType;if(n instanceof fa.Type){const t=e.fork();return ka(n,Ia(r)?r:{},t),t.ldelim(),e}return n instanceof fa.Enum?(e.int32("number"==typeof r?r:Number(r)),e):Aa(e,s.type,r)},La=(e,t,r)=>{if(0===r.length)return e;const s=t.resolve();if(Ca(s.type)&&t.packed){e.uint32(t.id<<3|2).fork();for(const s of r)Ua(e,t,s);return e.ldelim(),e}const n=wa(t);for(const i of r)e.uint32(t.id<<3|n),Ua(e,t,i);return e},ka=(e,t,r=fa.Writer.create())=>{const s=e.fieldsArray.slice().sort(fa.util.compareFieldsById);for(const n of s){const e=Ea(t,n.name);null!=e&&(n.repeated?La(r,n,Array.isArray(e)?e:[]):(r.uint32(n.id<<3|wa(n)),Ua(r,n,e)))}return r},Da=(e,t,r,s)=>{const n=t.resolve(),i=n.resolvedType;return i instanceof fa.Type?2!==r?void Ma(e,r,s):Pa(i,e,Oa(e,s)):i instanceof fa.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)},Pa=(e,t,r)=>{const s=t instanceof fa.Reader?t:fa.Reader.create(t),n=void 0===r?s.len:s.pos+r,i=(e=>{const t={};for(const r of e.fieldsArray)r.repeated&&(t[r.name]=[]);return t})(e),o=e.fieldsById;for(;s.pos<n;){const t=s.pos,r=s.uint32(),c=o[r>>>3],d=7&r;try{if(!c){Ma(s,d,n);continue}if(c.repeated){const e=Array.isArray(i[c.name])?i[c.name]:[];if(Sa(c)&&2===d){const t=Oa(s,n)+s.pos;for(;s.pos<t;)e.push(Da(s,c,0,t))}else{const t=Da(s,c,d,n);void 0!==t&&e.push(t)}i[c.name]=e;continue}const e=Da(s,c,d,n);void 0!==e&&(i[c.name]=e)}catch(a){if(a instanceof RangeError){const i=c?`${c.name}#${c.id}`:`unknown#${r>>>3}`;throw new RangeError(`${a.message}; protobufType=${e.fullName}; field=${i}; tag=${r}; wireType=${d}; tagPosition=${t}; readerPosition=${s.pos}; messageEnd=${n}`)}throw a}}return i},xa=(e,t)=>t?.longs===String?e.toString():t?.longs===Number?e.toNumber():e,Fa=(e,t)=>{const r=e.resolve();if(r.resolvedType instanceof fa.Type)return null;if(r.resolvedType instanceof fa.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&&_a(r.typeDefault)?xa(r.typeDefault,t):r.typeDefault},Ba=(e,t,r)=>{const s=e.resolve();if(void 0!==t)return s.resolvedType instanceof fa.Type?Ia(t)?Ga(s.resolvedType,t,r):t:s.resolvedType instanceof fa.Enum?r?.enums===String&&"number"==typeof t?s.resolvedType.valuesById[t]??t:t:s.long&&_a(t)?xa(t,r):"bytes"===s.type&&Ta(t)?((e,t)=>t?.bytes===String?fa.util.base64.encode(e,0,e.length):t?.bytes===Array?Array.prototype.slice.call(e):e)(t,r):t},Ga=(e,t,r)=>{const s={};for(const n of e.fieldsArray.slice().sort(fa.util.compareFieldsById)){const e=Ea(t,n.name);n.repeated?Array.isArray(e)?s[n.name]=e.map(e=>Ba(n,e,r)):(r?.arrays||r?.defaults)&&(s[n.name]=[]):null==e?r?.defaults&&(s[n.name]=Fa(n,r)):s[n.name]=Ba(n,e,r)}return s},qa=e=>{const t=e;t.__reflectionCodecInstalled||(t.__reflectionCodecInstalled=!0,e.encode=(t,r)=>ka(e,Ia(t)?t:{},r),e.decode=(t,r)=>Pa(e,t,r),e.fromObject=e=>Ia(e)?e:{},e.toObject=(t,r)=>Ga(e,Ia(t)?t:{},r),e.create=e=>e?{...e}:{},e.verify=()=>null)},$a=e=>{qa(e);for(const t of e.nestedArray)if(t instanceof fa.Type)$a(t);else if(t instanceof fa.Namespace)for(const e of t.nestedArray)e instanceof fa.Type&&$a(e)},ja=e=>{for(const t of e.nestedArray)t instanceof fa.Type?$a(t):t instanceof fa.Namespace&&ja(t)},Va=()=>{const e=fa.Type;e.__reflectionRuntimeInstalled||(e.generateConstructor=e=>()=>ba(e),fa.Type.prototype.setup=function(){return qa(this),this},fa.Type.prototype.create=function(e){return e?{...e}:{}},fa.Type.prototype.encode=function(e,t){return ka(this,Ia(e)?e:{},t)},fa.Type.prototype.decode=function(e,t){return Pa(this,e,t)},fa.Type.prototype.fromObject=function(e){return Ia(e)?e:{}},fa.Type.prototype.toObject=function(e,t){return Ga(this,Ia(e)?e:{},t)},fa.Type.prototype.verify=function(){return null},e.__reflectionRuntimeInstalled=!0)};let Ka=!1,za=null,Ha=null,Wa=null;const Ja=e=>e.startsWith(".")?e.slice(1):e,Qa=e=>e instanceof fa.Namespace,Za=e=>e instanceof fa.Type,Ya=e=>{for(const t of e.nestedArray)Za(t)?$a(t):Qa(t)&&Ya(t)},Xa=()=>{Ka||(fa.util.Long=Dn,fa.configure(),Ka=!0),Va();const e=fa.Root.fromJSON(ga);return Ya(e),e},ec=(e,t)=>{const r=e.nestedArray;for(const s of r){if(Za(s)){const e=Ja(s.fullName);$a(s),t.registerType(e,s);continue}Qa(s)&&ec(s,t)}},tc=(e,t,r)=>{const s=t instanceof Error?t.message:String(t);return dn(`Static proto ${r} failed.`,{code:cn,stage:en,retryable:!1,details:{typeName:e,operation:r,cause:s}})},rc=()=>za||(za=Xa(),za),sc=()=>{if(Wa)return Wa;const e=(()=>{if(Ha)return Ha;const e=new va,t=rc();return ec(t,e),Ha=e,e})();return Wa={encode(t,r){try{return e.getOrThrow(Ja(t)).encode(r)}catch(s){throw tc(t,s,"encode")}},decode(t,r){try{return e.getOrThrow(Ja(t)).decode(r)}catch(s){throw tc(t,s,"decode")}}},Wa},nc=e=>{const t={};if(!e)return 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},ic=async(e,t)=>{const r=e;if("function"!=typeof r.text){if("function"!=typeof r.json)return"";const e=await r.json();return t?e:JSON.stringify(e)}const s=await r.text();if(!t||0===s.length)return s;try{return JSON.parse(s)}catch{return s}},oc=e=>{const t=e?.fetchImpl;if("function"==typeof t)return{async request(r){const s=r.method??"GET",n={...r.headers??{}},i=new AbortController,o=r.timeoutMs??e?.timeoutMs??15e3;let a=!1;const c=()=>i.abort(r.signal?.reason);r.signal?.aborted?c():r.signal?.addEventListener("abort",c,{once:!0});const d=setTimeout(()=>{a=!0,i.abort()},o),u=((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:u,signal:i.signal});let o;if("arraybuffer"===r.responseType)o=await e.arrayBuffer();else if("text"===r.responseType)o=await e.text();else if("json"===r.responseType)o=await ic(e,!0);else{const t=e.headers.get("content-type")??"";o=await ic(e,t.includes("application/json"))}return{status:e.status,statusText:e.statusText,headers:nc(e.headers),data:o}}catch(l){const e=((e,t,r)=>t?"timeout":r?.aborted||e instanceof Error&&"AbortError"===e.name?"abort":"network")(l,a,r.signal);throw dn("Request adapter execution failed.",{code:nn,stage:Zs,retryable:"abort"!==e,details:{url:r.url,method:s,reason:e,cause:l instanceof Error?l.message:String(l)}})}finally{clearTimeout(d),r.signal?.removeEventListener("abort",c)}}}},ac=e=>"function"==typeof e.addEventListener&&"function"==typeof e.removeEventListener,cc=e=>"function"==typeof e.on&&"function"==typeof e.off,dc=(e,t,r)=>{if(ac(e))return e.addEventListener(t,r),()=>{e.removeEventListener(t,r)};if(cc(e)){const s=e;return s.on(t,r),()=>{s.off(t,r)}}throw dn("Socket event listener API is unsupported.",{code:an,stage:Xs,retryable:!1,details:{event:t}})},uc=(e,t,r)=>{if(ac(e)){const s=(...n)=>{e.removeEventListener(t,s),r(...n)};return e.addEventListener(t,s),()=>{e.removeEventListener(t,s)}}if(cc(e)){const s=e;if("function"==typeof s.once)return s.once?.(t,r),()=>{s.off(t,r)};let n=()=>{};return n=dc(e,t,(...e)=>{n(),r(...e)}),n}throw dn("Socket one-time listener API is unsupported.",{code:an,stage:Xs,retryable:!1,details:{event:t}})},lc=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?lc(e.data):null;var t},hc=e=>{const t=new Set,r=new Set,s=new Set,n=new Set;return dc(e,"open",()=>{t.forEach(e=>{e()})}),dc(e,"message",(...e)=>{const t=lc(e[0]);null!==t&&r.forEach(e=>{e(t)})}),dc(e,"error",(...e)=>{const t=e[0];s.forEach(e=>{e(t)})}),dc(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!==ln)throw dn("Socket is not open.",{code:an,stage:Xs,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)})}},pc=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(dn("Socket creation failed.",{code:an,stage:Xs,retryable:!0,details:{cause:l instanceof Error?l.message:String(l)}}))}let i,o=()=>{},a=()=>{},c=!1;const d=()=>{void 0!==i&&(clearTimeout(i),i=void 0)},u=()=>{c||(c=!0,o(),a(),d(),n.close(),s(dn("Socket connection timed out.",{code:an,stage:Xs,retryable:!0,details:{url:e.url,reason:"timeout"}})))};o=uc(n,"open",()=>{c||(c=!0,o(),a(),d(),r(hc(n)))}),a=uc(n,"error",e=>{if(c)return;c=!0,o(),a(),d();const t=e&&"object"==typeof e&&"type"in e?String(e.type):void 0;s(dn("Socket connection failed before open.",{code:an,stage:Xs,retryable:!0,details:{eventType:t}}))}),"number"==typeof e.timeoutMs&&e.timeoutMs>0&&(i=setTimeout(u,e.timeoutMs))})}},mc=(e,t)=>{throw dn("Upload adapter execution failed.",{code:on,stage:Ys,retryable:"abort"!==e,details:{reason:e,url:t.url}})},fc=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 dn("Web upload adapter only supports web-file source.",{code:on,stage:Ys,retryable:!1,details:{sourceType:t.source.sourceType}});const r=t.source.file;if(!r)throw dn("Upload source file is required for web-file uploads.",{code:on,stage:Ys,retryable:!1,details:{sourceType:t.source.sourceType}});const s="undefined"!=typeof Blob&&r instanceof Blob,n=t.source.name??"upload.bin",i=t.fileFieldName??"file";s?e.append(i,r,n):e.append(i,r)})(t,e),t},gc=(e,t,r)=>new Promise((s,n)=>{const i=e(),o=r.timeoutMs??t?.timeoutMs??3e4;((e,t)=>{e.upload&&t.onProgress&&e.upload.addEventListener("progress",e=>{if(!e.lengthComputable)return void t.onProgress?.({loaded:e.loaded});const r=e.total>0?e.loaded/e.total*100:void 0;t.onProgress?.({loaded:e.loaded,total:e.total,percent:r})})})(i,r),i.addEventListener("abort",()=>{try{mc("abort",r)}catch(e){n(e instanceof Error?e:new Error(String(e)))}}),i.addEventListener("timeout",()=>{try{mc("timeout",r)}catch(e){n(e instanceof Error?e:new Error(String(e)))}}),i.addEventListener("error",()=>{try{mc("network",r)}catch(e){n(e instanceof Error?e:new Error(String(e)))}}),i.addEventListener("load",()=>{s({status:i.status,body:i.responseText})});try{const e=fc(r);i.timeout=o,i.open(r.method??"POST",r.url),((e,t)=>{Object.entries(t??{}).forEach(([t,r])=>{e.setRequestHeader(t,r)})})(i,r.headers),i.send(e)}catch(a){n(dn("Upload adapter execution failed.",{code:on,stage:Ys,retryable:!1,details:{url:r.url,reason:"invalid-config",cause:a instanceof Error?a.message:String(a)}}))}}),yc=(e,t)=>e?"timeout":"abort",vc=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 gc(t,e,s);if("function"==typeof r)return(async(e,t,r)=>{const s=r.timeoutMs??t?.timeoutMs??3e4;let n=!1;const i="undefined"!=typeof AbortController?new AbortController:void 0,o=i&&Number.isFinite(s)?setTimeout(()=>{n=!0,i.abort()},s):void 0,a=((e,t)=>e??t?.signal)(r.signal,i);try{const t=fc(r),s=await e(r.url,{method:r.method??"POST",headers:r.headers,body:t,signal:a}),n=await s.text(),i=r.source.size;return"number"==typeof i&&r.onProgress?.({loaded:i,total:i,percent:i>0?100:void 0}),{status:s.status,body:n}}catch(c){const e=c instanceof Error&&"AbortError"===c.name;throw dn("Upload adapter execution failed.",{code:on,stage:Ys,retryable:!e,details:{reason:e?yc(n):"network",url:r.url,cause:c instanceof Error?c.message:String(c)}})}finally{o&&clearTimeout(o)}})(r,e,s);throw dn("Upload adapter execution failed.",{code:on,stage:Ys,retryable:!1,details:{reason:"missing-upload-runtime",url:s.url}})}}},Ic=(e,t)=>{const r=new e;return Object.entries(t.fields??{}).forEach(([e,t])=>{r.append(e,t)}),r.append(t.fileFieldName??"file",(e=>{const t=e.source;if("rn-uri"!==t.sourceType||!t.uri)throw dn("React Native upload adapter only supports rn-uri source.",{code:on,stage:Ys,retryable:!1,details:{sourceType:t.sourceType}});return{uri:t.uri,name:t.name??"upload.bin",type:t.mimeType??"application/octet-stream"}})(t)),r},bc=e=>{const t=e?.fetchImpl,r=e?.formDataCtor;if("function"==typeof t&&"function"==typeof r)return{async upload(s){const n=s.timeoutMs??e?.timeoutMs??3e4,i="function"==typeof AbortController?new AbortController:void 0;let o=!1;const a=i&&Number.isFinite(n)?setTimeout(()=>{o=!0,i.abort()},n):void 0;try{const e=Ic(r,s),n=await t(s.url,{method:s.method??"POST",headers:s.headers,body:e,signal:s.signal??i?.signal}),o=await n.text(),a=s.source.size;return"number"==typeof a&&s.onProgress?.({loaded:a,total:a,percent:a>0?100:void 0}),{status:n.status,body:o}}catch(c){if((e=>{if("object"!=typeof e||null===e)return!1;const t=e;return t.code===on&&t.stage===Ys})(c))throw c;const e=c instanceof Error&&"AbortError"===c.name;throw dn("React Native upload adapter execution failed.",{code:on,stage:Ys,retryable:!e||o,details:{url:s.url,reason:e?o?"timeout":"abort":"network",cause:c instanceof Error?c.message:String(c)}})}finally{void 0!==a&&clearTimeout(a)}}}},_c=(e,t)=>e+t&4294967295,Tc=(e,t,r,s,n,i)=>{return _c((o=_c(_c(t,e),_c(s,i)))<<(a=n)|o>>>32-a,r);var o,a},Cc=(e,t,r,s,n,i,o)=>Tc(t&r|~t&s,e,t,n,i,o),Sc=(e,t,r,s,n,i,o)=>Tc(t&s|r&~s,e,t,n,i,o),Ec=(e,t,r,s,n,i,o)=>Tc(t^r^s,e,t,n,i,o),wc=(e,t,r,s,n,i,o)=>Tc(r^(t|~s),e,t,n,i,o),Rc=(e,t)=>{let[r,s,n,i]=e;r=Cc(r,s,n,i,t[0]??0,7,-680876936),i=Cc(i,r,s,n,t[1]??0,12,-389564586),n=Cc(n,i,r,s,t[2]??0,17,606105819),s=Cc(s,n,i,r,t[3]??0,22,-1044525330),r=Cc(r,s,n,i,t[4]??0,7,-176418897),i=Cc(i,r,s,n,t[5]??0,12,1200080426),n=Cc(n,i,r,s,t[6]??0,17,-1473231341),s=Cc(s,n,i,r,t[7]??0,22,-45705983),r=Cc(r,s,n,i,t[8]??0,7,1770035416),i=Cc(i,r,s,n,t[9]??0,12,-1958414417),n=Cc(n,i,r,s,t[10]??0,17,-42063),s=Cc(s,n,i,r,t[11]??0,22,-1990404162),r=Cc(r,s,n,i,t[12]??0,7,1804603682),i=Cc(i,r,s,n,t[13]??0,12,-40341101),n=Cc(n,i,r,s,t[14]??0,17,-1502002290),s=Cc(s,n,i,r,t[15]??0,22,1236535329),r=Sc(r,s,n,i,t[1]??0,5,-165796510),i=Sc(i,r,s,n,t[6]??0,9,-1069501632),n=Sc(n,i,r,s,t[11]??0,14,643717713),s=Sc(s,n,i,r,t[0]??0,20,-373897302),r=Sc(r,s,n,i,t[5]??0,5,-701558691),i=Sc(i,r,s,n,t[10]??0,9,38016083),n=Sc(n,i,r,s,t[15]??0,14,-660478335),s=Sc(s,n,i,r,t[4]??0,20,-405537848),r=Sc(r,s,n,i,t[9]??0,5,568446438),i=Sc(i,r,s,n,t[14]??0,9,-1019803690),n=Sc(n,i,r,s,t[3]??0,14,-187363961),s=Sc(s,n,i,r,t[8]??0,20,1163531501),r=Sc(r,s,n,i,t[13]??0,5,-1444681467),i=Sc(i,r,s,n,t[2]??0,9,-51403784),n=Sc(n,i,r,s,t[7]??0,14,1735328473),s=Sc(s,n,i,r,t[12]??0,20,-1926607734),r=Ec(r,s,n,i,t[5]??0,4,-378558),i=Ec(i,r,s,n,t[8]??0,11,-2022574463),n=Ec(n,i,r,s,t[11]??0,16,1839030562),s=Ec(s,n,i,r,t[14]??0,23,-35309556),r=Ec(r,s,n,i,t[1]??0,4,-1530992060),i=Ec(i,r,s,n,t[4]??0,11,1272893353),n=Ec(n,i,r,s,t[7]??0,16,-155497632),s=Ec(s,n,i,r,t[10]??0,23,-1094730640),r=Ec(r,s,n,i,t[13]??0,4,681279174),i=Ec(i,r,s,n,t[0]??0,11,-358537222),n=Ec(n,i,r,s,t[3]??0,16,-722521979),s=Ec(s,n,i,r,t[6]??0,23,76029189),r=Ec(r,s,n,i,t[9]??0,4,-640364487),i=Ec(i,r,s,n,t[12]??0,11,-421815835),n=Ec(n,i,r,s,t[15]??0,16,530742520),s=Ec(s,n,i,r,t[2]??0,23,-995338651),r=wc(r,s,n,i,t[0]??0,6,-198630844),i=wc(i,r,s,n,t[7]??0,10,1126891415),n=wc(n,i,r,s,t[14]??0,15,-1416354905),s=wc(s,n,i,r,t[5]??0,21,-57434055),r=wc(r,s,n,i,t[12]??0,6,1700485571),i=wc(i,r,s,n,t[3]??0,10,-1894986606),n=wc(n,i,r,s,t[10]??0,15,-1051523),s=wc(s,n,i,r,t[1]??0,21,-2054922799),r=wc(r,s,n,i,t[8]??0,6,1873313359),i=wc(i,r,s,n,t[15]??0,10,-30611744),n=wc(n,i,r,s,t[6]??0,15,-1560198380),s=wc(s,n,i,r,t[13]??0,21,1309151649),r=wc(r,s,n,i,t[4]??0,6,-145523070),i=wc(i,r,s,n,t[11]??0,10,-1120210379),n=wc(n,i,r,s,t[2]??0,15,718787259),s=wc(s,n,i,r,t[9]??0,21,-343485551),e[0]=_c(r,e[0]),e[1]=_c(s,e[1]),e[2]=_c(n,e[2]),e[3]=_c(i,e[3])},Ac=(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},Nc=e=>{let t="";for(let r=0;r<4;r+=1){t+=(e>>8*r&255).toString(16).padStart(2,"0")}return t},Oc=e=>{const t=[1732584193,-271733879,-1732584194,271733878];let r=0;for(;r+64<=e.length;r+=64)Rc(t,Ac(e,r));const s=new Array(16).fill(0);let n=0;for(;r<e.length;r+=1){const t=n>>2;s[t]=(s[t]??0)|(e[r]??0)<<n%4*8,n+=1}const i=n>>2;s[i]=(s[i]??0)|128<<n%4*8,n>55&&(Rc(t,s),s.fill(0));const o=8*e.length;return s[14]=4294967295&o,s[15]=Math.floor(o/4294967296),Rc(t,s),t.map(Nc).join("")},Mc=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 dn("Image decode capability is missing for current platform",{code:sn,stage:tn,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(dn("Image decode failed",{code:on,stage:tn,retryable:!1,details:{reason:"image load error"}}))},s.src=t})},Uc=e=>{if(!(e=>"web-file"===e.sourceType&&"undefined"!=typeof Blob&&e.file instanceof Blob)(e))throw dn("Web image processor only supports web file source",{code:sn,stage:tn,retryable:!1,details:{sourceType:e.sourceType}});return e.file},Lc=()=>({async getImageInfo(e){const t=Uc(e),r=await Mc(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=Uc(e),s=await Mc(r);try{const r=((e,t,r)=>{const s=Math.min(e,t);if(s<=r)return{width:e,height:t};const n=r/s;return{width:Math.max(1,Math.round(e*n)),height:Math.max(1,Math.round(t*n))}})(s.width,s.height,t.maxShortEdge),i=((e,t)=>{if("undefined"!=typeof OffscreenCanvas)return new OffscreenCanvas(e,t);if("undefined"!=typeof document){const r=document.createElement("canvas");return r.width=e,r.height=t,r}throw dn("Canvas capability is missing for current platform",{code:sn,stage:tn,retryable:!1,details:{reason:"canvas unavailable"}})})(r.width,r.height),o=i.getContext("2d");if(!o)throw dn("Canvas 2d context is missing",{code:sn,stage:tn,retryable:!1});o.drawImage(s.image,0,0,r.width,r.height);const a="image/png"===(n=e.mimeType)||"image/webp"===n?n:"image/jpeg",c=await(async(e,t,r)=>{if("convertToBlob"in e&&"function"==typeof e.convertToBlob)return e.convertToBlob({type:t,quality:r});if("toBlob"in e&&"function"==typeof e.toBlob)return new Promise((s,n)=>{e.toBlob(e=>{e?s(e):n(dn("Image encode failed",{code:on,stage:tn,retryable:!1,details:{reason:"canvas toBlob returned null"}}))},t,r)});throw dn("Canvas encode capability is missing for current platform",{code:sn,stage:tn,retryable:!1,details:{reason:"canvas encode unavailable"}})})(i,a,t.quality),d=(e=>e.name??"image")(e),u="undefined"!=typeof File?new File([c],d,{type:a,lastModified:Date.now()}):void 0;return{source:{sourceType:"web-file",file:u??c,name:d,mimeType:a,size:u?.size??c.size},width:r.width,height:r.height,fileName:d,fileType:a,fileSize:u?.size??c.size,webFile:u}}finally{s.cleanup()}var n},async computeMd5(e){const t=Uc(e),r=await(async e=>{if("function"==typeof e.arrayBuffer)return e.arrayBuffer();if("undefined"==typeof FileReader)throw dn("Binary read capability is missing for current platform",{code:sn,stage:tn,retryable:!1,details:{reason:"blob.arrayBuffer unavailable"}});return new Promise((t,r)=>{const s=new FileReader;s.onerror=()=>{r(dn("Binary read failed",{code:on,stage:tn,retryable:!1}))},s.onload=()=>{s.result instanceof ArrayBuffer?t(s.result):r(dn("Binary read returned invalid result",{code:on,stage:tn,retryable:!1}))},s.readAsArrayBuffer(e)})})(t);return Oc(new Uint8Array(r))}}),kc=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)},Dc=e=>{if(!(e=>"miniapp-path"===e.sourceType&&"string"==typeof e.path&&e.path.length>0)(e))throw dn("Miniapp image processor only supports miniapp path source",{code:sn,stage:tn,retryable:!1,details:{sourceType:e.sourceType}});return e.path},Pc=e=>{const t=e.getFileSystemManager?.();if(t)return t;throw dn("Miniapp file system capability is missing",{code:sn,stage:tn,retryable:!1,details:{capability:"getFileSystemManager"}})},xc=e=>{if(!e)return;const t=e.toLowerCase();return t.startsWith("image/")?t:`image/${t}`},Fc=async(e,t)=>new Promise((r,s)=>{e.getImageInfo({src:t,success:e=>{r(e)},fail:e=>{s(e instanceof Error?e:new Error(kc(e)))}})}).catch(e=>{throw dn("Miniapp image info read failed",{code:on,stage:tn,retryable:!1,details:{src:t,cause:kc(e)}})}),Bc=(e,t)=>"string"==typeof t.path&&t.path.length>0?t.path:e,Gc=async(e,t)=>{if(!(e=>/^https?:\/\/tmp\//i.test(e))(t))return t;const r=await Fc(e,t);return Bc(t,r)},qc=e=>({async getImageInfo(t){const r=Dc(t),s=await Fc(e,r),n=xc(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=Dc(t);if("function"!=typeof e.compressImage)throw dn("Miniapp image compress capability is missing",{code:sn,stage:tn,retryable:!1,details:{capability:"compressImage"}});const n=await Fc(e,s),i=Bc(s,n),o=((e,t,r)=>{const s=Math.min(e,t);if(s<=r)return{width:e,height:t};const n=r/s;return{width:Math.max(1,Math.round(e*n)),height:Math.max(1,Math.round(t*n))}})(n.width,n.height,r.maxShortEdge),a=await new Promise((t,s)=>{e.compressImage?.({src:i,quality:Math.max(0,Math.min(100,Math.round(100*r.quality))),compressedWidth:o.width,compressedHeight:o.height,success:e=>{e.tempFilePath?t(e.tempFilePath):s(new Error("compressImage missing tempFilePath"))},fail:e=>{s(e instanceof Error?e:new Error(kc(e)))}})}).catch(e=>{throw dn("Miniapp image compress failed",{code:on,stage:tn,retryable:!1,details:{src:i,cause:kc(e)}})}),c=await Gc(e,a),d=await Fc(e,c),u=xc(d.type)??t.mimeType,l=await(async(e,t,r)=>{const s=Pc(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(kc(e)))}})}).catch(e=>{throw dn("Miniapp file info read failed",{code:on,stage:tn,retryable:!1,details:{filePath:t,cause:kc(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=Dc(t),s=await Gc(e,r),n=await(async(e,t)=>{const r=Pc(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(kc(e)))}})}).catch(e=>{throw dn("Miniapp file read failed",{code:on,stage:tn,retryable:!1,details:{filePath:t,cause:kc(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 Oc(n)}}),$c=new Set(["quotaexceedederror","ns_error_dom_quota_reached"]),jc=[/\bquota\b/i,/\bexceed(?:ed)?\s+storage\s+max(?:imum)?\s+size\b/i,/\b(?:storage\s+)?max(?:imum)?\s+size\b.*\bexceed(?:ed)?\b/i,/\bstorage\b.*\blimit\b.*\b(?:exceed(?:ed)?|reach(?:ed)?)\b/i],Vc=(e,t)=>{if("object"!=typeof e||null===e)return null;const r=e[t];return"string"==typeof r?r:null},Kc=e=>{if(!e)return!1;const t=Vc(e,"name");if(t&&$c.has(t.toLowerCase()))return!0;return["string"==typeof e?e:null,Vc(e,"message"),Vc(e,"errMsg")].some(e=>null!==e&&jc.some(t=>t.test(e)))},zc=e=>{if(e instanceof Error)return e;const t=Vc(e,"message")??Vc(e,"errMsg")??"Storage quota exceeded";return Object.assign(new Error(t),{name:"QuotaExceededError",cause:e})},Hc="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Wc=e=>Array.from(e,e=>e.toString(16).padStart(2,"0")).join(""),Jc=e=>e===Js.ALIPAY_MINIAPP||e===Js.DINGTALK_MINIAPP,Qc=e=>{const t=e.replace(/\s/g,"").replace(/-/g,"+").replace(/_/g,"/"),r=t.endsWith("==")?2:t.endsWith("=")?1:0,s=Math.max(0,Math.floor(3*t.length/4)-r),n=new Uint8Array(s);let i=0;for(let o=0;o<t.length;o+=4){const e=Hc.indexOf(t[o]??""),r=Hc.indexOf(t[o+1]??""),a=t[o+2]??"=",c=t[o+3]??"=",d="="===a?0:Hc.indexOf(a),u="="===c?0:Hc.indexOf(c);if(e<0||r<0||d<0||u<0)return new ArrayBuffer(0);const l=e<<18|r<<12|d<<6|u;for(const t of[16,8,0])i<s&&(n[i]=l>>t&255,i+=1)}return n.buffer},Zc=e=>"[object ArrayBuffer]"===Object.prototype.toString.call(e),Yc=e=>{const t=new Uint8Array(e.byteLength);return t.set(e),t},Xc=(e,t=0)=>{if(t>3||"object"!=typeof e||null===e||Array.isArray(e))return e;if(Zc(e)||ArrayBuffer.isView(e))return e;const r=e;return"data"in r&&r.data!==e?Xc(r.data,t+1):e},ed=(e,t=0)=>{if(t>3||null==e)return;if(e instanceof Uint8Array)return Yc(e);if(Zc(e))try{return Yc(new Uint8Array(e))}catch{return}if(ArrayBuffer.isView(e))return Yc(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=ed(r.data,t+1);if(e)return e}if("buffer"in r&&r.buffer!==e){const e=ed(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)}},td=(e,t)=>{if("string"==typeof e)return e;const r=e instanceof Uint8Array?e:new Uint8Array(e);if(Jc(t)){const s=(e=>{let t="";for(let r=0;r<e.length;r+=3){const s=e[r]??0,n=e[r+1],i=e[r+2],o=s<<16|(n??0)<<8|(i??0);t+=Hc[o>>18&63],t+=Hc[o>>12&63],t+=void 0===n?"=":Hc[o>>6&63],t+=void 0===i?"=":Hc[63&o]}return t})(r);return Vs("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:Wc(r.subarray(0,8))}),s}const s=new ArrayBuffer(r.byteLength);return new Uint8Array(s).set(r),s},rd=(e,t)=>"string"!=typeof e&&Jc(t),sd=(e,t)=>{const r=Xc(e.data);if("string"==typeof r){if(!Jc(t))return r;const s=Qc(r),n=new Uint8Array(s);return Vs("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:Wc(n.subarray(0,8)),decodedSuffixHex:Wc(n.subarray(Math.max(0,n.length-8)))}),s}const s=ed(r);if(!s){const s="object"==typeof e.data&&null!==e.data?e.data:void 0;return void Vs("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(!Jc(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 Vs("Mini program socket binary frame preserved",{operation:"platform.socket.frame.preserve-binary",hostPlatform:t,sourceType:Object.prototype.toString.call(r),sourceBytes:s.byteLength,sourcePrefixHex:Wc(s.subarray(0,8))}),s.buffer;const i=Qc(n),o=new Uint8Array(i);return Vs("Mini program socket Base64 buffer decoded",{operation:"platform.socket.frame.decode-base64-buffer",hostPlatform:t,sourceType:Object.prototype.toString.call(r),sourceBytes:s.byteLength,decodedBytes:i.byteLength,decodedPrefixHex:Wc(o.subarray(0,8)),decodedSuffixHex:Wc(o.subarray(Math.max(0,o.length-8)))}),i},nd=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),id=(e,t)=>("object"==typeof e||"function"==typeof e)&&null!==e&&"function"==typeof e[t],od=e=>e instanceof Error?e.message:nd(e)&&"string"==typeof e.errMsg?e.errMsg:nd(e)&&"string"==typeof e.errorMessage?e.errorMessage:String(e),ad=e=>e?{...e}:{},cd=e=>"number"==typeof e&&Number.isInteger(e)&&e>=100&&e<=599,ud=e=>cd(e.statusCode)?e.statusCode:cd(e.status)?e.status:void 0,ld=e=>{if(!nd(e))return{};const t={};return Object.entries(e).forEach(([e,r])=>{"string"==typeof r&&(t[e]=r)}),t},hd=e=>({...ld(e.headers),...ld(e.header)}),pd=(e,t)=>{if(!e)return()=>{};if(e.aborted)return t(),()=>{};const r=()=>{t()};return e.addEventListener("abort",r,{once:!0}),()=>{e.removeEventListener("abort",r)}},md=e=>{try{e.close()}catch{}},fd=(e,t)=>new Promise((r,s)=>{let n=!1,i=()=>{};const o=(e,r,o)=>{n||(n=!0,i(),s(dn(e,{code:nn,stage:Zs,retryable:o,details:{url:t.url,method:"GET",cause:od(r)}})))},a=e.downloadFile?.({url:t.url,header:ad(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=ed(e.data);t?r(t.buffer):s(new Error("downloaded file response is not binary"))},fail:s}):s(new Error("getFileSystemManager returned no file system manager"))}))(e,a).then(e=>{n||(n=!0,i(),Vs("Mini program binary response read from downloaded file",{operation:"platform.request.arraybuffer.download-file",url:t.url,filePathType:s.apFilePath?"apFilePath":"tempFilePath",status:s.statusCode??200,bytes:e.byteLength}),r({status:s.statusCode??200,headers:s.header??{},data:e}))}).catch(e=>{o("Mini program downloaded file read failed.",e,!1)}):o("Mini program download did not return a file path.",s,!1)},fail:e=>{o("Mini program file download failed.",e,!0)}});i=pd(t.signal,()=>{a?.abort(),o("Mini program file download aborted.","abort",!1)})}),gd=e=>({request:t=>"arraybuffer"!==t.responseType||void 0!==t.method&&"GET"!==t.method||!(e=>"function"==typeof e.downloadFile&&"function"==typeof e.getFileSystemManager)(e)?new Promise((r,s)=>{let n=()=>{};const i=e.request({url:t.url,method:t.method??"GET",header:ad(t.headers),data:t.body,timeout:t.timeoutMs??15e3,responseType:"arraybuffer"===t.responseType?"arraybuffer":"text",success:e=>{n();const i=ud(e);void 0!==i?r({status:i,headers:hd(e),data:e.data}):s(dn("Mini program request response status is invalid.",{code:nn,stage:Zs,retryable:!1,details:{url:t.url,method:t.method??"GET",statusCode:e.statusCode,status:e.status}}))},fail:e=>{n(),s(dn("Mini program request failed.",{code:nn,stage:Zs,retryable:!0,details:{url:t.url,method:t.method??"GET",cause:od(e)}}))}});n=pd(t.signal,()=>{i.abort(),s(dn("Mini program request aborted.",{code:nn,stage:Zs,retryable:!1,details:{url:t.url,method:t.method??"GET",reason:"abort"}}))})}):fd(e,t)}),yd=(e,t)=>({connect:r=>new Promise((s,n)=>{let i,o,a=!1;const c=()=>{void 0!==o&&(clearTimeout(o),o=void 0)},d=(e,t,s)=>{a||(a=!0,c(),i&&md(i),n(dn(t,{code:an,stage:Xs,retryable:s,details:{url:r.url,cause:od(e)}})))},u=e=>{if(!(id(r=e,"send")&&id(r,"close")&&id(r,"onOpen")&&id(r,"onMessage")&&id(r,"onError")&&id(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 md(n);i=n;const o=()=>{n.offOpen?.(u),n.offError?.(l)},u=()=>{a?md(n):(a=!0,c(),o(),s(((e,t,r=un)=>{const s=new Set,n=new Set,i=new Set,o=new Set;let a=r;return e.onOpen(()=>{a=ln,s.forEach(e=>{e()})}),e.onMessage(e=>{const r=sd(e,t);void 0!==r&&n.forEach(e=>{e(r)})}),e.onError(e=>{i.forEach(t=>{t(e)})}),e.onClose(e=>{a=pn,o.forEach(t=>{t({code:e.code,reason:e.reason})})}),{get readyState(){return a},send(r){if(a!==ln)throw dn("Mini program socket is not open.",{code:an,stage:Xs,retryable:!0,details:{readyState:a}});return new Promise((s,n)=>{e.send({data:td(r,t),...rd(r,t)?{isBuffer:!0}:{},success:s,fail:e=>{n(dn("Mini program socket send failed.",{code:an,stage:Xs,retryable:!0,details:{cause:od(e)}}))}})})},close(t,r){a=hn,e.close({code:t,reason:r})},onOpen:e=>(s.add(e),()=>{s.delete(e)}),onMessage:e=>(n.add(e),()=>{n.delete(e)}),onError:e=>(i.add(e),()=>{i.delete(e)}),onClose:e=>(o.add(e),()=>{o.delete(e)})}})(n,t,ln)))},l=e=>{o(),d(e.errMsg??"socket error","Mini program socket connection failed before open.",!0)};n.onOpen(u),n.onError(l)};let l;"number"==typeof r.timeoutMs&&r.timeoutMs>0&&(o=setTimeout(()=>{d("timeout","Mini program socket connection timed out.",!0)},r.timeoutMs));try{l=e.connectSocket({url:r.url,...t===Js.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))})}),vd=e=>({upload(t){const r=t.method??"POST";return"POST"!==r?Promise.reject(dn("Mini program upload only supports POST.",{code:on,stage:Ys,retryable:!1,details:{url:t.url,method:r,reason:"unsupported-method"}})):new Promise((r,s)=>{const n=(e=>{if("miniapp-path"!==e.sourceType||!e.path)throw dn("Mini program upload only supports miniapp-path source.",{code:on,stage:Ys,retryable:!1,details:{sourceType:e.sourceType}});return e})(t.source);let i=()=>{};const o=e.uploadFile({url:t.url,filePath:n.path,name:t.fileFieldName??"file",header:ad(t.headers),formData:t.fields,timeout:t.timeoutMs??3e4,success:e=>{i();const o=ud(e);void 0!==o?r({status:o,body:e.data}):s(dn("Mini program upload response status is invalid.",{code:on,stage:Ys,retryable:!1,details:{url:t.url,path:n.path,statusCode:e.statusCode,status:e.status}}))},fail:e=>{i(),s(dn("Mini program upload failed.",{code:on,stage:Ys,retryable:!0,details:{url:t.url,path:n.path,cause:od(e)}}))}});o.onProgressUpdate?.(e=>{t.onProgress?.({loaded:e.totalBytesSent,total:e.totalBytesExpectedToSend,percent:e.progress})}),i=pd(t.signal,()=>{o.abort(),s(dn("Mini program upload aborted.",{code:on,stage:Ys,retryable:!1,details:{url:t.url,path:n.path,reason:"abort"}}))})})}}),Id=(e,t)=>{const r=(e=>e===Js.ALIPAY_MINIAPP||e===Js.DINGTALK_MINIAPP)(t);return{async getItem(t){if(id(e,"getStorageSync"))try{const s=(e=>nd(e)&&"data"in e?e.data:e)(e.getStorageSync(r?{key:t}:t));return"string"==typeof s&&s.length>0?s:null}catch{return null}return id(e,"getStorage")?new Promise(r=>{e.getStorage({key:t,success:e=>{r("string"==typeof e.data&&e.data.length>0?e.data:null)},fail:()=>{r(null)}})}):null},async setItem(t,s){if(id(e,"setStorageSync"))try{r?e.setStorageSync({key:t,data:s}):e.setStorageSync(t,s)}catch(n){if(Kc(n))throw zc(n)}else if(id(e,"setStorage"))return new Promise((r,i)=>{try{e.setStorage({key:t,data:s,success:r,fail:e=>{Kc(e)?i(zc(e)):r()}})}catch(n){if(Kc(n))return void i(zc(n));r()}})},async removeItem(t){if(id(e,"removeStorageSync"))try{e.removeStorageSync(r?{key:t}:t)}catch{}else if(id(e,"removeStorage"))return new Promise(r=>{try{e.removeStorage({key:t,success:r,fail:()=>{r()}})}catch{r()}})}}},bd=(e,t)=>({getPlatform:()=>t,getNetworkType:()=>id(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 id(e,"onNetworkStatusChange")&&e.onNetworkStatusChange(r),id(e,"getNetworkType")&&e.getNetworkType({success:e=>{t("none"!==e.networkType)}}),()=>{id(e,"offNetworkStatusChange")&&e.offNetworkStatusChange(r)}},onAppVisibilityChange(t){const r=()=>{t(!0)},s=()=>{t(!1)};return id(e,"onAppShow")&&e.onAppShow(r),id(e,"onAppHide")&&e.onAppHide(s),t(!0),()=>{id(e,"offAppShow")&&e.offAppShow(r),id(e,"offAppHide")&&e.offAppHide(s)}}}),_d=(e,t=Js.WECHAT_MINIAPP,r=t)=>{const s=(e=>{if(id(e,"request")&&id(e,"connectSocket")&&id(e,"uploadFile"))return e;throw dn("Mini program platform capability is missing.",{code:sn,stage:Qs,retryable:!1,details:{capability:"request/connectSocket/uploadFile"}})})(e),n="function"==typeof s.getImageInfo?qc(s):void 0;return{request:gd(s),socket:yd(s,r),upload:vd(s),runtime:bd(s,t),storage:Id(s,r),imageProcessor:n}},Td=["request","upload","socket"],Cd={request:"request",upload:"upload",socket:"connect"},Sd=[Js.WEB,Js.ELECTRON_RENDERER,Js.REACT_NATIVE],Ed=(e,t)=>{if("object"!=typeof e&&"function"!=typeof e||null===e)return!1;return"function"==typeof e[t]},wd=e=>Sd.includes(e),Rd=(e,t)=>e!==Js.UNIAPP?wd(e):!Rn(t)&&!Nd(t)&&Cn(t),Ad=e=>Ed(e,"getImageInfo")&&Ed(e,"getFileSystemManager"),Nd=e=>!Rn(e)&&"app"===(e=>{try{const t=e.uni?.getSystemInfoSync?.(),r=t?.uniPlatform;return"string"==typeof r?r:void 0}catch{return}})(e),Od=(e,t)=>{if(wd(e)&&e!==Js.REACT_NATIVE)return Lc();if(Mn(e)&&Ad(t))return qc(t);if(e===Js.UNIAPP&&"object"==typeof t&&null!==t){const e=t;if(Cn(e))return Lc();if(Ad(e.uni))return qc(e.uni);if(Ad(e.wx))return qc(e.wx)}},Md=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())}},Ud=(e,t,r,s)=>{if(e===Js.UNIAPP&&Nd(r)&&void 0!==r.uni&&vn(r.uni))return{..._d(r.uni,e,t),proto:sc()};if(((e,t)=>!Rd(e,t)&&Mn(e))(e,r)&&vn(s))return{..._d(s,e,t),proto:sc()};const n=r.XMLHttpRequest,i=Rd(e,r),o=i?oc({fetchImpl:r.fetch}):void 0,a=i?pc({webSocketCtor:r.WebSocket}):void 0,c=e===Js.REACT_NATIVE?bc({fetchImpl:r.fetch,formDataCtor:r.FormData}):i?vc({xhrFactory:"function"==typeof n?()=>new n:void 0,fetchImpl:r.fetch}):void 0,d=i&&e!==Js.REACT_NATIVE?(u={platform:e,windowRef:r.window,documentRef:r.document,navigatorRef:r.navigator},{getPlatform:()=>u.platform,getNetworkType:()=>!1===u.navigatorRef?.onLine?Promise.resolve("none"):Promise.resolve(u.navigatorRef?.connection?.type??u.navigatorRef?.connection?.effectiveType??"unknown"),onNetworkChange(e){const t=u.windowRef;if(!t)return()=>{};const r=()=>{e(!0)},s=()=>{e(!1)};return t.addEventListener("online",r),t.addEventListener("offline",s),"boolean"==typeof u.navigatorRef?.onLine&&e(u.navigatorRef.onLine),()=>{t.removeEventListener("online",r),t.removeEventListener("offline",s)}},onAppVisibilityChange(e){const t=u.documentRef;if(!t)return()=>{};const r=()=>{e((e=>"hidden"!==e?.visibilityState)(t))};return t.addEventListener("visibilitychange",r),r(),()=>{t.removeEventListener("visibilitychange",r)}}}):(e=>({getPlatform:()=>e,onNetworkChange:e=>()=>{},onAppVisibilityChange:e=>()=>{}}))(e);var u;return{request:o,upload:c,socket:a,runtime:d,proto:sc(),storage:Md(r),imageProcessor:i&&e!==Js.REACT_NATIVE?Lc():Od(e,s)}},Ld=(e,t,r)=>{if(!t)return{...e,...r};const s=Td.filter(e=>void 0!==r[e]);if(s.length>0)throw dn("Transport adapter conflicts with network overrides.",{code:rn,stage:Qs,retryable:!1,details:{conflictingCapabilities:s}});const n=(e=>Object.fromEntries(Object.entries(e).filter(([,e])=>void 0!==e)))(r);return{...e,request:t.request,upload:t.upload,socket:t.socket,...n}},kd=(e,t)=>{if(void 0!==e)return e;throw dn("Platform adapter initialization failed.",{code:rn,stage:Qs,retryable:!1,details:{capability:t}})},Dd=e=>{(e=>{if(!e)return;const t=Td.flatMap(t=>{const r=Cd[t];return Ed(e[t],r)?[]:[`${t}.${r}`]});if(0!==t.length)throw dn("Transport adapter has invalid capabilities.",{code:rn,stage:Qs,retryable:!1,details:{source:"transportAdapter",invalidCapabilities:t}})})(e?.transportAdapter);const t=fn(e?.runtimeInput),r=On(t,e?.prefer),s=r.platform,n=Ud(s,r.hostPlatform,t,r.global),i=((e,t)=>e?"function"==typeof e?e(t):e:{})(e?.overrides,n),o=Ld(n,e?.transportAdapter,i),a=(e=>({request:void 0!==e.request,upload:void 0!==e.upload,socket:void 0!==e.socket,runtime:void 0!==e.runtime,proto:void 0!==e.proto,storage:void 0!==e.storage,imageProcessor:void 0!==e.imageProcessor}))(o);Ln(a);return{platform:s,platformId:s,capability:a,request:kd(o.request,"request"),upload:kd(o.upload,"upload"),socket:kd(o.socket,"socket"),runtime:kd(o.runtime,"runtime"),proto:kd(o.proto,"proto"),storage:kd(o.storage,"storage"),imageProcessor:o.imageProcessor}},Pd=e=>{if(e instanceof bt)return e;if((e=>"object"==typeof e&&null!==e)(e)){const t=e.details;if(e.code===sn){const r=t?.capability;if(e.stage===tn&&"string"==typeof r&&r.includes("FileSystem")){const r=e instanceof Error?e.message:"Upload failed";return new bt(r,{code:ot.UPLOAD_REQUEST_FAILED,details:t})}return new bt("Upload capability is missing for current platform",{code:ot.UPLOAD_REQUIRED_FIELD_MISSING,details:t})}if(e.stage===Ys)return(e=>{const t=e?.reason;return!("string"!=typeof t||!t.toLowerCase().includes("abort"))})(t)?new bt("Upload canceled",{code:ot.UPLOAD_ABORTED,details:t}):(e=>{const t=e?.reason;return!("string"!=typeof t||!t.toLowerCase().includes("timeout"))})(t)?new bt("Upload timeout",{code:ot.UPLOAD_TIMEOUT,details:t}):new bt("Upload failed",{code:ot.UPLOAD_REQUEST_FAILED,details:t})}const t=e instanceof Error?e.message:"Upload failed";return new bt(t,{code:ot.UPLOAD_REQUEST_FAILED,details:{cause:e}})},xd=e=>{if(e)return e;const t=fn(),r=pc({webSocketCtor:t.WebSocket});if(r)return r;throw dn("Socket capability is missing for current platform.",{code:sn,stage:Xs,retryable:!1,details:{capability:"socket"}})},Fd={maxAttempts:10,initialDelay:1e3,maxDelay:6e4,backoffMultiplier:2,randomSource:Math.random};class Bd{constructor(e={}){this.attemptCount=0,this.config={...Fd,...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 js(`Waiting ${e}ms before retry (attempt ${this.attemptCount})`),new Promise(t=>setTimeout(t,e))}}const Gd={interval:3e4,timeout:6e4},qd="function"==typeof TextDecoder?new TextDecoder:null;class $d{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(!$d.isRecord(r))return;"pong"===$d.readString(r.type)&&(this.markAlive(),js("Pong received"))},this.config={...Gd,...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),js("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),js("Heartbeat stopped")}sendPingInternal(){if(this.websocket&&this.websocket.readyState===ln)try{if(this.sendPing)this.sendPing();else{const e=JSON.stringify({type:"ping",timestamp:Date.now()});Promise.resolve(this.websocket.send(e)).catch(e=>{Ks("Failed to send ping:",e),this.resolveProbe(!1)})}this.resetTimeout(),js("Ping sent")}catch(e){Ks("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)?qd?.decode(t)??Hs(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(()=>{Vs("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!==ln)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 Vs("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 Vd=null;function Kd(){return Vd||(Vd=rc()),Vd}const zd="websdk2:device-info",Hd="webim",Wd="web",Jd=e=>{const t=Date.now(),r=e.deviceId,s=e.customOSPlatform,n=void 0!==s?e.customDeviceName:void 0,i=fn().localStorage,o=()=>{if(!i)return null;try{const t=i.getItem(zd);if(!t)return null;const r=JSON.parse(t);if("object"==typeof(e=r)&&null!==e&&!Array.isArray(e)&&"string"==typeof r.deviceId&&"string"==typeof r.deviceName&&"string"==typeof r.deviceUuid)return{deviceId:r.deviceId,deviceName:r.deviceName,deviceUuid:r.deviceUuid}}catch{return null}var e;return null},a=e=>{if(i)try{i.setItem(zd,JSON.stringify(e))}catch{}},c=e=>void 0===s?e:{deviceId:`custom${s}_${e.deviceUuid}`,deviceName:n??r,deviceUuid:e.deviceUuid};if(e.useFixedDeviceId){const e=o();if(e)return c(e);if(r===Hd){const e=`${Wd}_${t}`,s=c({deviceId:`${r}_${e}`,deviceName:r,deviceUuid:e});return a(s),s}if(void 0!==s){const e=c({deviceId:`webim_${Wd}_${r}`,deviceName:r,deviceUuid:`${Wd}_${t}`});return a(e),e}const n={deviceId:`webim_${Wd}_${r}`,deviceName:`webim_${Wd}_${r}`,deviceUuid:`webim_${Wd}_${r}`};return a(n),n}if(r===Hd){const e=`random_${Wd}_${t}`;return c({deviceId:`${r}_${e}`,deviceName:r,deviceUuid:e})}if(void 0!==s){return c({deviceId:`webim_${Wd}_${r}`,deviceName:r,deviceUuid:`random_${Wd}_${t}`})}return{deviceId:`webim_${Wd}_${r}`,deviceName:`webim_${Wd}_${r}`,deviceUuid:`webim_${Wd}_${r}`}},Qd=e=>({appKey:e.appKey,name:e.name,domain:e.domain,clientResource:e.clientResource}),Zd=e=>{if(/^\d+$/.test(e))return e;const t=Dn.fromString("1099511628211",!0);let r=Dn.fromString("1469598103934665603",!0);for(let s=0;s<e.length;s+=1)r=r.xor(Dn.fromInt(e.charCodeAt(s),!0)).multiply(t).toUnsigned();return r.isZero()?"1":r.toString()},Yd=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 Dn(t.low,t.high,Boolean(t.unsigned)).toString()}return e&&"function"==typeof e.toString?e.toString():""},Xd=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:kr,stringValue:JSON.stringify(s)})}catch{t.push({key:r,type:Lr,stringValue:Object.prototype.toString.call(s)})}else t.push({key:r,type:Lr,stringValue:s});else Number.isInteger(s)?t.push({key:r,type:Ar,varintValue:s}):t.push({key:r,type:Ur,doubleValue:s});else t.push({key:r,type:Rr,varintValue:s?1:0});return t},eu=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:Lr;if(s!==Rr)if(s!==Ar&&s!==Nr&&s!==Or)if(s!==Mr)if(s!==Ur){if(s!==kr)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},tu=()=>`${Date.now()}${Math.floor(1e6*Math.random()).toString().padStart(6,"0")}`,ru="X-Request-Id",su=new Set(["mute"]),nu={name:"name",title:"name",description:"description",max_users:"maxMembers",custom:"ext",mute:"muteAllMembers"},iu=e=>{if("string"!=typeof e)return;const t=e.trim();return t.length>0?t:void 0},ou=e=>{if(!e)return null;try{const t=JSON.parse(e);return!t||"object"!=typeof t||Array.isArray(t)?null:t}catch{return null}},au=(e,t)=>{const r=e?.map(e=>iu(e)).filter(e=>"string"==typeof e)??[];return r.length>0?r:t?[t]:[]},cu=(e,t)=>{const r=Number(e);if(!Number.isNaN(r)&&Number.isFinite(r)&&r>0)return r;const s=ou(t);if(!s)return;const n=s.muteExpire??s.mute_expire??s.expire??s.expired??s.expireAt??s.expiredAt,i=Number(n);return Number.isFinite(i)&&i>0?i:void 0},du=e=>{const t=ou(e);if(!t)return;const r={};for(const[s,n]of Object.entries(t)){const e=nu[s];if(!e)continue;let t=n;if(su.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},uu=e=>{const t=ou(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:iu(t.operator)??iu(t.username)}},lu=(e,t)=>({eventName:e,payload:t}),hu=e=>{const t={chatRoomId:e.chatRoomId,chatRoomName:e.chatRoomName},r=iu(e.from?.name),s=(n=e.to,iu(n?.[0]?.name));var n;switch(e.operation){case 1:return lu(qe,t);case 10:return lu(Ve,{...t,reason:e.reason,reasonCode:Number.isFinite(Number(e.reason))?Number(e.reason):0,participantId:s??r});case 17:return lu($e,{...t,memberIds:au(e.members,r),ext:e.ext??e.eventExt});case 18:return lu(je,{...t,memberIds:au(e.members,r)});case 20:return lu(Ye,{...t,oldOwnerId:r,newOwnerId:s});case 21:return lu(Qe,{...t,adminId:s??r});case 22:return lu(Ze,{...t,adminId:s??r});case 23:{const r=(e=>{const t=ou(e),r=t?.user_mute_time;if(!r||"object"!=typeof r||Array.isArray(r))return null;const s={};for(const[n,i]of Object.entries(r)){const e=Number(i);n&&Number.isFinite(e)&&(s[n]=e)}return Object.keys(s).length>0?s:null})(e.ext??e.eventExt),n=r?Object.keys(r):au(e.members,s),i=46388736e5;return lu(Ke,{...t,userIds:n,muteMembers:r??Object.fromEntries(n.map(e=>[e,i])),muteExpire:cu(e.reason,e.eventExt)??i})}case 24:return lu(ze,{...t,userIds:au(e.members,s)});case 25:return lu(Xe,{...t,announcement:e.reason??""});case 26:return lu(Xe,{...t,announcement:""});case 29:return lu(He,{...t,userIds:au(e.members,s)});case 30:return lu(We,{...t,userIds:au(e.members,s)});case 31:return lu(Je,{...t,isMuted:!0});case 32:return lu(Je,{...t,isMuted:!1});case 14:return lu(et,{...t,shouldFetchChatRoomDetail:!0,chatRoomPatch:du(e.eventExt)});case 43:{const s=uu(e.eventExt);return lu(rt,{...t,attributes:s.attributes,from:s.from??r})}case 44:{const s=uu(e.eventExt);return lu(st,{...t,keyList:s.keyList,from:s.from??r})}default:return null}},pu=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),mu=(e,t)=>{if(!e)return t;try{return JSON.parse(e)}catch{return t}},fu=["nickname","avatarUrl","mail","phone","gender","sign","birth","ext"],gu=e=>({userId:e.userId,nickname:e.nickname,avatarUrl:e.avatarUrl,sign:e.sign,ext:e.ext}),yu=e=>({userId:e}),vu=(e,t,r)=>{const s={userId:r};for(const n of fu){const r=t?.[n]??e?.[n];void 0!==r&&(s[n]=r)}return s},Iu=async(e,t)=>{const r=(e=>{const t=[],r=new Set;for(const s of e){const e=s.trim();e&&!r.has(e)&&(r.add(e),t.push(e))}return t})(e),s=new Map;if(0===r.length)return s;const n=t.cacheManager?.getUserInfoSummaries(r,!1)??[];for(const o of n)s.set(o.userId,gu(o));const i=r.filter(e=>!s.has(e));if(i.length>0&&t.fetchUserInfos){const e=await t.fetchUserInfos({userIds:i});for(const t of e)s.set(t.userId,t)}for(const o of r)s.has(o)||s.set(o,yu(o));return s},bu=e=>pu(e)?e:null,_u=e=>{if("string"==typeof e)return e},Tu=e=>{const t=_u(e)?.trim();return t||void 0},Cu=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}},Su=e=>{if("boolean"==typeof e)return e;if("string"==typeof e){if("true"===e)return!0;if("false"===e)return!1}},Eu=e=>{const t=bu(e);return t&&Array.isArray(t.data)?t.data:t&&Array.isArray(t.entities)?t.entities:Array.isArray(e)?e:[]},wu=e=>{const t=bu(e);return t?bu(t.data)?t.data:t:null},Ru=(e,t)=>{const r=bu(e),s=r&&bu(r.params),n=s?.[t];if(Array.isArray(n)&&0!==n.length)return Cu(n[0])},Au=(e,t)=>{const r=(e=>{const t=bu(e);return t?Cu(t.count):void 0})(e);if(void 0!==r&&void 0!==t)return r>=t},Nu=e=>Tu(e.groupId)??Tu(e.groupid)??Tu(e.id)??"",Ou=e=>_u(e.name)??_u(e.groupname)??_u(e.groupName)??"",Mu=e=>{const t=Eu(e),r=bu(t[0])??wu(e)??{},s=(e=>{const t=bu(e);if(!t)return null;const r=Nu(t);return r?{groupId:r,name:Ou(t),description:_u(t.description),memberCount:Cu(t.memberCount)??Cu(t.affiliations_count),public:Su(t.public),joinApprovalRequired:Su(t.joinApprovalRequired)??Su(t.approval)??Su(t.membersonly)??Su(t.members_only),allowInvites:Su(t.allowInvites)??Su(t.allowinvites)??Su(t.allow_user_invites),maxMembers:Cu(t.maxMembers)??Cu(t.maxusers),role:Tu(t.role)??Tu(t.permission),disabled:Su(t.disabled)}:null})(r)??{groupId:Nu(r),name:Ou(r)},n=Tu(r.owner)??Tu(r.admin)??Tu(r.member),i=(Array.isArray(r.affiliations)?r.affiliations:[]).map(e=>bu(e)).filter(e=>null!==e).map(e=>Cu(e.joined_time)).find(e=>void 0!==e);return{...s,owner:n?yu(n):void 0,inviteNeedConfirm:Su(r.inviteNeedConfirm)??Su(r.invite_need_confirm),muteAllMembers:Su(r.mute),ext:_u(r.ext)??_u(r.custom),createdAt:Cu(r.createdAt)??Cu(r.created),joinedAt:i,avatarUrl:_u(r.avatar),messageBlocked:Su(r.messageBlocked)??Su(r.isMessageBlocked)??Su(r.shieldgroup)}},Uu=e=>yu(e),Lu=e=>Eu(e).map(e=>Tu(e)).filter(e=>Boolean(e)).map(e=>Uu(e)),ku=e=>{const t=bu(e);if(!t)return null;const r=Tu(t.fileId)??Tu(t.file_id);if(!r)return null;const s=_u(t.fileName)??_u(t.file_name)??r,n=Tu(t.fileOwner)??Tu(t.file_owner);return{fileId:r,fileName:s,fileOwner:n?Uu(n):void 0,fileSize:Cu(t.fileSize)??Cu(t.file_size),createdAt:Cu(t.createdAt)??Cu(t.created)}},Du=new Set(["public","members_only","allow_user_invites","invite_need_confirm"]),Pu={name:"name",title:"name",description:"description",public:"public",members_only:"joinApprovalRequired",allow_user_invites:"allowInvites",max_users:"maxMembers",invite_need_confirm:"inviteNeedConfirm",custom:"ext"},xu=e=>{if("string"!=typeof e)return;const t=e.trim();return t.length>0?t:void 0},Fu=e=>{if(!e)return null;try{const t=JSON.parse(e);return!t||"object"!=typeof t||Array.isArray(t)?null:t}catch{return null}},Bu=(e,t)=>{const r=e?.map(e=>xu(e)).filter(e=>"string"==typeof e)??[];return r.length>0?r:t?[t]:[]},Gu=(e,t)=>{const r=Number(e);if(!Number.isNaN(r)&&Number.isFinite(r)&&r>0)return r;const s=Fu(t);if(!s)return;const n=s.muteExpire??s.mute_expire??s.expire??s.expired??s.expireAt??s.expiredAt,i=Number(n);return Number.isFinite(i)&&i>0?i:void 0},qu=e=>{const t=Fu(e);if(!t)return;const r={};for(const[s,n]of Object.entries(t)){const e=Pu[s];if(!e)continue;let t=n;if(Du.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},$u=(e,t)=>{const r=Fu(t)??Fu(e);return ku(r??void 0)??void 0},ju=(e,t)=>{const r=Fu(t)??Fu(e);return xu(r?.fileId)??xu(r?.file_id)??xu(e)??""},Vu=(e,t)=>({eventName:e,payload:t}),Ku=e=>{const t={groupId:e.groupId,groupName:e.groupName},r=xu(e.from?.name),s=(n=e.to,xu(n?.[0]?.name));var n;switch(e.operation){case 4:return Vu(X,{...t,applicantId:r,reason:e.reason});case 5:return Vu(ee,{...t,accepterId:r});case 6:return Vu(te,{...t,declinerId:r,applicantId:s,reason:e.reason});case 7:return Vu(Y,{...t,inviterId:r,reason:e.reason});case 8:return Vu(re,{...t,inviteeId:r,reason:e.reason});case 9:return Vu(se,{...t,inviteeId:r,reason:e.reason});case 10:return Vu(ne,t);case 1:return Vu(ie,t);case 19:return Vu(oe,{...t,inviterId:r,reason:e.reason});case 23:{const r=(e=>{const t=Fu(e),r=t?.user_mute_time;if(!r||"object"!=typeof r||Array.isArray(r))return null;const s={};for(const[n,i]of Object.entries(r)){const e=xu(n),t=Number(i);e&&Number.isFinite(t)&&t>0&&(s[e]=t)}return Object.keys(s).length>0?s:null})(e.ext),n=r?Object.keys(r):Bu(e.members,s);return Vu(ae,{...t,userIds:n,muteExpire:n.map(e=>r?.[e]).find(e=>void 0!==e)??Gu(e.reason,e.eventExt)})}case 24:return Vu(ce,{...t,userIds:Bu(e.members,s)});case 29:return Vu(de,{...t,userIds:Bu(e.members,s)});case 30:return Vu(ue,{...t,userIds:Bu(e.members,s)});case 31:return Vu(le,{...t,isMuted:!0});case 32:return Vu(le,{...t,isMuted:!1});case 21:return Vu(he,{...t,administratorId:s??r});case 22:return Vu(pe,{...t,administratorId:s??r});case 20:return Vu(me,{...t,oldOwnerId:r,newOwnerId:s});case 17:{const s=Bu(e.members,r);return Vu(fe,{...t,memberIds:s})}case 18:{const s=Bu(e.members,r);return Vu(ge,{...t,memberIds:s})}case 25:return Vu(ye,{...t,announcement:e.reason??""});case 26:return Vu(ye,{...t,announcement:""});case 27:return Vu(ve,{...t,sharedFile:$u(e.reason,e.eventExt)});case 28:return Vu(Ie,{...t,fileId:ju(e.reason,e.eventExt)});case 14:return Vu(be,{...t,shouldFetchGroupDetail:!0,groupPatch:qu(e.eventExt)});case 41:return Vu(_e,{...t,shouldFetchGroupDetail:!0,isDisabled:!0});case 42:return Vu(_e,{...t,shouldFetchGroupDetail:!0,isDisabled:!1});case 45:{const s=(e=>{const t=Fu(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:xu(t.username),attribute:s}})(e.eventExt);return Vu(Te,{...t,userId:s.userId,attribute:s.attribute,from:r,source:e.source??"direct"})}default:return null}},zu=new WeakMap,Hu=(e,t)=>{zu.set(e,t)},Wu=e=>zu.get(e)??null,Ju=(e,t)=>{const r=Wu(e);r&&Hu(t,r)},Qu=new WeakMap,Zu=e=>Qu.get(e),Yu=new WeakMap,Xu=e=>Yu.get(e),el=(e,t)=>{const r=Yu.get(e);r&&Yu.set(t,r)},tl="singleChat",rl="groupChat",sl=e=>{if("string"!=typeof e)return;const t=e.trim();return t.length>0?t:void 0},nl=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}},il=e=>{if(!Array.isArray(e))return;const t=e.map(e=>sl(e)).filter(e=>"string"==typeof e);return t.length>0?t:void 0},ol=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),al=(...e)=>{for(const t of e){const e=sl(t);if(e)return e}},cl=(e,t)=>Boolean(e&&t&&e===t),dl=(e,t,r)=>Boolean(e&&e===r.userId&&t&&r.clientResource&&t!==r.clientResource),ul=(e,t,r)=>{const s=il(e);if(s&&s.length>0)return s;const n=(t??[]).map(e=>sl(e.name)).filter(e=>"string"==typeof e);if(n.length>0)return n;const i=sl(r?.name);return i?[i]:[]},ll=e=>{const t=nl(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}}},hl=(e,t)=>{const r=al(e.to?.[0]?.clientResource);if(1!==e.to?.length||sl(e.to[0]?.name)!==t.userId||!dl(t.userId,r,t))return null;const s=(n=e.from,sl(n?.name)??"");var n;if(!s)return Vs("Discarded MultiDevice contact event without target user",{operation:e.operation}),null;const i=(e=>{switch(e){case 3:return"CONTACT_REMOVE";case 4:case 8:return"CONTACT_ACCEPT";case 5:case 9:return"CONTACT_DECLINE";case 6:return"CONTACT_BAN";case 7:return"CONTACT_ALLOW";default:return Vs("Discarded unknown MultiDevice contact operation",{operation:e}),"UNKNOWN"}})(e.operation);return"UNKNOWN"===i?null:{category:"contact",operation:i,targetUserId:s,rosterVersion:e.rosterVersion,ext:e.ext,deviceId:r,timestamp:e.timestamp,raw:e.raw}},pl=(e,t)=>{if(!e.groupId)return Vs("Discarded MultiDevice group event without groupId",{operation:e.operation}),null;const r=al(e.from?.clientResource,e.raw?.resource,e.raw?.clientResource);if(!dl(sl(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 Vs("Discarded unknown MultiDevice group operation",{operation:e}),"UNKNOWN"}})(e.operation);if("UNKNOWN"===s)return null;const n=ul(e.members,e.to,e.from);return{category:"group",operation:s,groupId:e.groupId,userIds:n.length>0?n:void 0,operatorId:sl(e.from?.name),groupName:e.groupName,deviceId:r,timestamp:e.timestamp,raw:e.raw}},ml=(e,t)=>{if(!e.threadId)return Vs("Discarded MultiDevice thread event without threadId",{operation:e.operation}),null;const r=al(e.from?.clientResource,e.raw?.resource,e.raw?.clientResource);if(!dl(sl(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 Vs("Discarded unknown MultiDevice thread operation",{operation:e}),"UNKNOWN"}})(e.operation);if("UNKNOWN"===s)return null;const n=ul(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:sl(e.from?.name),threadName:e.threadName,deviceId:r,timestamp:e.timestamp,raw:e.raw}},fl=(e,t)=>{if("pin"===e.operation||"pin_delete"===e.operation)return null;const r=al(e.res,e.raw?.resource,e.raw?.clientResource);if(cl(r,t.clientResource))return js("Discarded same-device MultiDevice conversation echo",{operation:e.operation,conversationId:e.id}),null;const s="chat"===(n=e.type)||"singleChat"===n?tl:rl;var n;const i=sl(e.id)??(s===tl?sl(e.from):void 0);if(!i)return Vs("Discarded MultiDevice conversation event without conversationId",{operation:e.operation}),null;const o=(e=>{switch(e){case"del":return"CONVERSATION_DELETED";case"top":return"CONVERSATION_PINNED";case"not_top":return"CONVERSATION_UNPINNED";case"mark":case"mark_delete":return"CONVERSATION_MARK";case"setSilentModeForConversation":case"removeSilentModeForConversation":return"CONVERSATION_MUTE_INFO_CHANGED";default:return Vs("Discarded unknown MultiDevice conversation operation",{operation:e}),"UNKNOWN"}})(e.operation);return"UNKNOWN"===o?null:{category:"conversation",operation:o,conversationId:i,conversationType:s,mark:"mark"===e.operation||"mark_delete"===e.operation?ll(e.ext):void 0,operatorId:sl(e.from),deviceId:r,timestamp:nl(e.ts),raw:e.raw}},gl=(e,t)=>{const r=al(e.resource,e.raw?.resource,e.raw?.clientResource);if(cl(r,t.clientResource))return js("Discarded same-device MultiDevice roaming delete echo",{conversationId:e.to}),null;const s=sl(e.to);if(!s)return Vs("Discarded MultiDevice roaming delete event without conversationId",{}),null;const n=sl(e.lastMsgId),i=il(e.msgIdList)??(n?[n]:void 0),o=nl(e.deleteTime);if(!i&&void 0===o)return Vs("Discarded MultiDevice roaming delete event without messageIds or beforeTimestamp",{conversationId:s}),null;const a=(e=>e&&"deleteRoaming"!==e&&"MESSAGE_REMOVED"!==e?(Vs("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?rl:tl,messageIds:i,beforeTimestamp:o,deviceId:r,raw:e.raw}},yl=e=>{switch(e){case"contact":return"onMultiDeviceContact";case"group":return"onMultiDeviceGroup";case"thread":return"onMultiDeviceThread";case"conversation":return"onMultiDeviceConversation";case"messageRemoved":return"onMultiDeviceMessageRemoved"}},vl=2147483647,Il=e=>{const t=Number(e);if(!Number.isFinite(t)||t<=0)return;const r=Math.floor(t);return r<=0||r>vl?void 0:r},bl=e=>{if("number"!=typeof e||!Number.isFinite(e)||e<=0)return;const t=e>vl?Math.floor(e/1e3):Math.floor(e);return Il(t)};var _l=4096,Tl=65547,Cl=15,Sl=2113929216,El=65536,wl=65536,Rl=10485760,Al={MANUAL:0,AUTO_IMMEDIATE:1,AUTO_THRESHOLD:2},Nl={SUCCESS:0,FAILED:-1,NOT_INITIALIZED:-2,INITIALIZED_FAILED:-3,COMPRESS_FAILED:-4,DECOMPRESS_FAILED:-5,PARAM_ERROR:-6,BUFFER_RESIZE_FAILED:-7};function Ol(e){if(!(e>0))return wl;if(e<=wl)return wl;if(e>1073741823)return e;for(var t=wl;t<e;)t*=2;return t}var Ml={byU16:0,byU32:1},Ul=0,Ll=1,kl=2,Dl=0,Pl=1;function xl(e,t){return e[t]|e[t+1]<<8}function Fl(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0}function Bl(e,t,r){e[t]=255&r,e[t+1]=r>>>8&255}var Gl="fast";function ql(e){return 2654435761*(e>>>0)>>>20&4095}function $l(e){return 2654435761*(e>>>0)>>>19&8191}function jl(e,t,r){if("fast"===Gl){var s=Fl(e,t);return r===Ml.byU16?$l(s):ql(s)}throw new Error("Unsupported hash strategy: "+Gl)}function Vl(e,t,r,s,n){r[t]=e-n}function Kl(e,t,r,s,n){Vl(t,jl(e,t,s),r,0,n)}function zl(e,t,r,s){return t[e]+s}function Hl(e,t,r,s,n){return zl(jl(e,t,s),r,0,n)}function Wl(e,t,r,s){for(var n=t;t<s-3;){if(Fl(e,t)!==Fl(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 Jl(e,t,r,s,n,i,o,a,c,d){var u,l,h,p=e.hashTable,m=s,f=m-e.dictSize,g=e.dictionary,y=e.dictionaryStart,v=y+e.dictSize,I=e.dictSize>0?v-s:0,b=s,_=s+n,T=_-12,C=_-5,S=0,E=i>0?i:r.length,w=0;if(n>Sl)return 0;switch(c){case Ul:default:u=s,l=s;break;case Ll:u=s-e.currentOffset,l=s-e.dictSize;break;case kl:u=s-e.currentOffset,l=s}if(a===Ml.byU16&&n>=Tl)return 0;if(n<13)return Yl(t,r,b,_,S,E,o);Kl(t,m,p,a,u),h=jl(t,++m,a);e:for(;;){var R,A,N=m,O=1,M=64;do{var U=h;if(m=N,N+=O,O=M++>>>6,N>T)return Yl(t,r,b,_,S,E,o);R=zl(U,p,0,u),c===kl&&(R<s?(w=I,l=y):(w=0,l=s)),h=jl(t,N,a),Vl(m,U,p,0,u)}while(d===Pl&&R<f||a!==Ml.byU16&&R+65535<m||!Ql(t,g,m,R,w,c,s));for(;m>b&&R+w>l;){var L=R+w-1;if(t[m-1]!==(c===kl&&R<s?g[L-y+e.dictionaryStart]:t[L]))break;m--,R--}var k=m-b;if(A=S++,o&&S+k+8+Math.floor(k/255)>E)return 0;if(k>=Cl){var D=k-Cl;for(r[A]=240;D>=255;)r[S++]=255,D-=255;r[S++]=D}else r[A]=k<<4;if(k>=16&&r.set&&t.subarray)r.set(t.subarray(b,b+k),S),S+=k;else for(var P=0;P<k;P++)r[S++]=t[b+P];t:for(;;){var x;if(Bl(r,S,m-R),S+=2,c===kl&&R<s){var F=m+(v-(R+w));if(F>C&&(F=C),(m+=4+(x=Zl(t,g,m+4,R+w+4-y+e.dictionaryStart,F,v-y)))===F&&F<C){var B=Wl(t,m,s,C);x+=B,m+=B}}else m+=4+(x=Wl(t,m+4,R+4,C));if(o&&S+6+(x>>>8)>E)return 0;if(x>=15){for(r[A]+=15,x-=15;x>=510;)r[S++]=255,r[S++]=255,x-=510;x>=255&&(x-=255,r[S++]=255),r[S++]=x}else r[A]+=x;if(b=m,m>T)break e;if(Kl(t,m-2,p,a,u),R=Hl(t,m,p,a,u),c===kl&&(R<s?(w=I,l=y):(w=0,l=s)),Kl(t,m,p,a,u),!((d!==Pl||R>=f)&&R+65535>=m&&Ql(t,g,m,R,w,c,s)))break t;r[A=S++]=0}h=jl(t,++m,a)}return Yl(t,r,b,_,S,E,o)}function Ql(e,t,r,s,n,i,o){var a,c=Fl(e,r);i===kl&&s+n<o?a=Fl(t,s+n):a=Fl(e,s+n);return c===a}function Zl(e,t,r,s,n,i,o){for(var a=r;s<i&&r<n&&t[s]===e[r];)s++,r++;return r-a}function Yl(e,t,r,s,n,i,o){var a=s-r;if(o&&n+a+1+Math.floor((a+255-Cl)/255)>i)return 0;if(a>=Cl){for(t[n++]=240,a-=Cl;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 Xl(e,t,r,s){var n,i=0;if(s&&t.ip>=r)return-1;do{if(i+=n=e[t.ip++],t.ip>r)return-1;if(i>2147483647)return-1}while(255===n);return i}function eh(e,t,r,s,n,i,o,a,c,d,u,l,h){if(null==e)return-1;if(i<0)return-1;var p=r,m=r+s,f=n,g=n+i,y=u-h,v=l+h,I=h<65536;if(0===i)return 1===s&&0===e[p]?0:-1;if(0===s)return-1;for(;;){var b,_,T,C;if(p>=m)return-(p-r)-1;if((_=(b=e[p++])>>>4)===Cl){var S=Xl(e,R={ip:p},m-Cl,!0);if(p=R.ip,-1===S)return-(p-r)-1;if(f+(_+=S)<f)return-(p-r)-1;if(p+_<p)return-(p-r)-1}if(T=f+_,o&&(T>g-12||p+_>m-8)||!o&&T>g-8){if(!o&&T!==g)return-(p-r)-1;if(o&&(p+_!==m||T>g))return-(p-r)-1;if(_>=16&&t.set&&e.subarray)t.set(e.subarray(p,p+_),f);else for(var E=0;E<_;E++)t[f+E]=e[p+E];p+=_,f+=_;break}if(_>=16&&t.set&&e.subarray)t.set(e.subarray(p,p+_),f);else for(E=0;E<_;E++)t[f+E]=e[p+E];if(f=T,(p+=_)+2>m)return-(p-r)-1;var w=xl(e,p);if(p+=2,C=T-w,I&&C+h<u)return-(p-r)-1;if(0===w)return-(p-r)-1;if(15===(_=15&b)){var R;S=Xl(e,R={ip:p},m-5+1,!1);if(p=R.ip,-1===S)return-(p-r)-1;if(f+(_+=S)<f)return-(p-r)-1}if(_+=4,d===kl&&C<u){if(f+_>g-5)return-(p-r)-1;if(_<=u-C){var A=v-(u-C);for(E=0;E<_;E++)t[f+E]=t[A+E];f+=_}else{var N=u-C;for(A=v-N,E=0;E<N;E++)t[f+E]=t[A+E];var O=_-N;if(O>(f+=N)-u)for(var M=u,U=f+O;f<U;)t[f++]=t[M++];else{for(E=0;E<O;E++)t[f+E]=t[u+E];f+=O}}}else{if(C<y)return-(p-r)-1;if(T=f+_,f-C<8)for(t[f]=t[C],t[f+1]=t[C+1],t[f+2]=t[C+2],t[f+3]=t[C+3],f+=4,C+=4;f<T;)t[f++]=t[C++];else for(;f<T;)t[f++]=t[C++]}}return o?f-n:p-r}function th(){return{hashTable:new Uint32Array(_l),currentOffset:0,initCheck:0,dictionary:null,dictionaryStart:0,dictSize:0,bufferStart:null}}function rh(e){e.hashTable.fill(0),e.currentOffset=0,e.initCheck=0,e.dictionary=null,e.dictionaryStart=0,e.dictSize=0,e.bufferStart=null}function sh(e,t,r,s,n,i,o,a){s=s||0;var c=e.dictionaryStart+e.dictSize,d=s;if(e.initCheck)return 0;e.dictSize>0&&d>c&&(d=c),function(e){if(e.currentOffset>2147483648){for(var t=e.currentOffset-65536,r=e.dictionaryStart+e.dictSize,s=0;s<e.hashTable.length;s++)e.hashTable[s]<t?e.hashTable[s]=0:e.hashTable[s]-=t;e.currentOffset=65536,e.dictSize>65536&&(e.dictSize=65536),e.dictionaryStart=r-e.dictSize}}(e);var u,l=s+n;e.dictionary&&l>e.dictionaryStart&&l<c&&(e.dictSize=c-l,e.dictSize>65536&&(e.dictSize=65536),e.dictSize<4&&(e.dictSize=0),e.dictionaryStart=c-e.dictSize);var h=e.dictSize<65536&&e.dictSize<e.currentOffset?Pl:Dl;return e.dictionary&&c===s?(u=Jl(e,t,r,s,n,o||0,a||!1,Ml.byU32,Ll,h),e.dictSize+=n,e.currentOffset+=n,u):(u=Jl(e,t,r,s,n,o||0,a||!1,Ml.byU32,kl,h),e.dictionary=t,e.dictionaryStart=s,e.dictSize=n,e.currentOffset+=n,u)}function nh(e,t,r,s){var n=e.dictionaryStart+e.dictSize;s>65536&&(s=65536),s>e.dictSize&&(s=e.dictSize);var i=n-s;if(t.set&&e.dictionary.subarray)t.set(e.dictionary.subarray(i,i+s),r);else for(var o=0;o<s;o++)t[r+o]=e.dictionary[i+o];return e.dictionary=t,e.dictionaryStart=r,e.dictSize=s,s}function ih(){return{externalDict:null,extDictStart:0,extDictSize:0,prefixEnd:0,prefixSize:0}}function oh(e,t,r,s){return e.prefixSize=s,e.prefixEnd=r+s,e.externalDict=null,e.extDictStart=0,e.extDictSize=0,1}function ah(e,t,r,s,n,i,o){var a;if(e.prefixEnd===i){if((a=eh(t,r,s,n,i,o,!0,0,0,kl,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=eh(t,r,s,n,i,o,!0,0,0,kl,i,e.extDictStart,e.extDictSize))<=0)return a;e.prefixSize=a,e.prefixEnd=i+a}return a}function ch(e){var t=(e=e||{}).minWorkArea||wl,r=e.maxWorkArea||Rl,s=e.shrinkThreshold||t;t<wl&&(t=wl),r<t&&(r=t),s<t&&(s=t),s>r&&(s=r),this.minBufferSize=El+t,this.maxBufferSize=El+r,this.shrinkThreshold=El+s,this.ringBufferSize=this.minBufferSize,this.shrinkMode=void 0!==e.shrinkMode?e.shrinkMode:Al.MANUAL,this.ringBuffer=new Uint8Array(this.ringBufferSize),this.offset=0,this.stream=th()}function dh(e){var t=(e=e||{}).minWorkArea||wl,r=e.maxWorkArea||Rl,s=e.shrinkThreshold||t;t<wl&&(t=wl),r<t&&(r=t),s<t&&(s=t),s>r&&(s=r),this.minBufferSize=El+t,this.maxBufferSize=El+r,this.shrinkThreshold=El+s,this.ringBufferSize=this.minBufferSize,this.shrinkMode=void 0!==e.shrinkMode?e.shrinkMode:Al.MANUAL,this.ringBuffer=new Uint8Array(this.ringBufferSize),this.offset=0,this.streamDecode={externalDict:null,extDictStart:0,extDictSize:0,prefixEnd:0,prefixSize:0}}ch.prototype._resizeBuffer=function(e){var t=new Uint8Array(e),r=0;if(this.offset>0){var s=this.offset<El?this.offset:El,n=this.offset>El?this.offset-El:0;t.set(this.ringBuffer.subarray(n,n+s),0),nh(this.stream,t,0,s),r=s}return this.ringBuffer=t,this.ringBufferSize=e,this.offset=r,!0},ch.prototype.compress=function(e,t){var r=e.length;if(r<=0)return Nl.PARAM_ERROR;if(r>this.maxBufferSize-El)return Nl.PARAM_ERROR;if(r>this.ringBufferSize-El){var s=Ol(r),n=El+s;if(n>this.maxBufferSize&&(n=this.maxBufferSize),!this._resizeBuffer(n))return Nl.BUFFER_RESIZE_FAILED}this.offset+r>this.ringBufferSize&&(nh(this.stream,this.ringBuffer,0,El),this.offset=El);var i=this.offset;this.ringBuffer.set(e,i);var o=sh(this.stream,this.ringBuffer,t,i,r,0,t.length,!0);return o<=0?Nl.COMPRESS_FAILED:(this.offset+=r,this._tryAutoShrink(),o)},ch.prototype.reset=function(){this.offset=0,rh(this.stream)},ch.prototype.shrink=function(){this.ringBufferSize>this.minBufferSize&&this._resizeBuffer(this.minBufferSize)},ch.prototype._tryAutoShrink=function(){this.shrinkMode!==Al.MANUAL&&(this.ringBufferSize<=this.minBufferSize||(this.shrinkMode===Al.AUTO_IMMEDIATE||this.shrinkMode===Al.AUTO_THRESHOLD&&this.ringBufferSize>this.shrinkThreshold)&&this.shrink())},ch.prototype.getWorkArea=function(){return this.ringBufferSize-El},ch.prototype.getRingBufferSize=function(){return this.ringBufferSize},ch.prototype.getBaseBufferSize=function(){return this.minBufferSize},ch.prototype.getMaxBufferSize=function(){return this.maxBufferSize},ch.prototype.getCurrentOffset=function(){return this.offset},ch.prototype.getShrinkMode=function(){return this.shrinkMode},ch.prototype.setShrinkMode=function(e){this.shrinkMode=e},ch.prototype.getShrinkThreshold=function(){return this.shrinkThreshold},ch.prototype.setShrinkThreshold=function(e){var t=this.minBufferSize-El,r=this.maxBufferSize-El;if(e<t||e>r)return Nl.PARAM_ERROR;this.shrinkThreshold=El+e},dh.prototype._resizeBuffer=function(e){var t=new Uint8Array(e),r=0;if(this.offset>0){var s=this.offset<El?this.offset:El,n=this.offset>El?this.offset-El:0;t.set(this.ringBuffer.subarray(n,n+s),0),r=s,oh(this.streamDecode,0,0,s)}return this.ringBuffer=t,this.ringBufferSize=e,this.offset=r,!0},dh.prototype.decompress=function(e,t,r){var s=e.length;if(s<=0||r<=0)return Nl.PARAM_ERROR;if(r>this.maxBufferSize-El)return Nl.PARAM_ERROR;if(r>this.ringBufferSize-El){var n=Ol(r),i=El+n;if(i>this.maxBufferSize&&(i=this.maxBufferSize),!this._resizeBuffer(i))return Nl.BUFFER_RESIZE_FAILED}if(this.offset+r>this.ringBufferSize){var o=this.offset-El;o>0&&this.ringBuffer.set(this.ringBuffer.subarray(o,o+El),0),oh(this.streamDecode,this.ringBuffer,0,El),this.offset=El}var a=ah(this.streamDecode,e,this.ringBuffer,0,s,this.offset,r);return a<=0?Nl.DECOMPRESS_FAILED:(t.set(this.ringBuffer.subarray(this.offset,this.offset+a),0),this.offset+=a,this._tryAutoShrink(),a)},dh.prototype.reset=function(){this.offset=0,this.streamDecode={externalDict:null,extDictStart:0,extDictSize:0,prefixEnd:0,prefixSize:0}},dh.prototype.shrink=function(){this.ringBufferSize>this.minBufferSize&&this._resizeBuffer(this.minBufferSize)},dh.prototype._tryAutoShrink=function(){this.shrinkMode!==Al.MANUAL&&(this.ringBufferSize<=this.minBufferSize||(this.shrinkMode===Al.AUTO_IMMEDIATE||this.shrinkMode===Al.AUTO_THRESHOLD&&this.ringBufferSize>this.shrinkThreshold)&&this.shrink())},dh.prototype.getWorkArea=function(){return this.ringBufferSize-El},dh.prototype.getRingBufferSize=function(){return this.ringBufferSize},dh.prototype.getBaseBufferSize=function(){return this.minBufferSize},dh.prototype.getMaxBufferSize=function(){return this.maxBufferSize},dh.prototype.getCurrentOffset=function(){return this.offset},dh.prototype.getShrinkMode=function(){return this.shrinkMode},dh.prototype.setShrinkMode=function(e){this.shrinkMode=e},dh.prototype.getShrinkThreshold=function(){return this.shrinkThreshold},dh.prototype.setShrinkThreshold=function(e){var t=this.minBufferSize-El,r=this.maxBufferSize-El;if(e<t||e>r)return Nl.PARAM_ERROR;this.shrinkThreshold=El+e};const uh={LZ4_MAX_INPUT_SIZE:Sl,BLOCK_MAX_SIZE:65536,DICT_SIZE:El,DEFAULT_WORK_AREA:wl,DEFAULT_MAX_WORK:Rl,SHRINK_MODE:Al,LZ4_ERROR:Nl,alignToPowerOf2:Ol,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".');Gl=e},getHashStrategy:function(){return Gl},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>Sl)return 0;if(0===s)return t.length>n?(t[n]=0,1):0;var i=s<Tl?Ml.byU16:Ml.byU32;return Jl({hashTable:new Uint32Array(i===Ml.byU16?8192:_l),currentOffset:0,dictSize:0,dictionary:null,dictionaryStart:0},e,t,r,s,0,!1,i,Ul,Dl)},compressLimited:function(e,t,r,s,n,i){if(null==e)return 0;if(null==t)return 0;if(r=r||0,s=void 0===s?e.length:s,n=n||0,r<0||n<0)return 0;if(s<0||i<0)return 0;if(r+s>e.length)return 0;if(s>Sl)return 0;if(i<1)return 0;if(0===s)return t[n]=0,1;var o=s<Tl?Ml.byU16:Ml.byU32;return Jl({hashTable:new Uint32Array(o===Ml.byU16?8192:_l),currentOffset:0,dictSize:0,dictionary:null,dictionaryStart:0},e,t,r,s,i,!0,o,Ul,Dl)},compressBound:function(e){return e<0||e>Sl?0:e+Math.floor(e/255)+16},decompressSafe:function(e,t,r,s,n,i){return null==e||null==t?-1:(n=n||0,(r=r||0)<0||n<0||s<0||i<0||r+s>e.length||n+i>t.length?-1:eh(e,t,r,s,n,i,!0,0,0,Ul,n,null,0))},decompressFast:function(e,t,r,s,n){return eh(e,t,r=r||0,0,s=s||0,n,!1,0,0,Ll,s-65536,0,65536)},createStream:th,resetStream:rh,loadDict:function(e,t,r,s){if(e.initCheck&&rh(e),s<4)return e.dictionary=null,e.dictSize=0,0;s>65536&&(r=r+s-65536,s=65536);var n=r-e.currentOffset;e.dictionary=t,e.dictionaryStart=r,e.dictSize=s,e.currentOffset+=s;for(var i=r,o=r+s;i<=o-4;)Kl(t,i,e.hashTable,Ml.byU32,n),i+=3;return s},compressContinue:sh,saveDict:nh,createStreamDecode:ih,setStreamDecode:oh,decompressSafeContinue:ah,RingBufferEncoder:ch,RingBufferDecoder:dh,_hashU16:$l,_hashU32:ql,_TABLE_TYPE:Ml},lh=268435455,hh=new Uint32Array(256);let ph=!1;function mh(e){!function(){if(!ph){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;hh[e]=t>>>0}ph=!0}}();let t=4294967295;for(let r=0;r<e.length;r+=1){const s=e[r]??0;t=t>>>8^(hh[255&(t^255&s)]??0)}return(4294967295^t)>>>0}var fh=(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))(fh||{});const gh=268435455;class yh{constructor(){this.mode=-1,this.enableUplinkCompression=!1,this.enableDownlinkCompression=!1;const e={minWorkArea:uh.DEFAULT_WORK_AREA,maxWorkArea:uh.DEFAULT_MAX_WORK,shrinkMode:uh.SHRINK_MODE.MANUAL};this.encoder=new uh.RingBufferEncoder(e),this.decoder=new uh.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>gh)throw new Error(`Data size exceeds maximum allowed: ${t.length}`);const r=uh.compressBound(t.length),s=new Uint8Array(r),n=this.encoder.compress(t,s);if(n<0)throw new Error(`LZ4 compression failed with error code: ${n}`);const i=s.subarray(0,n),o=function(e){if(e<0)throw new Error("encodeLength: Length must be non-negative");if(e>lh)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=mh(t),c=new Uint8Array(o.length+4+n);let d=0;c.set(o,d),d+=o.length;return new DataView(c.buffer).setUint32(d,a,!1),d+=4,c.set(i,d),c}decompress(e){const t=e instanceof ArrayBuffer?new Uint8Array(e):e;if(!t||0===t.length)return new Uint8Array(0);if(t.length<5)throw new Error("Compressed data is too short: must contain at least length and CRC32");const r={offset:0},s=function(e,t){if(t.offset>=e.length)throw new Error("decodeLength: No data to decode: offset beyond data length");let r=0,s=0;for(;t.offset<e.length;){const n=e[t.offset]??0;if(t.offset+=1,r|=(127&n)<<s,!(128&n))return r>>>0;if(s+=7,s>=28)throw new Error("decodeLength: Invalid length encoding: exceeds 4 bytes")}throw new Error("decodeLength: Incomplete length encoding: missing terminator byte")}(t,r);if(s>gh)throw new Error(`Original size exceeds maximum allowed: ${s}`);if(t.length<r.offset+4)throw new Error("Compressed data is too short: missing CRC32 checksum");const n=new DataView(t.buffer,t.byteOffset+r.offset,4).getUint32(0,!1);r.offset+=4;const i=t.subarray(r.offset),o=new Uint8Array(s),a=this.decoder.decompress(i,o,s);if(a<0||a!==s)throw new Error(`LZ4 decompression failed: expected ${s}, got ${a}`);const c=mh(o);if(c!==n)throw new Error(`CRC32 checksum mismatch: expected ${n}, got ${c}`);return o}reset(){this.encoder.reset(),this.decoder.reset()}}const vh=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),Ih=(e,t)=>ka(e,t).finish();class bh{constructor(e){this.compressor=null,this.compressionFailureCount=0,this.maxCompressionFailures=1,this.context=(e=>{const t=Jd({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:[sr],compressType:[nr],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=Kd(),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:[nr],encryptType:[sr],protocolCompressType:this.getRequestedCompressTypes(),deviceUuid:this.context.deviceUuid,deviceName:this.context.deviceName,resource:this.context.deviceId,actionVersion:"v6.0",authToken:`{"token":"$t$${this.context.token}"}`,sessionId:this.context.sessionId,...this.context.serviceId?{serviceId:this.context.serviceId}:{},...void 0!==this.context.customOSPlatform?{osCustomValue:this.context.customOSPlatform}:{},...this.context.loginExtensionInfo?{reason:this.context.loginExtensionInfo}:{}},n=Ih(t,s),i={version:0,guid:Qd({appKey:this.context.appKey,name:this.context.userId,domain:this.context.domain,clientResource:this.context.clientResource}),command:St,deviceId:0,encryptType:[sr],payload:n,traceId:tu()};return Ih(r,i)}encodeHeartbeat(){const e=Kd(),t=e.lookupType("easemob.pb.CommUnreadUL"),r=e.lookupType("easemob.pb.MSync"),s=Ih(t,{}),n={version:0,encryptType:[sr],command:Tt,payload:s,traceId:tu()};return Ih(r,n)}encodeStatisticRebuild(){const e=Kd(),t=e.lookupType("easemob.pb.StatisticsBody"),r=e.lookupType("easemob.pb.Meta"),s=e.lookupType("easemob.pb.CommSyncUL"),n=e.lookupType("easemob.pb.MSync"),i=Ih(t,{operation:0}),o=r.decode(new Uint8Array);o.id=Date.now(),o.ns=Jt,o.payload=i;const a=s.decode(new Uint8Array);a.meta=o;const c=Ih(s,a);return Ih(n,{version:0,encryptType:[sr],command:_t,payload:c,traceId:tu()})}decodeProvision(e){const t=Kd().lookupType("easemob.pb.Provision").decode(e),r=t.status??{},s="number"==typeof r.errorCode?r.errorCode:ar,n="string"==typeof r.reason?r.reason:void 0,i="string"==typeof t.resource?t.resource:void 0,o="string"==typeof t.authToken?t.authToken:void 0,a=Array.isArray(t.protocolCompressType)?t.protocolCompressType:void 0,c="number"==typeof t.protocolCompressDirection?t.protocolCompressDirection:void 0;return this.configureCompression(a,c),{ok:s===or,statusCode:s,reason:n,resource:i,authToken:o,protocolCompressType:a,protocolCompressDirection:c}}decodeLogout(e){const t=Kd().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=Kd().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=Kd().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=Kd(),r=t.lookupType("easemob.pb.CommSyncDL"),s=t.lookupType("easemob.pb.MessageBody"),n=r.decode(e);js("decodeSync commSyncDl",{hasMetas:Array.isArray(n.metas)});const i=Array.isArray(n.metas)?n.metas:[],o=this.decodeAck(n);o?.ok&&(o.chatRoomInfo=this.decodeChatRoomJoinInfo(i));const a=Yd(n.metaId),c=Yd(n.nextKey),d=n.queue??void 0,u="boolean"==typeof n.isLast?n.isLast:void 0,l=[],h=[];if(a&&"0"!==a){const e=this.useReplacedMessageContents?this.decodeReplacedMessage(i,s):void 0;for(const t of i){const e=this.decodeNotifyMeta(t);e.length>0&&h.push(...e)}return{ack:o,messages:l,notifies:h.length>0?h:void 0,metaId:a,queue:d,nextKey:c,isLast:u,replacedMessage:e}}for(const p of i){const e=this.decodeChatMeta(p,s);e&&l.push(e);const t=this.decodeChatActionMeta(p,s);t&&h.push(t);const r=this.decodeNotifyMeta(p);r.length>0&&h.push(...r)}return{ack:o,messages:l,notifies:h.length>0?h:void 0,metaId:a,queue:d,nextKey:c,isLast:u}}decodeReplacedMessage(e,t){for(const r of e){const e=this.decodeChatMeta(r,t);if(e)return e}}decodeChatMeta(e,t){if(!e||"object"!=typeof e)return null;const r=e,s=r.payload;let n=null;if(s instanceof Uint8Array?n=s:s instanceof ArrayBuffer?n=new Uint8Array(s):ArrayBuffer.isView(s)&&(n=new Uint8Array(s.buffer,s.byteOffset,s.byteLength)),!n)return null;if(("number"==typeof r.ns?r.ns:void 0)!==Qt)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)!==Qt)return null;try{const e=t.decode(n);if(!e||"object"!=typeof e)return null;const s=e,i="number"==typeof s.type?s.type:wt;if(i!==Ot&&i!==Ut&&i!==Lt&&i!==kt&&i!==Mt)return null;const o=this.readJid(r.to),a=Number(Yd(r.timestamp))||Date.now(),c=this.resolveActionConversationType(o.domain,s.meta,s),{senderId:d,receiverId:u}=this.resolveIncomingMessageParties(r,s,c),l=this.resolveActionConversationId(d,u,c);if(i===Lt)return!0===s.clearAllUnreadMessageCount?{type:"multiDevice",eventName:"onMultiDeviceConversation",data:{category:"conversation",operation:"ALL_CONVERSATIONS_UNREAD_MESSAGE_COUNT_CLEARED",timestamp:a}}:l?{type:"multiDevice",eventName:"onMultiDeviceConversation",data:{category:"conversation",operation:"CONVERSATION_UNREAD_MESSAGE_COUNT_CLEARED",conversationId:l,conversationType:"groupChat"===c?"groupChat":"singleChat",timestamp:a}}:null;if(i===Ot){js("Received READ_ACK MessageBody",s);const e=(Array.isArray(s.ackMessageIds)?s.ackMessageIds:[]).map(e=>Yd(e)).filter(e=>Boolean(e)),t=Yd(s.ackMessageId);if(0===e.length&&t&&e.push(t),0===e.length||!l)return null;const r=eu(Array.isArray(s.ext)?s.ext.filter(vh):void 0),n=vh(r.group_ack_count)?r.group_ack_count:{},i=e.flatMap(e=>{const t=n[e];return"number"==typeof t&&Number.isInteger(t)&&t>=0?[{messageId:e,count:t}]:[]});return{type:"message_receipts",data:{messageIds:e,conversationId:l,conversationType:"groupChat"===c?"groupChat":"singleChat",timestamp:a,..."groupChat"===c?{receiptDetails:i}:{}}}}if(i===Mt){const e=Yd(s.ackMessageId);return e&&l?{type:"message_delivered",data:{messageId:e,from:d,to:u,conversationId:l,conversationType:"singleChat"}}:null}if(i===Ut){const e=Yd(s.ackMessageId);return e&&l?{type:"message_recalled",data:{messageId:e,conversationId:l,conversationType:c,timestamp:a}}:null}const h=Yd(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:eu(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!==Xt&&r!==Yt&&r!==Zt&&r!==Jt)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===Yt?this.decodeRosterMeta(t,n):r===Zt?this.decodeMucMeta(t,n):r===Jt?this.decodeStatisticGroupReceiptNotifies(t,n):this.decodeNotifyPayload(n):[]}decodeStatisticGroupReceiptNotifies(e,t){try{const r=Kd(),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(!vh(n)||!Array.isArray(n.group_ack))return[];const i=this.readMetaTimestamp(e)??Date.now(),o=new Map;for(const e of n.group_ack){if(!vh(e))continue;const t="string"==typeof e.groupId&&e.groupId.length>0?e.groupId:"";for(const[r,s]of Object.entries(e)){if("groupId"===r)continue;const e="number"==typeof s?s:"string"==typeof s&&s.trim().length>0?Number(s):Number.NaN;!r||!Number.isInteger(e)||e<0||o.set(r,{conversationId:t,count:e})}}return js("Decoded MSync statistic group read receipts",{receiptDetails:Array.from(o,([e,{conversationId:t,count:r}])=>({messageId:e,conversationId:t,count:r}))}),Array.from(o,([e,{conversationId:t,count:r}])=>({type:"message_receipts",data:{messageIds:[e],conversationId:t,conversationType:"groupChat",timestamp:i,receiptDetails:[{messageId:e,count:r}]}}))}catch{return[]}}decodeStatisticMeta(e){if(!e||"object"!=typeof e)return null;const t=e;if(t.ns!==Jt)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=Kd(),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=Kd(),s=r.lookupType("easemob.pb.RosterBody").decode(t),n="number"==typeof s.operation?s.operation:-1,i=this.readRosterJid(s.from),o=this.readRosterJidList(s.to),a="string"==typeof s.reason?s.reason:"",c="string"==typeof s.rosterVer&&s.rosterVer.trim().length>0?s.rosterVer:void 0,d=i.name??"",u=o[0]?.name??"";if(!d&&!u)return[];const l=hl({operation:n,from:i,to:o,rosterVersion:c,ext:a,timestamp:this.readMetaTimestamp(e),raw:s},this.msyncCodecContext());if(l)return[this.createMultiDeviceNotify(l)];const h=this.mapRosterOperationToEvent(n,{from:d,to:u,message:a,rosterVersion:c});return h?[{type:"contact",eventName:h.eventName,data:h.payload}]:[]}catch{return[]}}readRosterJid(e){if(!e||"object"!=typeof e)return{};const t=e;return{name:"string"==typeof t.name?t.name:void 0,clientResource:"string"==typeof t.clientResource?t.clientResource:void 0}}readRosterJidList(e){return Array.isArray(e)&&0!==e.length?e.map(e=>this.readRosterJid(e)):[]}readJid(e){if(!e||"object"!=typeof e)return{};const t=e;return{name:"string"==typeof t.name?t.name:void 0,clientResource:"string"==typeof t.clientResource?t.clientResource:void 0,domain:"string"==typeof t.domain?t.domain:void 0}}decodeMucMeta(e,t){try{const r=Kd(),s=r.lookupType("easemob.pb.MUCBody").decode(t),n="number"==typeof s.operation?s.operation:-1,i=!0===s.isChatroom,o=!0===s.isThread,a=this.readJid(s.from),c=Array.isArray(s.to)?s.to.map(e=>this.readJid(e)):[],d=s.eventInfo&&"object"==typeof s.eventInfo?s.eventInfo:void 0,u=Array.isArray(s.members)?s.members.filter(e=>"string"==typeof e):[],l=a.name===this.context.userId&&a.clientResource&&a.clientResource!==this.context.clientResource?"multiDevice":"direct";if(o){const t=ml({operation:n,threadId:this.readJid(s.mucId).name??"",threadName:"string"==typeof s.mucName?s.mucName:void 0,parentId:this.readJid(s.mucParentId).name??void 0,from:a,to:c,members:u,timestamp:this.readMetaTimestamp(e),raw:s},this.msyncCodecContext());if(t)return[this.createMultiDeviceNotify(t)];const r=37===n&&c.some(e=>e.name===this.context.userId),i=this.readJid(s.mucId).name??"",o=this.readJid(s.mucParentId).name??"";return r&&i&&o?[{type:"thread",eventName:"onChatThreadChange",data:{eventName:"onChatThreadChange",payload:{id:i,name:"string"==typeof s.mucName?s.mucName:void 0,muc_parent_id:o,timestamp:this.readMetaTimestamp(e),from:a.name,userIds:[this.context.userId],operation:"kick"}}}]:[]}if(!i){const t=pl({operation:n,groupId:this.readJid(s.mucId).name??"",groupName:"string"==typeof s.mucName?s.mucName:void 0,from:a,to:c,reason:"string"==typeof s.reason?s.reason:void 0,eventExt:"string"==typeof d?.ext?d.ext:void 0,members:u,timestamp:this.readMetaTimestamp(e),raw:s},this.msyncCodecContext());if(t)return[this.createMultiDeviceNotify(t)]}const h=i?hu({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}):Ku({operation:n,groupId:this.readJid(s.mucId).name??"",groupName:"string"==typeof s.mucName?s.mucName:void 0,from:a,to:c,reason:"string"==typeof s.reason?s.reason:void 0,eventExt:"string"==typeof d?.ext?d.ext:void 0,ext:"string"==typeof s.ext?s.ext:void 0,members:u,source:l});return h?[{type:i?"chatroom":"group",eventName:i?"onChatRoomNotify":"onGroupNotify",data:h}]:[]}catch{return[]}}mapRosterOperationToEvent(e,t){const r={from:t.from,to:t.to,message:t.message,userInfo:{userId:t.from||t.to}};switch(((e,t)=>{t&&Qu.set(e,t)})(r,t.rosterVersion),e){case 2:return{eventName:"onContactInvited",payload:r};case 3:return{eventName:"onContactDeleted",payload:r};case 4:return{eventName:"onContactAdded",payload:r};case 5:case 9:return{eventName:"onContactRefuse",payload:r};case 8:return{eventName:"onContactAgreed",payload:r};default:return null}}decodeNotifyPayload(e){try{let t="";for(let i=0;i<e.length;i+=1){const r=e[i];if(void 0===r)return[];t+=`%${r.toString(16)}`}const r=decodeURIComponent(t),s=JSON.parse(r);js("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:vh(s.data)?s.data:s}}]}if("conv"===n){const e=vh(s.data)?s.data:s,t=[],r="string"==typeof e.op?e.op:"";if("pin"===r||"pin_delete"===r)return[{type:n,eventName:"onPinnedMessageChanged",data:e}];const i=fl({operation:r,id:"string"==typeof e.id?e.id:"",type:"string"==typeof e.type?e.type:void 0,from:"string"==typeof e.from?e.from:void 0,res:"string"==typeof e.res?e.res:void 0,ts:e.ts,ext:"string"==typeof e.ext?e.ext:void 0,raw:e},this.msyncCodecContext());return i&&t.push(this.createMultiDeviceNotify(i)),t}if("roaming_delete"===n){const e=vh(s.data)?s.data:s,t=gl({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(!ol(s))continue;const e=al(s.operator_resource,s.resource,s.clientResource);if(cl(e,t.clientResource))continue;const n=sl(s.group)??sl(s.user);if(!n||!ol(s.data))continue;const i=sl(s.group)?rl:tl,o=s.data;r.push({category:"conversation",operation:"CONVERSATION_MUTE_INFO_CHANGED",conversationId:n,conversationType:i,remindType:sl(o.type),silentMode:o,deviceId:e,raw:s})}return r})(vh(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(Yd(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:yl(e.category),data:e}}decodeNotice(e){const t=Kd().lookupType("easemob.pb.CommNotice").decode(e);return{queue:t.queue&&"object"==typeof t.queue?t.queue:void 0}}decodeUnread(e){const t=Kd().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=Kd(),r=t.lookupType("easemob.pb.CommSyncUL"),s=t.lookupType("easemob.pb.MSync"),n=Ih(r,{queue:e}),i={version:0,encryptType:[sr],command:_t,payload:n,traceId:tu()};return Ih(s,i)}encodeLastSession(e,t){const r=Kd(),s=r.lookupType("easemob.pb.CommSyncUL"),n=r.lookupType("easemob.pb.MSync"),i=Ih(s,{queue:e,key:t}),o={version:0,encryptType:[sr],command:_t,payload:i,traceId:tu()};return Ih(n,o)}encodeChatMessage(e,t){const r=Kd(),s=r.lookupType("easemob.pb.CommSyncUL"),n=r.lookupType("easemob.pb.MSync"),i=this.buildChatMeta(e,t),o=Ih(s,{meta:i}),a={version:0,encryptType:[sr],command:_t,payload:o,traceId:tu()};return Ih(n,a)}encodeCombineMessageMeta(e){const t=Kd().lookupType("easemob.pb.Meta"),r=Zd(e.msgServerId||e.msgLocalId),s=this.buildChatMeta(e,r,!0);return Ih(t,s)}buildChatMeta(e,t,r=!1){const s=Kd().lookupType("easemob.pb.MessageBody"),n=this.buildContent(e),i=this.resolveMessageProfileVersionFields(e),o=this.buildMessageMeta(e),a=this.resolveOutboundMessageTarget(e.conversationId,e.conversationType),c=r?e.from||e.sender.userId:this.context.userId,d=r&&e.to||a.name,u={type:this.resolveChatType(e),from:{name:c},to:{name:d},contents:[n],ext:Xd(e.ext??{}),...o?{meta:o}:{},...i,...e.needReadReceipt?{msgConfig:{allowGroupAck:!0}}:{}},l=Ih(s,u),h="singleChat"===e.conversationType?this.context.domain:"conference.easemob.com",p=this.resolveDirectedUsers(e),m=this.resolveMetaExt(e);return{id:t,to:Qd({appKey:this.context.appKey,name:d,domain:h,clientResource:r?void 0:a.clientResource}),...r?{timestamp:e.timestamp}:{},ns:Qt,payload:l,routetype:this.resolveRouteType(e),directedUsers:p,ext:m,...void 0!==e.webhookEnv?{env:e.webhookEnv}:{}}}encodeActionMessage(e,t){const r=Kd(),s=r.lookupType("easemob.pb.MessageBody"),n=r.lookupType("easemob.pb.CommSyncUL"),i=r.lookupType("easemob.pb.MSync"),o=r.lookupEnum("easemob.pb.MessageBody.EditScope"),a=this.resolveOutboundMessageTarget(e.conversationId,e.conversationType),c=e.body&&e.messageType?[this.buildContent({msgServerId:e.messageId??"",msgLocalId:t,from:this.context.userId,to:e.conversationId,sender:{userId:this.context.userId},conversationId:e.conversationId,conversationType:e.conversationType,type:e.messageType,sendStatus:"sending",ext:e.ext??{},timestamp:Date.now(),body:e.body})]:[],d={type:this.resolveActionMessageType(e),from:{name:this.context.userId},to:{name:a.name},contents:c,ext:Xd(e.ext??{})};"recall"!==e.kind&&"deliveryAck"!==e.kind||(d.ackMessageId=e.messageId),"sendMessageReadReceipts"===e.kind&&(d.ackMessageIds=e.messageIds,"groupChat"===e.conversationType&&(d.msgConfig={allowGroupAck:!0})),"clearConversationUnreadMessageCount"===e.kind&&(d.sendToPeer=e.sendToPeer??!1),"clearAllConversationUnreadMessageCount"===e.kind&&(d.sendToPeer=e.sendToPeer??!1,d.clearAllUnreadMessageCount=e.clearAllUnreadMessageCount??!0),"update"===e.kind&&(d.editMessageId=e.messageId,d.editScope=e.ext&&Object.keys(e.ext).length>0?o.values.BODY_AND_EXT:o.values.BODY);const u=Ih(s,d);if("clearAllConversationUnreadMessageCount"===e.kind){const e=s.decode(u),r=s.fields.clearAllUnreadMessageCount;js("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:Qd({appKey:this.context.appKey,name:a.name,domain:"singleChat"===e.conversationType?this.context.domain:"conference.easemob.com",clientResource:a.clientResource}),ns:Qt,payload:u,routetype:er,directedUsers:[],ext:[]},h=Ih(n,{meta:l}),p={version:0,encryptType:[sr],command:_t,payload:h,traceId:tu()};return Ih(i,p)}encodeChatRoomOperation(e,t){const r=Kd(),s=r.lookupType("easemob.pb.MUCBody"),n=r.lookupType("easemob.pb.CommSyncUL"),i=r.lookupType("easemob.pb.MSync"),o={mucId:Qd({appKey:this.context.appKey,name:e.chatRoomId,domain:"conference.easemob.com"}),operation:"join"===e.operation?2:3,from:{name:this.context.userId},isChatroom:!0};"join"===e.operation&&(void 0!==e.ext&&(o.ext=e.ext),void 0!==e.leaveOtherRooms&&(o.leaveOtherRooms=e.leaveOtherRooms));const a=Ih(s,o),c={id:t,from:Qd({appKey:this.context.appKey,name:this.context.userId,domain:this.context.domain,clientResource:this.context.clientResource}),to:{domain:this.context.domain},ns:Zt,payload:a},d=Ih(n,{meta:c}),u={version:0,encryptType:[sr],command:_t,payload:d,traceId:tu()};return Ih(i,u)}decodeServerMessageMeta(e){const t=Kd(),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?zs(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 Zd(e)}decodeChatRoomJoinInfo(e){const t=Kd().lookupType("easemob.pb.MUCBody");for(const s of e){if(!vh(s)||s.ns!==Zt)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(!vh(e)||!vh(e.status))continue;const r=e.status.chatroomInfo;if("string"!=typeof r||""===r)continue;const s=JSON.parse(r);if(!vh(s))continue;const i=s[this.context.userId];if(!vh(i))continue;const o=i;return{..."boolean"==typeof o.is_all_mute?{isAllMembersMuted:o.is_all_mute}:{},..."number"==typeof o.create_timestamp?{createTimestamp:o.create_timestamp}:{},..."boolean"==typeof o.is_in_white_list?{isInAllowlist:o.is_in_white_list}:{},..."number"==typeof o.member_count?{memberCount:o.member_count}:{},muteExpireTimestamp:"number"==typeof o.mute_duration&&0!==o.mute_duration?o.mute_duration:-1}}catch(r){Ks("Failed to decode chat room info from ACK",r)}}}decodeAck(e){const t=Yd(e.metaId);if(!t||"0"===t)return;const r=e.status??{},s="number"==typeof r.errorCode?r.errorCode:ar,n="string"==typeof r.reason?r.reason:void 0;return{protocolId:t,serverId:Yd(e.serverId),ok:s===or,statusCode:s,reason:n}}decodeMessage(e,t){const r="number"==typeof t.type?t.type:Rt;if(!this.isPublicMessageType(r))return null;const s=(Array.isArray(t.contents)?t.contents:[])[0];if(!s)return null;const n=this.resolveConversationType(r),{senderUserId:i,senderId:o,receiverId:a}=this.resolveIncomingMessageParties(e,t,n),c=o===this.context.userId?"SEND":"RECEIVE",d="singleChat"===n?"SEND"===c?a:o:a,u=this.decodeContent(s);if(!u)return null;const l=eu(t.ext),h=eu(e.ext),p=Number(Yd(e.timestamp))||Date.now(),m=Yd(e.id),f=this.resolveBroadcast(h),g=this.resolvePriority(h),y=this.resolveMessageMetaPayload(t.meta,e.meta),v=this.resolveContentReplaced(y),I=this.resolveReactions(y),b=this.resolveModifiedInfo(y),_=this.resolveChatThreadMessageContext(y),T=this.resolveChatThreadOverview(y),C=this.resolveProfileVersionTime(t.userInfoUpdateTime),S=this.resolveProfileVersionTime(t.namecardUpdateTime),E={msgServerId:m,msgLocalId:"",from:o,to:a,sender:{userId:i},conversationId:d,conversationType:n,type:u.type,sendStatus:"sent",ext:l,timestamp:p,body:u.body,direct:c,isOnline:this.resolveMessageIsOnline(r,h)};Hu(E,{userInfoUpdateTime:C,namecardUpdateTime:S});const w=this.decodeStreamMeta(t.stream,s);w&&(E.type="text",E.body={content:w.fullText},E.stream=w),void 0!==f&&(E.isBroadcast=f),void 0!==g&&(E.priority=g),void 0!==v&&(E.isContentReplaced=v),I&&(E.reactions=I),b&&(E.modifiedInfo=b),_&&(E.isChatThread=!0,E.chatThread=_);const R=this.resolvePeerRead(y,n,c);void 0!==R&&(E.isPeerRead=R);const A=this.resolveGroupReadCount(y,n);void 0!==A&&(E.groupReadCount=A),T&&(E.chatThreadOverview=T);const N=t.msgConfig;return N?.allowGroupAck&&(E.needReadReceipt=!0),E}resolveMessageProfileVersionFields(e){const t=Wu(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 Il(Yd(e))}isPublicMessageType(e){return e===Rt||e===At||e===Nt}resolveMessageIsOnline(e,t){if(e===Nt)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(Yd(r.streamSeq));if(!Number.isFinite(s))return;const n="number"==typeof r.streamStatus?r.streamStatus:zt,i="number"==typeof r.streamError?r.streamError:0,o="number"==typeof r.streamFinishReason?r.streamFinishReason:void 0,a=this.resolveContentText(t),c=a;return{customType:"string"==typeof r.streamType?r.streamType:void 0,seq:s,status:this.mapStreamStatus(n,i),errorType:i,finishReason:o,deltaText:a,fullText:c}}mapStreamStatus(e,t){return t>0?nt.ERROR:e===Vt?nt.START:e===Kt?nt.START_COMPLETED:e===Ht?nt.COMPLETED:e===Wt?nt.FULL:nt.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:Dt,text:t.content}}if("cmd"===e.type){const t=e.body;return{type:qt,action:t.action}}if("custom"===e.type){const t=e.body;return{type:$t,customEvent:t.event,customExts:Xd(t.params??{})}}if("location"===e.type){const t=e.body;return{type:Ft,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:Pt,displayName:r.filename,remotePath:r.originalImageUrl??"",imageType:(t=s,t===hs?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:xt,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:Bt,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:Dt,subType:0,text:Xu(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:Gt,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:Dt,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===jt||t===Dt&&(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===Dt)return{type:"text",body:{content:"string"==typeof e.text?e.text:""}};if(t===qt)return{type:"cmd",body:{action:"string"==typeof e.action?e.action:""}};if(t===$t){const t=eu(e.customExts);return{type:"custom",body:{event:"string"==typeof e.customEvent?e.customEvent:"",params:t}}}if(t===Ft)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===Pt){const t=e.size??{},r="number"==typeof t.width?t.width:0,s="number"==typeof t.height?t.height:0,n=Ss(e.imageType)===hs,i="string"==typeof e.remotePath?e.remotePath:"",o=Ts(i,{deriveVariants:!this.useCustomAttachmentUpload}),a="string"==typeof e.thumbnailRemotePath&&e.thumbnailRemotePath.length>0?e.thumbnailRemotePath:void 0;return{type:"image",body:{localUrl:"",filename:"string"==typeof e.displayName?e.displayName:"image",filetype:"application/octet-stream",width:r,height:s,isGif:1===e.subType,isOriginalImage:n,originalImageUrl:o.originalImageUrl,bigImageUrl:o.bigImageUrl,secret:"string"==typeof e.secretKey?e.secretKey:void 0,fileLength:"number"==typeof e.fileLength?e.fileLength:void 0,thumbnailUrl:a??o.thumbnailUrl}}}if(t===xt){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===Bt){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===Gt){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 At;case"chatRoom":return Nt;default:return Rt}}resolveActionConversationType(e,t,r){const s=this.resolveConversationTypeFromMeta(t);if(s)return s;const n=r?.msgConfig&&"object"==typeof r.msgConfig?r.msgConfig:null;return!0===n?.allowGroupAck||"conference.easemob.com"===e?"groupChat":"singleChat"}resolveConversationTypeFromMeta(e){if("string"!=typeof e||0===e.length)return null;try{const t=JSON.parse(e),r=t.edit_msg&&"object"==typeof t.edit_msg?t.edit_msg:void 0,s=("string"==typeof t.chat_type?t.chat_type:void 0)??("string"==typeof t.chatType?t.chatType:void 0)??("string"==typeof t.type?t.type:void 0)??("string"==typeof r?.chat_type?r.chat_type:void 0);if("chat:user"===s||"singleChat"===s)return"singleChat";if("chat:group"===s||"groupChat"===s)return"groupChat";if("chat:room"===s||"chatRoom"===s)return"chatRoom"}catch{}return null}resolveActionConversationId(e,t,r){return"singleChat"===r?e===this.context.userId?t:e:t}resolveOutboundMessageTarget(e,t){if("singleChat"!==t)return{name:e};const r=`${this.context.userId}/`;if(!e.startsWith(r))return{name:e};const s=e.slice(r.length);return s?{name:this.context.userId,clientResource:s}:{name:e}}resolveIncomingMessageParties(e,t,r){const s=this.readJid(e.from),n=this.readJid(e.to),i=this.readJid(t.from),o=this.readJid(t.to),a=i.name??s.name??"",c=o.name??n.name??"";if(!("singleChat"===r&&a===this.context.userId&&c===this.context.userId))return{senderUserId:a,senderId:a,receiverId:c};return{senderUserId:a,senderId:s.clientResource&&s.clientResource!==this.context.clientResource?`${a}/${s.clientResource}`:a,receiverId:n.clientResource?`${c}/${n.clientResource}`:c}}resolveActionMessageType(e){switch(e.kind){case"clearConversationUnreadMessageCount":case"clearAllConversationUnreadMessageCount":return Lt;case"sendMessageReadReceipts":return Ot;case"deliveryAck":return Mt;case"recall":return Ut;case"update":return kt;default:return Rt}}resolveConversationType(e){return e===At?"groupChat":e===Nt?"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?Xd({chatroom_msg_tag:this.mapPriorityToTag(e.priority)}):[]}resolveRouteType(e){return this.resolveDirectedUsers(e).length>0?rr:this.resolveDeliverOnlineOnly(e)?tr:er}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(!vh(r))return;const s="string"==typeof r.operator?r.operator:"",n=this.toFiniteNumber(r.count),i=this.toFiniteNumber(r.edit_time);return s&&void 0!==n&&void 0!==i?{operatorId:s,operationCount:n,operationTime:i}:void 0}resolveChatThreadMessageContext(e){const t=this.parseMetaPayload(e),r=t?.thread;if(!vh(r)||0===Object.keys(r).length)return;const s=this.readString(r.msg_parent_id??r.messageId),n=this.readString(r.muc_parent_id??r.parentId);if(!s||!n)return;const i=this.readString(r.thread_name??r.chatThreadName);return{messageId:s,parentId:n,...i?{chatThreadName:i}:{}}}resolveChatThreadOverview(e){const t=this.parseMetaPayload(e),r=t?.thread_overview??t?.threadOverview;if(!vh(r)||0===Object.keys(r).length)return;const s=this.readString(r.id??r.thread_id??r.chatThreadId),n=this.readString(r.muc_parent_id??r.parentId);if(!s||!n)return;const i=this.readString(r.name),o=this.resolveChatThreadOverviewLastMessage(r.last_message??r.lastMessage,s);return{chatThreadId:s,parentId:n,...i?{name:i}:{},...void 0!==o?{lastMessage:o}:{},...this.numberField("createdAt",r.create_timestamp??r.createdAt),...this.numberField("updatedAt",r.update_timestamp??r.updatedAt),...this.numberField("messageCount",r.message_count??r.messageCount)}}resolveChatThreadOverviewLastMessage(e,t){if(!vh(e)||0===Object.keys(e).length)return null;const r=this.readString(e.msgId??e.msg_id??e.id);if(!r)return null;const s=this.toFiniteNumber(e.timestamp)??0,n=this.resolveThreadLastMessagePayload(e),i=this.readString(n?.from)??this.readString(e.from)??"",o=this.readString(n?.to)??this.readString(e.to)??t,a=Array.isArray(n?.bodies)?n.bodies:[],c=vh(a[0])?a[0]:null,d=this.readString(c?.type)??this.readString(e.type),u=this.mapThreadMessageType(d),l=this.normalizeThreadLastMessageBody(u,c,e),h=t,p=i===this.context.userId?"SEND":"RECEIVE";return{msgServerId:r,msgLocalId:"",from:i,to:o,sender:{userId:i},conversationId:h,conversationType:"groupChat",type:u,sendStatus:"sent",ext:vh(n?.ext)?n.ext:{},timestamp:s,body:l,direct:p}}resolveThreadLastMessagePayload(e){const t=e.payload;if(vh(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=Ts(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:vh(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(Hs(t));return vh(e)?e:null}catch{return null}}if(vh(e))return e;if("string"==typeof e)try{const t=JSON.parse(e);return vh(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(vh).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?[]:[ir]}configureCompression(e,t){if(!e||!e.includes(ir))return void this.disableCompression();this.compressor||(this.compressor=new yh);const r=this.resolveCompressionMode(t);this.compressor.mode=r,this.compressor.enableUplinkCompression=r===fh.UPLINK_ONLY||r===fh.BIDIRECTIONAL,this.compressor.enableDownlinkCompression=r===fh.DOWNLINK_ONLY||r===fh.BIDIRECTIONAL}resolveCompressionMode(e){return 0===e?fh.UPLINK_ONLY:1===e?fh.DOWNLINK_ONLY:2===e?fh.BIDIRECTIONAL:fh.NONE}disableCompression(){this.compressor&&(this.compressor.mode=fh.NONE,this.compressor.enableUplinkCompression=!1,this.compressor.enableDownlinkCompression=!1)}}const _h=1e3,Th="direct";class Ch{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 Sh{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 Eh={none:0,disconnected:0,ethernet:1,lan:1,wifi:2,"slow-2g":7,"2g":7,"3g":7,"4g":7,"5g":7,cellular:7},wh=()=>{const e=fn(),t=e.crypto?.randomUUID;return("function"==typeof t?t.call(e.crypto):void 0)??`${Date.now()}_${Math.random().toString(36).slice(2)}`};class Rh{constructor(e){this.currentState="disabled",this.networkType=-1,this.now=e.now??Date.now,this.randomId=e.randomId??wh;const t=new Sh({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 Ch({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:Eh[e.trim().toLowerCase()]??-1)(e)}applyDnsSwitch(e){if(this.session){if("true"===e)return this.currentState="enabled",void this.queue.enable();this.currentState="disabled",this.queue.clear()}else this.currentState="disabled"}startOperation(e){const t=this.session?.sessionId;if(!t||"disabled"===this.currentState)return this.createNoopOperation();const r=`opr_${this.randomId()}`,s=this.now();let n=!1,i=!1,o=`req_${this.randomId()}`,a=0,c="";const d=()=>!n&&!i&&this.session?.sessionId===t,u=(t,s,n,i,o)=>{d()&&(a=o.success?0:o.code,c=o.success?"":o.description??"",this.enqueue(9675,{uid:e.uid??this.session?.uid,operationId:r,requestid:s,operationName:e.operationName,operationType:e.operationType,requestName:t.requestName??e.operationName,subrequestid:String(n),requestMethod:t.method??"",requestUrl:t.url??"",requestElapse:Math.max(0,this.now()-i),code:o.code,codeDesc:o.description??"",isLastApi:0,isSuccess:o.success?1:0,accessChannel:this.session?.accessChannel??Th,msgId:e.msgId,messageType:e.messageType,resultCount:o.resultCount}))},l=(e,t,r,s)=>{const n=this.now();let i=!1;return{retry:()=>(s.next+=1,l(e,t,s.next,s)),finish:s=>{i||(i=!0,u(e,t,r,n,s))}}};return{startRequest:(e={})=>(o=`req_${this.randomId()}`,l(e,o,1,{next:1})),finish:t=>{d()&&(n=!0,this.enqueue(9675,{uid:e.uid??this.session?.uid,operationId:r,requestid:o,operationName:e.operationName,operationType:e.operationType,requestName:"",subrequestid:"0",requestMethod:"",requestUrl:"",requestElapse:Math.max(0,this.now()-s),code:t.success?0:t.code??a,codeDesc:t.success?"":t.description??c,isLastApi:1,isSuccess:t.success?1:0,accessChannel:this.session?.accessChannel??Th,msgId:e.msgId,messageType:e.messageType,resultCount:t.resultCount}))},discard:()=>{i=!0}}}reset(){this.currentState="disabled",this.session=void 0,this.queue.clear()}enqueue(e,t){const r=this.session;if(!r||"disabled"===this.currentState)return;const s={lts:this.now(),net:this.networkType,appkey:r.appKey,sdkServiceId:r.serviceId,sdkProduct:0,uikitVersion:r.uikitVersion??"",...t},n={eventId:e,body:Object.fromEntries(Object.entries(s).filter(([,e])=>void 0!==e))};this.queue.enqueue({appKey:r.appKey,wire:n})}createNoopOperation(){const e={retry:()=>e,finish:()=>{}};return{startRequest:()=>e,finish:()=>{},discard:()=>{}}}}let Ah;const Nh=e=>{Ah?.updateSession(e)},Oh=e=>{Ah?.applyDnsSwitch(e)},Mh=e=>{Ah?.updateNetworkType(e)},Uh=e=>{if("disabled"!==Ah?.state)return Ah?.startOperation(e)},Lh=()=>{Ah?.reset(),Ah=void 0},kh=e=>new ht("Connection attempt cancelled",{code:ot.CONNECTION_CANCELLED,details:{stage:e,cancelled:!0,retryable:!0}}),Dh=e=>e instanceof ht&&e.code===ot.CONNECTION_CANCELLED&&!0===e.details?.cancelled;class Ph{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.reconnectDelayReject=null,this.reconnectTask=null,this.pendingReconnectReason=null,this.reconnectInProgress=!1,this.reconnectPaused=!1,this.terminalDisconnectError=null,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.connectionAttemptGeneration=0,this.activeConnectionAttemptCancel=null,this.activeLoginDeadline=null,this.tokenLifecycle=null,this.tokenWillExpireTimerId=null,this.tokenExpiredTimerId=null,this.config={heartBeatWait:3e4,autoReconnectNumMax:10,connectTimeout:1e4,...e},this.eventHub=r,this.msyncCodec=new bh({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 Bd({maxAttempts:this.config.autoReconnectNumMax,initialDelay:1e3,maxDelay:6e4,backoffMultiplier:2}),this.heartbeatManager=new $d({interval:this.config.heartBeatWait,timeout:6e4}),this.connectionEventNormalizer=new Ws,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 ht("Token is expired",{code:ot.AUTH_TOKEN_EXPIRED,details:{stage:"token"}});return this.config.token=e,this.connection.token=e,this.msyncCodec.updateToken(e),this.setupTokenLifecycle(e,t,r),Vs("Connection token renewed",{userId:this.config.userId,expireAt:t}),{token:e,expireAt:t}}handleOnline(){if(Vs("Network online event received",this.getReconnectDiagnostic()),this.isOnline=!0,this.terminalDisconnectError)return void Vs("Network online recovery skipped",{guard:"terminal-disconnect",...this.getReconnectDiagnostic()});const e=this.offlineRecoverPending?C:T;this.offlineRecoverPending=!1,this.resumeReconnect(e)}handleOffline(){Vs("Network offline event received",this.getReconnectDiagnostic()),this.isOnline=!1,this.offlineRecoverPending=!0,this.reconnectPaused=!0,this.clearReconnectTimer(),this.cancelActiveConnectionAttempt(),this.stopHeartbeat(),this.closeWebSocket(N,!0),Vs("Network offline state applied",this.getReconnectDiagnostic())}async handleForeground(){if(this.terminalDisconnectError)return void Vs("Foreground recovery skipped",{guard:"terminal-disconnect",...this.getReconnectDiagnostic()});if(!this.isLoggedIn)return;if(!this.isOnline)return;if(this.reconnectInProgress)return void Vs("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(S,!0,!0),this.resumeReconnect(S)}}catch(t){if(Vs("Foreground heartbeat check failed",t),this.reconnectInProgress||this.websocket!==e)return;this.closeWebSocket(S,!0,!0),this.resumeReconnect(S)}}resumeReconnect(e){if(this.terminalDisconnectError)Vs("Reconnect recovery skipped",{guard:"terminal-disconnect",reason:e,...this.getReconnectDiagnostic()});else if(this.isLoggedIn)return this.reconnectTask||this.reconnectInProgress?(this.pendingReconnectReason=e,void Vs("Reconnect recovery queued",{guard:"reconnect-in-progress",reason:e,...this.getReconnectDiagnostic()})):void(this.connection.status===s&&this.websocket||(this.reconnectPaused=!1,this.resetReconnectState(),Vs("Reconnect recovery requested",{reason:e,...this.getReconnectDiagnostic()}),this.triggerReconnect(e)))}handleSendTimeout(e){this.isLoggedIn&&this.isOnline&&(this.reconnectPaused||e.reason===E&&Vs("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,terminalDisconnectCode:this.terminalDisconnectError?.code,offlineRecoverPending:this.offlineRecoverPending,reconnectAttempts:this.reconnectAttempts,hasWebSocket:null!==this.websocket,hasReconnectTimer:null!==this.reconnectTimerId,hasReconnectTask:null!==this.reconnectTask,hasActiveConnectionAttempt:null!==this.activeConnectionAttemptCancel}}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 ht))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(Hs(e))}catch{return!1}return!(!Array.isArray(t)||t.length<2)&&(3e3===t[0]&&"normal closed"===t[1])}clearReconnectTimer(){const e=this.reconnectDelayReject;this.reconnectDelayReject=null,this.reconnectTimerId&&(clearTimeout(this.reconnectTimerId),this.reconnectTimerId=null),e?.(kh("retry-delay"))}resolveLoginStageTimeout(e){return this.isLoginPhase&&this.activeLoginDeadline?this.activeLoginDeadline.clamp(e):e}isLoginDeadlineExpired(){return Boolean(this.isLoginPhase&&this.activeLoginDeadline&&this.activeLoginDeadline.remainingMs()<=0)}requireLoginTimeoutError(){const e=this.activeLoginDeadline;return e?(e.expire(),e.createTimeoutError()):new ht("Login timeout",{code:ot.CONNECTION_LOGIN_TIMEOUT,details:{stage:"login",retryable:!0}})}async waitForReconnectDelay(){const e=this.connectionRetry.getRetryDelay(),t=this.resolveLoginStageTimeout(e);if(t<=0)throw this.requireLoginTimeoutError();Vs("Reconnect retry scheduled",{delayMs:Math.round(t),...this.getReconnectDiagnostic()}),this.clearReconnectTimer(),await new Promise((e,r)=>{this.reconnectDelayReject=e=>{this.reconnectDelayReject=null,r(e)},this.reconnectTimerId=setTimeout(()=>{this.reconnectTimerId=null,this.reconnectDelayReject=null,e()},t)})}buildConnectionEventPayload(e,t){const r=this.connection.error instanceof ht?this.connection.error:void 0;return{state:e,reason:t,attempt:this.reconnectAttempts,maxAttempts:this.resolveEffectiveMaxAttempts(),isLoginPhase:this.isLoginPhase,isOnline:this.isOnline,errorCode:r?.code,errorMessage:r?.message,timestamp:Date.now()}}dispatchConnectionEvent(e,r){if(e===t&&!this.hasEverConnected)return;if(e===i&&!this.isLoggedIn)return;if(this.isLoginPhase&&(e===t||e===i))return;const s=this.buildConnectionEventPayload(e,r),n=this.connectionEventNormalizer.normalize(e,s);n&&this.eventHub.dispatch(n.eventName,n.payload)}updateStatus(e,t,r,n=!1){const i=this.connection.status!==e;(i||n)&&(i&&(this.connection.status=e,this.connection.lastConnectedAt=e===s?Date.now():void 0),r&&this.dispatchConnectionEvent(e,t),js("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 Vs("Provision auth token has invalid payload");const r=Number(t.expires_in);if(!Number.isFinite(r))return void Vs("Provision auth token has invalid expires_in");this.setupTokenLifecycle(this.connection.token??this.config.token,r)}catch(t){Vs("Failed to parse provision auth token expiration",t)}}emitTokenWillExpire(){this.tokenLifecycle&&!this.tokenLifecycle.willExpireEmitted&&(this.tokenLifecycle.willExpireEmitted=!0,Vs("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,Vs("Token expired"),this.eventHub.dispatch(l,void 0))}isTokenExpiredConnectionError(e){return e instanceof ht&&e.code===ot.AUTH_TOKEN_EXPIRED}handleTokenExpiredDisconnect(e){Vs("Connection closing because token expired",{source:e}),this.connection.error=new ht("Token expired",{code:ot.AUTH_TOKEN_EXPIRED,details:{stage:"token",source:e,retryable:!1}}),this.emitTokenExpired(),this.clearTokenTimers(),this.clearReconnectTimer(),this.cancelActiveConnectionAttempt(),this.resetProvisionHandlers(),this.stopHeartbeat(),this.reconnectPaused=!0,this.reconnectInProgress=!1,this.offlineRecoverPending=!1,this.isLoginPhase=!1,this.isLoggedIn=!1,this.closeWebSocket(O,!0,!0),this.updateStatus(t,O,!0)}startHeartbeat(e){this.heartbeatManager.start(e,()=>{this.triggerReconnect(S)},()=>{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(e){if(!this.reconnectInProgress)if(this.connection.status!==s&&this.connection.status!==r){this.isLoginPhase=!0,this.activeLoginDeadline=e??null,this.terminalDisconnectError=null,this.reconnectPaused=!1,this.resetReconnectState(),this.connectionEventNormalizer.reset();try{await this.connectWithRetry(b,!0),this.isLoggedIn=!0}catch(n){throw this.isLoggedIn=!1,n instanceof ht&&n.code===ot.CONNECTION_LOGIN_TIMEOUT&&"login"===n.details?.stage&&(this.cancelActiveConnectionAttempt(),this.closeWebSocket(R,!1,!1),this.updateStatus(t,R,!1)),n}finally{this.isLoginPhase=!1,this.activeLoginDeadline=null}}else Vs("Connection already established or connecting")}async connectWithRetry(e,o){if(Vs("Reconnect flow requested",{reason:e,throwOnFailure:o,...this.getReconnectDiagnostic()}),this.reconnectInProgress)return void Vs("Reconnect flow skipped",{guard:"reconnect-in-progress",reason:e,...this.getReconnectDiagnostic()});if(this.connection.status===s&&this.websocket)return;if(this.reconnectPaused)return void Vs("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,d=null;const u=this.resolveEffectiveMaxAttempts();this.connectionRetry.reset(),Vs("Reconnect flow started",{reason:e,throwOnFailure:o,maxAttempts:u,...this.getReconnectDiagnostic()});try{for(;this.connectionRetry.getAttemptCount()<u;){if(this.isLoginDeadlineExpired())throw this.requireLoginTimeoutError();if(!this.isLoginPhase&&(this.reconnectPaused||!this.isOnline||!this.isLoggedIn)){d=kh("ws");break}this.connectionRetry.recordAttempt(),this.reconnectAttempts=this.connectionRetry.getAttemptCount(),this.connection.reconnectAttempts=this.reconnectAttempts;const t=this.isLoginPhase?r:n;Vs("Reconnect attempt started",{attempt:this.reconnectAttempts,maxAttempts:u,reason:e,nextStatus:t,...this.getReconnectDiagnostic()}),this.updateStatus(t,e,!0,!0),this.prepareForConnectAttempt();try{return await this.connectOnce(),void this.handleConnectSuccess(e)}catch(l){if(a=l,this.isLoginDeadlineExpired())throw this.requireLoginTimeoutError();if(Dh(l)){d=l,Vs("Reconnect attempt cancelled",{attempt:this.reconnectAttempts,reason:e,...this.getReconnectDiagnostic()});break}if(Vs("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()>=u)break;if(this.reconnectPaused||!this.isOnline&&!this.isLoginPhase){Vs("Reconnect retry loop interrupted",{reason:e,attempt:this.reconnectAttempts,maxAttempts:u,...this.getReconnectDiagnostic()});break}try{await this.waitForReconnectDelay()}catch(l){if(!Dh(l))throw l;d=l,Vs("Reconnect retry delay cancelled",{reason:e,attempt:this.reconnectAttempts,...this.getReconnectDiagnostic()});break}}if(d){if(o)throw d;return}if(c){if(this.connection.error=c,o)throw this.updateStatus(t,R,!1),c;return this.reconnectPaused=!0,void this.updateStatus(t,R,!0)}if(o)throw this.updateStatus(t,R,!1),a??new ht("Connection failed",{code:ot.CONNECTION_WEBSOCKET_ERROR,details:{stage:"ws"}});this.reconnectPaused=!0,Vs("Reconnect attempts exhausted",{reason:e,attempt:this.reconnectAttempts,maxAttempts:u,lastError:a,...this.getReconnectDiagnostic()}),this.updateStatus(i,A,!0)}finally{this.reconnectInProgress=!1,Vs("Reconnect flow finished",{reason:e,...this.getReconnectDiagnostic()})}}async connectOnce(){await this.createWebSocketConnection()}prepareForConnectAttempt(){this.cancelActiveConnectionAttempt(),this.clearReconnectTimer(),this.stopHeartbeat(),this.resetProvisionHandlers(),this.resetSyncState(),this.websocket&&this.closeWebSocket(_,!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),Vs("Connection established successfully")}sendPostProvisionInitialSync(){this.sendMsyncPayload(this.msyncCodec.encodeHeartbeat()),this.sendMsyncPayload(this.msyncCodec.encodeStatisticRebuild())}triggerReconnect(e){if(Vs("Reconnect trigger received",{reason:e,...this.getReconnectDiagnostic()}),this.terminalDisconnectError)return Vs("Reconnect trigger skipped",{guard:"terminal-disconnect",reason:e,...this.getReconnectDiagnostic()}),Promise.resolve();if(!this.isLoggedIn)return Vs("Reconnect trigger skipped",{guard:"not-logged-in",reason:e,...this.getReconnectDiagnostic()}),Promise.resolve();if(this.reconnectTask)return Vs("Reconnect task reused",{reason:e,...this.getReconnectDiagnostic()}),this.reconnectTask;if(this.reconnectInProgress)return Vs("Reconnect trigger skipped",{guard:"reconnect-in-progress-without-task",reason:e,...this.getReconnectDiagnostic()}),Promise.resolve();if(this.reconnectPaused)return Vs("Reconnect trigger skipped",{guard:"reconnect-paused",reason:e,...this.getReconnectDiagnostic()}),Promise.resolve();this.connection.status===s&&this.websocket&&this.closeWebSocket(e,!0,!0);const t=this.connectWithRetry(e,!1).finally(()=>(this.reconnectTask===t&&(this.reconnectTask=null),this.startPendingReconnectIfNeeded()??void 0));return this.reconnectTask=t,t}recoverConnectionForSend(){return this.connection.status===s&&this.websocket?Promise.resolve():this.terminalDisconnectError||!this.isLoggedIn||!this.isOnline||this.isLoginPhase||0===this.config.autoReconnectNumMax?(Vs("Send connection recovery skipped",{guard:"connection-not-recoverable",...this.getReconnectDiagnostic()}),Promise.resolve()):this.reconnectTask?(Vs("Send connection recovery reused",this.getReconnectDiagnostic()),this.reconnectTask):(this.reconnectPaused=!1,this.resetReconnectState(),Vs("Send connection recovery requested",this.getReconnectDiagnostic()),this.triggerReconnect(_))}startPendingReconnectIfNeeded(){const e=this.pendingReconnectReason;return this.pendingReconnectReason=null,!e||null!==this.terminalDisconnectError||!this.isLoggedIn||!this.isOnline||this.connection.status===s&&this.websocket?null:(this.reconnectPaused=!1,this.resetReconnectState(),Vs("Queued reconnect recovery started",{reason:e,...this.getReconnectDiagnostic()}),this.triggerReconnect(e))}handleDisconnection(e){Vs("Connection disconnection handled",{reason:e,...this.getReconnectDiagnostic()}),this.stopHeartbeat(),this.updateStatus(t,e,!0),e!==O&&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(){const e=this.resolveLoginStageTimeout(this.config.connectTimeout);return e<=0?Promise.reject(this.requireLoginTimeoutError()):new Promise((t,r)=>{const s=++this.connectionAttemptGeneration,n=this.pickNextServerUrl();js("WebSocket connecting",{url:n}),this.clearSocketListeners();let i=!1,o=!1,a=null;const c=()=>{this.connectionAttemptGeneration===s&&(this.activeConnectionAttemptCancel=null)},d=e=>{i||(i=!0,a&&(clearTimeout(a),a=null),c(),r(e))};this.activeConnectionAttemptCancel=()=>{const e=kh(o?"provision":"ws");this.rejectPendingProvision(e),d(e)},a=setTimeout(()=>{Vs("WebSocket connection attempt timed out",{url:n,connectTimeout:e,...this.getReconnectDiagnostic()}),d(this.isLoginDeadlineExpired()?this.requireLoginTimeoutError():new ht("Connection timeout",{code:ot.CONNECTION_TIMEOUT,details:{stage:"ws"}}))},e),this.socketAdapter.connect({url:n,timeoutMs:e}).then(e=>{if(i||s!==this.connectionAttemptGeneration||this.reconnectPaused)return Vs("WebSocket connection result discarded",{url:n,cancelled:i||s!==this.connectionAttemptGeneration,reconnectPaused:this.reconnectPaused,...this.getReconnectDiagnostic()}),e.close(),void d(kh("ws"));a&&(clearTimeout(a),a=null),this.websocket=e,this.socketGeneration+=1,this.inboundMessageQueue=Promise.resolve(),this.attachSocketListeners(e,this.socketGeneration),o=!0,this.startProvision().then(()=>{if(this.resetProvisionHandlers(),i||s!==this.connectionAttemptGeneration||this.reconnectPaused)return Vs("Provision result discarded",{url:n,cancelled:i||s!==this.connectionAttemptGeneration,reconnectPaused:this.reconnectPaused,...this.getReconnectDiagnostic()}),this.closeWebSocket(R,!1,!1),void d(kh("provision"));i||(i=!0,a&&(clearTimeout(a),a=null),c(),t())}).catch(e=>{this.resetProvisionHandlers(),this.closeWebSocket(R,!1,!1),d(e instanceof Error?e:new Error(String(e)))})}).catch(e=>{if(i)return;const t=e instanceof ht?e:new ht("Failed to create WebSocket",{code:ot.CONNECTION_WEBSOCKET_ERROR,details:{stage:"ws",cause:e instanceof Error?e.message:String(e)}});this.handleConnectionError(t,R),d(t)})}).catch(e=>{if(e instanceof ht)throw e;const t=new ht("Failed to create WebSocket",{code:ot.CONNECTION_WEBSOCKET_ERROR,details:{stage:"ws",cause:e instanceof Error?e.message:String(e)}});throw this.handleConnectionError(t,R),t})}cancelActiveConnectionAttempt(){this.activeConnectionAttemptCancel?.()}handleWebSocketClose(e){this.suppressNextCloseEvent?this.suppressNextCloseEvent=!1:(Vs("WebSocket closed",{code:e.code,reason:e.reason}),this.provisionReject&&this.rejectProvisionAfterQueuedMessages(),this.websocket=null,this.clearSocketListeners(),this.stopHeartbeat(),this.handleDisconnection(w))}async rejectProvisionAfterQueuedMessages(){try{await this.inboundMessageQueue}catch{}this.provisionReject&&(this.provisionReject(new ht("Provision interrupted",{code:ot.CONNECTION_PROVISION_CLOSED,details:{stage:"provision"}})),this.resetProvisionHandlers())}handleConnectionError(e,t){Ks("Connection error:",e),this.connection.error=e,this.provisionTimeoutId&&(clearTimeout(this.provisionTimeoutId),this.provisionTimeoutId=null);const r=e instanceof ht?e:new ht(e.message,{code:ot.CONNECTION_WEBSOCKET_ERROR,details:{stage:"provision",retryable:!0}});if(this.rejectPendingProvision(r)||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(Vs("Terminal connection error received",{code:e.code,message:e.message,details:e.details}),this.connection.error=e,this.terminalDisconnectError=e,this.reconnectPaused=!0,this.reconnectInProgress=!1,this.offlineRecoverPending=!1,this.pendingReconnectReason=null,this.isLoggedIn=!1,this.cancelActiveConnectionAttempt(),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;js("WebSocket message received",{dataType:typeof e});const s=await this.msyncCodec.normalizeIncoming(e);if(t!==this.socketGeneration)return;if(js("handleWebSocketMessage data",{length:s.length}),!s.length)return;const n=this.msyncCodec.decompressIncoming(s);if(!n){const e=null!==this.provisionReject;return Ks("Failed to decompress mSync payload, closing connection",{stage:e?"provision":"connected"}),void(e?(this.rejectPendingProvision(new ht("Failed to decompress Provision payload",{code:ot.CONNECTION_WEBSOCKET_ERROR,details:{stage:"provision",cause:"decompression-failed",retryable:!0}})),this.closeWebSocket(R,!1,!1)):this.websocket?.close())}if(this.isServerNormalClosePayload(n))return void js("Ignore server normal close payload",{length:n.length});let i=null;try{i=this.msyncCodec.decodeMsync(n)}catch(r){const e=r instanceof Error?r:new Error("Failed to decode mSync payload");if(e instanceof RangeError)return void Vs("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 Vs("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(),js("handleWebSocketMessage decoded",{command:i.command}),i.command){case St:this.handleProvisionMessage(i.payload);break;case Et:this.handleLogoutMessage(i.payload);break;case Ct:this.handleNoticeMessage(i.payload);break;case Tt:this.handleUnreadMessage(i.payload);break;case _t:this.handleSyncMessage(i.payload)}}catch(r){const e=r instanceof Error?r:new Error("Failed to handle mSync payload");Ks("Failed to handle mSync payload",e),this.handleConnectionError(e,R)}}startProvision(){const e=this.resolveLoginStageTimeout(1e4);if(e<=0)return Promise.reject(this.requireLoginTimeoutError());this.provisionPromise=new Promise((e,t)=>{this.provisionResolve=e,this.provisionReject=t}),this.provisionTimeoutId&&clearTimeout(this.provisionTimeoutId),this.provisionTimeoutId=setTimeout(()=>{this.rejectPendingProvision(this.isLoginDeadlineExpired()?this.requireLoginTimeoutError():new ht("Provision timeout",{code:ot.CONNECTION_PROVISION_TIMEOUT,details:{stage:"provision",retryable:!0}}))},e);try{const e=this.msyncCodec.encodeProvision();js("startProvision provision",{length:e.length}),this.sendMsyncPayload(e)}catch{this.provisionReject?.(new ht("Provision send failed",{code:ot.CONNECTION_WEBSOCKET_ERROR,details:{stage:"provision"}})),this.resetProvisionHandlers()}return this.provisionPromise}handleProvisionMessage(e){const t=this.msyncCodec.decodeProvision(e);if(this.isLoginPhase&&this.activeLoginDeadline?.markProvisionReceived(),this.provisionTimeoutId&&(clearTimeout(this.provisionTimeoutId),this.provisionTimeoutId=null),t.ok)this.msyncCodec.updateResource(t.resource),this.setupTokenLifecycleFromProvision(t.authToken),this.provisionResolve?.();else{Vs("Provision rejected",{statusCode:t.statusCode,reason:t.reason});const e=Wr(t.statusCode,t.reason),r=e.code===ot.UNKNOWN?ot.CONNECTION_PROVISION_REJECTED:e.code;this.provisionReject?.(new ht("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&&Vs("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,R);if(!this.messageReceiver)return;const r=this.messageReceiver.handleSyncPayload(e);if(js("handleSyncMessage result",{result:r}),!r)return;(void 0!==r.queue||void 0!==r.nextKey||void 0!==r.isLast)&&this.handleSyncQueueState(r)}handleSyncQueueState(e){js("[QueueSync] handleSyncQueueState",{isLast:e.isLast,nextKey:e.nextKey,queueName:e.queue?this.getQueueName(e.queue):null,queueId:e.queue?this.getQueueId(e.queue):null,queuesLength:this.queues.length});const t=this.resolveSyncQueueState(e);if(!t)return e.queue&&e.isLast?(this.queues=this.queues.filter(e=>null!==this.getQueueId(e)),void this.sendNextQueue()):e.queue&&e.nextKey?void this.sendLastSession(e.queue,e.nextKey):void 0;const{queue:r,queueId:s}=t;if(this.offlineMessageSyncing&&this.offlineMessageQueueNames.has(s)){const t=this.offlineMessageQueueCounts.get(s)??0;this.offlineMessageQueueCounts.set(s,t+e.messages.length),this.offlineMessageTotalCount+=e.messages.length}const n=e.nextKey;if(e.isLast)return this.finishOfflineMessageQueue(s),this.removeQueueEntry(r),this.nextKey=null,this.currentQueueId=null,this.currentQueue=null,void this.sendNextQueue();if(n){if(n!==this.nextKey||!this.isSameQueue(r,this.currentQueue))return this.nextKey=n,this.currentQueueId=s,this.currentQueue=r,void this.sendLastSession(r,n);this.removeQueueEntry(r),this.sendNextQueue()}}resolveSyncQueueState(e){const t=e.queue&&"object"==typeof e.queue?e.queue:void 0,r=t?this.getQueueName(t):null,s=t?this.getQueueId(t):null,n=void 0!==t&&null!==s&&(0===this.queues.length||this.queues.some(e=>this.isSameQueue(e,t)));if(t&&s&&n)return{queue:t,queueId:s};const i=this.currentQueue&&this.queues.some(e=>this.isSameQueue(e,this.currentQueue))?this.currentQueue:void 0,o=this.currentQueueId?this.queues.find(e=>this.getQueueId(e)===this.currentQueueId):void 0,a=i??o??this.queues[0],c=a?this.getQueueName(a):null,d=a?this.getQueueId(a):null;return a&&d?(Vs("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);Vs("Logout message received",t)}resolveStatisticDisconnectError(e){for(const t of e)switch(t.operation){case 1:return new ht("User has been removed",{code:ot.USER_REMOVED,details:{stage:"statistics",operation:t.operation,retryable:!1}});case 2:return new ht("The user is already logged on another device",{code:ot.USER_LOGIN_ANOTHER_DEVICE,details:{stage:"statistics",operation:t.operation,retryable:!1,...t.reason?{loginInfoCustomExt:t.reason}:{}}});case 3:return new ht("The user was kicked by changing password",{code:ot.USER_KICKED_BY_CHANGE_PASSWORD,details:{stage:"statistics",operation:t.operation,retryable:!1}});case 4:return new ht("The user was kicked by other device",{code:ot.USER_KICKED_BY_OTHER_DEVICE,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.cancelActiveConnectionAttempt(),this.clearTokenTimers(),this.tokenLifecycle=null,this.resetProvisionHandlers(),this.stopHeartbeat(),this.reconnectPaused=!0,this.reconnectInProgress=!1,this.isLoginPhase=!1,this.isLoggedIn=!1,this.terminalDisconnectError=null,this.offlineRecoverPending=!1,this.closeWebSocket(w,!0,!0),this.updateStatus(t,w,!0),this.resetSyncState(),this.reconnectAttempts=0,this.connection.reconnectAttempts=0,this.connection.error=void 0,this.hasEverConnected=!1,this.connectionEventNormalizer.reset(),Vs("Connection disconnected"),Promise.resolve()}destroy(){this.disconnect(),this.eventHub.removeEventHandler(this.internalHandlerId)}resolveSocketAdapter(e){return xd(e.socketAdapter)}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;Vs("WebSocket error",{stage:"ws"});const t=new ht("WebSocket connection error",{code:ot.CONNECTION_WEBSOCKET_ERROR,details:{stage:"ws"}});this.handleConnectionError(t,R)}),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===ln)try{const t=this.msyncCodec.prepareOutgoing(e);js("WebSocket send payload",{length:t.length}),Promise.resolve(this.websocket.send(t)).catch(e=>{Ks("Failed to send mSync payload",e),this.websocket?.close()})}catch(t){Ks("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);js("sendBackqueue payload",{length:t.length}),this.sendMsyncPayload(t)}sendLastSession(e,t){js("sendLastSession queue",{queueName:this.getQueueName(e),nextKey:t});const r=this.msyncCodec.encodeLastSession(e,t);this.sendMsyncPayload(r)}sendNextQueue(){js("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=Uh({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 xh=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()}},Fh=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},Bh=()=>{const e=fn().crypto;return e&&"function"==typeof e.randomUUID?e.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`},Gh=new Uint8Array([99,109]),qh=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),$h=e=>Array.isArray(e)&&e.every(qh),jh=e=>"string"==typeof e?e:void 0,Vh=e=>"number"==typeof e&&Number.isFinite(e)?e:void 0,Kh=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},zh=(e,t)=>{const r=e[t],s=e[t+1],n=e[t+2],i=e[t+3];if("number"!=typeof r||"number"!=typeof s||"number"!=typeof n||"number"!=typeof i)throw new gt("Combine payload length header is invalid",{code:ot.COMBINE_PARSE_FAILED});return r<<24|s<<16|n<<8|i},Hh=e=>{let t=0;for(let r=2;r<e.length;r+=1)r%2==1&&(t^=e[r]??0);return t},Wh=(e,t)=>{const r=Kd().lookupType(e).decode(t);if(!qh(r))throw new Error(`${e} decoded result is invalid`);return r},Jh=e=>qh(e)&&"string"==typeof e.name?e.name:"",Qh=(e,t,r)=>{const s=($h(e.contents)?e.contents:[])[0];if(!s)throw new Error("MessageBody contents is empty");const n=(e=>{const t=Vh(e.type)??Dt,r=Boolean(jh(e.remotePath))||Boolean(jh(e.title))||Boolean(jh(e.summary))||(Vh(e.combineLevel)??0)>0,s=t===Dt&&0===e.subType&&r;if(t===jt||s){const t=Vh(e.combineLevel)??0;return{type:"combine",body:{title:jh(e.title)??"",summary:jh(e.summary)??"",filename:jh(e.displayName)??"combine",filetype:"application/octet-stream",url:jh(e.remotePath),secret:jh(e.secretKey),fileLength:Vh(e.fileLength),combineLevel:t},combineLevel:t}}if(t===Dt)return{type:"text",body:{content:jh(e.text)??""}};if(t===qt)return{type:"cmd",body:{action:jh(e.action)??""}};if(t===$t){const t=eu($h(e.customExts)?e.customExts:void 0);return{type:"custom",body:{event:jh(e.customEvent)??"",params:t}}}if(t===Ft)return{type:"location",body:{latitude:Vh(e.latitude)??0,longitude:Vh(e.longitude)??0,address:jh(e.address),buildingName:jh(e.buildingName)}};if(t===Pt){const t=qh(e.size)?e.size:{},r=jh(e.remotePath)??"",s=Ts(r),n=jh(e.thumbnailRemotePath),i=Ss(e.imageType)===hs;return{type:"image",body:{localUrl:"",filename:jh(e.displayName)??"image",filetype:"application/octet-stream",width:Vh(t.width)??0,height:Vh(t.height)??0,isGif:1===e.subType,isOriginalImage:i,originalImageUrl:s.originalImageUrl,bigImageUrl:s.bigImageUrl,secret:jh(e.secretKey),fileLength:Vh(e.fileLength),thumbnailUrl:n??s.thumbnailUrl}}}if(t===xt){const t=qh(e.size)?e.size:{};return{type:"video",body:{url:jh(e.remotePath)??"",filename:jh(e.displayName)??"video",filetype:"application/octet-stream",duration:Vh(e.duration)??0,width:Vh(t.width),height:Vh(t.height),secret:jh(e.secretKey),fileLength:Vh(e.fileLength),thumbnailUrl:jh(e.thumbnailRemotePath)}}}if(t===Bt)return{type:"voice",body:{url:jh(e.remotePath)??"",filename:jh(e.displayName)??"voice",filetype:"application/octet-stream",duration:Vh(e.duration)??0,secret:jh(e.secretKey),fileLength:Vh(e.fileLength)}};if(t===Gt)return{type:"file",body:{url:jh(e.remotePath)??"",filename:jh(e.displayName)??"file",filetype:"application/octet-stream",secret:jh(e.secretKey),fileLength:Vh(e.fileLength)}};return null})(s);if(!n)throw new Error("MessageBody content type is unsupported");const i=Jh(e.from)||Jh(r?.from)||`unknown-${t}`,o=Jh(e.to)||Jh(r?.to)||`unknown-${t}`,a=(c=e.type)===At?"groupChat":c===Nt?"chatRoom":"singleChat";var c;const d=o||i,u=Number(Yd(r?.timestamp))||Date.now(),l=eu($h(e.ext)?e.ext:void 0),h={msgServerId:Yd(r?.id),msgLocalId:"",type:n.type,sender:{userId:i},conversationId:d,conversationType:a,timestamp:u,body:n.body,ext:l};return"number"==typeof n.combineLevel&&(h.body.combineLevel=n.combineLevel),h},Zh=(e,t)=>{const r=[];try{const n=Wh("easemob.pb.Meta",e),i=(s=n.payload)instanceof Uint8Array?s:s instanceof ArrayBuffer?new Uint8Array(s):ArrayBuffer.isView(s)?new Uint8Array(s.buffer,s.byteOffset,s.byteLength):void 0;if(i&&i.length>0){const e=Wh("easemob.pb.MessageBody",i);return Qh(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=Wh("easemob.pb.MessageBody",e);return Qh(r,t)}catch(n){r.push(n instanceof Error?n.message:String(n))}try{const r=Wh("easemob.pb.MessageBody.Content",e);return Qh({type:Rt,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("; "))},Yh=(e,t)=>{const r=Hs(e);try{const e=JSON.parse(r);if(!qh(e))throw new gt("Combine payload item is invalid",{code:ot.COMBINE_PARSE_FAILED,details:{index:t}});return e}catch(s){if(s instanceof gt)throw s;try{return Zh(e,t)}catch(n){throw new gt("Combine payload item parse failed",{code:ot.COMBINE_PARSE_FAILED,details:{index:t,cause:s instanceof Error?s.message:String(s),protobufCause:n instanceof Error?n.message:String(n)}})}}},Xh=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),ep=(e,t,r)=>{throw new mt(e,{code:r,details:{fields:[{path:t,message:e,rule:"invalid_format"}]}})},tp=e=>{if("combine"!==e.type)return 0;const t=e.combineLevel;return"number"==typeof t?t:Xh(e.body)&&"number"==typeof e.body.combineLevel?e.body.combineLevel:0},rp=(e,t)=>{if(e.sender.userId||ep(`messageList[${t}] sender.userId is required`,`messageList[${t}].sender.userId`,ot.COMBINE_INVALID_INPUT),e.conversationId&&["singleChat","groupChat","chatRoom"].includes(e.conversationType)||ep(`messageList[${t}] conversation is invalid`,`messageList[${t}].conversationId`,ot.COMBINE_INVALID_INPUT),(!Number.isInteger(e.timestamp)||e.timestamp<=0)&&ep(`messageList[${t}] timestamp must be positive integer`,`messageList[${t}].timestamp`,ot.COMBINE_INVALID_INPUT),Xh(e.body)||ep(`messageList[${t}] body must be object`,`messageList[${t}].body`,ot.COMBINE_INVALID_INPUT),"combine"===e.type){const r=tp(e);(!Number.isInteger(r)||r<0)&&ep(`messageList[${t}] combineLevel is invalid`,`messageList[${t}].combineLevel`,ot.COMBINE_INVALID_INPUT),r>10&&ep(`messageList[${t}] combineLevel exceeds limit`,`messageList[${t}].combineLevel`,ot.COMBINE_LEVEL_EXCEEDED)}},sp=(e,t=300)=>{(!Number.isInteger(e)||e<=0)&&ep("messageList must not be empty","messageList",ot.COMBINE_INVALID_INPUT),(!Number.isInteger(t)||t<=0||t>300)&&ep("max items is invalid","maxItems",ot.COMBINE_INVALID_INPUT),e>t&&ep(`messageList max length is ${t}`,"messageList",ot.COMBINE_ITEM_LIMIT_EXCEEDED)},np=e=>{sp(e.length);for(let t=0;t<e.length;t+=1){const r=e[t];void 0!==r?rp(r,t):ep(`messageList[${t}] is required`,`messageList[${t}]`,ot.COMBINE_INVALID_INPUT)}},ip=e=>{let t=0;for(const r of e){if("combine"!==r.type)continue;const e=tp(r);e>t&&(t=e)}return t+1},op=e=>{(!Number.isInteger(e)||e<=0)&&ep("combineLevel must be positive integer","combineLevel",ot.COMBINE_INVALID_INPUT),e>10&&ep("combineLevel must be <= 10","combineLevel",ot.COMBINE_LEVEL_EXCEEDED)},ap=e=>"groupChat"===e?1:"chatRoom"===e?2:0;class cp{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(it(e))throw new ft("Stream message send is not supported",{code:ot.STREAM_SEND_NOT_SUPPORTED,details:{msgLocalId:e.msgLocalId,retryable:!1}});if(!this.websocket||this.websocket.readyState!==ln){const t=this.msyncCodec.toProtocolId(e.msgLocalId);throw new ft("WebSocket is not connected",{code:ot.MESSAGE_NOT_CONNECTED,details:{msgLocalId:e.msgLocalId,protocolId:t,retryable:!0}})}let s={...e,sendStatus:"sending"};Ju(e,s),js("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"};Ju(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 Ju(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&&js("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&&js("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:ap(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:ap(e.conversationType)});return new Promise((r,s)=>{const n=this.msyncCodec.toProtocolId(e.msgLocalId),i=setTimeout(()=>{this.pendingMessages.delete(n),this.finishPendingDataReport(t,{code:ot.MESSAGE_ACK_TIMEOUT,success:!1,description:"Message ACK timeout"}),s(new ft("Message ACK timeout",{code:ot.MESSAGE_ACK_TIMEOUT,details:{msgLocalId:e.msgLocalId,protocolId:n,retryable:!0}}))},this.ackTimeout);this.pendingMessages.set(n,{kind:"message",message:e,protocolId:n,timeoutId:i,resolve:e=>{clearTimeout(i),r(e)},reject:e=>{clearTimeout(i),s(e)},report:t});try{if(!this.websocket||this.websocket.readyState!==ln)throw new ft("WebSocket is not connected",{code:ot.MESSAGE_NOT_CONNECTED,details:{msgLocalId:e.msgLocalId,protocolId:n,retryable:!0}});const r=this.msyncCodec.encodeChatMessage(e,n),o=this.msyncCodec.prepareOutgoing(r);Promise.resolve(this.websocket.send(o)).catch(r=>{const o=r instanceof Error?r.message:String(r);this.pendingMessages.delete(n),clearTimeout(i),this.finishPendingDataReport(t,{code:-1,success:!1,description:o}),Vs("Message send socket failure",{msgLocalId:e.msgLocalId,protocolId:n,websocketReadyState:this.websocket?.readyState??null,cause:o}),s(new ft(`WebSocket send failed: ${o}`,{code:ot.MESSAGE_NOT_CONNECTED,details:{msgLocalId:e.msgLocalId,protocolId:n,retryable:!0,cause:o}}))}),js("Message sent",{msgLocalId:e.msgLocalId,protocolId:n})}catch(o){if(this.pendingMessages.delete(n),clearTimeout(i),this.finishPendingDataReport(t,{code:o instanceof ft?o.code:ot.MESSAGE_ENCODE_FAILED,success:!1,description:o instanceof Error?o.message:String(o)}),o instanceof ft)throw o;throw new ft("Message encode failed",{code:ot.MESSAGE_ENCODE_FAILED,details:{msgLocalId:e.msgLocalId,protocolId:n,retryable:!0}})}})}async sendProtocolPayload(e,t,r,s){return new Promise((n,i)=>{const o=setTimeout(()=>{this.pendingMessages.delete(e),this.finishPendingDataReport(s,{code:ot.MESSAGE_ACK_TIMEOUT,success:!1,description:"Message ACK timeout"}),i(new ft("Message ACK timeout",{code:ot.MESSAGE_ACK_TIMEOUT,details:{protocolId:e,retryable:!0}}))},this.ackTimeout);this.pendingMessages.set(e,{kind:"action",protocolId:e,timeoutId:o,createAckError:r,resolve:n,reject:i,report:s});try{if(!this.websocket||this.websocket.readyState!==ln)throw new ft("WebSocket is not connected",{code:ot.MESSAGE_NOT_CONNECTED,details:{protocolId:e,retryable:!0}});const r=this.msyncCodec.prepareOutgoing(t);Promise.resolve(this.websocket.send(r)).catch(t=>{const r=t instanceof Error?t.message:String(t);this.pendingMessages.delete(e),clearTimeout(o),this.finishPendingDataReport(s,{code:-1,success:!1,description:r}),i(new ft(`WebSocket action send failed: ${r}`,{code:ot.MESSAGE_NOT_CONNECTED,details:{protocolId:e,retryable:!0,cause:r}}))})}catch(a){if(this.pendingMessages.delete(e),clearTimeout(o),this.finishPendingDataReport(s,{code:a instanceof ft?a.code:ot.MESSAGE_ENCODE_FAILED,success:!1,description:a instanceof Error?a.message:String(a)}),a instanceof ft)throw a;i(new ft("Message encode failed",{code:ot.MESSAGE_ENCODE_FAILED,details:{protocolId:e,retryable:!1}}))}})}prepareCombineMessage(e){const t=e.body,r=t.messageList??[];np(r);const s=ip(r);op(s);const n=((e,t)=>{try{const r=e.map((e,r)=>{const s=t(e,r);if(0===s.length)throw new ft("Combine payload item encode failed",{code:ot.COMBINE_ENCODE_FAILED,details:{index:r}});return s}),s=Gh.length+r.reduce((e,t)=>e+4+t.length,0)+1,n=new Uint8Array(s);let i=0;n.set(Gh,i),i+=Gh.length;for(const e of r){const t=Kh(e.length);n.set(t,i),i+=t.length,n.set(e,i),i+=e.length}const o=Hh(n.subarray(0,n.length-1));return n[n.length-1]=o,n}catch(r){if(r instanceof ft)throw r;throw new ft("Combine payload encode failed",{code:ot.COMBINE_ENCODE_FAILED,details:{cause:r instanceof Error?r.message:String(r)}})}})(r,e=>this.msyncCodec.encodeCombineMessageMeta(e)),i=new ArrayBuffer(n.byteLength);new Uint8Array(i).set(n);const o=new File([i],t.filename||"combine",{type:t.filetype||"application/octet-stream"}),a=Fh(o);if(!a&&!this.attachmentUploader)throw new ft("Combine payload local url generation failed",{code:ot.COMBINE_ENCODE_FAILED});xh.set(e.msgLocalId,o);const c={...e,body:{...t,combineLevel:s,fileLength:n.byteLength,filename:t.filename||"combine",filetype:t.filetype||"application/octet-stream",url:a??t.url}};return Ju(e,c),el(e,c),c}handleAck(e,t,r,s){const n=this.pendingMessages.get(e);if(!n)return void js("Received ACK without a tracked pending message",{protocolId:e});if("action"===n.kind)return this.pendingMessages.delete(e),this.finishPendingDataReport(n.report,{code:200,success:!0}),void n.resolve({protocolId:e,serverId:t??"",statusCode:0,chatRoomInfo:s});const i={...n.message,...this.resolveReplacedMessage(n.message,r),sendStatus:"sent",msgServerId:t||r?.msgServerId||n.message.msgServerId};Ju(n.message,i),this.pendingMessages.delete(e),this.finishPendingDataReport(n.report,{code:200,success:!0}),"image"!==i.type&&"video"!==i.type&&"voice"!==i.type&&"file"!==i.type&&"combine"!==i.type||xh.delete(i.msgLocalId),js("Message ACK matched",{protocolId:e,msgLocalId:i.msgLocalId,msgServerId:i.msgServerId??null,type:i.type,conversationType:i.conversationType,conversationId:i.conversationId}),this.eventHub.dispatch(I,i),n.resolve(i)}resolveReplacedMessage(e,t){return t?{type:t.type,body:t.body,ext:t.ext,timestamp:t.timestamp||e.timestamp}:{}}handleSendError(e,t){const r=this.pendingMessages.get(e);if(!r)return;if("action"===r.kind)return this.pendingMessages.delete(e),this.finishPendingDataReport(r.report,{code:t instanceof ft?t.code:-1,success:!1,description:t.message}),void r.reject(t);const s={...r.message,sendStatus:"failed"};Ju(r.message,s),this.pendingMessages.delete(e),this.finishPendingDataReport(r.report,{code:t instanceof ft?t.code:-1,success:!1,description:t.message}),Vs("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 ft("Message sender destroyed",{code:ot.MESSAGE_SENDER_DESTROYED,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)>=_h){return void(("message"===e.category?this.messageReportSaturated:this.chatRoomReportSaturated)||(Vs("DataReport correlation limit reached",{category:e.category}),"message"===e.category?this.messageReportSaturated=!0:this.chatRoomReportSaturated=!0))}const t=Uh({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<_h&&(this.messageReportSaturated=!1)):(this.chatRoomReportCount=Math.max(0,this.chatRoomReportCount-1),this.chatRoomReportCount<_h&&(this.chatRoomReportSaturated=!1)))}}class dp{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!==nt.START&&t.stream.status!==nt.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 up{constructor(e,t){this.completedIds=new Set,this.eventHub=e,this.cache=t??new dp}handle(e){const t=this.resolveMessageId(e);if(!t)return void Vs("stream message id missing, skip dispatch");if(this.completedIds.has(t))return void js("stream message already completed, ignore",{msgId:t});if(e.stream.status===nt.FULL)return void this.handleFullChunk(t,e);const r=this.cache.get(t);if(r?.completed)return void js("stream session completed, ignore chunk",{msgId:t,seq:e.stream.seq});const{duplicate:s}=this.cache.addChunk(t,e);s?js("stream duplicate chunk ignored",{msgId:t,seq:e.stream.seq}):e.stream.errorType>0?this.dispatchServerError(t,e):this.dispatchSequentialChunks(t)}destroy(){this.cache.clearAll(),this.completedIds.clear()}dispatchSequentialChunks(e){const t=this.cache.getSequentialChunks(e);if(0!==t.length)for(const r of t){const t=this.cache.get(e);if(!t)return;const s=t.fullText,n=r.stream.deltaText,i=`${s}${n}`,o=r.stream.errorType>0?nt.ERROR:r.stream.status,a=this.buildDispatchMessage(r,{status:o,fullText:i,deltaText:n});if(this.eventHub.dispatch(U,a),this.cache.markDispatched(e,r,i),o===nt.START_COMPLETED||o===nt.COMPLETED||o===nt.ERROR){const t=o===nt.ERROR?"timeout_error":"normal";return this.cache.markCompleted(e,t,i),this.cache.clear(e),void this.markCompleted(e)}}else js("stream chunks pending for missing seq",{msgId:e})}handleFullChunk(e,t){const r=this.cache.get(e),s=r?.fullText??"",n=this.resolveFullText(t,s),i=this.resolveDeltaText(s,n,t.stream.deltaText),o=!r||-1===r.lastDispatchedSeq&&0===r.chunksBySeq.size,a=t.stream.errorType>0?nt.ERROR:o?nt.START_COMPLETED:nt.COMPLETED,c=this.buildDispatchMessage(t,{status:a,fullText:n,deltaText:i});this.eventHub.dispatch(U,c);const d=a===nt.ERROR?"timeout_error":"fallback_full";this.cache.markCompleted(e,d,n),this.cache.clear(e),this.markCompleted(e)}dispatchServerError(e,t){const r=this.cache.get(e),s=r?.fullText??"",n=this.resolveFullText(t,s),i=this.resolveDeltaText(s,n,t.stream.deltaText),o=this.buildDispatchMessage(t,{status:nt.ERROR,fullText:n,deltaText:i});this.eventHub.dispatch(U,o),this.cache.markCompleted(e,"timeout_error",n),this.cache.clear(e),this.markCompleted(e)}buildDispatchMessage(e,t){return{...e,body:{...e.body,content:t.fullText},stream:{...e.stream,status:t.status,fullText:t.fullText,deltaText:t.deltaText}}}resolveMessageId(e){return e.msgServerId&&e.msgServerId.length>0?e.msgServerId:e.msgLocalId}resolveFullText(e,t){const r=e.stream.fullText;if(r&&r.length>=t.length)return r;const s=e.body.content;return s&&s.length>=t.length?s:`${t}${e.stream.deltaText}`}resolveDeltaText(e,t,r){return t.startsWith(e)?t.slice(e.length):r}markCompleted(e){if(this.completedIds.add(e),this.completedIds.size<=2048)return;const t=this.completedIds.values().next().value;t&&this.completedIds.delete(t)}}class lp{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 hp=e=>"object"==typeof e&&null!==e&&!Array.isArray(e);class pp{constructor(e,t,r){this.eventHub=r,this.messageSender=t,this.msyncCodec=e,this.streamMessageHandler=new up(r),this.messageContexts=new Map,this.recentMessageIds=new lp(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{js("handleSyncPayload payload",{length:e.length});const t=this.msyncCodec.decodeSync(e);js("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&&(js("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){Ks("Failed to decode sync payload",t)}return null}handleAck(e,t){if(e.ok)return js("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));Vs("ACK rejected",{protocolId:e.protocolId,statusCode:e.statusCode,reason:e.reason,hasReplacedMessage:Boolean(t)});const r=((e,t)=>{const r=Wr(e,t),s=r.code===ot.UNKNOWN?ot.MESSAGE_SEND_FAILED:r.code;return{code:s,message:Jr[s]??(t?`Message send failed: ${t}`:"Message send failed for an unknown reason"),retryable:r.retryable}})(e.statusCode,e.reason),s=new ft(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(it(e))return void this.streamMessageHandler.handle(e);this.rememberMessageContext(e),this.sendDeliveryAckIfNeeded(e);const t=this.resolveMessageContextId(e);this.recentMessageIds.checkAndRecord(t)?js("Duplicate message ignored",{messageId:t}):(this.eventHub.dispatch(M,e),js("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=>{Vs("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(k,t)}handleUserInfoNotify(e){const t="subscribe_metadata_updated"===e.type||"contact_metadata_updated"===e.type||"user_metadata_updated"===e.type?e.type:"subscribe_metadata_updated"===e.eventName||"contact_metadata_updated"===e.eventName||"user_metadata_updated"===e.eventName?e.eventName:null;if(!t)return;const r=e.data;if(!r||"object"!=typeof r)return;const s=r,n="string"==typeof s.username?s.username:"string"==typeof s.userId?s.userId:"user_metadata_updated"===t?this.msyncCodec.getContext().userId:"",i=s.metadata&&"object"==typeof s.metadata&&!Array.isArray(s.metadata)?s.metadata:null,o="number"==typeof s.lastModified?s.lastModified:"string"==typeof s.lastModified?Number(s.lastModified):Number.NaN;if(!n||!i||!Number.isFinite(o))return;const a={notifyType:t,userId:n,metadata:i,lastModified:o};this.eventHub.dispatch(v,a)}handleContactNotify(e){if(js("[RosterSync] handleContactNotify",{eventName:e.eventName,type:e.type}),"string"!=typeof e.eventName)return;if(e.eventName!==z&&e.eventName!==H&&e.eventName!==W&&e.eventName!==J&&e.eventName!==Q)return;const t=e.data;if(!t||"object"!=typeof t)return;const r=t;"string"==typeof r.from&&r.from&&"string"==typeof r.to&&r.to&&"string"==typeof r.message&&this.eventHub.dispatch(e.eventName,r)}handlePresenceNotify(e){const t=e.data;if(!t||"object"!=typeof t)return;const r=t,s=Array.isArray(r.values)?r.values:[];if(0===s.length)return;const n=[];for(const i of s){if(!i||"object"!=typeof i)continue;const e=i,t=this.normalizePresenceStatus(e.status),r="string"==typeof e.uid?e.uid:"";r&&n.push({userId:r,statusDetails:t,ext:"string"==typeof e.ext?e.ext:"",lastTime:Number(e.last_time)||0,expire:Number(e.expiry)||0})}0!==n.length&&this.eventHub.dispatch(K,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(!hp(r)||"string"!=typeof r.messageId)continue;const e=this.resolveReactionConversationContext(r);e&&this.eventHub.dispatch(F,{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(!hp(e.data))return;const t=e.data;if("pin"!==t.op&&"pin_delete"!==t.op)return;const r=this.msyncCodec.getContext();if("string"==typeof t.res&&t.res===r.clientResource&&"string"==typeof t.from&&t.from===r.userId)return;const s="string"==typeof t.ext?t.ext:"",n="string"==typeof t.type?t.type:"",i="string"==typeof t.from?t.from:"",o="string"==typeof t.id?t.id:"";s&&i&&o&&this.eventHub.dispatch(B,{messageId:s,conversationId:"chat"===n?i:o,conversationType:"chat"===n?"singleChat":"groupChat",operation:"pin"===t.op?"pin":"unpin",operatorId:i,pinTime:"number"==typeof t.ts?t.ts:Number(t.ts)||void 0})}handleMultiDeviceNotify(e){if(!hp(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(!hp(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(!hp(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(!hp(e.data))return;const t=e.data;"string"==typeof t.messageId&&"string"==typeof t.conversationId&&this.eventHub.dispatch(D,{messageId:t.messageId,conversationId:t.conversationId,conversationType:"singleChat"})}handleMessageRecalledNotify(e){if(!hp(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(!hp(e.data))return;const t=e.data;if("string"!=typeof t.messageId||"string"!=typeof t.conversationId||"string"!=typeof t.conversationType||!hp(t.message)||"string"!=typeof t.message.type||!hp(t.message.body)||!hp(t.message.ext))return;const r={type:t.message.type,body:this.normalizeUpdatedMessageBody(t.message.type,t.message.body),ext:t.message.ext,...hp(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(x,{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)hp(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)!hp(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 mp=()=>{const e=globalThis;return"function"==typeof e.fetch?e.fetch:void 0},fp=()=>oc({fetchImpl:mp()})??{request:e=>Promise.reject(dn("Request capability is missing for current platform.",{code:sn,stage:Zs,retryable:!1,details:{capability:"request"}}))},gp=e=>e??fp(),yp=e=>e instanceof Error?e.message:String(e);class vp{constructor(e){this.requestAdapter=gp(e)}async downloadAndParse(e){const t=e.url.trim();if(!t)throw new mt("Combine message url is required",{code:ot.COMBINE_INVALID_INPUT,details:{fields:[{path:"url",message:"Combine message url is required",rule:"required"}]}});const r="number"==typeof e.maxItems?e.maxItems:300;sp(1,r);const s=bs(t,e.secret);try{const t=await this.requestAdapter.request({url:s,method:"GET",responseType:"arraybuffer",timeoutMs:e.timeoutMs??15e3,headers:{[ru]:tu()}});if(401===t.status||403===t.status)throw new pt(401===t.status?"Combine payload download unauthorized":"Combine payload download forbidden",{code:401===t.status?ot.AUTH_UNAUTHORIZED:ot.AUTH_FORBIDDEN,details:{url:s,httpStatus:t.status}});if(t.status>=400)throw new gt("Combine payload download failed",{code:ot.COMBINE_DOWNLOAD_FAILED,details:{status:t.status,url:s}});const n=(e=>{if(e.length<Gh.length+1)throw new gt("Combine payload is too short",{code:ot.COMBINE_PARSE_FAILED});const t=e.subarray(0,Gh.length);if(t[0]!==Gh[0]||t[1]!==Gh[1])throw new gt("Combine payload header is invalid",{code:ot.COMBINE_PARSE_FAILED});const r=e.subarray(0,e.length-1),s=Hh(r),n=e[e.length-1]??0;if(n!==s)throw new gt("Combine payload checksum failed",{code:ot.COMBINE_PARSE_FAILED,details:{expectedChecksum:s,actualChecksum:n}});const i=[];let o=Gh.length;const a=e.length-1;for(;o<a;){if(o+4>a)throw new gt("Combine payload length header is incomplete",{code:ot.COMBINE_PARSE_FAILED});const t=zh(e,o);if(o+=4,t<=0||o+t>a)throw new gt("Combine payload item length is invalid",{code:ot.COMBINE_PARSE_FAILED,details:{itemLength:t}});const r=e.subarray(o,o+t);o+=t;const s=Yh(r,i.length);i.push(s)}if(o!==a)throw new gt("Combine payload has unexpected trailing bytes",{code:ot.COMBINE_PARSE_FAILED,details:{offset:o,expected:a}});return i})((e=>{if(e instanceof Uint8Array)return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);if("string"==typeof e)return zs(e);throw new gt("Combine payload response type is invalid",{code:ot.COMBINE_DOWNLOAD_FAILED})})(t.data));return sp(n.length,r),np(n),n.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(n){if(n instanceof mt||n instanceof pt||n instanceof gt)throw n;throw new gt("Combine payload download or parse failed",{code:ot.COMBINE_DOWNLOAD_FAILED,details:{cause:yp(n),url:s}})}}}const Ip=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"}},bp=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 _p{constructor(e){this.requestAdapter=gp(e)}async download(e,t=15e3){if("image"!==e.type&&"video"!==e.type&&"voice"!==e.type&&"file"!==e.type)throw new mt("message does not contain downloadable attachment",{code:ot.ATTACHMENT_INVALID,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 mt("attachment url is required",{code:ot.ATTACHMENT_INVALID,details:{fields:[{path:"message.body.url",message:"is required",rule:"required"}]}});let n;try{n=await this.requestAdapter.request({url:bs(r,s),method:"GET",responseType:"arraybuffer",timeoutMs:t,headers:{[ru]:tu()}})}catch(i){if("object"==typeof i&&null!==i&&i.code===sn)throw new lt("request adapter is required for attachment download");throw i}if(401===n.status)throw new pt("attachment download unauthorized",{code:ot.AUTH_UNAUTHORIZED,details:{url:r,httpStatus:n.status}});if(403===n.status)throw new pt("attachment download forbidden",{code:ot.AUTH_FORBIDDEN,details:{url:r,httpStatus:n.status}});if(404===n.status){const e=("string"==typeof n.data?n.data:"").includes("expired");throw new ut(e?"attachment file is expired":"attachment not found",e?ot.ATTACHMENT_EXPIRED:ot.ATTACHMENT_NOT_FOUND)}if(429===n.status)throw new ut("attachment download rate limited",ot.SERVICE_LIMIT_EXCEEDED);if(n.status>=400)throw new ut("attachment download failed",ot.FILE_DOWNLOAD_FAILED,{details:{status:n.status,url:r}});return{filename:Ip(e),mimeType:bp(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 Tp=(e,t,r)=>({Authorization:`Bearer ${e}`,Accept:t,[ru]:tu(),...r??{}}),Cp=async e=>{const t=Tp(e.token,"application/json",e.headers),r=Date.now(),s="upload.multipart.init"===e.operation?"REST_INIT_UPLOAD_TASK_IN_PARTS":"upload.multipart.complete"===e.operation?"REST_COMPLETE_UPLOAD_PART":"REST_ABORT_UPLOAD_PART",n=e.dataReportOperation?.startRequest({requestName:s,method:e.method,url:e.url});let i=0;js("Upload request start",{operation:e.operation,method:e.method});try{const s=await e.requestAdapter.request({url:e.url,method:e.method,headers:t,responseType:"json",timeoutMs:Qr});i=s.status;const a=Date.now()-r;if(s.status<200||s.status>=300)throw Vs("Upload response error",{operation:e.operation,method:e.method,status:s.status,duration:a}),new bt("Upload request failed",{code:ot.UPLOAD_REQUEST_FAILED,details:{url:e.url,status:s.status}});js("Upload response success",{operation:e.operation,method:e.method,status:s.status,duration:a});const c="string"==typeof(o=s.data)?JSON.parse(o):o;return n?.finish({code:s.status,success:!0}),c}catch(a){if(n?.finish({code:0!==i?i:a instanceof bt?a.code:ot.UPLOAD_REQUEST_FAILED,success:!1,description:a instanceof Error?a.message:String(a)}),a instanceof bt)throw a;throw Vs("Upload request failed",{operation:e.operation,method:e.method}),new bt("Upload request failed",{code:ot.UPLOAD_REQUEST_FAILED,details:{url:e.url}})}var o},Sp=async e=>{const t=Date.now(),r=e.dataReportOperation?.startRequest({requestName:"REST_UPLOAD_PART",method:"PUT",url:e.url});js("Upload part start",{operation:"upload.multipart.part",partNumber:e.partNumber});try{const s=await e.uploadAdapter.upload({url:e.url,method:"PUT",headers:Tp(e.token,"*/*",{"restrict-access":"true"}),source:{sourceType:"web-file",file:e.part,name:`${e.fileName}.part-${e.partNumber}`,mimeType:e.fileType,size:e.part.size},fields:{part_number:e.partNumber},fileFieldName:"part_file",timeoutMs:Qr,onProgress:t=>e.onProgress?.(t.loaded)}),n=Date.now()-t;if(s.status<200||s.status>=300)throw new bt("Upload part failed",{code:ot.UPLOAD_REQUEST_FAILED,details:{url:e.url,partNumber:e.partNumber,status:s.status,response:s.body}});js("Upload part success",{operation:"upload.multipart.part",partNumber:e.partNumber,duration:n}),r?.finish({code:s.status,success:!0})}catch(s){const t=Pd(s),n=t.details&&"object"==typeof t.details?t.details:void 0;throw r?.finish({code:t.code,success:!1,description:t.message}),Vs("Upload part failed",{operation:"upload.multipart.part",partNumber:e.partNumber}),new bt(t.message,{code:t.code,details:{...n,url:e.url,partNumber:e.partNumber}})}},Ep=async e=>{if(e.fileSize<=as)throw new bt("Multipart not required",{code:ot.UPLOAD_REQUEST_FAILED,details:{reason:"file size below threshold"}});const{config:t,file:r,conversationId:s,conversationType:n,fileName:i,fileType:o,fileSize:a,messageType:c,imageType:d,md5:u,width:l,height:h}=e,p=(e=>gp(e))(t.requestAdapter),m=(e=>{if(e)return e;const t=vc();if(t)return t;throw new bt("Upload adapter is required for multipart upload",{code:ot.UPLOAD_REQUIRED_FIELD_MISSING,details:{capability:"upload"}})})(t.uploadAdapter),{orgName:f,appName:g}=fs(t.appKey),y=`${t.restBaseUrl}/${f}/${g}/sdk/chatfiles/part-upload`;let v;try{v=await Cp({url:y,method:"POST",token:t.token,operation:"upload.multipart.init",requestAdapter:p,dataReportOperation:e.dataReportOperation})}catch(O){throw new bt("Multipart init failed",{code:ot.UPLOAD_REQUEST_FAILED,details:{stage:"init",cause:O,url:y}})}const I=(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:cs,n="string"==typeof t?.uuid?t.uuid:"";if(!n)throw new bt("Multipart init failed",{code:ot.UPLOAD_REQUEST_FAILED,details:{response:e}});return{fileMaxSize:r,partMinSize:s,uuid:n}})(v);if(I.fileMaxSize&&a>I.fileMaxSize)throw new bt("File size exceeds limit",{code:ot.UPLOAD_SIZE_EXCEEDED,details:{fileSize:a,maxSize:I.fileMaxSize}});const b=I.partMinSize||cs,_=Math.ceil(a/b),T=Array.from({length:_},()=>0),C=`${t.restBaseUrl}/${f}/${g}/sdk/chatfiles/part-upload/${I.uuid}`,S=[],E=(t,r)=>{T[t]=r;const s=T.reduce((e,t)=>e+t,0),n=a?s/a*100:void 0;e.callbacks?.onFileUploadProgress?.({loaded:s,total:a,percent:n})};for(let M=0;M<_;M+=1){const s=M*b,n=Math.min(a,s+b),c=r.slice(s,n),d=String(M+1),u=Sp({url:C,token:t.token,partNumber:d,part:c,fileName:i,fileType:o,uploadAdapter:m,onProgress:e=>E(M,e),dataReportOperation:e.dataReportOperation}).finally(()=>{const e=S.indexOf(u);e>=0&&S.splice(e,1)});S.push(u),S.length>=4&&await Promise.race(S)}await Promise.all(S);const w=gs(n),R=Is(`${t.restBaseUrl}/${f}/${g}/sdk/chatfiles/part-upload/${I.uuid}`,{"restrict-access":"true","chat-type":w,"chat-target":s,"thumbnail-width":e.thumbnailWidth,"thumbnail-height":e.thumbnailHeight,md5:u??"",..."image"===c?{imageType:Cs(d),width:l,height:h}:{}}),A=await Cp({url:R,method:"POST",token:t.token,operation:"upload.multipart.complete",requestAdapter:p,dataReportOperation:e.dataReportOperation}),N=Es({response:A,restBaseUrl:t.restBaseUrl,orgName:f,appName:g,fileType:o,fileName:i,fallbackSize:a,messageType:c,imageType:d,useCustomAttachmentUpload:t.useCustomAttachmentUpload});return e.callbacks?.onFileUploadComplete?.(N),N},wp=async e=>{const{config:t,file:r,conversationId:s,conversationType:n,messageType:i,imageType:o,md5:a,width:c,height:d,fileName:u,fileType:l,fileSize:h}=e,p=(e=>{if(e)return e;const t=vc();if(t)return t;throw new bt("Upload adapter is required for simple upload",{code:ot.UPLOAD_REQUIRED_FIELD_MISSING,details:{capability:"upload"}})})(t.uploadAdapter),{orgName:m,appName:f}=fs(t.appKey),g=gs(n),y=Is(`${t.restBaseUrl}/${m}/${f}/chatfiles`,{"chat-type":g,"chat-target":s,md5:a??"",..."image"===i?{imageType:Cs(o),width:c,height:d}:{}}),v=Date.now(),I=e.dataReportOperation?.startRequest({requestName:"UPLOAD_MSG_ATTACH",method:"POST",url:y});js("Upload request start",{operation:"upload.simple",method:"POST",fileSize:h,messageType:i});const b={};let _;void 0!==e.thumbnailWidth&&(b["thumbnail-width"]=String(e.thumbnailWidth)),void 0!==e.thumbnailHeight&&(b["thumbnail-height"]=String(e.thumbnailHeight));try{_=await p.upload({url:y,method:"POST",headers:{"restrict-access":"true",Accept:"*/*",Authorization:`Bearer ${t.token}`,[ru]:tu()},source:{sourceType:"web-file",file:r,name:u,mimeType:l,size:h},fields:b,fileFieldName:"file",timeoutMs:Qr,onProgress:t=>e.callbacks?.onFileUploadProgress?.(t)})}catch(T){const t=Pd(T),r=t.details&&"object"==typeof t.details?t.details:void 0,s=new bt(t.message,{code:t.code,details:{...r,url:y,...t.code===ot.UPLOAD_TIMEOUT?{timeout:Qr}:{}}});throw I?.finish({code:s.code,success:!1,description:s.message}),s.code===ot.UPLOAD_ABORTED?(Vs("Upload request aborted",{operation:"upload.simple"}),e.callbacks?.onFileUploadCanceled?.()):s.code===ot.UPLOAD_TIMEOUT?Vs("Upload request timeout",{operation:"upload.simple",timeout:Qr}):Vs("Upload request failed",{operation:"upload.simple"}),s}try{const r=JSON.parse(_.body),s=Date.now()-v;if(_.status>=400)throw Vs("Upload response error",{operation:"upload.simple",status:_.status,duration:s}),new bt("Upload failed",{code:ot.UPLOAD_REQUEST_FAILED,details:{status:_.status,response:r}});js("Upload response success",{operation:"upload.simple",status:_.status,duration:s});const n=Es({response:r,restBaseUrl:t.restBaseUrl,orgName:m,appName:f,fileType:l,fileName:u,fallbackSize:h,messageType:i,imageType:o,useCustomAttachmentUpload:t.useCustomAttachmentUpload});return e.callbacks?.onFileUploadComplete?.(n),I?.finish({code:_.status||200,success:!0}),n}catch(T){throw I?.finish({code:T instanceof bt?T.code:ot.UPLOAD_REQUEST_FAILED,success:!1,description:T instanceof Error?T.message:String(T)}),T instanceof Error?T:new Error(String(T))}},Rp=Lc(),Ap=e=>Object.prototype.toString.call(e),Np=e=>{const t=e&&"object"==typeof e?e:null,r="string"==typeof t?.path?t.path:void 0,s="string"==typeof t?.uri?t.uri:void 0,n="string"==typeof t?.name?t.name:void 0,i="string"==typeof t?.type?t.type:void 0,o="number"==typeof t?.size?t.size:void 0;return{kind:Ap(e),isFile:"undefined"!=typeof File&&e instanceof File,isBlob:"undefined"!=typeof Blob&&e instanceof Blob,hasPath:"string"==typeof r&&r.length>0,pathPrefix:r?r.slice(0,48):void 0,hasUri:"string"==typeof s&&s.length>0,uriPrefix:s?s.slice(0,48):void 0,name:n,type:i,size:o}},Op=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}),Mp=e=>"image"===e||"video"===e||"voice"===e||"file"===e||"combine"===e,Up=e=>"object"==typeof e&&null!==e,Lp=(e,t)=>{const r=Up(t)?t:void 0,s=r?.code===sn&&r.stage===tn;return"miniapp-path"===e&&(e=>{if(!Up(e))return!1;const t=Up(e.details)?e.details:void 0;return e.code===sn&&e.stage===tn&&"string"==typeof t?.capability&&t.capability.includes("FileSystem")})(t)||"rn-uri"===e&&s};class kp{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(!Mp(e.type))return e;const r=e.body;if(this.hasUploadedRemoteResource(e.type,r))return e;const s=this.resolveUploadUrl(e.type,r),n=xh.get(e.msgLocalId),i=Boolean(n);if(Vs("Attachment upload prepare entry",{operation:"upload.prepare.entry",msgLocalId:e.msgLocalId,messageType:e.type,conversationType:e.conversationType,hasFile:i,uploadUrl:s,cachedFile:Np(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||!ms(e))(s,i))return e;if(!n)throw new bt("Attachment file is required",{code:ot.UPLOAD_REQUIRED_FIELD_MISSING,details:{msgLocalId:e.msgLocalId,url:s}});if(!this.config?.restBaseUrl)throw new bt("REST base url is required for upload",{code:ot.UPLOAD_REQUIRED_FIELD_MISSING,details:{reason:"restBaseUrl missing"}});let o,a,c;try{o=await this.prepareAttachmentUpload(e,r,n),o.precheck?.hit||(c=Uh({operationName:"UPLOAD_MSG_ATTACH",operationType:"REST",msgId:e.msgLocalId,messageType:e.type})),a=o.precheck?.hit?this.buildPrecheckedUploadResult(e,o,t):await this.uploadAttachment(e,o,t,c),c?.finish({code:0,success:!0})}catch(d){const e=Pd(d);throw c?.finish({code:e.code,success:!1,description:e.message}),e.code===ot.UPLOAD_ABORTED&&t?.onFileUploadCanceled?.(),t?.onFileUploadError?.(e),e}return this.buildPreparedMessage(e,o,a)}resolveUploadUrl(e,t){if("image"===e){const e=t;return("string"==typeof e.localUrl?e.localUrl.trim():"")||("string"==typeof e.originalImageUrl?e.originalImageUrl.trim():"")}return"url"in t&&"string"==typeof t.url?t.url.trim():""}hasUploadedRemoteResource(e,t){if("image"===e){const e=t;return"string"==typeof e.originalImageUrl&&ms(e.originalImageUrl)}return"url"in t&&"string"==typeof t.url&&ms(t.url)}async prepareAttachmentUpload(e,t,r){const s=((e,t)=>{if(!e)throw new bt("Attachment file is required",{code:ot.UPLOAD_REQUIRED_FIELD_MISSING,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=os({file:e,fallbackName:t.filename,fallbackMimeType:t.filetype,fallbackSize:r});if("web-file"===s.source.sourceType&&!s.webFile)throw new bt("Attachment file is required",{code:ot.UPLOAD_REQUIRED_FIELD_MISSING,details:{reason:"web file missing"}});return s})(r,t);if(Vs("Attachment file normalized",{operation:"upload.prepare.normalized",messageType:e.type,fileInfo:Op(s)}),"image"!==e.type){return{body:t,fileInfo:s,md5FileInfo:s,precheck:await this.maybePrecheck(e,s,s,void 0)}}const n=t,i=await this.resolveImageCandidate(n,s),o={...n,width:i.width,height:i.height,isOriginalImage:i.imagePolicy.resolvedImageType===hs},a=await this.maybePrecheck(e,i.fileInfo,s,i.imagePolicy.resolvedImageType);return{body:o,fileInfo:i.fileInfo,md5FileInfo:s,imageType:i.imagePolicy.resolvedImageType,precheck:a,originalWidth:n.width,originalHeight:n.height}}async resolveImageCandidate(e,t){const r=(e=>e.isGif?{resolvedImageType:hs,reason:"gif-force-origin"}:e.isOriginalImage?{resolvedImageType:hs,reason:"explicit-original"}:{resolvedImageType:ps,reason:"default-large"})(e);if(Vs("Image send policy resolved",{operation:"upload.image.policy",reason:r.reason,imageType:r.resolvedImageType,isGif:e.isGif,source:Op(t)}),r.resolvedImageType===hs){let s=e.width,n=e.height;if(!s||!n){const e=this.resolveImageProcessor(t.source.sourceType);Vs("Image original info resolving",{operation:"upload.image.info",processorSourceType:t.source.sourceType,source:Op(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);Vs("Image big generation start",{operation:"upload.image.big.start",processorSourceType:t.source.sourceType,source:Op(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 Vs("Image big generation failed, fallback to original",{operation:"upload.image.big-fallback",reason:r.reason,error:s instanceof Error?s.message:String(s),source:Op(t)}),{imagePolicy:{resolvedImageType:hs,reason:"large-fallback-origin"},sourceKind:"origin",fileInfo:t,width:e.width??0,height:e.height??0}}}async maybePrecheck(e,t,r,s){if(!Mp(e.type))return;if(!0!==this.config?.enableMd5Check)return void js("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=_s({messageType:e.type,fileSize:t.fileSize,imageType:s});if(!n.shouldPrecheck)return void js("Attachment precheck skipped",{operation:"upload.precheck.skip",messageType:e.type,imageType:s,fileSize:t.fileSize,thresholdBytes:n.thresholdBytes});let i;try{i=await this.computeMd5(r)}catch(a){if(Lp(r.source.sourceType,a))return void Vs("Attachment precheck skipped because md5 is unavailable",{operation:"upload.precheck.md5-unavailable",messageType:e.type,imageType:s,thresholdType:n.thresholdType,source:Op(r),error:a instanceof Error?a.message:String(a)});throw a}const o=await this.requestPrecheck(e,n.thresholdType,i,s);return js(o.hit?"Attachment precheck hit":"Attachment precheck miss",{operation:o.hit?"upload.precheck.hit":"upload.precheck.miss",messageType:e.type,imageType:s,exists:o.exists,existsType:o.existsType,uuid:o.uuid,hasShareSecret:"string"==typeof o.shareSecret&&o.shareSecret.length>0}),{...o,md5:i}}async computeMd5(e){const t=this.resolveImageProcessor(e.source.sourceType);return Vs("Attachment md5 compute start",{operation:"upload.md5.start",source:Op(e)}),t.computeMd5(e.source)}resolveImageProcessor(e){if(this.config?.imageProcessor)return Vs("Image processor resolved from platform adapter",{operation:"upload.image.processor",sourceType:e,processor:"platform"}),this.config.imageProcessor;if("web-file"===e)return Vs("Image processor resolved from web fallback",{operation:"upload.image.processor",sourceType:e,processor:"web-fallback"}),Rp;throw Vs("Image processor missing",{operation:"upload.image.processor-missing",sourceType:e}),dn("Image processor capability is missing for current platform",{code:sn,stage:tn,retryable:!1,details:{capability:"imageProcessor",sourceType:e}})}async requestPrecheck(e,t,r,s){if(!this.config)throw new bt("Upload config is required",{code:ot.UPLOAD_REQUIRED_FIELD_MISSING});const{orgName:n,appName:i}=fs(this.config.appKey),o=Is(`${this.config.restBaseUrl}/${n}/${i}/chatfiles/exists`,{md5:r,..."image"===e.type?{imageType:Cs(s)}:{}}),a=await this.requestJson({url:o,method:"GET",headers:{Authorization:`Bearer ${this.config.token}`,Accept:"application/json"},operation:"upload.precheck"}).catch(n=>{Vs("Attachment precheck failed, fallback to upload",{operation:"upload.precheck.fail-open",messageType:e.type,imageType:s,thresholdType:t,md5:r,error:n instanceof Error?n.message:String(n)})});return a?(e=>{const t=e.entities?.[0],r=!0===t?.exists,s="string"==typeof t?.uuid&&t.uuid.length>0?t.uuid:void 0,n=t,i=n?.["exists-type"]??n?.existsType,o="origin"===i?hs:i===ps||i===hs?i:void 0,a="string"==typeof t?.["share-secret"]?t["share-secret"]:void 0;if(r&&!s)throw new bt("Upload precheck response missing uuid",{code:ot.UPLOAD_REQUEST_FAILED,details:{response:e}});return{uuid:s,exists:r,existsType:o,shareSecret:a,hit:(c={exists:r,uuid:s},c.exists&&"string"==typeof c.uuid&&c.uuid.length>0)};var c})(a):{exists:!1,hit:!1}}async requestJson(e){return this.requestByAdapter(gp(this.config?.requestAdapter),e)}async requestByAdapter(e,t){const r=await e.request({url:t.url,method:t.method,headers:t.headers,responseType:"json",timeoutMs:Qr});if(r.status>=400)throw new bt("Upload precheck request failed",{code:ot.UPLOAD_REQUEST_FAILED,details:{url:t.url,status:r.status,operation:t.operation}});return"string"==typeof r.data?JSON.parse(r.data):r.data}buildPrecheckedUploadResult(e,t,r){if(!this.config||!t.precheck)throw new bt("Precheck result is required",{code:ot.UPLOAD_REQUEST_FAILED});if(!t.precheck.uuid)throw new bt("Precheck hit missing uuid",{code:ot.UPLOAD_REQUEST_FAILED,details:{precheck:t.precheck}});if(!Mp(e.type))throw new bt("Attachment message type is invalid",{code:ot.UPLOAD_REQUIRED_FIELD_MISSING,details:{messageType:e.type}});const{orgName:s,appName:n}=fs(this.config.appKey),i="image"===e.type?t.precheck.existsType??t.imageType:void 0,o="image"===e.type&&i===hs?t.md5FileInfo:t.fileInfo,a="image"===e.type&&i===hs?t.originalWidth:"image"===e.type?t.body.width:void 0,c="image"===e.type&&i===hs?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=Es({response:d,restBaseUrl:this.config.restBaseUrl,orgName:s,appName:n,fileType:o.fileType,fileName:o.fileName,fallbackSize:o.fileSize,messageType:e.type,imageType:i,width:a,height:c,useCustomAttachmentUpload:this.config.useCustomAttachmentUpload});return r?.onFileUploadComplete?.(u),u}async uploadAttachment(e,t,r,s){if(!this.config)throw new bt("Upload config is required",{code:ot.UPLOAD_REQUIRED_FIELD_MISSING});if(!Mp(e.type))throw new bt("Attachment message type is invalid",{code:ot.UPLOAD_REQUIRED_FIELD_MISSING,details:{messageType:e.type}});const n=e.type,i=await this.resolveUploadMetadata(n,t);if(!t.fileInfo.webFile){if(this.config.uploadAdapter)return this.uploadByAdapter(this.config.uploadAdapter,e,t,i,r);throw new bt("Upload adapter is required for non-web file source",{code:ot.UPLOAD_REQUIRED_FIELD_MISSING,details:{sourceType:t.fileInfo.source.sourceType}})}const o={message:e,file:t.fileInfo.webFile,conversationId:e.conversationId,conversationType:e.conversationType,messageType:n,imageType:t.imageType,md5:i.md5,width:i.width,height:i.height,fileName:t.fileInfo.fileName,fileType:t.fileInfo.fileType,fileSize:t.fileInfo.fileSize,thumbnailWidth:this.resolveThumbnailWidth(n,t.body),thumbnailHeight:this.resolveThumbnailHeight(n,t.body),callbacks:r,config:this.config,dataReportOperation:s},a=!1!==this.config?.enableMultipartUpload,c=a&&t.fileInfo.fileSize>as;if(Vs("Attachment web upload selected",{operation:"upload.web.selected",messageType:n,source:Op(t.fileInfo),multipartEnabled:a,uploadMode:c?"multipart":"simple"}),c)try{return await Ep(o)}catch(d){const e=d instanceof bt?d.details:void 0;if(e&&"object"==typeof e&&"init"===e.stage)return wp(o);throw d}return this.config.uploadAdapter?(Vs("Attachment upload adapter selected",{operation:"upload.adapter.selected",messageType:n,source:Op(t.fileInfo),adapter:"platform",hasUploadAdapter:!0}),this.uploadByAdapter(this.config.uploadAdapter,e,t,i,r)):wp(o)}async uploadByAdapter(e,t,r,s,n){if(!this.config)throw new bt("Upload config is required",{code:ot.UPLOAD_REQUIRED_FIELD_MISSING});const{orgName:i,appName:o}=fs(this.config.appKey),a=gs(t.conversationType);if(!Mp(t.type))throw new bt("Attachment message type is invalid",{code:ot.UPLOAD_REQUIRED_FIELD_MISSING,details:{messageType:t.type}});const c=t.type,d=Is(`${this.config.restBaseUrl}/${i}/${o}/chatfiles`,{"chat-type":a,"chat-target":t.conversationId,md5:s.md5,..."image"===c?{imageType:Cs(r.imageType),width:s.width,height:s.height}:{}}),u={},l={"restrict-access":"true",Accept:"*/*",Authorization:`Bearer ${this.config.token}`,[ru]:tu()},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)),Vs("Attachment adapter upload start",{operation:"upload.adapter.start",messageType:c,source:Op(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?ot.FILE_TOO_LARGE:"string"==typeof e&&e.includes("content improper")?ot.FILE_CONTENT_IMPROPER:ot.UPLOAD_REQUEST_FAILED;throw new bt("Upload failed",{code:t,details:{status:m.status,response:m.body}})}let f;try{f=JSON.parse(m.body)}catch(y){throw new bt("Upload response parse failed",{code:ot.UPLOAD_REQUEST_FAILED,details:{response:m.body,cause:y instanceof Error?y.message:String(y)}})}const g=Es({response:f,restBaseUrl:this.config.restBaseUrl,orgName:i,appName:o,fileType:r.fileInfo.fileType,fileName:r.fileInfo.fileName,fallbackSize:r.fileInfo.fileSize,messageType:c,imageType:r.imageType,width:s.width,height:s.height,useCustomAttachmentUpload:this.config.useCustomAttachmentUpload});return n?.onFileUploadComplete?.(g),g}buildPreparedMessage(e,t,r){if("image"===e.type){const s=t.body,n={...e,body:{...s,isOriginalImage:r.isOriginalImage??s.isOriginalImage,originalImageUrl:r.originalImageUrl??s.originalImageUrl,bigImageUrl:r.bigImageUrl??s.bigImageUrl,secret:r.secret??s.secret,fileLength:r.fileLength??s.fileLength??t.fileInfo.fileSize,filetype:r.filetype??s.filetype,filename:r.filename??s.filename,thumbnailUrl:r.thumbnailUrl??s.thumbnailUrl,width:r.width??s.width,height:r.height??s.height}};return Ju(e,n),el(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 Ju(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 Ju(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 Ju(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 Ju(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(!Lp(t.md5FileInfo.source.sourceType,n))throw n;Vs("Attachment upload continues without md5",{operation:"upload.md5.unavailable",messageType:e,source:Op(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 Dp{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 Pp="__internal:core";class xp{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 Ph({...e,socketAdapter:e.socketAdapter??e.platformAdapter?.socket},this.eventHub);const r=this.connectionManager.getMsyncCodec(),s=e.restBaseUrl?new kp({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 cp(r,null,this.eventHub,s),this.messageReceiver=new pp(r,this.messageSender,this.eventHub),e.enableDeliveryReceipt&&this.messageReceiver.setDeliveryAckEnabled(!0),this.combineMessageDownloader=new vp(e.platformAdapter?.request),this.attachmentDownloader=new _p(e.platformAdapter?.request),this.connectionManager.setMessageReceiver(this.messageReceiver),this.platformAdapter=e.platformAdapter??null,this.setupEventHandlers(),this.registerNetworkListeners()}setupEventHandlers(){this.eventHub.addEventHandler(Pp,{[a]:e=>{const t=this.connectionManager.getWebSocket();t&&this.messageSender.setWebSocket(t)},[c]:e=>{this.messageSender.setWebSocket(null)},[d]:e=>{this.messageSender.setWebSocket(null)},[I]:e=>{this.messageReceiver.rememberSentMessageContext(e)}})}registerNetworkListeners(){const e=this.resolveRuntimeAdapter();this.runtimeEventBridge=new Dp(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(e){return this.connectionManager.connect(e)}async disconnect(){return this.connectionManager.disconnect()}getConnectionStatus(){return this.connectionManager.getConnectionStatus()}recoverConnectionForSend(){return this.connectionManager.recoverConnectionForSend()}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(Pp),xh.clear()}}const Fp=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)},Bp=e=>{const t=new Uint8Array(fa.util.base64.length(e));return fa.util.base64.decode(e,t,0),t};class Gp{getCrypto(){return fn().crypto}constructor(e,t){if(this.enabled=(()=>{const e=fn();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=On(e);if("web"!==t.framework&&"worker"!==t.framework&&t.platform!==Js.ELECTRON_RENDERER)return!1;const r=e.crypto;return void 0!==r&&void 0!==r.subtle&&"function"==typeof r.getRandomValues&&"undefined"!=typeof TextEncoder&&"undefined"!=typeof TextDecoder})(),this.enabled){const r=`${e}:${t}`;this.keyPromise=this.deriveKey(r)}else this.keyPromise=null}isEnabled(){return this.enabled}async encrypt(e){if(!this.enabled||!this.keyPromise)return e;const t=await this.keyPromise,r=new TextEncoder,s=this.getCrypto().getRandomValues(new Uint8Array(12)),n=r.encode(e),i=await this.getCrypto().subtle.encrypt({name:"AES-GCM",iv:s},t,n),o={__enc:!0,v:1,alg:"AES-GCM",kdf:"SHA-256",iv:Fp(s),ct:Fp(new Uint8Array(i))};return JSON.stringify(o)}async decrypt(e){if(!this.enabled||!this.keyPromise)return e;let t;try{t=JSON.parse(e)}catch{return e}if(!(e=>{if(!e||"object"!=typeof e)return!1;const t=e;return!0===t.__enc&&1===t.v&&"AES-GCM"===t.alg&&"SHA-256"===t.kdf&&"string"==typeof t.iv&&"string"==typeof t.ct})(t))return e;try{const e=await this.keyPromise,r=Bp(t.iv),s=Bp(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 qp="conversationMap",$p="userInfoMap",jp="groupNamecardMap",Vp="contactRelationMap",Kp="contactVersion",zp="contactMeta",Hp="sessionListMap",Wp="sessionListCheckpoint",Jp="joinedGroupPreview",Qp="metadata",Zp=(e,t)=>`IMSDK_${e.appKey}_${e.userId}_${t}_v${e.schemaVersion}`;class Yp{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 Xp=()=>{const e="undefined"!=typeof window?window.localStorage:void 0;if(e&&"function"==typeof e.getItem)return e;const t=fn().localStorage;return t&&"function"==typeof t.getItem?t:null};class em{constructor(e,t){this.storage=t??em.createLocalStorageAdapter(),this.cryptoAdapter=e??null}static createLocalStorageAdapter(){if(!em.checkAvailable())return null;const e=Xp();return e?{getItem:t=>Promise.resolve(e.getItem(t)),setItem:(t,r)=>(e.setItem(t,r),Promise.resolve()),removeItem:t=>(e.removeItem(t),Promise.resolve())}:null}static checkAvailable(){const e=Xp();if(!e)return!1;try{const t="__im_sdk_cache_test__";return e.setItem(t,"1"),e.removeItem(t),!0}catch{return!1}}async readAsync(e,t){if(!this.storage)return t;try{const r=await this.storage.getItem(e);if(!r)return t;let s=r;if(this.cryptoAdapter&&this.cryptoAdapter.isEnabled()){const e=await this.cryptoAdapter.decrypt(r);if(null===e)return t;s=e}return mu(s,t)}catch(r){return Vs("CacheStore read failed",r),t}}async writeAsync(e,t){await this.writeInternal(e,t,!1)}async writeStrictAsync(e,t){await this.writeInternal(e,t,!0)}async writeInternal(e,t,r){if(!this.storage)return;const s=(e=>{try{return JSON.stringify(e)}catch{return null}})(t);if(null!==s)try{const t=this.cryptoAdapter&&this.cryptoAdapter.isEnabled()?await this.cryptoAdapter.encrypt(s):s;await this.storage.setItem(e,t)}catch(n){if(Kc(n))throw n;if(r)throw n;Vs("CacheStore write failed",n)}else if(r)throw new TypeError("CacheStore value cannot be serialized")}async remove(e){if(this.storage)try{await this.storage.removeItem(e)}catch(t){Vs("CacheStore remove failed",t)}}}const tm={version:"",lastVersionCheckAt:0,lastVersionSource:"metadata"},rm={cacheIntegrity:"incomplete",reason:"first_sync_pending",lastSyncTs:0,lastSuccessfulVersion:"",lastSyncMode:"skipped"};class sm{constructor(){this.items=new Map,this.versionState=tm,this.meta=rm}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(!pu(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 pu(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"}:tm}normalizeMeta(e){return pu(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"}:rm}}const nm=(e,t,r)=>{if(t<=0)return{kept:e,removed:[]};const s=[],n=[];for(const i of e)r-i.lastUpdate>t?n.push(i):s.push(i);return{kept:s,removed:n}},im=(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}},om=e=>{if(!Array.isArray(e))return[];const t=new Set,r=[],s=e;for(const n of s){const e="string"==typeof n&&n.startsWith("mark_")?n.slice(5):n,s="number"==typeof e?e:"string"==typeof e?Number.parseInt(e,10):Number.NaN;if(!Number.isInteger(s)||s<0||s>19)continue;const i=s;t.has(i)||(t.add(i),r.push(i))}return r};class am{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=nm(this.items,e,t);return this.items=[...r.kept],r.removed.length>0}evictByLru(e){const t=im(this.items,e);return this.items=[...t.kept],t.removed.length>0}trimMax(e){if(!e||this.items.length<=e)return!1;const t=[...this.items].sort((e,t)=>e.lastAccess-t.lastAccess),r=Math.max(this.items.length-e,0),s=t.slice(0,r),n=new Set(s);return this.items=this.items.filter(e=>!n.has(e)),s.length>0}findIndex(e,t){return this.items.findIndex(r=>r.conversationId===e&&r.type===t)}normalizeItem(e,t){if(!e||"object"!=typeof e)return null;const r=e;if("string"!=typeof r.conversationId||0===r.conversationId.length)return null;const s="single"===(n=r.type)||"chat"===n||"singleChat"===n?"singleChat":"group"===n||"groupchat"===n||"groupChat"===n?"groupChat":"room"===n||"chatroom"===n||"chatRoom"===n?"chatRoom":null;var n;if(!s)return null;const i=this.normalizeMessage(r.lastMessage);return{conversationId:r.conversationId,type:s,lastMessage:i,unreadCount:"number"==typeof r.unreadCount?r.unreadCount:0,isPinned:"boolean"==typeof r.isPinned?r.isPinned:void 0,pinnedTime:"number"==typeof r.pinnedTime?r.pinnedTime:void 0,marks:om(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(!pu(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=pu(e.body)?e.body:{},i="number"==typeof e.userInfoUpdateTime?e.userInfoUpdateTime:void 0,o="number"==typeof e.namecardUpdateTime?e.namecardUpdateTime:void 0;return t?{msgId:t,type:r,body:n,timestamp:s,userInfoUpdateTime:i,namecardUpdateTime:o}:null}}const cm=(e,t)=>`${e}:${t}`;class dm{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(cm(e.groupId,e.userId),e)}}getAll(){return Array.from(this.items.values())}get(e,t,r,s){const n=cm(e,t),i=this.items.get(n);return i?(s&&this.items.set(n,{...i,lastAccess:r}),i):null}getByGroupId(e,t,r){const s=[];for(const n of this.items.values())n.groupId===e&&(s.push(n),r&&this.items.set(cm(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=cm(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(cm(t.groupId,t.userId))}removeExpired(e,t,r=new Set){const s=Array.from(this.items.values()),n=s.filter(e=>!r.has(e.userId)),i=nm(n,e,t),o=new Set(i.removed.map(e=>cm(e.groupId,e.userId)));this.items.clear();for(const a of s)o.has(cm(a.groupId,a.userId))||this.items.set(cm(a.groupId,a.userId),a);return i.removed.length>0}evictByLru(e,t=new Set){const r=Array.from(this.items.values()),s=r.filter(e=>!t.has(e.userId)),n=im(s,Math.min(e,s.length)),i=new Set(n.removed.map(e=>cm(e.groupId,e.userId)));this.items.clear();for(const o of r)i.has(cm(o.groupId,o.userId))||this.items.set(cm(o.groupId,o.userId),o);return n.removed.length>0}trimMax(e,t=new Set){return!(e<=0||this.items.size<=e)&&this.evictByLru(Math.max(this.items.size-e,0),t)}normalizeItem(e,t){if(!e||!pu(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 um=100,lm=3e3,hm=e=>({...e}),pm=e=>"object"==typeof e&&null!==e,mm=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 fm{constructor(){this.items=[],this.meta={integrity:"unknown",limited:!1,storageLimit:um,serverLimit:lm,source:"localPreview"}}load(e){if(!e)return this.items=[],void(this.meta={integrity:"unknown",limited:!1,storageLimit:um,serverLimit:lm,source:"localPreview"});const t=Array.isArray(e.items)?e.items.map(e=>{return pm(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:mm(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,um),this.meta=(e=>{const t=pm(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:um,serverLimit:"number"==typeof t.serverLimit?t.serverLimit:lm,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=>hm(e)).slice(0,um),this.meta={...e.meta,source:"localPreview",storageLimit:um,serverLimit:lm,integrity:e.meta.limited?"limited":e.meta.integrity}}getSnapshot(){return{items:this.items.map(e=>hm(e)),meta:{...this.meta,source:"localPreview"}}}exportRecord(){return{items:this.items.map(e=>hm(e)),meta:{...this.meta,source:"localPreview"}}}}const gm=e=>"singleChat"===e||"groupChat"===e||"chatRoom"===e?e:null,ym=e=>{const t={...e};return delete t.type,t},vm=e=>{if(!pu(e))return null;const t="string"==typeof e.msgServerId?e.msgServerId:null;if(null===t||"string"!=typeof e.from||"number"!=typeof e.timestamp||!pu(e.body))return null;const r=((e,t)=>{if(pu(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=gm(e.conversationType),n=(e=>{if("sending"===e||"sent"===e||"failed"===e)return e})(e.sendStatus??e.status),i=(e=>{if("SEND"===e||"RECEIVE"===e)return e})(e.direct),o=(e=>{if(pu(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:ym(e.body),timestamp:e.timestamp,..."string"==typeof e.conversationId?{conversationId:e.conversationId}:{},...s?{conversationType:s}:{},..."string"==typeof e.type&&e.type.length>0?{type:e.type}:{},...n?{sendStatus:n}:{},...i?{direct:i}:{},...o?{modifiedInfo:o}:{},...void 0!==a?{userInfoUpdateTime:a}:{},...void 0!==c?{namecardUpdateTime:c}:{}}},Im=e=>{if(!Array.isArray(e))return[];const t=new Set,r=[],s=e;for(const n of s){const e="string"==typeof n&&n.startsWith("mark_")?n.slice(5):n,s="number"==typeof e?e:"string"==typeof e?Number.parseInt(e,10):Number.NaN;if(!Number.isInteger(s)||s<0||s>19)continue;const i=s;t.has(i)||(t.add(i),r.push(i))}return r},bm=(e,t)=>{const r="number"==typeof e.pinnedTimestamp?e.pinnedTimestamp:0,s="number"==typeof t.pinnedTimestamp?t.pinnedTimestamp:0;if(r!==s)return s-r;const n=e.lastMessageAt??e.updatedAt,i=t.lastMessageAt??t.updatedAt;return n!==i?i-n:e.conversationId.localeCompare(t.conversationId)};class _m{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(bm)}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(bm)}exportItems(){return this.items.map(({updatedAt:e,...t})=>t)}normalizeItem(e,t){if(!pu(e))return null;const r=e,s="string"==typeof r.conversationId?r.conversationId:"";if(!s)return null;const n=gm(r.conversationType);if(!n)return null;const i="string"==typeof r.conversationName&&r.conversationName.length>0?r.conversationName:s,o="string"==typeof r.conversationAvatar?r.conversationAvatar:void 0;return{conversationId:s,conversationType:n,unreadCount:"number"==typeof e.unreadCount&&e.unreadCount>=0?Math.floor(e.unreadCount):0,lastMessage:vm(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:Im(e.marks),readAt:"number"==typeof r.readAt?r.readAt:void 0,remindType:(a=e.remindType,"DEFAULT"===a||"ALL"===a||"AT"===a||"NONE"===a?a:"mentionOnly"===a?"AT":"mute"===a?"NONE":"DEFAULT"),conversationName:i,conversationAvatar:o,updatedAt:"number"==typeof e.updatedAt?e.updatedAt:t};var a}}class Tm{constructor(){this.items=new Map}load(e,t){this.items.clear();for(const r of e){const e=this.normalizeItem(r,t);e&&this.items.set(e.userId,e)}}getAll(){return Array.from(this.items.values())}getByIds(e,t,r){const s=[];for(const n of e){const e=this.items.get(n);e&&(s.push(e),r&&this.items.set(n,{...e,lastAccess:t}))}return s}setAll(e,t){for(const r of e){const e=this.normalizeItem(r,t);if(!e)continue;const s=this.items.get(e.userId),n=s?.lastAccess??e.lastAccess;this.items.set(e.userId,{...e,lastAccess:n,lastUpdate:e.lastUpdate})}}remove(e){for(const t of e)this.items.delete(t)}removeExpired(e,t,r=new Set){const s=Array.from(this.items.values()),n=s.filter(e=>!r.has(e.userId)),i=nm(n,e,t),o=new Set(i.removed.map(e=>e.userId));this.items.clear();for(const a of s)o.has(a.userId)||this.items.set(a.userId,a);return i.removed.length>0}evictByLru(e,t=new Set){const r=Array.from(this.items.values()),s=r.filter(e=>!t.has(e.userId)),n=im(s,Math.min(e,s.length)),i=new Set(n.removed.map(e=>e.userId));this.items.clear();for(const o of r)i.has(o.userId)||this.items.set(o.userId,o);return n.removed.length>0}trimMax(e,t=new Set){if(e<=0||this.items.size<=e)return!1;const r=Array.from(this.items.values()),s=Math.max(r.length-e,0);return this.evictByLru(s,t)}normalizeItem(e,t){if(!e||"object"!=typeof e)return null;if(!pu(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 Cm=e=>"number"==typeof e.pinnedTimestamp?e.pinnedTimestamp:0,Sm=e=>e.lastMessageAt??e.updatedAt,Em=e=>[...e].sort((e,t)=>{const r=Cm(t)-Cm(e);if(0!==r)return r;const s=Sm(t)-Sm(e);return 0!==s?s:e.conversationId.localeCompare(t.conversationId)}),wm=e=>`${e.conversationType}:${e.conversationId}`,Rm=(e,t)=>t.lastMessage?e.lastMessage?t.lastMessage.timestamp>=e.lastMessage.timestamp?t.lastMessage:e.lastMessage:t.lastMessage:e.lastMessage,Am=(e,t)=>((e,t)=>Sm(t)>Sm(e))(e,t)?{...e,unreadCount:Math.max(e.unreadCount,t.unreadCount),lastMessage:Rm(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,Nm=e=>{const t=new Map,r=new Set;for(const i of e.snapshot)r.add(wm(i));for(const i of e.existing)t.set(wm(i),i);const s=e.snapshot.map(e=>{const r=t.get(wm(e));return r?Am(e,r):e}),n=e.existing.filter(t=>!r.has(wm(t))&&((e,t)=>"number"==typeof t&&e.updatedAt>t)(t,e.syncStartedAt));return Em([...s,...n])},Om=["userId","nickname","avatarUrl","mail","phone","gender","sign","birth","ext"],Mm=e=>({userId:e.userId,nickname:e.nickname,avatarUrl:e.avatarUrl,sign:e.sign,ext:e.ext}),Um=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 Lm{constructor(){this.records=new Map}clear(){this.records.clear()}get(e,t=!1,r=Date.now()){const s=this.records.get(e)??null;if(!s||!t)return s;const n={...s,lastAccess:r};return this.records.set(e,n),n}setAll(e,t=Date.now()){for(const r of e){const e=r.lastModified??t,s=this.records.get(r.profile.userId),n=s?.lastAccess??t;this.records.set(r.profile.userId,{profile:r.profile,lastModified:e,lastAccess:n,source:r.source})}}applyPatch(e,t,r=Date.now()){const s=this.records.get(e.userId),n={userId:e.userId,...t??{},...s?.profile??{}};if(s&&e.lastModified<s.lastModified)return{applied:!1,reason:"stale",record:s};const i={...n,...e.attributes,userId:e.userId};if(s&&e.lastModified===s.lastModified&&(o=s.profile,a=i,Om.every(e=>o[e]===a[e])))return{applied:!1,reason:"duplicate",record:s};var o,a;const c={profile:i,lastModified:e.lastModified,lastAccess:s?.lastAccess??r,source:"subscription"===e.source?"subscription_notify":"contact"===e.source?"contact_notify":"own_notify"};return this.records.set(e.userId,c),{applied:!0,reason:"applied",record:c}}}const km=["conversation","userInfo","groupNamecard","sessionList","joinedGroupPreview","contactRelation","contactVersion","contactMeta"];class Dm{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 Gp(e.appKey,e.userId);this.store=new em(t??void 0,e.storageAdapter);const r={appKey:e.appKey,userId:e.userId,schemaVersion:this.config.schemaVersion};this.conversationKey=Zp(r,qp),this.userInfoKey=Zp(r,$p),this.groupNamecardKey=Zp(r,jp),this.sessionListKey=Zp(r,Hp),this.sessionListCheckpointKey=Zp(r,Wp),this.joinedGroupPreviewKey=Zp(r,Jp),this.contactRelationKey=Zp(r,Vp),this.contactVersionKey=Zp(r,Kp),this.contactMetaKey=Zp(r,zp),this.metadataKey=Zp(r,Qp),this.metadataStore=new Yp(this.store,this.metadataKey,this.config.schemaVersion),this.conversationCache=new am,this.userInfoCache=new Tm,this.groupNamecardCache=new dm,this.sessionListCache=new _m,this.joinedGroupPreviewCache=new fm,this.contactCache=new sm,this.userInfoRuntimeStore=new Lm,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 fm;if(r.setSnapshot(e),await this.store.writeStrictAsync(this.joinedGroupPreviewKey,r.exportRecord()),this.getDomainRevision("joinedGroupPreview")!==t)return this.ensureFlushScheduled(),this.loadJoinedGroupPreviewSnapshot();this.joinedGroupPreviewCache.setSnapshot(e),this.mutationRevision+=1,this.domainRevisions.set("joinedGroupPreview",this.mutationRevision);const s=this.pendingDirtyRevisions.get("joinedGroupPreview");return void 0!==s&&s<=this.mutationRevision&&this.pendingDirtyRevisions.delete("joinedGroupPreview"),await this.metadataStore.touchLastFlush(),this.loadJoinedGroupPreviewSnapshot()}async removeJoinedGroupPreview(e){const t=this.loadJoinedGroupPreviewSnapshot(),r=t.items.filter(t=>t.groupId!==e);return r.length===t.items.length?t:(this.applyJoinedGroupPreviewSnapshot({items:r,meta:{...t.meta}}),await this.flushPending(),this.loadJoinedGroupPreviewSnapshot())}loadSessionListCheckpoint(){return this.sessionListCheckpoint}async flushPending(){null!==this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null),null!==this.flushIdleHandle&&"undefined"!=typeof cancelIdleCallback&&(cancelIdleCallback(this.flushIdleHandle),this.flushIdleHandle=null),await this.flushNow(),this.activeFlushPromise&&await this.activeFlushPromise,this.pendingDirtyRevisions.size>0&&await this.flushNow()}resetSessionListCheckpoint(){this.sessionListCheckpoint={lastSyncTime:0,lastSyncFinishedTs:0,sessionsLastSyncTs:0,lastSuccessfulAt:0},this.scheduleFlush(["sessionList"])}loadUserInfoSummaries(){return this.userInfoCache.getAll()}loadGroupNamecards(e){return e?this.groupNamecardCache.getByGroupId(e,Date.now(),!1):this.groupNamecardCache.getAll()}loadContactSnapshot(e="cache"){const t=this.contactCache.buildSnapshot(this.userInfoCache.getAll(),e);return{...t,items:t.items.map(e=>({...e,userInfo:this.userInfoRuntimeStore.get(e.userId,!1)?.profile??e.userInfo}))}}loadContactRelationRecords(){return this.contactCache.getAll()}loadContactVersionState(){return this.contactCache.getVersionState()}loadContactCacheMeta(){return this.contactCache.getMeta()}markConversationAccess(e){const t=Date.now();this.conversationCache.updateLastAccess(e,t)&&this.scheduleFlush(["conversation"])}setCurrentConversation(e){this.currentConversation={conversationId:e.conversationId,type:e.type}}resetCurrentConversation(){this.currentConversation=null}getCurrentConversation(){return this.currentConversation}clearConversationUnreadMessageCount(e){const t=e.readAt??Date.now();let r=!1,s=!1;const n=this.conversationCache.getAll().map(n=>n.conversationId!==e.conversationId||n.type!==e.type?n:(r=!0,0===n.unreadCount?n:(s=!0,{...n,unreadCount:0,lastUpdate:t})));let i=!1;const o=this.sessionListCache.getAll().map(s=>s.conversationId!==e.conversationId||s.conversationType!==e.type?s:(r=!0,0===s.unreadCount&&s.readAt===t?s:(i=!0,{...s,unreadCount:0,readAt:t,updatedAt:t})));return s||i?(s&&this.conversationCache.setAll(n),i&&this.sessionListCache.setAll(o),this.scheduleFlush(["conversation","sessionList"]),{items:this.sessionListCache.exportItems(),changed:!0,matched:r}):{items:this.sessionListCache.exportItems(),changed:!1,matched:r}}clearAllConversationUnreadMessageCount(e){const t=e?.readAt??Date.now(),r=this.conversationCache.getAll(),s=r.map(e=>0===e.unreadCount?e:{...e,unreadCount:0,lastUpdate:t}),n=this.sessionListCache.getAll(),i=n.map(e=>0===e.unreadCount&&e.readAt===t?e:{...e,unreadCount:0,readAt:t,updatedAt:t}),o=!this.isConversationListEqual(r,s),a=!this.isSessionListEqual(n,i);return o||a?(o&&this.conversationCache.setAll(s),a&&this.sessionListCache.setAll(i),this.scheduleFlush(["conversation","sessionList"]),{items:this.sessionListCache.exportItems(),changed:!0}):{items:this.sessionListCache.exportItems(),changed:!1}}applyConversationPinnedMutation(e){const t=Date.now(),r=this.conversationCache.getAll(),s=this.conversationCache.getAll().map(r=>r.conversationId!==e.conversationId||r.type!==e.type?r:{...r,isPinned:e.isPinned,pinnedTime:e.isPinned?e.pinnedTime??t:0,lastUpdate:t}),n=this.sessionListCache.getAll(),i=n.map(r=>r.conversationId!==e.conversationId||r.conversationType!==e.type?r:{...r,isPinned:e.isPinned,pinnedTimestamp:e.isPinned?e.pinnedTime??t:0,updatedAt:t}),o=!this.isConversationListEqual(r,s),a=!this.isSessionListEqual(n,i);return o||a?(o&&this.conversationCache.setAll(s),a&&this.sessionListCache.setAll(i),this.scheduleFlush(["conversation","sessionList"]),{items:this.sessionListCache.exportItems(),changed:!0}):{items:this.sessionListCache.exportItems(),changed:!1}}deleteConversation(e){const t=this.conversationCache.getAll(),r=this.sessionListCache.getAll();if("number"==typeof e.deletedAt&&this.getConversationLatestUpdate(t,r,e.conversationId,e.type)>e.deletedAt)return{items:this.sessionListCache.exportItems(),changed:!1};if("number"==typeof e.deletedAt){const t=this.buildConversationKey(e.conversationId,e.type),r=this.conversationDeletionTimestamps.get(t)??0;this.conversationDeletionTimestamps.set(t,Math.max(r,e.deletedAt))}const s=t.filter(t=>t.conversationId!==e.conversationId||t.type!==e.type),n=r.filter(t=>t.conversationId!==e.conversationId||t.conversationType!==e.type),i=s.length!==t.length,o=n.length!==r.length;return i||o?(i&&this.conversationCache.setAll(s),o&&this.sessionListCache.setAll(n),this.scheduleFlush(["conversation","sessionList"]),{items:this.sessionListCache.exportItems(),changed:!0}):{items:this.sessionListCache.exportItems(),changed:!1}}clearConversations(){const e=this.conversationCache.getAll().length>0,t=this.sessionListCache.getAll().length>0;return e||t?(e&&this.conversationCache.setAll([]),t&&this.sessionListCache.setAll([]),this.scheduleFlush(["conversation","sessionList"]),{items:this.sessionListCache.exportItems(),changed:!0}):{items:this.sessionListCache.exportItems(),changed:!1}}applyConversationMarkMutation(e){const t=new Set(e.conversations.filter(e=>e.applied).map(e=>`${e.conversationType}:${e.conversationId}`));if(0===t.size)return{items:this.sessionListCache.exportItems(),changed:!1};const r=Date.now(),s=t=>"addMark"===e.operation?t.includes(e.mark)?t:[...t,e.mark]:t.filter(t=>t!==e.mark),n=this.conversationCache.getAll(),i=n.map(e=>{const n=`${e.type}:${e.conversationId}`;if(!t.has(n))return e;const i=s(e.marks);return this.areConversationMarksEqual(i,e.marks)?e:{...e,marks:i,lastUpdate:r}}),o=this.sessionListCache.getAll(),a=o.map(e=>{const n=`${e.conversationType}:${e.conversationId}`;if(!t.has(n))return e;const i=s(e.marks);return this.areConversationMarksEqual(i,e.marks)?e:{...e,marks:i,updatedAt:r}}),c=!this.isConversationListEqual(n,i),d=!this.isSessionListEqual(o,a);return c||d?(c&&this.conversationCache.setAll(i),d&&this.sessionListCache.setAll(a),this.scheduleFlush(["conversation","sessionList"]),{items:this.sessionListCache.exportItems(),changed:!0}):{items:this.sessionListCache.exportItems(),changed:!1}}replaceSessionList(e,t,r){const s=Date.now(),n=e.map(e=>({...e,updatedAt:e.lastMessageAt??s})),i=Nm({snapshot:n,existing:this.sessionListCache.getAll(),syncStartedAt:r?.syncStartedAt});this.sessionListCache.setAll(this.hydrateSessionListRecordsFromLocalProfiles(i,s)),t&&(this.sessionListCheckpoint={...this.sessionListCheckpoint,...t}),this.scheduleFlush(["sessionList"])}mergeSessionListIncremental(e,t){this.sessionListCache.setAll(this.hydrateSessionListRecordsFromLocalProfiles(this.buildIncrementalSessionListRecords(e))),t&&(this.sessionListCheckpoint={...this.sessionListCheckpoint,...t}),this.scheduleFlush(["sessionList"])}async commitSessionListSync(e){this.activeFlushPromise&&await this.activeFlushPromise,this.sessionListCommitInProgress=!0;let t=[],r=this.getDomainRevision("sessionList");try{let s=!1;for(;!s;){const n=this.getDomainRevision("sessionList");t=this.buildSessionListSyncCandidate(e),await this.writeSessionListStorageRecord(t,e.checkpoint,!0),r=this.getDomainRevision("sessionList"),r===n&&(s=!0)}this.sessionListCache.setAll(t),this.sessionListCheckpoint=e.checkpoint;const n=this.pendingDirtyRevisions.get("sessionList");return void 0!==n&&n<=r&&this.pendingDirtyRevisions.delete("sessionList"),await this.metadataStore.touchLastFlush(),{items:this.sessionListCache.exportItems(),checkpoint:this.sessionListCheckpoint}}finally{this.sessionListCommitInProgress=!1,this.pendingDirtyRevisions.size>0&&this.ensureFlushScheduled()}}setUserInfoSummaries(e){const t=Date.now();this.userInfoCache.setAll(e,t),this.userInfoCache.trimMax(this.config.maxUserInfoCount),this.refreshContactCacheIntegrity(!1),this.scheduleFlush(["userInfo","contactMeta"])}upsertRuntimeUserInfos(e){0!==e.length&&this.userInfoRuntimeStore.setAll(e)}getRuntimeUserInfo(e,t=!1){return this.userInfoRuntimeStore.get(e,t)?.profile??null}applyUserInfoNotifyPatch(e){const t=this.userInfoCache.getByIds([e.userId],Date.now(),!1)[0],r=t?Mm(t):void 0;return this.userInfoRuntimeStore.applyPatch(e,r)}updateUserInfoSummaryFromRuntime(e){const t=this.userInfoRuntimeStore.get(e,!1);t&&this.setUserInfoSummaries([Um(t)])}getUserInfoSummaries(e,t){const r=Date.now(),s=this.userInfoCache.getByIds(e,r,t);return t&&this.scheduleFlush(["userInfo"]),s}removeUserInfo(e){this.userInfoCache.remove(e),this.refreshContactCacheIntegrity(!1),this.scheduleFlush(["userInfo","contactMeta"])}getGroupNamecard(e,t,r){const s=this.groupNamecardCache.get(e,t,Date.now(),r);return r&&s&&this.scheduleFlush(["groupNamecard"]),s}setGroupNamecards(e){const t=Date.now();this.groupNamecardCache.setAll(e,t),"number"==typeof this.config.maxGroupNamecardCount&&this.groupNamecardCache.trimMax(this.config.maxGroupNamecardCount),this.scheduleFlush(["groupNamecard"])}removeGroupNamecards(e){this.groupNamecardCache.remove(e),this.scheduleFlush(["groupNamecard"])}setContactVersionState(e){this.contactCache.setVersionState(e),this.scheduleFlush(["contactVersion"])}markContactCacheIncomplete(e){this.contactCache.updateMeta({cacheIntegrity:"incomplete",reason:e}),this.scheduleFlush(["contactMeta"])}applyContactSync(e){const t=this.loadContactSnapshot("cache"),r=Date.now();this.userInfoCache.setAll(e.userInfos.map(e=>({userId:e.userId,nickname:e.nickname,avatarUrl:e.avatarUrl,sign:e.sign,ext:e.ext,lastAccess:r,lastUpdate:r})),r),"full"===e.mode?this.contactCache.replaceAll(e.relations):this.contactCache.upsert(e.relations),this.userInfoCache.trimMax(this.config.maxUserInfoCount),this.contactCache.setVersionState({version:e.version,lastVersionCheckAt:r,lastVersionSource:"sync_page"}),this.contactCache.updateMeta({cacheIntegrity:"complete",lastSyncTs:e.lastSyncTs,lastSuccessfulVersion:e.version,lastSyncMode:e.mode}),this.refreshContactCacheIntegrity(!1),this.scheduleFlush(["userInfo","contactRelation","contactVersion","contactMeta"]);const s=this.loadContactSnapshot("sync");return{snapshot:s,changed:this.buildContactSnapshotSignature(t)!==this.buildContactSnapshotSignature(s)}}refreshSessionListDisplayFromUserInfos(e){const t=new Map;for(const d of e){if(!d.userId)continue;const e=t.get(d.userId);"number"==typeof e&&"number"==typeof d.lastModified&&e>=d.lastModified||t.set(d.userId,d.lastModified)}if(0===t.size)return{items:this.sessionListCache.exportItems(),changed:!1};const r=Date.now(),s=this.loadContactSnapshot("cache").items,n=new Map(s.map(e=>[e.userId,e])),i=new Map(this.userInfoCache.getAll().map(e=>[e.userId,e])),o=this.sessionListCache.getAll().map(e=>{let s=e;if("singleChat"===e.conversationType&&!this.shouldSkipSessionUserDisplayRefresh(e.conversationId,t,i)){const t=n.get(e.conversationId),o=this.resolveSessionDisplayUserInfo(e.conversationId,i),a=this.buildSingleSessionDisplayFields(e.conversationId,t,o,e.conversationName,e.conversationAvatar);e.conversationName===a.conversationName&&e.conversationAvatar===a.conversationAvatar||(s={...s,conversationName:a.conversationName,conversationAvatar:a.conversationAvatar,updatedAt:r})}const o=s.lastMessage;if(o&&!this.shouldSkipSessionUserDisplayRefresh(o.sender.userId,t,i)){const e=n.get(o.sender.userId),t=this.resolveSessionDisplayUserInfo(o.sender.userId,i),a=this.buildSessionMessageSender(o.sender.userId,o.sender,e,t);this.isSenderEqual(o.sender,a)||(s={...s,lastMessage:{...o,sender:a},updatedAt:r})}return s}),a=this.sessionListCache.getAll(),c=!this.isSessionListEqual(a,o);return c&&(this.sessionListCache.setAll(o),this.scheduleFlush(["sessionList"])),{items:this.sessionListCache.exportItems(),changed:c}}refreshSessionListDisplayFromJoinedGroups(e,t){const r=new Map;for(const a of e){const e=a.groupId.trim();e&&r.set(e,a)}if(0===r.size)return{items:this.sessionListCache.exportItems(),changed:!1};const s=Date.now(),n=this.sessionListCache.getAll().map(e=>{if("groupChat"!==e.conversationType)return e;const n=r.get(e.conversationId);if(!n)return e;const i=Boolean(e.conversationName.trim())&&e.conversationName!==e.conversationId;if(t?.onlyWhenNameMissing&&i)return e;const o=n.name?.trim(),a=o||e.conversationName,c=n.avatarUrl??e.conversationAvatar,d=this.mapJoinedGroupRemindTypeToSession(n.remindType),u=void 0!==d&&d!==e.remindType;return a!==e.conversationName||c!==e.conversationAvatar||u?{...e,conversationName:a,conversationAvatar:c,remindType:u?d:e.remindType,updatedAt:s}:e}),i=this.sessionListCache.getAll(),o=!this.isSessionListEqual(i,n);return o&&(this.sessionListCache.setAll(n),this.scheduleFlush(["sessionList"])),{items:this.sessionListCache.exportItems(),changed:o}}removeContact(e){return this.applyContactLocalPatch(()=>this.contactCache.remove(e))}updateContactRemark(e,t){return this.applyContactLocalPatch(()=>this.contactCache.updateRemark(e,t,Date.now()))}applyContactRosterNotice(e){const t=this.loadContactSnapshot("cache"),r=Date.now(),s="add"===e.action?this.contactCache.addByNotice(e.userId,r):this.contactCache.remove(e.userId),n="string"==typeof e.rosterVersion&&e.rosterVersion.trim().length>0&&this.contactCache.updateVersionFromNotice(e.rosterVersion,r);(s||n)&&(this.refreshContactCacheIntegrity(!1),this.scheduleFlush(["contactRelation","contactVersion","contactMeta"]));const i=this.loadContactSnapshot("cache");return{snapshot:i,changed:this.buildContactSnapshotSignature(t)!==this.buildContactSnapshotSignature(i)}}updateConversationsFromServer(e,t){const r=Date.now(),s=this.conversationCache.getAll(),n=this.mergeConversationLists(s,e,r,t?.syncStartedAt),i=!this.isConversationListEqual(s,n);return this.conversationCache.setAll(n),this.config.maxConversations&&this.conversationCache.trimMax(this.config.maxConversations),this.scheduleFlush(["conversation"]),{items:n,changed:i}}applyIncomingMessageToConversations(e){const t=this.resolveConversationFromMessage(e);if(!t)return{items:this.conversationCache.getAll(),changed:!1};const r=Date.now(),s=this.conversationCache.getAll(),n=s.findIndex(e=>e.conversationId===t.conversationId&&e.type===t.type),i=n>=0?s[n]:void 0,o=this.buildConversationFromMessage(e,i,r);if(!o)return{items:s,changed:!1};const a=[o,...s.filter((e,t)=>t!==n)];return this.isConversationListEqual(s,a)?{items:s,changed:!1}:(this.conversationCache.setAll(a),this.config.maxConversations&&this.conversationCache.trimMax(this.config.maxConversations),this.scheduleFlush(["conversation"]),{items:this.conversationCache.getAll(),changed:!0})}applyIncomingMessageToSessionList(e){const t=this.resolveConversationFromMessage(e);if(!t)return{items:this.sessionListCache.exportItems(),changed:!1};const r=this.sessionListCache.getAll(),s=r.find(e=>e.conversationId===t.conversationId&&e.conversationType===t.type),n=this.conversationCache.getAll().find(e=>e.conversationId===t.conversationId&&e.type===t.type)??this.buildConversationFromMessage(e,void 0,Date.now());if(!n)return{items:this.sessionListCache.exportItems(),changed:!1};const i=(e=>{const t=wm(e.nextRecord),r=e.existing.filter(e=>wm(e)!==t);return Em([e.nextRecord,...r])})({existing:r,nextRecord:this.buildSessionListRecordFromConversation(n,e,s,Date.now())});return this.isSessionListEqual(r,i)?{items:this.sessionListCache.exportItems(),changed:!1}:(this.sessionListCache.setAll(i),this.scheduleFlush(["sessionList"]),{items:this.sessionListCache.exportItems(),changed:!0})}async loadFromStorage(){const e=Date.now(),t=await this.readDump(this.conversationKey);this.conversationCache.load(t,e);const r=await this.readDump(this.userInfoKey);this.userInfoCache.load(r,e);const s=await this.readDump(this.groupNamecardKey);this.groupNamecardCache.load(s,e);const n=await this.readValue(this.sessionListKey,null),i=n&&pu(n)&&Array.isArray(n.items)?n.items:[];this.sessionListCache.load(i,e);const o=(n&&pu(n)&&pu(n.checkpoint)?n.checkpoint:null)??await this.readValue(this.sessionListCheckpointKey,null);this.sessionListCheckpoint=this.normalizeSessionListCheckpoint(o);const a=await this.readValue(this.joinedGroupPreviewKey,null);this.joinedGroupPreviewCache.load(a);const c=await this.readDump(this.contactRelationKey),d=await this.readValue(this.contactVersionKey,null),u=await this.readValue(this.contactMetaKey,null);this.contactCache.load(c,d,u),this.refreshContactCacheIntegrity(!1),await this.metadataStore.load()}async readDump(e){const t=await this.store.readAsync(e,{items:[]});return t&&pu(t)&&Array.isArray(t.items)?t.items:[]}async readValue(e,t){return await this.store.readAsync(e,t)}normalizeSessionListCheckpoint(e){return e&&pu(e)?{lastSyncTime:"number"==typeof e.lastSyncTime?e.lastSyncTime:0,lastSyncFinishedTs:"number"==typeof e.lastSyncFinishedTs?e.lastSyncFinishedTs:0,sessionsLastSyncTs:"number"==typeof e.sessionsLastSyncTs?e.sessionsLastSyncTs:0,lastSuccessfulAt:"number"==typeof e.lastSuccessfulAt?e.lastSuccessfulAt:0}:{lastSyncTime:0,lastSyncFinishedTs:0,sessionsLastSyncTs:0,lastSuccessfulAt:0}}scheduleFlush(e){this.markDirty(e),this.ensureFlushScheduled()}markDirty(e){if(0!==e.length){this.mutationRevision+=1;for(const t of e)this.domainRevisions.set(t,this.mutationRevision),this.pendingDirtyRevisions.set(t,this.mutationRevision)}}getDomainRevision(e){return this.domainRevisions.get(e)??0}ensureFlushScheduled(){null===this.flushTimer&&null===this.flushIdleHandle&&("undefined"==typeof requestIdleCallback?this.flushTimer=setTimeout(()=>{this.flushTimer=null,this.flushNow()},this.config.flushIntervalMs):this.flushIdleHandle=requestIdleCallback(()=>{this.flushIdleHandle=null,this.flushNow()},{timeout:this.config.flushIntervalMs}))}takePendingDirtyBatch(){const e=this.pendingDirtyRevisions;return this.pendingDirtyRevisions=new Map,e}restoreDirtyBatch(e){for(const[t,r]of e){const e=this.pendingDirtyRevisions.get(t)??0;this.pendingDirtyRevisions.set(t,Math.max(r,e))}}addQuotaCleanupDomains(e,t){"none"!==t&&(this.mutationRevision+=1,this.domainRevisions.set(t,this.mutationRevision),this.domainRevisions.set("contactMeta",this.mutationRevision),e.set(t,this.mutationRevision),e.set("contactMeta",this.mutationRevision))}async flushNow(){if(this.activeFlushPromise)return void(await this.activeFlushPromise);const e=this.takePendingDirtyBatch();if(this.sessionListCommitInProgress){const t=e.get("sessionList");void 0!==t&&(e.delete("sessionList"),this.restoreDirtyBatch(new Map([["sessionList",t]])))}if(0===e.size)return;const t=this.flushDirtyBatch(e);this.activeFlushPromise=t;try{await t}finally{this.activeFlushPromise=null,this.pendingDirtyRevisions.size>0&&this.ensureFlushScheduled()}}async flushDirtyBatch(e){try{const s=6;for(let n=0;n<=s;n+=1)try{return await this.writeDirtyDomains(e),void(await this.metadataStore.touchLastFlush())}catch(t){if(!Kc(t))return this.restoreDirtyBatch(e),void Vs("Cache flush failed",t);const s=this.handleQuotaExceeded();if(this.addQuotaCleanupDomains(e,s),"none"===s)return void Vs("Cache flush failed: no cache entry can be evicted",t);try{await this.writeDomain(s)}catch(r){if(!Kc(r))return this.restoreDirtyBatch(e),void Vs("Cache quota cleanup persistence failed",r)}}Vs("Cache flush failed after quota cleanup attempts")}finally{}}async writeDirtyDomains(e){for(const t of km)e.has(t)&&await this.writeDomain(t)}async writeDomain(e){switch(e){case"conversation":return void(await this.store.writeAsync(this.conversationKey,{items:this.conversationCache.getAll()}));case"userInfo":return void(await this.store.writeAsync(this.userInfoKey,{items:this.userInfoCache.getAll()}));case"groupNamecard":return void(await this.store.writeAsync(this.groupNamecardKey,{items:this.groupNamecardCache.getAll()}));case"sessionList":return void(await this.writeSessionListStorageRecord());case"joinedGroupPreview":return void(await this.store.writeAsync(this.joinedGroupPreviewKey,this.joinedGroupPreviewCache.exportRecord()));case"contactRelation":return void(await this.store.writeAsync(this.contactRelationKey,{items:this.contactCache.getAll()}));case"contactVersion":return void(await this.store.writeAsync(this.contactVersionKey,this.contactCache.getVersionState()));case"contactMeta":await this.store.writeAsync(this.contactMetaKey,this.contactCache.getMeta())}}async writeSessionListStorageRecord(e=this.sessionListCache.getAll(),t=this.sessionListCheckpoint,r=!1){const s={items:e,checkpoint:t};r?await this.store.writeStrictAsync(this.sessionListKey,s):await this.store.writeAsync(this.sessionListKey,s),await this.store.remove(this.sessionListCheckpointKey)}buildIncrementalSessionListRecords(e){const t=this.sessionListCache.getAll(),r=new Map;for(const n of t)r.set(`${n.conversationType}:${n.conversationId}`,n);const s=Date.now();return(e=>{const t=e.incoming.filter(e=>Cm(e)>0),r=new Map;for(const n of e.incoming)r.set(wm(n),n);const s=t.length>0?e.existing.filter(e=>!r.has(wm(e))&&0===Cm(e)):e.existing.filter(e=>!r.has(wm(e)));return Em([...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(Nm({snapshot:r,existing:this.sessionListCache.getAll(),syncStartedAt:e.syncStartedAt}),t)}filterItemsAgainstConversationDeletions(e){return e.filter(e=>{const t=this.buildConversationKey(e.conversationId,e.conversationType),r=this.conversationDeletionTimestamps.get(t);if(void 0===r)return!0;return Math.max(e.lastMessageAt??0,e.lastMessage?.timestamp??0)>r})}getConversationLatestUpdate(e,t,r,s){const n=e.find(e=>e.conversationId===r&&e.type===s),i=t.find(e=>e.conversationId===r&&e.conversationType===s);return Math.max(n?.lastUpdate??0,n?.lastMessage?.timestamp??0,i?.updatedAt??0,i?.lastMessageAt??0,i?.lastMessage?.timestamp??0)}handleQuotaExceeded(){const e=Date.now(),t=1e3*this.config.ttlSeconds;if(this.groupNamecardCache.removeExpired(t,e))return this.contactCache.updateMeta({cacheIntegrity:"incomplete",reason:"quota_exceeded"}),this.refreshContactCacheIntegrity(!1),"groupNamecard";const r=this.groupNamecardCache.getAll().length;if(r>0){const e=this.calculateEvictCount(r,.2);if(this.groupNamecardCache.evictByLru(e))return this.contactCache.updateMeta({cacheIntegrity:"incomplete",reason:"quota_exceeded"}),this.refreshContactCacheIntegrity(!1),"groupNamecard"}if(this.userInfoCache.removeExpired(t,e))return this.contactCache.updateMeta({cacheIntegrity:"incomplete",reason:"quota_exceeded"}),this.refreshContactCacheIntegrity(!1),"userInfo";const s=this.evictByPolicy();return this.contactCache.updateMeta({cacheIntegrity:"incomplete",reason:"quota_exceeded"}),this.refreshContactCacheIntegrity(!1),s}evictByPolicy(){const e=this.userInfoCache.getAll().length;if(e>0){const t=this.calculateEvictCount(e,.2);return t>0?(this.userInfoCache.evictByLru(t),"userInfo"):"none"}const t=this.conversationCache.getAll().length,r=this.calculateEvictCount(t,.05);return r>0?(this.conversationCache.evictByLru(r),"conversation"):"none"}calculateEvictCount(e,t){if(e<=0)return 0;const r=Math.floor(e*t);return Math.max(r,1)}mergeConversationLists(e,t,r,s){const n=new Map,i=new Map;for(const d of e){const e=this.buildConversationKey(d.conversationId,d.type);n.set(e,d.lastAccess),i.set(e,d)}const o=[],a=new Set;for(const d of t){const e=this.buildConversationKey(d.conversationId,d.type);a.add(e);const t=n.get(e)??r;o.push({...d,marks:Array.isArray(d.marks)?d.marks:[],lastAccess:t,lastUpdate:r})}const c=e.filter(e=>{const t=this.buildConversationKey(e.conversationId,e.type);return!a.has(t)&&("number"==typeof s&&e.lastUpdate>s)});return[...o,...c]}isConversationListEqual(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r+=1){const s=e[r],n=t[r];if(!s||!n)return!1;if(this.buildConversationSignature(s)!==this.buildConversationSignature(n))return!1}return!0}buildConversationSignature(e){const t=e.lastMessage,r=t?`${t.msgId}:${t.type}:${t.timestamp}:${JSON.stringify(t.body)}`:"none",s=e.isPinned?"1":"0",n="number"==typeof e.pinnedTime?e.pinnedTime:0,i=e.marks.join(",");return`${e.type}:${e.conversationId}:${e.unreadCount}:${s}:${n}:${i}:${r}`}buildConversationKey(e,t){return`${t}:${e}`}areConversationMarksEqual(e,t){return e.length===t.length&&e.every((e,r)=>e===t[r])}buildConversationFromMessage(e,t,r=Date.now()){const s=this.resolveConversationFromMessage(e);if(!s)return null;const n=e.msgServerId||e.msgLocalId,i=t?.lastMessage?.msgId!==n&&this.shouldIncreaseUnreadForMessage(e)?(t?.unreadCount??0)+1:t?.unreadCount??0,o="SEND"===e.direct?r:t?.lastAccess??r;return{conversationId:s.conversationId,type:s.type,lastMessage:this.buildMessageSnippet(e),unreadCount:i,isPinned:t?.isPinned,pinnedTime:t?.pinnedTime,marks:t?.marks??[],lastAccess:o,lastUpdate:r}}resolveConversationFromMessage(e){if(e.isChatThread||"cmd"===e.type)return null;if("string"!=typeof e.conversationId||!e.conversationId)return null;if("singleChat"===e.conversationType){const t="RECEIVE"===e.direct&&e.from.startsWith(`${this.userId}/`)&&e.sender.userId===this.userId,r="SEND"===e.direct||t?e.conversationId:"string"==typeof e.sender.userId?e.sender.userId:"";return r?{conversationId:r,type:"singleChat"}:null}return"groupChat"===e.conversationType?{conversationId:e.conversationId,type:"groupChat"}:"chatRoom"===e.conversationType?{conversationId:e.conversationId,type:"chatRoom"}:null}buildMessageSnippet(e){const t=(e=>{const t=Wu(e);return{userInfoUpdateTime:t?.userInfoUpdateTime,namecardUpdateTime:"groupChat"===e.conversationType?t?.namecardUpdateTime:void 0}})(e);return{msgId:e.msgServerId||e.msgLocalId,type:e.type,body:this.normalizeMessageBody(e.body),timestamp:e.timestamp,userInfoUpdateTime:t.userInfoUpdateTime,namecardUpdateTime:t.namecardUpdateTime,modifiedInfo:e.modifiedInfo}}normalizeMessageBody(e){return e&&"object"==typeof e&&!Array.isArray(e)?e:{}}buildSessionListRecordFromConversation(e,t,r,s=Date.now()){const n=new Map(this.loadContactSnapshot("cache").items.map(e=>[e.userId,e])),i=n.get(e.conversationId),o=this.userInfoRuntimeStore.get(e.conversationId,!1)?.profile,a=this.userInfoCache.getByIds([e.conversationId],s,!1)[0],c=o??(a?{userId:a.userId,nickname:a.nickname,avatarUrl:a.avatarUrl,sign:a.sign,ext:a.ext}:null),d=e.lastMessage,u=r?.conversationName,l=r?.conversationAvatar,h="string"==typeof t.sender.userId?t.sender.userId:"",p=this.resolveSessionDisplayUserInfo(h),m=this.buildSessionMessageSender(h,t.sender,n.get(h),p),f="singleChat"===e.type?"SEND"===t.direct?e.conversationId:this.userId:e.conversationId,g="singleChat"===e.type?this.buildSingleSessionDisplayFields(e.conversationId,i,c,u,l):"chatRoom"===e.type?this.buildChatRoomSessionDisplayFields(e.conversationId,u,l):this.buildGroupSessionDisplayFields(e.conversationId,u,l);return{conversationId:e.conversationId,conversationType:e.type,unreadCount:this.resolveSessionListUnreadCount(e,t,r),lastMessage:d?{msgServerId:d.msgId,from:h,to:f,sender:m,conversationId:e.conversationId,conversationType:e.type,type:t.type,sendStatus:t.sendStatus,timestamp:d.timestamp,direct:t.direct,body:d.body}:null,lastMessageAt:d?.timestamp??e.lastUpdate,isPinned:e.isPinned,pinnedTimestamp:e.pinnedTime,marks:[],readAt:r?.readAt,remindType:r?.remindType??"DEFAULT",conversationName:g.conversationName,conversationAvatar:g.conversationAvatar,updatedAt:s}}resolveSessionListUnreadCount(e,t,r){const s=r?.unreadCount,n=t.msgServerId||t.msgLocalId;return r?.lastMessage?.msgServerId!==n&&this.shouldIncreaseUnreadForMessage(t)?"number"==typeof s?Math.max(e.unreadCount,s+1):e.unreadCount:"number"==typeof s?Math.max(e.unreadCount,s):e.unreadCount}shouldIncreaseUnreadForMessage(e){if("RECEIVE"!==e.direct||!1===e.isOnline)return!1;const t=this.resolveConversationFromMessage(e);return!t||!this.currentConversation||(this.currentConversation.conversationId!==t.conversationId||this.currentConversation.type!==t.type)}buildSingleSessionDisplayFields(e,t,r,s,n){const i=t?.remark?.trim(),o=t?.userInfo.avatarUrl??r?.avatarUrl??n;if(i)return{conversationName:i,conversationAvatar:o};const a=t?.userInfo.nickname?.trim()||r?.nickname?.trim();return a?{conversationName:a,conversationAvatar:o}:s?{conversationName:s,conversationAvatar:o}:{conversationName:e,conversationAvatar:o}}shouldSkipSessionUserDisplayRefresh(e,t,r){if(!t.has(e))return!0;const s=t.get(e),n=r.get(e);return"number"==typeof s&&"number"==typeof n?.lastUpdate&&n.lastUpdate>s}hydrateSessionListRecordsFromLocalProfiles(e,t=Date.now()){const r=this.loadContactSnapshot("cache").items,s=new Map(r.map(e=>[e.userId,e])),n=new Map(this.userInfoCache.getAll().map(e=>[e.userId,e]));return e.map(e=>{const r=e.lastMessage;if(!r)return e;const i=r.sender.userId,o=s.get(i),a=this.resolveSessionDisplayUserInfo(i,n),c="singleChat"===e.conversationType&&i===e.conversationId?this.buildSingleChatPeerMessageSender(i,r.sender,o,a):this.buildSessionMessageSender(i,r.sender,o,a);return this.isSenderEqual(r.sender,c)?e:{...e,lastMessage:{...r,sender:c},updatedAt:t}})}resolveSessionDisplayUserInfo(e,t){const r=this.userInfoRuntimeStore.get(e,!1)?.profile;if(r)return r;const s=t?.get(e)??this.userInfoCache.getByIds([e],Date.now(),!1)[0];return s?Mm(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 Pm{constructor(){this.handlers=new Map}addEventHandler(e,t){this.handlers.set(e,t)}removeEventHandler(e){this.handlers.delete(e)}dispatch(e,t){const r=[],s=[];for(const i of this.handlers.entries()){const[e]=i;e.startsWith("__internal")?r.push(i):s.push(i)}const n=this.dispatchToHandlers(e,t,r);n?n.then(()=>{this.dispatchToHandlers(e,t,s)}):this.dispatchToHandlers(e,t,s)}dispatchToHandlers(e,t,r){let s=null;for(const[,n]of r){const r=n[e];r&&(s=s?s.then(async()=>{await this.invokeHandler(e,t,r)}):this.invokeHandler(e,t,r))}return s}invokeHandler(e,t,r){try{const s=r(t);return this.isPromiseLike(s)?Promise.resolve(s).then(()=>{}).catch(t=>{this.reportHandlerError(e,t)}):null}catch(s){return this.reportHandlerError(e,s),null}}reportHandlerError(e,t){e!==V.LOG&&Ks(`Event handler error for ${e}`,t)}isPromiseLike(e){return"object"==typeof e&&null!==e&&"then"in e&&"function"==typeof e.then}}const xm={maxAttempts:3,initialDelay:1e3,maxDelay:6e4,backoffMultiplier:2,jitter:!0};function Fm(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 Bm(e){return new Promise(t=>setTimeout(t,e))}const Gm=e=>{const t={...e};return delete t.type,t},qm=(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:Gm(r.body),modifiedInfo:r.modifiedInfo,userInfoUpdateTime:r.userInfoUpdateTime,namecardUpdateTime:r.namecardUpdateTime}},$m=async(e,t)=>{const r=(e=>{const t=e.groupManager;return"function"==typeof t?.getGroupInfoList?t:null})(t);if(!r)return new Map;const s=[...new Set(e.filter(e=>"groupChat"===e.type).map(e=>e.conversationId))];if(0===s.length)return new Map;const n=[];for(let a=0;a<s.length;a+=50)n.push(s.slice(a,a+50));const i=new Map;let o=0;return await Promise.all(Array.from({length:Math.min(3,n.length)},async()=>await(async()=>{for(;o<n.length;){const e=o;o+=1;const t=n[e];if(t)try{const e=await r.getGroupInfoList({groupIds:t});for(const t of e)t.groupId&&i.set(t.groupId,t)}catch{}}})())),i},jm=async(e,t)=>{const r=await $m(e,t);return e.map(e=>((e,t,r)=>{const s=t.getContactSnapshot()?.items.find(t=>t.userId===e.conversationId),n=((e,t)=>{const r=e.getCacheManager();if(!r)return null;const s=r.getRuntimeUserInfo(t,!1);if(s)return s;const n=r.getUserInfoSummaries([t],!1)[0];return n?{userId:n.userId,nickname:n.nickname,avatarUrl:n.avatarUrl,sign:n.sign,ext:n.ext}:null})(t,e.conversationId),i="singleChat"===e.type?((e,t,r)=>{const s=t?.remark?.trim();if(s)return{conversationName:s,conversationAvatar:t?.userInfo.avatarUrl??r?.avatarUrl};const n=t?.userInfo.nickname?.trim()||r?.nickname?.trim();return n?{conversationName:n,conversationAvatar:t?.userInfo.avatarUrl??r?.avatarUrl}:{conversationName:e,conversationAvatar:t?.userInfo.avatarUrl??r?.avatarUrl}})(e.conversationId,s,n):"groupChat"===e.type?(o=e.conversationId,a=r.get(e.conversationId),a?.name?{conversationName:a.name,conversationAvatar:a.avatarUrl}:{conversationName:o}):(e=>({conversationName:e}))(e.conversationId);var o,a;return{conversationId:e.conversationId,conversationType:e.type,unreadCount:e.unreadCount,lastMessage:qm(e,t),lastMessageAt:e.lastMessage?.timestamp??e.lastUpdate,isPinned:e.isPinned,pinnedTimestamp:e.pinnedTime,marks:[],readAt:void 0,remindType:"DEFAULT",conversationName:i.conversationName,conversationAvatar:i.conversationAvatar}})(e,t,r))};class Vm{constructor(e=`session-list-${Bh()}`){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 ut("Session-list sync session cannot re-enter syncing state after completion",ot.CONTACT_SYNC_CURSOR_INVALID);this.status="syncing"}pushBatch(e){if(e.requestId!==this.requestId)throw new ut("Session-list sync requestId mismatch",ot.CONTACT_SYNC_CURSOR_INVALID,{details:{expected:this.requestId,received:e.requestId}});if(this.isTerminal())throw new ut("Session-list sync batch received after terminal state",ot.CONTACT_SYNC_CURSOR_INVALID,{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 Km=0,zm=5,Hm=10,Wm=11,Jm=1,Qm=2,Zm=1,Ym=2,Xm=3,ef=e=>e===Jm?"groupChat":e===Qm?"chatRoom":"singleChat",tf=()=>Kd().lookupType("easemob.pb.MessageBody"),rf=e=>{const t=tf().toObject(tf().decode(e),{longs:Number,bytes:Uint8Array}),r=Array.isArray(t.contents)?t.contents:[],s=(n=r[0])&&"object"==typeof n&&!Array.isArray(n)?n:{};var n;const i="number"==typeof s.type?s.type:Dt,o="string"==typeof s.remotePath&&s.remotePath.length>0||"string"==typeof s.title&&s.title.length>0||"string"==typeof s.summary&&s.summary.length>0||"number"==typeof s.combineLevel&&s.combineLevel>0,a=Object.prototype.hasOwnProperty.call(s,"subType")&&0===s.subType;return i===jt||i===Dt&&(a||o)?{type:"combine",title:"string"==typeof s.title?s.title:"",summary:"string"==typeof s.summary?s.summary:"",filename:"string"==typeof s.displayName?s.displayName:"combine",filetype:"application/octet-stream",url:"string"==typeof s.remotePath?s.remotePath:void 0,secret:"string"==typeof s.secretKey?s.secretKey:void 0,fileLength:"number"==typeof s.fileLength?s.fileLength:void 0,combineLevel:"number"==typeof s.combineLevel?s.combineLevel:0}:i===Dt?{type:"text",content:"string"==typeof s.text?s.text:""}:1===i?{type:"image",filename:"string"==typeof s.displayName?s.displayName:"image",remotePath:"string"==typeof s.remotePath?s.remotePath:""}:2===i?{type:"video",filename:"string"==typeof s.displayName?s.displayName:"video",remotePath:"string"==typeof s.remotePath?s.remotePath:""}:3===i?{type:"location",latitude:"number"==typeof s.latitude?s.latitude:0,longitude:"number"==typeof s.longitude?s.longitude:0,address:"string"==typeof s.address?s.address:void 0}:4===i?{type:"voice",filename:"string"==typeof s.displayName?s.displayName:"voice",remotePath:"string"==typeof s.remotePath?s.remotePath:"",duration:"number"==typeof s.duration?s.duration:0}:5===i?{type:"file",filename:"string"==typeof s.displayName?s.displayName:"file",remotePath:"string"==typeof s.remotePath?s.remotePath:""}:6===i?{type:"cmd",action:"string"==typeof s.action?s.action:""}:7===i?{type:"custom",event:"string"==typeof s.customEvent?s.customEvent:""}:{}},sf=e=>{const t=e.session_id??"",r=(e=>{if(!e)return null;try{const t=JSON.parse(e);if(t&&"object"==typeof t&&!Array.isArray(t))return t}catch{return null}return null})(e.metadata),s="string"==typeof r?.nickname?r.nickname:void 0,n="string"==typeof r?.remark?r.remark:void 0,i="string"==typeof r?.avatarurl?r.avatarurl:"string"==typeof r?.avatarUrl?r.avatarUrl:void 0;return n?{conversationName:n,conversationAvatar:i}:s?{conversationName:s,conversationAvatar:i}:{conversationName:t,conversationAvatar:i}},nf=e=>{const t={...e};return delete t.type,t},of=e=>"singleChat"===e.conversationType?e.from===e.currentUserId?e.conversationId:e.currentUserId:e.conversationId,af=(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:of({conversationId:r.conversationId,conversationType:r.conversationType,from:s,currentUserId:r.currentUserId}),sender:n,conversationId:r.conversationId,conversationType:r.conversationType,type:(i=t.type,"text"===i||"image"===i||"file"===i||"voice"===i||"video"===i||"location"===i||"custom"===i||"cmd"===i||"combine"===i?i:"text"),timestamp:e.timestamp??0,body:nf(t)};var i},cf=e=>{if(!Array.isArray(e))return[];const t=new Set,r=[],s=e;for(const n of s){const e="string"==typeof n&&n.startsWith("mark_")?n.slice(5):n,s="number"==typeof e?e:"string"==typeof e?Number.parseInt(e,10):Number.NaN;if(!Number.isInteger(s)||s<0||s>19)continue;const i=s;t.has(i)||(t.add(i),r.push(i))}return r},df=(e,t)=>e.sessions.map(e=>{const r=(e=>{if(!e||0===e.byteLength)return{};try{return rf(e)}catch{return{}}})(e.last_message?.payload),s=e.session_id??"",n=ef(e.session_type),i=(e=>{const t=e.session_id??"",r=ef(e.session_type);return"groupChat"===r||"chatRoom"===r?{conversationName:e.group_name??t,conversationAvatar:e.group_avatar}:sf(e)})(e);return{conversationId:s,conversationType:n,unreadCount:e.unread_count??0,lastMessage:af(e.last_message,r,{conversationId:s,conversationType:n,currentUserId:t,singleChatPeerDisplay:"singleChat"===n?i:void 0}),lastMessageAt:e.updated_at,isPinned:"number"==typeof e.pinned_time?e.pinned_time>0:void 0,pinnedTimestamp:e.pinned_time,marks:cf(e.marks),readAt:e.read_receipt,remindType:(o=e.remind_type,o===Zm?"ALL":o===Ym?"AT":o===Xm?"NONE":"DEFAULT"),conversationName:i.conversationName,conversationAvatar:i.conversationAvatar};var o}),uf={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 lf=null,hf=!1;const pf=()=>lf||(hf||(fa.util.Long=Dn,fa.configure(),hf=!0),Va(),lf=fa.Root.fromJSON(uf),ja(lf),lf),mf=e=>pf().lookupType(e),ff=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}},gf=e=>{if(!e||"object"!=typeof e)return;const t=e;return{resource:"string"==typeof t.resource?t.resource:"",timestamp:ff(t.timestamp)??0,requestId:"string"==typeof t.request_id?t.request_id:"string"==typeof t.requestId?t.requestId:"",protocolVersion:ff(t.protocol_version)??ff(t.protocolVersion)??0}},yf=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}},vf=e=>{if(!e||"object"!=typeof e)return;const t=e;return{id:"string"==typeof t.id?t.id:void 0!==ff(t.id)?String(ff(t.id)):void 0,from:yf(t.from),timestamp:ff(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 If{constructor(){this.requestType=mf("easemob.sessionlist.GetSessionListRequest"),this.responseType=mf("easemob.sessionlist.GetSessionListResponse"),this.errorType=mf("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:Km}}tryDecodeRequest(e){try{const t=this.requestType.toObject(this.requestType.decode(e),{longs:String,bytes:Uint8Array}),r=ff(t.type);return r!==Hm?null:{type:r,header:gf(t.header),org:"string"==typeof t.org?t.org:"",app:"string"==typeof t.app?t.app:"",username:"string"==typeof t.username?t.username:"",lastSyncTime:ff(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=ff(t.type);return r!==Wm?null:{type:r,header:gf(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:ff(t.session_type),last_message:vf(t.last_message),updated_at:ff(t.updated_at),pinned_time:ff(t.pinned_time),unread_count:ff(t.unread_count),marks:Array.isArray(t.marks)?t.marks.filter(e=>"string"==typeof e):void 0,read_receipt:ff(t.read_receipt),remind_type:ff(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:ff(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=ff(t.type);return r!==zm?null:{type:r,header:gf(t.header),code:ff(t.code)??0,message:"string"==typeof t.message?t.message:"Unknown session-list error"}}catch{return null}}}const bf=async e=>{const t=e.client.getCacheManager(),r=e.client.getRestContext(),s=e.client.getSessionListSyncWsUrls();if(!t||0===s.length)throw new ht("session-list sync websocket is unavailable",{code:ot.CONNECTION_WEBSOCKET_ERROR,details:{protocol:"session-list",stage:"socket_connect"}});const[n,i]=r.appKey.split("#");if(!n||!i)throw new mt("session-list appKey is invalid",{code:ot.VALIDATION_INVALID_FORMAT,details:{appKey:r.appKey}});const o=t.loadSessionListCheckpoint(),a=(e=>({type:10,header:{resource:e.resource,timestamp:Date.now(),requestId:e.requestId,protocolVersion:e.protocolVersion??1},org:e.org,app:e.app,username:e.username,lastSyncTime:e.lastSyncTime,includeEmpty:e.params?.includeEmpty??!1,includeMark:!0}))({requestId:e.session.getRequestId(),resource:r.clientResource,org:n,app:i,username:r.userId,lastSyncTime:(c=o.sessionsLastSyncTs,Math.max(0,c-2e4)),params:e.params});var c;const d=new If;let u=0,l=o.sessionsLastSyncTs;return await e.client.getSharedSyncWebSocketSession().request({dataType:"conversation",label:"session-list-sync",requestId:e.session.getRequestId(),encode:()=>d.encodeRequest(a),decode:e=>{const t=d.decode(e);return{type:t.type,requestId:"header"in t?t.header?.requestId:void 0,frame:t}},onFrame:t=>{if(5===t.type&&"code"in t&&"message"in t)throw 1002===(s=t).code?new pt(s.message,{code:ot.AUTH_TOKEN_EXPIRED,details:{protocol:"session-list",responseCode:s.code}}):1003===s.code?new ut(s.message,ot.SERVER_BUSY,{details:{protocol:"session-list",responseCode:s.code}}):1501===s.code||1001===s.code?new mt(s.message,{code:ot.VALIDATION_INVALID_FORMAT,details:{protocol:"session-list",responseCode:s.code}}):1503===s.code?new ut(s.message,ot.OPERATION_UNSUPPORTED,{details:{protocol:"session-list",responseCode:s.code}}):(s.code,new ut(s.message,ot.REST_BUSINESS_UNKNOWN,{details:{protocol:"session-list",responseCode:s.code}}));var s;if(11!==t.type)throw new ut("session-list response type is invalid",ot.MESSAGE_DECODE_FAILED,{details:{responseType:t.type}});const n=t,i=n.header?.requestId;if(i&&i!==e.session.getRequestId())return;u+=1,js("Decoded session-list sync raw response",{requestId:e.session.getRequestId(),batchSequence:u,response:n});const o=df(n,r.userId),a=e.session.pushBatch({requestId:e.session.getRequestId(),batchSequence:u,sessions:o,isLastBatch:!0===n.isLastBatch,lastSyncFinishedTs:n.lastSyncFinishedTs});if("number"==typeof n.lastSyncFinishedTs&&(l=n.lastSyncFinishedTs),!a.done)return;return{done:!0,result:{items:e.session.getItems(),lastSyncFinishedTs:l}}}})},_f=e=>new mt(`${e} must be a local paging cursor returned by SDK`,{code:ot.VALIDATION_INVALID_FORMAT,details:{fields:[{path:e,message:`${e} must be a local paging cursor returned by SDK`,rule:"invalid_format"}]}}),Tf=(e,t,r)=>{const s=e+t;return s<r?String(s):""},Cf=e=>({...e}),Sf=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}},Ef=e=>"AT"===e||"NONE"===e||"ALL"===e?e:null,wf=e=>{if(!Number.isInteger(e.pageSize)||e.pageSize<=0)throw new mt("pageSize must be a positive integer",{code:ot.VALIDATION_INVALID_FORMAT,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 _f(t);const r=Number.parseInt(e,10);if(!Number.isSafeInteger(r)||r<0)throw _f(t);return r})(e.cursor,"cursor"),r=[];for(const s of e.items){if("chatRoom"===s.conversationType)continue;const e=Ef(s.remindType);e&&r.push({conversationId:s.conversationId,conversationType:s.conversationType,remindType:e})}return{conversations:r.slice(t,t+e.pageSize),cursor:Tf(t,e.pageSize,r.length)}},Rf=()=>Date.now(),Af={maxAttempts:3,initialDelay:3e3,maxDelay:5e3,backoffMultiplier:1,jitter:!0},Nf=(e,t)=>({status:e,determinedAt:Rf(),reason:t}),Of=e=>e instanceof ut&&(e.code===ot.SERVER_BUSY||1103===e.code),Mf=e=>({dataType:"conversation",code:e.code,stage:"fallback",message:e.message,retryable:Of(e)});class Uf{constructor(e){this.running=null,this.currentSession=null,this.activeFinish=null,this.cancelled=!1,this.capabilityState={status:"unknown"},this.client=e}getCapabilityState(){return this.capabilityState}cancel(){this.cancelForTeardown()?.()}cancelForTeardown(){this.cancelled=!0,this.currentSession?.cancel();const e=this.activeFinish;return this.activeFinish=null,e?()=>{e({dataType:"conversation",status:"failed",error:{dataType:"conversation",code:ot.SESSION_LIST_CANCELLED,stage:"cancelled",message:"session-list sync cancelled",retryable:!1}})}:null}refresh(e){return this.cancelled?Promise.resolve([]):(this.running||(this.currentSession=new Vm,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[];let s=!1;const n=e=>{s||(s=!0,this.client.emitSyncDataFinished(e))};this.activeFinish=n;try{this.client.emitSyncDataStart("conversation");const s=await this.tryDirectFallback(r);if(this.cancelled)return[];if(s)return this.client.emitConversationListUpdate("conversation",!0),n({dataType:"conversation",status:"success"}),s;const o=r.loadSessionListCheckpoint().sessionsLastSyncTs>0?"incremental":"full";let a=0;const c=await async function(e,t,r={}){const s={...xm,...r};let n;for(let o=1;o<=s.maxAttempts;o++)try{return await e()}catch(i){if(n=i,!t(i))throw i;if(o>=s.maxAttempts)throw i;const e=Fm(o,s);await Bm(e)}throw n}(async()=>{if(this.cancelled)throw new ut("session-list sync controller is cancelled");a+=1;const r=1===a?e:this.createRetrySession();r.start();try{return await bf({client:this.client,session:r,params:t})}catch(s){throw this.cancelled||r.fail(),s}},e=>!this.cancelled&&Of(e),Af);if(this.cancelled)return[];const d={result:c,syncStartedAt:e.getStartedAt()},u=d.result.items;this.capabilityState={status:"available",determinedAt:Rf()};const l={lastSyncTime:d.result.lastSyncFinishedTs,lastSyncFinishedTs:d.result.lastSyncFinishedTs,sessionsLastSyncTs:d.result.lastSyncFinishedTs,lastSuccessfulAt:Rf()};try{if(await r.commitSessionListSync({items:u,mode:o,checkpoint:l,syncStartedAt:d.syncStartedAt}),this.cancelled)return[]}catch(i){if(this.cancelled)return[];e.fail();const t=new yt("Session-list final persistence failed",{details:{cause:i instanceof Error?i.message:String(i)}});return this.client.emitConversationListUpdate("conversation",!0),n({dataType:"conversation",status:"failed",error:Mf(t)}),r.loadSessionList()}const h=r.loadSessionList();return r.updateConversationsFromServer(h.map(Sf),{syncStartedAt:d.syncStartedAt}),await r.flushPending(),this.cancelled?[]:(this.client.emitConversationListUpdate("conversation","full"===o),n({dataType:"conversation",status:"success"}),h)}catch(i){if(this.cancelled)return[];const t=i instanceof ut?i:new ut(i instanceof Error?i.message:String(i));e.fail();const s=(e=>e.code===ot.OPERATION_UNSUPPORTED||e.code===ot.AUTH_UNAUTHORIZED?{capabilityState:Nf("unsupported",e.message),shouldUseFallback:!0}:e.code===ot.AUTH_TOKEN_EXPIRED||e.code===ot.AUTH_BIND_ANOTHER_DEVICE?{shouldUseFallback:!0}:e.code===ot.SERVER_BUSY||1103===e.code?{shouldUseFallback:!0,shouldRetry:!0}:e.code===ot.CONTACT_SYNC_CURSOR_INVALID?{shouldUseFallback:!0,shouldResetCheckpoint:!0}:{shouldUseFallback:!0})(t);s.capabilityState&&(this.capabilityState=s.capabilityState),s.shouldResetCheckpoint&&r.resetSessionListCheckpoint();const o=await this.buildFallbackSessionList(r);return this.cancelled?[]:(s.shouldUseFallback&&r.replaceSessionList(o),this.client.emitConversationListUpdate("conversation",!0),n({dataType:"conversation",status:"failed",error:Mf(t)}),o)}finally{this.activeFinish===n&&(this.activeFinish=null)}}async tryDirectFallback(e){if("unsupported"===(t=this.capabilityState).status||"unconfigured"===t.status){const t=await this.buildFallbackSessionList(e);return this.cancelled||e.replaceSessionList(t),t}var t;const r=this.client.hasSessionListSyncWsUrl(),s=this.client.isSessionListDnsProbeAvailable();if(!r&&!s){this.capabilityState=Nf("unconfigured","session-list sync websocket is unavailable");const t=await this.buildFallbackSessionList(e);return this.cancelled||e.replaceSessionList(t),t}return null}createRetrySession(){return new Vm}async buildFallbackSessionList(e){return await(async(e,t)=>await jm(e,t))(e.loadConversationSummaries(),this.client)}}const Lf=e=>"[object ArrayBuffer]"===Object.prototype.toString.call(e),kf=async e=>{if("string"==typeof e||Lf(e)||ArrayBuffer.isView(e))return(e=>"string"==typeof e?(new TextEncoder).encode(e):Lf(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 ut("sync websocket frame payload type is invalid",ot.CONTACT_SYNC_PROTO_DECODE_FAILED,{details:{stage:"response_decode",payloadType:typeof e}})},Df=e=>{const t=Math.max(e-1,0),r=1e3*Math.pow(2,t);return Math.min(r,5e3)},Pf=async e=>{await new Promise(t=>{setTimeout(t,e)})},xf=e=>e instanceof Error?e:new Error(String(e));class Ff{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 ut("sync websocket session is cancelled",ot.CONTACT_SYNC_CANCELLED,{details:{stage:"cancelled",requestId:e.requestId}});if(this.pending.has(e.requestId))throw new ut("sync websocket requestId is duplicated",ot.VALIDATION_INVALID_FORMAT,{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,xf(r))}return await t}cancel(e="sync-websocket-cancelled"){this.cancelled=!0;const t=new ut("sync websocket cancelled",ot.CONTACT_SYNC_CANCELLED,{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!==ln){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&&Vs("sync websocket retry started",this.buildLogContext({reason:e?.message}));try{return void(await this.openSocket())}catch(t){if(e=xf(t),this.cancelled||0===this.pending.size)throw e;if(this.attempt>=3)throw Vs("sync websocket retry exhausted",this.buildLogContext({reason:e.message})),e;const r=Df(this.attempt);Vs("sync websocket retry scheduled",this.buildLogContext({delayMs:r,reason:e.message})),await Pf(r)}}throw new ht("sync websocket retry exhausted",{code:ot.CONTACT_SYNC_SOCKET_FAILED,details:{stage:"socket_connect",reason:e?.message??"unknown"}})}async openSocket(){const e=await this.getUrls();if(0===e.length)throw new ht("sync websocket urls are unavailable",{code:ot.CONTACT_SYNC_SOCKET_FAILED,details:{stage:"socket_connect"}});const t=e[this.urlIndex%e.length];if(this.urlIndex+=1,!t)throw new ht("sync websocket url is invalid",{code:ot.CONTACT_SYNC_SOCKET_FAILED,details:{stage:"socket_connect"}});this.activeUrl=t,this.state="connecting",Vs("sync websocket connect started",this.buildLogContext());const r=xd(this.socketAdapter);let s=null;try{const e=await Promise.race([r.connect({url:t}),new Promise((e,t)=>{s=setTimeout(()=>{t(this.buildConnectionError("sync websocket socket connect timeout","socket_connect"))},5e3)})]);s&&clearTimeout(s),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(),Vs("sync websocket connected",this.buildLogContext())}catch(n){if(s&&clearTimeout(s),this.state="idle",this.closeSocket(4e3,"sync-websocket-connect-failed"),n instanceof ht)throw n;throw this.buildConnectionError("sync websocket socket create failed","socket_connect",{cause:n instanceof Error?n.message:String(n)})}}async handleMessage(e){try{this.resetIdleTimer();const t=await kf(e);if(!(await this.routeFrame(t)))return}catch(t){const e=xf(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(xf(s)),this.closeIfComplete()}return!0}t.requestId||1!==t.type||r||(r={pending:n,frame:t.frame})}catch(s){t.push(xf(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 ut("sync websocket frame decode failed",ot.CONTACT_SYNC_PROTO_DECODE_FAILED,{details:{stage:"response_decode",cause:t[0]?.message}});return Vs("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?(Vs("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(xf(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===ln)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)}))}),Vs("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||(Vs("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>=hn||(this.state="closing",r.close(e,t))}buildConnectionError(e,t,r={}){return new ht(e,{code:ot.CONTACT_SYNC_SOCKET_FAILED,details:{stage:t,url:this.activeUrl,...r}})}buildLogContext(e={}){return{attempt:this.attempt,maxAttempts:3,url:ct(this.activeUrl),pendingCount:this.pending.size,dataTypes:[...new Set([...this.pending.values()].map(e=>e.dataType))],...e}}}const Bf=(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 Gf(e,t,r){if(!e)return;const s=r&&"object"==typeof r?r:{},n="string"==typeof s.error?s.error:void 0,i=(e=>"string"==typeof e.error_code||"number"==typeof e.error_code?e.error_code:"string"==typeof e.errorCode||"number"==typeof e.errorCode?e.errorCode:"string"==typeof e.error||"number"==typeof e.error?e.error:"string"==typeof e.code||"number"==typeof e.code?e.code:void 0)(s),o="string"==typeof s.error_description?s.error_description:"string"==typeof s.message?s.message:"string"==typeof s.desc?s.desc:void 0,a=(e,t=!1)=>{const r=(e,r,s)=>({reasonKey:e,entry:r,matchedBy:t?"common":s});if(n&&e[n])return r(n,e[n],"key");for(const[n,i]of Object.entries(e))if(Bf(i,s))return r(n,i,"field");if(void 0!==i)for(const[s,n]of Object.entries(e)){if(n.code===i||n.canonicalCode===i)return r(s,n,"code");if(Array.isArray(n.aliases)&&n.aliases.includes(String(i)))return r(s,n,"alias")}if(o)for(const[s,n]of Object.entries(e))if(Array.isArray(n.aliases)&&n.aliases.includes(o))return r(s,n,"alias")},c=t?e.apis[t]:void 0,d=c?a(c.errors):void 0;if(d)return d;for(const u of Object.values(e.common)){const e=a(u.errors,!0);if(e)return e}}function qf(e){const t=e.entry?.code??ot.REST_BUSINESS_UNKNOWN,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 It(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 $f={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"}},jf=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/[^a-zA-Z0-9]+/g,"_").replace(/^_+|_+$/g,"").toUpperCase();class Vf{constructor(e,t){this.baseUrl=e.replace(/\/$/,""),this.timeout=t?.timeout??15e3,this.errorMap=t?.errorMap,this.requestAdapter=gp(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 mt("Invalid request parameters",{code:ot.VALIDATION_UNKNOWN,details:{...n,canonicalCode:ot.VALIDATION_UNKNOWN}});if(401===e){const e=[r,s].some(e=>"string"==typeof e&&/token[ _-]?(?:has[ _-]?)?expired/i.test(e)),t=e?ot.AUTH_TOKEN_EXPIRED:ot.AUTH_UNAUTHORIZED;return new pt(e?"Authentication token expired":"Authentication failed",{code:t,details:{...n,reasonKey:e?"token_expired":"unauthorized",canonicalCode:t}})}return 403===e?new pt("Access forbidden",{code:ot.AUTH_FORBIDDEN,details:{...n,canonicalCode:ot.AUTH_FORBIDDEN}}):429===e?new It("REST rate limit exceeded",{code:ot.SERVICE_LIMIT_EXCEEDED,details:{...n,retryable:!0,reasonKey:"request_rate_limited",canonicalCode:ot.SERVICE_LIMIT_EXCEEDED}}):e>=500?new It("REST business error: request failed",{code:ot.REST_BUSINESS_UNKNOWN,details:{...n,retryable:!0,reasonKey:"server_unknown_error",canonicalCode:ot.REST_BUSINESS_UNKNOWN}}):void 0}async request(e,t={}){const r=`${this.baseUrl}${e}`,s=t.method??"GET",n=Date.now(),i=this.sanitizeUrl(r);js("REST request",{method:s,url:i,operation:t.operation});const o=t.operation?(e=>{const t=$f[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_${jf(e)}`,operationType:r}})(t.operation):void 0,a=o?Uh(o):void 0,c=a?.startRequest({requestName:o?.operationName,method:s,url:r});let d=0;const u={...this.defaultHeaders,...t.headers};if(this.includeRequestId&&(u[ru]=tu()),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"):e||(u["Content-Type"]="application/json")}else if("GET"===s)for(const h of Object.keys(u))"content-type"===h.toLowerCase()&&delete u[h];try{const e=await this.requestAdapter.request({url:r,method:s,headers:u,body:t.body,timeoutMs:t.timeout??this.timeout});d=e.status;const o=((e,t)=>{if("string"!=typeof e)return e;const r=Object.entries(t).find(([e])=>"content-type"===e.toLowerCase()),s=e.trim();if(!(r?.[1].includes("application/json")||s.startsWith("{")&&s.endsWith("}")||s.startsWith("[")&&s.endsWith("]")))return e;try{return JSON.parse(s)}catch{return e}})(e.data,e.headers),l=Date.now()-n;(e.status<200||e.status>=300)&&(Vs("REST response error",{method:s,url:i,status:e.status,duration:l}),this.handleErrorPayload(e.status,e.statusText??"",o,{operation:t.operation,url:r,method:s})),js("REST response",{method:s,url:i,status:e.status,duration:l});const h=(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}})(o);return c?.finish({code:e.status,success:!0,resultCount:h}),a?.finish({code:0,success:!0,resultCount:h}),o}catch(l){const e=0!==d?d:l instanceof ut?l.code:-1,n=l instanceof Error?l.message:String(l);if(c?.finish({code:e,success:!1,description:n}),a?.finish({code:e,success:!1,description:n}),l instanceof ut)throw l;const o=(e=>{if(!e||"object"!=typeof e)return;const t=e.details;if(!t||"object"!=typeof t)return;const r=t.reason;return"abort"===r||"network"===r||"timeout"===r?r:void 0})(l);if(l instanceof Error&&"AbortError"===l.name||"timeout"===o)throw Vs("REST request timeout",{method:s,url:i,timeout:t.timeout??this.timeout}),new vt(`Request timeout: ${r}`,{code:ot.REST_TIMEOUT,details:{url:r,method:s,timeout:t.timeout??this.timeout}});throw Vs("REST request failed",{method:s,url:i}),new vt(`Request failed: ${r}`,{code:ot.REST_NETWORK_ERROR,details:{url:r,method:s,...o?{reason:o}:{}}})}}handleErrorPayload(e,t,r,s){const n=r&&"object"==typeof r?r:{},i=((e,t)=>{if(!e.error||"object"!=typeof e.error||Array.isArray(e.error))return;const r=e.error,s=r.code;if("number"!=typeof s&&"string"!=typeof s)return;const n=String(s);return/^\d{7}$/.test(n)&&Number(n.slice(0,3))===t?r:void 0})(n,e),o=i?{...n,code:i.code,message:i.message}:r,a=Gf(this.errorMap,s.operation,o),c="string"==typeof n.error?n.error:void 0,d="number"==typeof n.error_code||"string"==typeof n.error_code?n.error_code:"number"==typeof n.errorCode||"string"==typeof n.errorCode?n.errorCode:"number"==typeof n.code||"string"==typeof n.code?n.code:"string"==typeof n.error?n.error:"number"==typeof i?.code||"string"==typeof i?.code?i.code:void 0,u="string"==typeof n.message?n.message:"string"==typeof n.error_description?n.error_description:"string"==typeof n.desc?n.desc:"string"==typeof i?.message?i.message:void 0,l=!!(401!==e&&403!==e||void 0!==c&&"unauthorized"!==c&&"auth_failed"!==c&&"forbidden"!==c)&&(void 0!==c||"string"==typeof n.error_description||"string"==typeof n.message||"string"==typeof n.desc);if(s.operation&&a)throw qf({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 qf({apiName:s.operation,serverCode:d,serverMessage:u,httpStatus:e,mapped:!1,reasonKey:c});throw new vt(`HTTP ${e}: ${t}`,{code:ot.REST_HTTP_ERROR,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 Kf=async(e,t,r)=>{const{orgName:s,appName:n}=fs(e.appKey),i=`/${s}/${n}/user/${encodeURIComponent(e.userId)}/roster/metadata/version`,o=new Vf(e.restBaseUrl,{requestAdapter:r,includeRequestId:!0});o.setAuthToken(e.token);try{return((e,t)=>{const r=Date.now(),s=e=>{const s="string"==typeof e.version?e.version:"string"==typeof e.rosterVersion?e.rosterVersion:"";return{version:s,requiresSync:("boolean"==typeof e.requiresSync?e.requiresSync:"boolean"==typeof e.needSync?e.needSync:"boolean"==typeof e.need_sync?e.need_sync:void 0)??s!==t,checkedAt:"number"==typeof e.checkedAt?e.checkedAt:"number"==typeof e.timestamp?e.timestamp:r}};if(pu(e))return pu(e.data)?s(e.data):s(e);throw new mt("Invalid contact metadata response",{code:ot.VALIDATION_INVALID_FORMAT,details:{payload:e}})})(await o.get(i),t)}catch(a){if(a instanceof mt)throw a;const e=a instanceof ut&&a.details?a.details:{};throw new vt("Contact metadata request failed",{code:ot.CONTACT_SYNC_METADATA_FAILED,details:{stage:"metadata",cause:a instanceof Error?a.message:String(a),httpStatus:"number"==typeof e.httpStatus?e.httpStatus:void 0,sourceCode:a instanceof ut?a.code:void 0}})}};var zf,Hf,Wf;(Hf=zf||(zf={})).assertEqual=e=>{},Hf.assertIs=function(e){},Hf.assertNever=function(e){throw new Error},Hf.arrayToEnum=e=>{const t={};for(const r of e)t[r]=r;return t},Hf.getValidEnumValues=e=>{const t=Hf.objectKeys(e).filter(t=>"number"!=typeof e[e[t]]),r={};for(const s of t)r[s]=e[s];return Hf.objectValues(r)},Hf.objectValues=e=>Hf.objectKeys(e).map(function(t){return e[t]}),Hf.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},Hf.find=(e,t)=>{for(const r of e)if(t(r))return r},Hf.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&Number.isFinite(e)&&Math.floor(e)===e,Hf.joinValues=function(e,t=" | "){return e.map(e=>"string"==typeof e?`'${e}'`:e).join(t)},Hf.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t,(Wf||(Wf={})).mergeShapes=(e,t)=>({...e,...t});const Jf=zf.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Qf=e=>{switch(typeof e){case"undefined":return Jf.undefined;case"string":return Jf.string;case"number":return Number.isNaN(e)?Jf.nan:Jf.number;case"boolean":return Jf.boolean;case"function":return Jf.function;case"bigint":return Jf.bigint;case"symbol":return Jf.symbol;case"object":return Array.isArray(e)?Jf.array:null===e?Jf.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?Jf.promise:"undefined"!=typeof Map&&e instanceof Map?Jf.map:"undefined"!=typeof Set&&e instanceof Set?Jf.set:"undefined"!=typeof Date&&e instanceof Date?Jf.date:Jf.object;default:return Jf.unknown}},Zf=zf.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 Yf 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 Yf))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,zf.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()}}Yf.create=e=>new Yf(e);const Xf=(e,t)=>{let r;switch(e.code){case Zf.invalid_type:r=e.received===Jf.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case Zf.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,zf.jsonStringifyReplacer)}`;break;case Zf.unrecognized_keys:r=`Unrecognized key(s) in object: ${zf.joinValues(e.keys,", ")}`;break;case Zf.invalid_union:r="Invalid input";break;case Zf.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${zf.joinValues(e.options)}`;break;case Zf.invalid_enum_value:r=`Invalid enum value. Expected ${zf.joinValues(e.options)}, received '${e.received}'`;break;case Zf.invalid_arguments:r="Invalid function arguments";break;case Zf.invalid_return_type:r="Invalid function return type";break;case Zf.invalid_date:r="Invalid date";break;case Zf.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}"`:zf.assertNever(e.validation):r="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case Zf.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 Zf.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 Zf.custom:r="Invalid input";break;case Zf.invalid_intersection_types:r="Intersection results could not be merged";break;case Zf.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case Zf.not_finite:r="Number must be finite";break;default:r=t.defaultError,zf.assertNever(e)}return{message:r}};let eg=Xf;function tg(e,t){const r=eg,s=(e=>{const{data:t,path:r,errorMaps:s,issueData:n}=e,i=[...r,...n.path||[]],o={...n,path:i};if(void 0!==n.message)return{...n,path:i,message:n.message};let a="";const c=s.filter(e=>!!e).slice().reverse();for(const d of c)a=d(o,{data:t,defaultError:a}).message;return{...n,path:i,message:a}})({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===Xf?void 0:Xf].filter(e=>!!e)});e.common.issues.push(s)}class rg{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 sg;"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 rg.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 sg;if("aborted"===n.status)return sg;"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 sg=Object.freeze({status:"aborted"}),ng=e=>({status:"dirty",value:e}),ig=e=>({status:"valid",value:e}),og=e=>"aborted"===e.status,ag=e=>"dirty"===e.status,cg=e=>"valid"===e.status,dg=e=>"undefined"!=typeof Promise&&e instanceof Promise;var ug,lg;(lg=ug||(ug={})).errToObj=e=>"string"==typeof e?{message:e}:e||{},lg.toString=e=>"string"==typeof e?e:e?.message;class hg{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 pg=(e,t)=>{if(cg(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 Yf(e.common.issues);return this._error=t,this._error}}};function mg(e){if(!e)return{};const{errorMap:t,invalid_type_error:r,required_error:s,description:n}=e;if(t&&(r||s))throw new Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');if(t)return{errorMap:t,description:n};return{errorMap:(t,n)=>{const{message:i}=e;return"invalid_enum_value"===t.code?{message:i??n.defaultError}:void 0===n.data?{message:i??s??n.defaultError}:"invalid_type"!==t.code?{message:n.defaultError}:{message:i??r??n.defaultError}},description:n}}class fg{get description(){return this._def.description}_getType(e){return Qf(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:Qf(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new rg,ctx:{common:e.parent.common,data:e.data,parsedType:Qf(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(dg(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:Qf(e)},s=this._parseSync({data:e,path:r.path,parent:r});return pg(r,s)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Qf(e)};if(!this["~standard"].async)try{const r=this._parseSync({data:e,path:[],parent:t});return cg(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=>cg(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:Qf(e)},s=this._parse({data:e,path:r.path,parent:r}),n=await(dg(s)?s:Promise.resolve(s));return pg(r,n)}refine(e,t){const r=e=>"string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(e):t;return this._refinement((t,s)=>{const n=e(t),i=()=>s.addIssue({code:Zf.custom,...r(t)});return"undefined"!=typeof Promise&&n instanceof Promise?n.then(e=>!!e||(i(),!1)):!!n||(i(),!1)})}refinement(e,t){return this._refinement((r,s)=>!!e(r)||(s.addIssue("function"==typeof t?t(r,s):t),!1))}_refinement(e){return new fy({schema:this,typeName:wy.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 gy.create(this,this._def)}nullable(){return yy.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Yg.create(this)}promise(){return py.create(this,this._def)}or(e){return ty.create([this,e],this._def)}and(e){return sy.create(this,e,this._def)}transform(e){return new fy({...mg(this._def),schema:this,typeName:wy.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new vy({...mg(this._def),innerType:this,defaultValue:t,typeName:wy.ZodDefault})}brand(){return new _y({typeName:wy.ZodBranded,type:this,...mg(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new Iy({...mg(this._def),innerType:this,catchValue:t,typeName:wy.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return Ty.create(this,e)}readonly(){return Cy.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const gg=/^c[^\s-]{8,}$/i,yg=/^[0-9a-z]+$/,vg=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Ig=/^[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,bg=/^[a-z0-9_-]{21}$/i,_g=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Tg=/^[-+]?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)?)??$/,Cg=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let Sg;const Eg=/^(?:(?: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])$/,wg=/^(?:(?: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])$/,Rg=/^(([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]))$/,Ag=/^(([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])$/,Ng=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Og=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Mg="((\\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])))",Ug=new RegExp(`^${Mg}$`);function Lg(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 kg(e){return new RegExp(`^${Lg(e)}$`)}function Dg(e){let t=`${Mg}T${Lg(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 Pg(e,t){return!("v4"!==t&&t||!Eg.test(e))||!("v6"!==t&&t||!Rg.test(e))}function xg(e,t){if(!_g.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 Fg(e,t){return!("v4"!==t&&t||!wg.test(e))||!("v6"!==t&&t||!Ag.test(e))}class Bg extends fg{_parse(e){this._def.coerce&&(e.data=String(e.data));if(this._getType(e)!==Jf.string){const t=this._getOrReturnCtx(e);return tg(t,{code:Zf.invalid_type,expected:Jf.string,received:t.parsedType}),sg}const t=new rg;let r;for(const s of this._def.checks)if("min"===s.kind)e.data.length<s.value&&(r=this._getOrReturnCtx(e,r),tg(r,{code:Zf.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),tg(r,{code:Zf.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),t.dirty());else if("length"===s.kind){const n=e.data.length>s.value,i=e.data.length<s.value;(n||i)&&(r=this._getOrReturnCtx(e,r),n?tg(r,{code:Zf.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):i&&tg(r,{code:Zf.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),t.dirty())}else if("email"===s.kind)Cg.test(e.data)||(r=this._getOrReturnCtx(e,r),tg(r,{validation:"email",code:Zf.invalid_string,message:s.message}),t.dirty());else if("emoji"===s.kind)Sg||(Sg=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Sg.test(e.data)||(r=this._getOrReturnCtx(e,r),tg(r,{validation:"emoji",code:Zf.invalid_string,message:s.message}),t.dirty());else if("uuid"===s.kind)Ig.test(e.data)||(r=this._getOrReturnCtx(e,r),tg(r,{validation:"uuid",code:Zf.invalid_string,message:s.message}),t.dirty());else if("nanoid"===s.kind)bg.test(e.data)||(r=this._getOrReturnCtx(e,r),tg(r,{validation:"nanoid",code:Zf.invalid_string,message:s.message}),t.dirty());else if("cuid"===s.kind)gg.test(e.data)||(r=this._getOrReturnCtx(e,r),tg(r,{validation:"cuid",code:Zf.invalid_string,message:s.message}),t.dirty());else if("cuid2"===s.kind)yg.test(e.data)||(r=this._getOrReturnCtx(e,r),tg(r,{validation:"cuid2",code:Zf.invalid_string,message:s.message}),t.dirty());else if("ulid"===s.kind)vg.test(e.data)||(r=this._getOrReturnCtx(e,r),tg(r,{validation:"ulid",code:Zf.invalid_string,message:s.message}),t.dirty());else if("url"===s.kind)try{new URL(e.data)}catch{r=this._getOrReturnCtx(e,r),tg(r,{validation:"url",code:Zf.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),tg(r,{validation:"regex",code:Zf.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),tg(r,{code:Zf.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),tg(r,{code:Zf.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),tg(r,{code:Zf.invalid_string,validation:{endsWith:s.value},message:s.message}),t.dirty());else if("datetime"===s.kind){Dg(s).test(e.data)||(r=this._getOrReturnCtx(e,r),tg(r,{code:Zf.invalid_string,validation:"datetime",message:s.message}),t.dirty())}else if("date"===s.kind){Ug.test(e.data)||(r=this._getOrReturnCtx(e,r),tg(r,{code:Zf.invalid_string,validation:"date",message:s.message}),t.dirty())}else if("time"===s.kind){kg(s).test(e.data)||(r=this._getOrReturnCtx(e,r),tg(r,{code:Zf.invalid_string,validation:"time",message:s.message}),t.dirty())}else"duration"===s.kind?Tg.test(e.data)||(r=this._getOrReturnCtx(e,r),tg(r,{validation:"duration",code:Zf.invalid_string,message:s.message}),t.dirty()):"ip"===s.kind?Pg(e.data,s.version)||(r=this._getOrReturnCtx(e,r),tg(r,{validation:"ip",code:Zf.invalid_string,message:s.message}),t.dirty()):"jwt"===s.kind?xg(e.data,s.alg)||(r=this._getOrReturnCtx(e,r),tg(r,{validation:"jwt",code:Zf.invalid_string,message:s.message}),t.dirty()):"cidr"===s.kind?Fg(e.data,s.version)||(r=this._getOrReturnCtx(e,r),tg(r,{validation:"cidr",code:Zf.invalid_string,message:s.message}),t.dirty()):"base64"===s.kind?Ng.test(e.data)||(r=this._getOrReturnCtx(e,r),tg(r,{validation:"base64",code:Zf.invalid_string,message:s.message}),t.dirty()):"base64url"===s.kind?Og.test(e.data)||(r=this._getOrReturnCtx(e,r),tg(r,{validation:"base64url",code:Zf.invalid_string,message:s.message}),t.dirty()):zf.assertNever(s);return{status:t.value,value:e.data}}_regex(e,t,r){return this.refinement(t=>e.test(t),{validation:t,code:Zf.invalid_string,...ug.errToObj(r)})}_addCheck(e){return new Bg({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...ug.errToObj(e)})}url(e){return this._addCheck({kind:"url",...ug.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...ug.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...ug.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...ug.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...ug.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...ug.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...ug.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...ug.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...ug.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...ug.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...ug.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...ug.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,...ug.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,...ug.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...ug.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...ug.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...ug.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...ug.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...ug.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...ug.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...ug.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...ug.errToObj(t)})}nonempty(e){return this.min(1,ug.errToObj(e))}trim(){return new Bg({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Bg({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Bg({...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 Gg(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}Bg.create=e=>new Bg({checks:[],typeName:wy.ZodString,coerce:e?.coerce??!1,...mg(e)});class qg extends fg{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)!==Jf.number){const t=this._getOrReturnCtx(e);return tg(t,{code:Zf.invalid_type,expected:Jf.number,received:t.parsedType}),sg}let t;const r=new rg;for(const s of this._def.checks)if("int"===s.kind)zf.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),tg(t,{code:Zf.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),tg(t,{code:Zf.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),tg(t,{code:Zf.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),r.dirty())}else"multipleOf"===s.kind?0!==Gg(e.data,s.value)&&(t=this._getOrReturnCtx(e,t),tg(t,{code:Zf.not_multiple_of,multipleOf:s.value,message:s.message}),r.dirty()):"finite"===s.kind?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),tg(t,{code:Zf.not_finite,message:s.message}),r.dirty()):zf.assertNever(s);return{status:r.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,ug.toString(t))}gt(e,t){return this.setLimit("min",e,!1,ug.toString(t))}lte(e,t){return this.setLimit("max",e,!0,ug.toString(t))}lt(e,t){return this.setLimit("max",e,!1,ug.toString(t))}setLimit(e,t,r,s){return new qg({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:ug.toString(s)}]})}_addCheck(e){return new qg({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:ug.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:ug.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:ug.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:ug.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:ug.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:ug.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:ug.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:ug.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:ug.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&&zf.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)}}qg.create=e=>new qg({checks:[],typeName:wy.ZodNumber,coerce:e?.coerce||!1,...mg(e)});class $g extends fg{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)!==Jf.bigint)return this._getInvalidInput(e);let t;const r=new rg;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),tg(t,{code:Zf.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),tg(t,{code:Zf.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),tg(t,{code:Zf.not_multiple_of,multipleOf:s.value,message:s.message}),r.dirty()):zf.assertNever(s);return{status:r.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return tg(t,{code:Zf.invalid_type,expected:Jf.bigint,received:t.parsedType}),sg}gte(e,t){return this.setLimit("min",e,!0,ug.toString(t))}gt(e,t){return this.setLimit("min",e,!1,ug.toString(t))}lte(e,t){return this.setLimit("max",e,!0,ug.toString(t))}lt(e,t){return this.setLimit("max",e,!1,ug.toString(t))}setLimit(e,t,r,s){return new $g({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:ug.toString(s)}]})}_addCheck(e){return new $g({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:ug.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:ug.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:ug.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:ug.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:ug.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}}$g.create=e=>new $g({checks:[],typeName:wy.ZodBigInt,coerce:e?.coerce??!1,...mg(e)});class jg extends fg{_parse(e){this._def.coerce&&(e.data=Boolean(e.data));if(this._getType(e)!==Jf.boolean){const t=this._getOrReturnCtx(e);return tg(t,{code:Zf.invalid_type,expected:Jf.boolean,received:t.parsedType}),sg}return ig(e.data)}}jg.create=e=>new jg({typeName:wy.ZodBoolean,coerce:e?.coerce||!1,...mg(e)});class Vg extends fg{_parse(e){this._def.coerce&&(e.data=new Date(e.data));if(this._getType(e)!==Jf.date){const t=this._getOrReturnCtx(e);return tg(t,{code:Zf.invalid_type,expected:Jf.date,received:t.parsedType}),sg}if(Number.isNaN(e.data.getTime())){return tg(this._getOrReturnCtx(e),{code:Zf.invalid_date}),sg}const t=new rg;let r;for(const s of this._def.checks)"min"===s.kind?e.data.getTime()<s.value&&(r=this._getOrReturnCtx(e,r),tg(r,{code:Zf.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),tg(r,{code:Zf.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),t.dirty()):zf.assertNever(s);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(e){return new Vg({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:ug.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:ug.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}}Vg.create=e=>new Vg({checks:[],coerce:e?.coerce||!1,typeName:wy.ZodDate,...mg(e)});class Kg extends fg{_parse(e){if(this._getType(e)!==Jf.symbol){const t=this._getOrReturnCtx(e);return tg(t,{code:Zf.invalid_type,expected:Jf.symbol,received:t.parsedType}),sg}return ig(e.data)}}Kg.create=e=>new Kg({typeName:wy.ZodSymbol,...mg(e)});class zg extends fg{_parse(e){if(this._getType(e)!==Jf.undefined){const t=this._getOrReturnCtx(e);return tg(t,{code:Zf.invalid_type,expected:Jf.undefined,received:t.parsedType}),sg}return ig(e.data)}}zg.create=e=>new zg({typeName:wy.ZodUndefined,...mg(e)});class Hg extends fg{_parse(e){if(this._getType(e)!==Jf.null){const t=this._getOrReturnCtx(e);return tg(t,{code:Zf.invalid_type,expected:Jf.null,received:t.parsedType}),sg}return ig(e.data)}}Hg.create=e=>new Hg({typeName:wy.ZodNull,...mg(e)});class Wg extends fg{constructor(){super(...arguments),this._any=!0}_parse(e){return ig(e.data)}}Wg.create=e=>new Wg({typeName:wy.ZodAny,...mg(e)});class Jg extends fg{constructor(){super(...arguments),this._unknown=!0}_parse(e){return ig(e.data)}}Jg.create=e=>new Jg({typeName:wy.ZodUnknown,...mg(e)});class Qg extends fg{_parse(e){const t=this._getOrReturnCtx(e);return tg(t,{code:Zf.invalid_type,expected:Jf.never,received:t.parsedType}),sg}}Qg.create=e=>new Qg({typeName:wy.ZodNever,...mg(e)});class Zg extends fg{_parse(e){if(this._getType(e)!==Jf.undefined){const t=this._getOrReturnCtx(e);return tg(t,{code:Zf.invalid_type,expected:Jf.void,received:t.parsedType}),sg}return ig(e.data)}}Zg.create=e=>new Zg({typeName:wy.ZodVoid,...mg(e)});class Yg extends fg{_parse(e){const{ctx:t,status:r}=this._processInputParams(e),s=this._def;if(t.parsedType!==Jf.array)return tg(t,{code:Zf.invalid_type,expected:Jf.array,received:t.parsedType}),sg;if(null!==s.exactLength){const e=t.data.length>s.exactLength.value,n=t.data.length<s.exactLength.value;(e||n)&&(tg(t,{code:e?Zf.too_big:Zf.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&&(tg(t,{code:Zf.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&&(tg(t,{code:Zf.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 hg(t,e,t.path,r)))).then(e=>rg.mergeArray(r,e));const n=[...t.data].map((e,r)=>s.type._parseSync(new hg(t,e,t.path,r)));return rg.mergeArray(r,n)}get element(){return this._def.type}min(e,t){return new Yg({...this._def,minLength:{value:e,message:ug.toString(t)}})}max(e,t){return new Yg({...this._def,maxLength:{value:e,message:ug.toString(t)}})}length(e,t){return new Yg({...this._def,exactLength:{value:e,message:ug.toString(t)}})}nonempty(e){return this.min(1,e)}}function Xg(e){if(e instanceof ey){const t={};for(const r in e.shape){const s=e.shape[r];t[r]=gy.create(Xg(s))}return new ey({...e._def,shape:()=>t})}return e instanceof Yg?new Yg({...e._def,type:Xg(e.element)}):e instanceof gy?gy.create(Xg(e.unwrap())):e instanceof yy?yy.create(Xg(e.unwrap())):e instanceof ny?ny.create(e.items.map(e=>Xg(e))):e}Yg.create=(e,t)=>new Yg({type:e,minLength:null,maxLength:null,exactLength:null,typeName:wy.ZodArray,...mg(t)});class ey extends fg{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=zf.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==Jf.object){const t=this._getOrReturnCtx(e);return tg(t,{code:Zf.invalid_type,expected:Jf.object,received:t.parsedType}),sg}const{status:t,ctx:r}=this._processInputParams(e),{shape:s,keys:n}=this._getCached(),i=[];if(!(this._def.catchall instanceof Qg&&"strip"===this._def.unknownKeys))for(const a in r.data)n.includes(a)||i.push(a);const o=[];for(const a of n){const e=s[a],t=r.data[a];o.push({key:{status:"valid",value:a},value:e._parse(new hg(r,t,r.path,a)),alwaysSet:a in r.data})}if(this._def.catchall instanceof Qg){const e=this._def.unknownKeys;if("passthrough"===e)for(const t of i)o.push({key:{status:"valid",value:t},value:{status:"valid",value:r.data[t]}});else if("strict"===e)i.length>0&&(tg(r,{code:Zf.unrecognized_keys,keys:i}),t.dirty());else if("strip"!==e)throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const e=this._def.catchall;for(const t of i){const s=r.data[t];o.push({key:{status:"valid",value:t},value:e._parse(new hg(r,s,r.path,t)),alwaysSet:t in r.data})}}return r.common.async?Promise.resolve().then(async()=>{const e=[];for(const t of o){const r=await t.key,s=await t.value;e.push({key:r,value:s,alwaysSet:t.alwaysSet})}return e}).then(e=>rg.mergeObjectSync(t,e)):rg.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(e){return ug.errToObj,new ey({...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:ug.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new ey({...this._def,unknownKeys:"strip"})}passthrough(){return new ey({...this._def,unknownKeys:"passthrough"})}extend(e){return new ey({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new ey({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:wy.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new ey({...this._def,catchall:e})}pick(e){const t={};for(const r of zf.objectKeys(e))e[r]&&this.shape[r]&&(t[r]=this.shape[r]);return new ey({...this._def,shape:()=>t})}omit(e){const t={};for(const r of zf.objectKeys(this.shape))e[r]||(t[r]=this.shape[r]);return new ey({...this._def,shape:()=>t})}deepPartial(){return Xg(this)}partial(e){const t={};for(const r of zf.objectKeys(this.shape)){const s=this.shape[r];e&&!e[r]?t[r]=s:t[r]=s.optional()}return new ey({...this._def,shape:()=>t})}required(e){const t={};for(const r of zf.objectKeys(this.shape))if(e&&!e[r])t[r]=this.shape[r];else{let e=this.shape[r];for(;e instanceof gy;)e=e._def.innerType;t[r]=e}return new ey({...this._def,shape:()=>t})}keyof(){return uy(zf.objectKeys(this.shape))}}ey.create=(e,t)=>new ey({shape:()=>e,unknownKeys:"strip",catchall:Qg.create(),typeName:wy.ZodObject,...mg(t)}),ey.strictCreate=(e,t)=>new ey({shape:()=>e,unknownKeys:"strict",catchall:Qg.create(),typeName:wy.ZodObject,...mg(t)}),ey.lazycreate=(e,t)=>new ey({shape:e,unknownKeys:"strip",catchall:Qg.create(),typeName:wy.ZodObject,...mg(t)});class ty extends fg{_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 Yf(e.ctx.common.issues));return tg(t,{code:Zf.invalid_union,unionErrors:r}),sg});{let e;const s=[];for(const i of r){const r={...t,common:{...t.common,issues:[]},parent:null},n=i._parseSync({data:t.data,path:t.path,parent:r});if("valid"===n.status)return n;"dirty"!==n.status||e||(e={result:n,ctx:r}),r.common.issues.length&&s.push(r.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;const n=s.map(e=>new Yf(e));return tg(t,{code:Zf.invalid_union,unionErrors:n}),sg}}get options(){return this._def.options}}function ry(e,t){const r=Qf(e),s=Qf(t);if(e===t)return{valid:!0,data:e};if(r===Jf.object&&s===Jf.object){const r=zf.objectKeys(t),s=zf.objectKeys(e).filter(e=>-1!==r.indexOf(e)),n={...e,...t};for(const i of s){const r=ry(e[i],t[i]);if(!r.valid)return{valid:!1};n[i]=r.data}return{valid:!0,data:n}}if(r===Jf.array&&s===Jf.array){if(e.length!==t.length)return{valid:!1};const r=[];for(let s=0;s<e.length;s++){const n=ry(e[s],t[s]);if(!n.valid)return{valid:!1};r.push(n.data)}return{valid:!0,data:r}}return r===Jf.date&&s===Jf.date&&+e===+t?{valid:!0,data:e}:{valid:!1}}ty.create=(e,t)=>new ty({options:e,typeName:wy.ZodUnion,...mg(t)});class sy extends fg{_parse(e){const{status:t,ctx:r}=this._processInputParams(e),s=(e,s)=>{if(og(e)||og(s))return sg;const n=ry(e.value,s.value);return n.valid?((ag(e)||ag(s))&&t.dirty(),{status:t.value,value:n.data}):(tg(r,{code:Zf.invalid_intersection_types}),sg)};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}))}}sy.create=(e,t,r)=>new sy({left:e,right:t,typeName:wy.ZodIntersection,...mg(r)});class ny extends fg{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==Jf.array)return tg(r,{code:Zf.invalid_type,expected:Jf.array,received:r.parsedType}),sg;if(r.data.length<this._def.items.length)return tg(r,{code:Zf.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),sg;!this._def.rest&&r.data.length>this._def.items.length&&(tg(r,{code:Zf.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 hg(r,e,r.path,t)):null}).filter(e=>!!e);return r.common.async?Promise.all(s).then(e=>rg.mergeArray(t,e)):rg.mergeArray(t,s)}get items(){return this._def.items}rest(e){return new ny({...this._def,rest:e})}}ny.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ny({items:e,typeName:wy.ZodTuple,rest:null,...mg(t)})};class iy extends fg{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!==Jf.object)return tg(r,{code:Zf.invalid_type,expected:Jf.object,received:r.parsedType}),sg;const s=[],n=this._def.keyType,i=this._def.valueType;for(const o in r.data)s.push({key:n._parse(new hg(r,o,r.path,o)),value:i._parse(new hg(r,r.data[o],r.path,o)),alwaysSet:o in r.data});return r.common.async?rg.mergeObjectAsync(t,s):rg.mergeObjectSync(t,s)}get element(){return this._def.valueType}static create(e,t,r){return new iy(t instanceof fg?{keyType:e,valueType:t,typeName:wy.ZodRecord,...mg(r)}:{keyType:Bg.create(),valueType:e,typeName:wy.ZodRecord,...mg(t)})}}class oy extends fg{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!==Jf.map)return tg(r,{code:Zf.invalid_type,expected:Jf.map,received:r.parsedType}),sg;const s=this._def.keyType,n=this._def.valueType,i=[...r.data.entries()].map(([e,t],i)=>({key:s._parse(new hg(r,e,r.path,[i,"key"])),value:n._parse(new hg(r,t,r.path,[i,"value"]))}));if(r.common.async){const e=new Map;return Promise.resolve().then(async()=>{for(const r of i){const s=await r.key,n=await r.value;if("aborted"===s.status||"aborted"===n.status)return sg;"dirty"!==s.status&&"dirty"!==n.status||t.dirty(),e.set(s.value,n.value)}return{status:t.value,value:e}})}{const e=new Map;for(const r of i){const s=r.key,n=r.value;if("aborted"===s.status||"aborted"===n.status)return sg;"dirty"!==s.status&&"dirty"!==n.status||t.dirty(),e.set(s.value,n.value)}return{status:t.value,value:e}}}}oy.create=(e,t,r)=>new oy({valueType:t,keyType:e,typeName:wy.ZodMap,...mg(r)});class ay extends fg{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==Jf.set)return tg(r,{code:Zf.invalid_type,expected:Jf.set,received:r.parsedType}),sg;const s=this._def;null!==s.minSize&&r.data.size<s.minSize.value&&(tg(r,{code:Zf.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&&(tg(r,{code:Zf.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),t.dirty());const n=this._def.valueType;function i(e){const r=new Set;for(const s of e){if("aborted"===s.status)return sg;"dirty"===s.status&&t.dirty(),r.add(s.value)}return{status:t.value,value:r}}const o=[...r.data.values()].map((e,t)=>n._parse(new hg(r,e,r.path,t)));return r.common.async?Promise.all(o).then(e=>i(e)):i(o)}min(e,t){return new ay({...this._def,minSize:{value:e,message:ug.toString(t)}})}max(e,t){return new ay({...this._def,maxSize:{value:e,message:ug.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}ay.create=(e,t)=>new ay({valueType:e,minSize:null,maxSize:null,typeName:wy.ZodSet,...mg(t)});class cy extends fg{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})}}cy.create=(e,t)=>new cy({getter:e,typeName:wy.ZodLazy,...mg(t)});class dy extends fg{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return tg(t,{received:t.data,code:Zf.invalid_literal,expected:this._def.value}),sg}return{status:"valid",value:e.data}}get value(){return this._def.value}}function uy(e,t){return new ly({values:e,typeName:wy.ZodEnum,...mg(t)})}dy.create=(e,t)=>new dy({value:e,typeName:wy.ZodLiteral,...mg(t)});class ly extends fg{_parse(e){if("string"!=typeof e.data){const t=this._getOrReturnCtx(e),r=this._def.values;return tg(t,{expected:zf.joinValues(r),received:t.parsedType,code:Zf.invalid_type}),sg}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 tg(t,{received:t.data,code:Zf.invalid_enum_value,options:r}),sg}return ig(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 ly.create(e,{...this._def,...t})}exclude(e,t=this._def){return ly.create(this.options.filter(t=>!e.includes(t)),{...this._def,...t})}}ly.create=uy;class hy extends fg{_parse(e){const t=zf.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==Jf.string&&r.parsedType!==Jf.number){const e=zf.objectValues(t);return tg(r,{expected:zf.joinValues(e),received:r.parsedType,code:Zf.invalid_type}),sg}if(this._cache||(this._cache=new Set(zf.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const e=zf.objectValues(t);return tg(r,{received:r.data,code:Zf.invalid_enum_value,options:e}),sg}return ig(e.data)}get enum(){return this._def.values}}hy.create=(e,t)=>new hy({values:e,typeName:wy.ZodNativeEnum,...mg(t)});class py extends fg{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==Jf.promise&&!1===t.common.async)return tg(t,{code:Zf.invalid_type,expected:Jf.promise,received:t.parsedType}),sg;const r=t.parsedType===Jf.promise?t.data:Promise.resolve(t.data);return ig(r.then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}}py.create=(e,t)=>new py({type:e,typeName:wy.ZodPromise,...mg(t)});class fy extends fg{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===wy.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=>{tg(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 sg;const s=await this._def.schema._parseAsync({data:e,path:r.path,parent:r});return"aborted"===s.status?sg:"dirty"===s.status||"dirty"===t.value?ng(s.value):s});{if("aborted"===t.value)return sg;const s=this._def.schema._parseSync({data:e,path:r.path,parent:r});return"aborted"===s.status?sg:"dirty"===s.status||"dirty"===t.value?ng(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?sg:("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?sg:("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(!cg(e))return sg;const i=s.transform(e.value,n);if(i instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:i}}return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(e=>cg(e)?Promise.resolve(s.transform(e.value,n)).then(e=>({status:t.value,value:e})):sg)}zf.assertNever(s)}}fy.create=(e,t,r)=>new fy({schema:e,typeName:wy.ZodEffects,effect:t,...mg(r)}),fy.createWithPreprocess=(e,t,r)=>new fy({schema:t,effect:{type:"preprocess",transform:e},typeName:wy.ZodEffects,...mg(r)});class gy extends fg{_parse(e){return this._getType(e)===Jf.undefined?ig(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}gy.create=(e,t)=>new gy({innerType:e,typeName:wy.ZodOptional,...mg(t)});class yy extends fg{_parse(e){return this._getType(e)===Jf.null?ig(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}yy.create=(e,t)=>new yy({innerType:e,typeName:wy.ZodNullable,...mg(t)});class vy extends fg{_parse(e){const{ctx:t}=this._processInputParams(e);let r=t.data;return t.parsedType===Jf.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}vy.create=(e,t)=>new vy({innerType:e,typeName:wy.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...mg(t)});class Iy extends fg{_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 dg(s)?s.then(e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new Yf(r.common.issues)},input:r.data})})):{status:"valid",value:"valid"===s.status?s.value:this._def.catchValue({get error(){return new Yf(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}Iy.create=(e,t)=>new Iy({innerType:e,typeName:wy.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...mg(t)});class by extends fg{_parse(e){if(this._getType(e)!==Jf.nan){const t=this._getOrReturnCtx(e);return tg(t,{code:Zf.invalid_type,expected:Jf.nan,received:t.parsedType}),sg}return{status:"valid",value:e.data}}}by.create=e=>new by({typeName:wy.ZodNaN,...mg(e)});class _y extends fg{_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 Ty extends fg{_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?sg:"dirty"===e.status?(t.dirty(),ng(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?sg:"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 Ty({in:e,out:t,typeName:wy.ZodPipeline})}}class Cy extends fg{_parse(e){const t=this._def.innerType._parse(e),r=e=>(cg(e)&&(e.value=Object.freeze(e.value)),e);return dg(t)?t.then(e=>r(e)):r(t)}unwrap(){return this._def.innerType}}function Sy(e,t){const r="function"==typeof e?e(t):"string"==typeof e?{message:e}:e;return"string"==typeof r?{message:r}:r}function Ey(e,t={},r){return e?Wg.create().superRefine((s,n)=>{const i=e(s);if(i instanceof Promise)return i.then(e=>{if(!e){const e=Sy(t,s),i=e.fatal??r??!0;n.addIssue({code:"custom",...e,fatal:i})}});if(!i){const e=Sy(t,s),i=e.fatal??r??!0;n.addIssue({code:"custom",...e,fatal:i})}}):Wg.create()}var wy,Ry;Cy.create=(e,t)=>new Cy({innerType:e,typeName:wy.ZodReadonly,...mg(t)}),(Ry=wy||(wy={})).ZodString="ZodString",Ry.ZodNumber="ZodNumber",Ry.ZodNaN="ZodNaN",Ry.ZodBigInt="ZodBigInt",Ry.ZodBoolean="ZodBoolean",Ry.ZodDate="ZodDate",Ry.ZodSymbol="ZodSymbol",Ry.ZodUndefined="ZodUndefined",Ry.ZodNull="ZodNull",Ry.ZodAny="ZodAny",Ry.ZodUnknown="ZodUnknown",Ry.ZodNever="ZodNever",Ry.ZodVoid="ZodVoid",Ry.ZodArray="ZodArray",Ry.ZodObject="ZodObject",Ry.ZodUnion="ZodUnion",Ry.ZodDiscriminatedUnion="ZodDiscriminatedUnion",Ry.ZodIntersection="ZodIntersection",Ry.ZodTuple="ZodTuple",Ry.ZodRecord="ZodRecord",Ry.ZodMap="ZodMap",Ry.ZodSet="ZodSet",Ry.ZodFunction="ZodFunction",Ry.ZodLazy="ZodLazy",Ry.ZodLiteral="ZodLiteral",Ry.ZodEnum="ZodEnum",Ry.ZodEffects="ZodEffects",Ry.ZodNativeEnum="ZodNativeEnum",Ry.ZodOptional="ZodOptional",Ry.ZodNullable="ZodNullable",Ry.ZodDefault="ZodDefault",Ry.ZodCatch="ZodCatch",Ry.ZodPromise="ZodPromise",Ry.ZodBranded="ZodBranded",Ry.ZodPipeline="ZodPipeline",Ry.ZodReadonly="ZodReadonly";const Ay=Bg.create,Ny=qg.create,Oy=jg.create;Wg.create;const My=Jg.create,Uy=Qg.create,Ly=Yg.create,ky=ey.create,Dy=ty.create;sy.create,ny.create;const Py=iy.create,xy=ly.create;py.create,gy.create,yy.create;class Fy{static validate(e,t){try{return{success:!0,data:e.parse(t)}}catch(r){if(r instanceof Yf){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)?ot.VALIDATION_REQUIRED:ot.VALIDATION_INVALID_FORMAT;return{success:!1,error:new mt(t,{code:s,details:{fields:e}})}}return{success:!1,error:new mt("Unknown validation error",{code:ot.VALIDATION_UNKNOWN,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 mt("Unknown validation error",{code:ot.VALIDATION_UNKNOWN,details:{fields:[]}})}static safeParse(e,t){return this.validate(e,t)}}const By=e=>Ay().regex(/^https?:\/\/\S+$/i,e),Gy=ky({appKey:Ay().min(1,"appKey is required").optional(),appId:Ay().min(1,"appId is required").optional(),enableUserInfoSync:Oy().optional(),enableSyncData:Ly(xy(["conversation","contact","group"])).optional(),enableDeliveryReceipt:Oy().optional(),deleteConversationOnGroupDestroyed:Oy().optional(),syncConversationListConfig:ky({includeEmpty:Oy().optional()}).strict().optional(),useCustomAttachmentUpload:Oy().optional(),useFixedDeviceId:Oy().optional(),deviceId:Ay().min(1,"deviceId is required").optional(),serviceConfig:ky({dnsConfigUrls:Ly(By("serviceConfig.dnsConfigUrls item must be a valid URL")).nonempty().optional(),serverUrls:ky({restApiUrl:By("serviceConfig.serverUrls.restApiUrl must be a valid URL").optional(),wsUrl:(qy="serviceConfig.serverUrls.wsUrl must be a valid URL",Ay().regex(/^wss?:\/\/\S+$/i,qy)).optional()}).optional()}).optional(),useReplacedMessageContents:Oy().optional(),customDeviceName:Ay().min(1,"customDeviceName is required").optional(),customOSPlatform:Ny().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:Ay().min(1,"uiKitVersion is required").optional(),loginExtensionInfo:Ay().max(1024,"loginExtensionInfo must be at most 1024 characters").optional(),managers:Ly(My()).optional(),platformAdapterOptions:ky({prefer:xy(["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:Ey(e=>"object"==typeof e&&null!==e).optional(),transportAdapter:Ey(e=>"object"==typeof e&&null!==e).optional(),overrides:Ey(e=>"object"==typeof e&&null!==e||"function"==typeof e).optional()}).strict().optional()}).passthrough().superRefine((e,t)=>{const r=Number(void 0!==e.appKey)+Number(void 0!==e.appId);0===r?t.addIssue({code:Zf.custom,path:["appKey"],message:"appKey or appId is required"}):r>1&&t.addIssue({code:Zf.custom,path:["appId"],message:"appKey and appId cannot be used together"}),"enableMd5Check"in e&&t.addIssue({code:Zf.custom,path:["enableMd5Check"],message:"enableMd5Check is removed; attachment precheck is controlled by DNS_CONFIG"}),"enableHttpDns"in e&&t.addIssue({code:Zf.custom,path:["enableHttpDns"],message:"enableHttpDns is removed; configure serviceConfig.serverUrls for fixed URLs"}),"dnsConfigUrls"in e&&t.addIssue({code:Zf.custom,path:["dnsConfigUrls"],message:"dnsConfigUrls is moved to serviceConfig.dnsConfigUrls"}),"serverUrls"in e&&t.addIssue({code:Zf.custom,path:["serverUrls"],message:"serverUrls is moved to serviceConfig.serverUrls"}),"profileSync"in e&&t.addIssue({code:Zf.custom,path:["profileSync"],message:"profileSync is internal; profile sync scheduling uses SDK defaults"}),"cacheEncryptionMode"in e&&t.addIssue({code:Zf.custom,path:["cacheEncryptionMode"],message:"cacheEncryptionMode is internal; cache encryption defaults to auto"}),"enableAutoSyncContacts"in e&&t.addIssue({code:Zf.custom,path:["enableAutoSyncContacts"],message:"enableAutoSyncContacts is removed; use enableSyncData: ['contact']"});const s=e.serviceConfig&&"object"==typeof e.serviceConfig?e.serviceConfig:void 0,n=s?.serverUrls&&"object"==typeof s.serverUrls?s.serverUrls:void 0;s?.dnsConfigUrls&&n&&t.addIssue({code:Zf.custom,path:["serviceConfig"],message:"serviceConfig.dnsConfigUrls and serviceConfig.serverUrls cannot be used together"}),n&&(void 0!==e.appId&&t.addIssue({code:Zf.custom,path:["serviceConfig","serverUrls"],message:"serviceConfig.serverUrls cannot be used when initialized with appId"}),n?.restApiUrl||t.addIssue({code:Zf.custom,path:["serviceConfig","serverUrls","restApiUrl"],message:"serviceConfig.serverUrls.restApiUrl is required when serverUrls is configured"}),n?.wsUrl||t.addIssue({code:Zf.custom,path:["serviceConfig","serverUrls","wsUrl"],message:"serviceConfig.serverUrls.wsUrl is required when serverUrls is configured"}))});var qy;const $y=ky({userId:Ay().min(1,"userId is required"),token:Ay().min(1,"token is required")}),jy=ky({timeoutMs:Ny().int("timeoutMs must be an integer").min(5e3,"timeoutMs must be at least 5000").max(Zr,"timeoutMs must be at most 120000").optional()}).strict(),Vy=Ay().trim().min(1,"token is required"),Ky=ky({channelName:Ay().trim().min(1,"channelName is required").optional()}).optional(),zy=Ly(Ny({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))),Hy=ky({protocol:Ay(),domain:Ay().optional(),ip:Ay().optional(),port:Dy([Ay(),Ny()]).optional()}).passthrough(),Wy=ky({app_key:Ay().optional(),rest:ky({hosts:Ly(Hy).nonempty()}),"msync-wx":ky({hosts:Ly(Hy).nonempty()}),"sync-ws":ky({hosts:Ly(Hy).nonempty()}).optional(),enableReportLogs:xy(["true","false"]).optional(),reportInterval:Ny().positive().finite().optional(),enableDataReport:xy(["true","false"]).optional(),enableMd5Check:xy(["true","false"]).optional(),uploadinparts_enable:xy(["true","false"]).optional()}).passthrough(),Jy=e=>encodeURIComponent(e).replace(/[!'()~]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`).replace(/%20/g,"+"),Qy=e=>"function"==typeof URLSearchParams?new URLSearchParams(e):(e=>{const t=new Map;if(e)for(const[r,s]of Object.entries(e))t.set(r,s);return{set(e,r){t.set(e,r)},toString:()=>Array.from(t,([e,t])=>`${Jy(e)}=${Jy(t)}`).join("&")}})(e),Zy="5.1.2",Yy=["https://rs.chat.rtnsvc.com","https://rs.easemob.com","https://rs.chat.realtimemesh.com"],Xy=["msync-wx","msync-ws","msync","msync-web","websocket","websocket-im","im-websocket","im-ws","socket"];function ev(e){return"object"==typeof e&&null!==e}function tv(e){return Array.isArray(e)?{hosts:e}:function(e){return ev(e)&&"hosts"in e&&Array.isArray(e.hosts)}(e)?{hosts:e.hosts}:void 0}function rv(e){if(!ev(e))return Fy.validateOrThrow(Wy,e);const t=tv(e.rest),r=function(e,t,r){for(const s of t){const t=tv(e[s]);if(t)return{key:s,section:t}}for(const[s,n]of Object.entries(e)){if(!r(s))continue;const e=tv(n);if(e)return{key:s,section:e}}}(e,Xy,e=>{const t=e.toLowerCase();return t.includes("msync")||t.includes("websocket")||"socket"===t||"im-ws"===t}),s={...e,rest:t??e.rest,"msync-wx":r?.section},n="true"===(i=e.enableReportLogs)||!0===i?"true":"false"===i||!1===i?"false":void 0;var i;n&&(s.enableReportLogs=n);const o=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!==o?s.reportInterval=o:delete s.reportInterval;const a=function(e){if("true"===e||"false"===e)return e}(e.enableDataReport);a?s.enableDataReport=a:delete s.enableDataReport;const c=function(e){if("true"===e||"false"===e)return e}(e.enableMd5Check);c?s.enableMd5Check=c:delete s.enableMd5Check;const d=function(e){if("true"===e||"false"===e)return e}(e.uploadinparts_enable);return d?s.uploadinparts_enable=d:delete s.uploadinparts_enable,r&&"msync-wx"!==r.key&&Vs("DNS config websocket section normalized",{sourceKey:r.key}),Fy.validateOrThrow(Wy,s)}function sv(e,t){const r=e.domain||e.ip;if(!r)throw new mt("DNS host missing domain/ip",{code:ot.VALIDATION_REQUIRED,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 nv(e,t){return"https"===e?"https":"http"===e?"http":t}function iv(e,t){const r=e.domain||e.ip;if(!r)throw new mt("DNS rest host missing domain/ip",{code:ot.VALIDATION_REQUIRED,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 ov(e,t){const r=e.filter(e=>e.protocol===t);return r.length>0?r:"http"===t?e.filter(e=>"https"===e.protocol):[]}function av(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 cv(e,t,r,s){const n=new Vf(e,{requestAdapter:r,includeRequestId:!0});let i="/easemob/server.json",o=!0;try{const t=new URL(e),r=""!==t.pathname&&"/"!==t.pathname,s=""!==t.search;(r||s)&&(i="",o=!1)}catch{i="/easemob/server.json",o=!0}if(o){i=`${i}?${(void 0!==t.appId?Qy({app_id:t.appId,sdk_version:Zy,file_version:"1"}):Qy({app_key:t.appKey,_v:String(Date.now())})).toString()}`}return rv(await n.get(i,{timeout:s}))}async function dv(e){const t=e.baseUrls&&e.baseUrls.length>0?e.baseUrls:Yy;if(0===t.length)throw new mt("DNS_CONFIG list is empty",{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:"serviceConfig.dnsConfigUrls",message:"DNS_CONFIG list is empty",rule:"required"}]}});const r=e.pageProtocol??("undefined"==typeof window||"https:"===window.location?.protocol?"https":"http");let s;for(const o of t){const t=e.loginDeadline,n=t?.remainingMs();if(t&&void 0!==n&&n<=0)throw t.createTimeoutError();try{const t=void 0!==e.appId?{appId:e.appId}:{appKey:e.appKey},s=void 0===n?void 0:Math.min(15e3,n),i=await cv(o,t,e.requestAdapter,s),a=void 0!==e.appId?i.app_key:e.appKey;if("string"!=typeof a||0===a.length)throw new mt("DNS app_key is required for appId initialization",{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:"dns.app_key",message:"DNS app_key is required for appId initialization",rule:"required"}]}});const c=av(ov(i["msync-wx"].hosts,r));if(0===c.length)throw new mt("DNS msync-wx hosts resolution failed",{code:ot.VALIDATION_INVALID_FORMAT,details:{fields:[{path:"dns.msync-wx.hosts",message:"DNS msync-wx hosts resolution failed",rule:"invalid_format"}]}});const d=c[0];if(!d)throw new mt("DNS msync-wx hosts resolution failed",{code:ot.VALIDATION_INVALID_FORMAT,details:{fields:[{path:"dns.msync-wx.hosts",message:"DNS msync-wx hosts resolution failed",rule:"invalid_format"}]}});const u=ov(i.rest.hosts,r);if(0===u.length)throw new mt("DNS rest hosts resolution failed",{code:ot.VALIDATION_INVALID_FORMAT,details:{fields:[{path:"dns.rest.hosts",message:"DNS rest hosts resolution failed",rule:"invalid_format"}]}});const l=u[0];if(!l)throw new mt("DNS rest hosts resolution failed",{code:ot.VALIDATION_INVALID_FORMAT,details:{fields:[{path:"dns.rest.hosts",message:"DNS rest hosts resolution failed",rule:"invalid_format"}]}});const h=c.map(e=>sv(e,nv(e.protocol,r))),p=sv(d,nv(d.protocol,r));return{appKey:a,websocketUrl:p,websocketUrls:h,baseUrl:o,restBaseUrl:iv(l,nv(l.protocol,r)),dnsConfig:i}}catch(i){if(t&&t.remainingMs()<=0)throw t.createTimeoutError();Vs("DNS config candidate failed",{baseUrl:o,reason:i instanceof Error?i.message:String(i),error:i instanceof Error&&"function"==typeof i.toJSON?i.toJSON():i}),s=i}}const n={stage:"dns"};throw s&&(n.reason=s.message,"code"in s&&"number"==typeof s.code&&(n.causeCode=s.code)),new ht("DNS_CONFIG exhausted",{code:ot.CONNECTION_DNSLIST_FAILED,details:n})}const uv=e=>{const t=(e=>{const t=e.trim(),r=/^(https?):\/\//i.exec(t);if(!r?.[1])throw new mt("REST API URL must use http or https protocol");const s=r[1].toLowerCase(),n=t.slice(r[0].length),i=n.search(/[/?#]/),o=i>=0?n.slice(0,i):n,a=o.lastIndexOf("@"),c=a>=0?o.slice(a+1):o;if(!c)throw new mt("REST API URL host is required");let d,u;if(c.startsWith("[")){const e=c.indexOf("]");if(e<=1)throw new mt("REST API URL IPv6 host is invalid");d=c.slice(0,e+1);const t=c.slice(e+1);if(t){if(!t.startsWith(":"))throw new mt("REST API URL authority is invalid");u=t.slice(1)}}else{const e=c.lastIndexOf(":");if(e>=0){if(c.indexOf(":")!==e)throw new mt("REST API URL IPv6 host must use brackets");d=c.slice(0,e),u=c.slice(e+1)}else d=c}if(!d)throw new mt("REST API URL host is required");if(void 0!==u){const e=Number(u);if(!/^\d+$/.test(u)||e<1||e>65535)throw new mt("REST API URL port is invalid")}return{protocol:s,host:d,port:u}})(e),r="http"===t.protocol&&"80"===t.port||"https"===t.protocol&&"443"===t.port,s="https"===t.protocol?"wss":"ws",n=t.port&&!r?`:${t.port}`:"";return`${s}://${t.host}${n}/ws`},lv=e=>new mt(e,{code:ot.VALIDATION_INVALID_FORMAT,details:{reason:"invalid_rest_response"}}),hv=e=>{if(!pu(e))throw lv("Invalid REST response");return pu(e.data)?e.data:e},pv=(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}}},mv=(e,t)=>{for(const r of t){const t=e[r];if("string"==typeof t)return t}},fv=e=>{const{orgName:t,appName:r}=fs(e.appKey);return`/${t}/${r}`},gv=async(e,t)=>{const r=await e.get((e=>`${fv(e)}/sdk/users/${encodeURIComponent(e.userId)}/token/expires`)(t),{operation:"getTokenExpireTimestamp"});return(e=>{const t=hv(e),r=pv(t,["expire_timestamp","expireTimestamp","expireAt"]);if(void 0===r)throw lv("Invalid token expires response");return r})(r)},yv=async(e,t,r)=>{const s=await e.get(((e,t)=>{const r=Qy({channelName:t?.channelName??"*"});return`${fv(e)}/users/${encodeURIComponent(e.userId)}/token/rtc?${r.toString()}`})(t,r),{operation:"getRtcTokenInfo"});return(e=>{const t=hv(e);return{appId:mv(t,["app_id","appId"])??"",rtcToken:mv(t,["rtc_token","rtcToken","RTCToken"])??"",channelName:mv(t,["channel_name","channelName"])??"",rtcUid:pv(t,["rtcUid","RTCUId","rtc_uid"])??0,expireAt:pv(t,["expires_in","expire","expireAt"])??0}})(s)},vv=async(e,t,r)=>{const s=await e.post((e=>`${fv(e)}/rtc_mapper/batch/get`)(t),{data:r},{operation:"getUserIdsWithRtcUids"});return(e=>{const t=hv(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)},Iv=async(e,t)=>{const r=await e.get((e=>`${fv(e)}/users/${encodeURIComponent(e.userId)}/resources`)(t),{operation:"getSelfIdsOnOtherPlatform"});return((e,t)=>{const r=pu(e)&&Array.isArray(e.data)?e.data:[],s=[];for(const n of r){if(!pu(n))continue;const e=mv(n,["res","resource","clientResource"]);e&&e!==t.clientResource&&s.push(`${t.userId}/${e}`)}return s})(r,t)},bv=(...e)=>{const t={},r={};for(const s of e)Object.assign(t,s.common),Object.assign(r,s.apis);return{common:t,apis:r}},_v={common:{validation:{range:"100-110",errors:{MISSING_REQUIRED:{code:110},INVALID_FORMAT:{code:110},UNKNOWN:{code:110}}},auth:{range:"108,200-215",errors:{ALREADY_LOGIN:{code:200},NOT_LOGIN:{code:201},UNAUTHORIZED:{code:202},FORBIDDEN:{code:210},TOKEN_EXPIRED:{code:108},BIND_ANOTHER_DEVICE:{code:213},LOGIN_TOO_MANY_DEVICES:{code:214},USER_MUTED:{code:215}}},connection:{range:"1,100,202,300-304",errors:{TIMEOUT:{code:301},LOGIN_TIMEOUT:{code:301},WEBSOCKET_ERROR:{code:300},NOT_CREATED:{code:1},CLOSED_BEFORE_READY:{code:300},CANCELLED:{code:1},PROVISION_TIMEOUT:{code:301},PROVISION_REJECTED:{code:202},PROVISION_CLOSED:{code:300},DNSLIST_FAILED:{code:304},SERVER_BUSY:{code:302}}},storage:{range:"3",errors:{OPERATION_FAILED:{code:3}}},message:{range:"1,300-511",errors:{NOT_CONNECTED:{code:300},ACK_TIMEOUT:{code:301},SEND_FAILED:{code:303},SENDER_DESTROYED:{code:1},ENCODE_FAILED:{code:500},DECODE_FAILED:{code:500},ACK_MISSING:{code:301}}},transport:{range:"2,301,303",errors:{NETWORK_ERROR:{code:2},TIMEOUT:{code:301},HTTP_ERROR:{code:303},BUSINESS_UNKNOWN:{code:303}}},upload:{range:"1,100,110,301,402,405",errors:{REQUIRED_FIELD_MISSING:{code:110},INVALID_APPKEY:{code:100},SIZE_EXCEEDED:{code:405},REQUEST_FAILED:{code:402},TIMEOUT:{code:301},ABORTED:{code:1}}},unknown:{range:"1,4",errors:{UNKNOWN:{code:1},SERVICE_LIMIT_EXCEEDED:{code:4}}},push:{range:"1500,1501,1502",errors:{TOKEN_UPLOAD_FAILED:{code:1500},SILENT_MODE_OPERATION_FAILED:{code:1501},PUSH_LANGUAGE_OPERATION_FAILED:{code:1502}}},chatroom:{range:"700-707",errors:{CHATROOM_INVALID_ID:{code:700},CHATROOM_NOT_JOINED:{code:702},CHATROOM_PERMISSION_DENIED:{code:703},CHATROOM_MEMBERS_FULL:{code:704},CHATROOM_NOT_EXIST:{code:705},CHATROOM_OWNER_NOT_ALLOW_LEAVE:{code:706},CHATROOM_USER_IN_BLOCKLIST:{code:707}}}},apis:{}},Tv=e=>({userId:e}),Cv=e=>({userId:e.userId,nickname:e.nickname,avatarUrl:e.avatarUrl,sign:e.sign,ext:e.ext}),Sv=e=>e,Ev=async(e,t)=>{const r=(e=>{const t=[],r=new Set;for(const s of e){const e=s.trim();e&&!r.has(e)&&(r.add(e),t.push(e))}return t})(e),s=new Map;if(0===r.length)return s;const n=t.cacheManager?.getUserInfoSummaries(r,!1)??[];for(const o of n)s.set(o.userId,Cv(o));const i=r.filter(e=>!s.has(e));if(i.length>0&&t.fetchUserInfos){const e=await t.fetchUserInfos({userIds:i});for(const t of e)s.set(t.userId,Sv(t))}for(const o of r)s.has(o)||s.set(o,Tv(o));return s};class wv{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=>{Vs("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 Rv{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(Vs("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)}}class Av{constructor(e,t,r=Date.now){this.attemptId=e,this.timeoutMs=t,this.now=r,this.timeoutId=null,this.status="active",this.expiresAt=this.now()+t,this.timeoutPromise=new Promise((e,r)=>{this.timeoutId=setTimeout(()=>{"active"===this.status&&(this.status="expired",this.timeoutId=null,r(this.createTimeoutError()))},t)}),this.timeoutPromise.catch(()=>{})}getStatus(){return this.status}remainingMs(){return"expired"===this.status?0:Math.max(0,this.expiresAt-this.now())}clamp(e){return Math.max(0,Math.min(e,this.remainingMs()))}race(e){return"expired"===this.status||0===this.remainingMs()?(e.catch(()=>{}),this.expire(),Promise.reject(this.createTimeoutError())):"active"!==this.status?e:Promise.race([e,this.timeoutPromise])}markProvisionReceived(){return"active"===this.status&&(this.status="provision-received",this.clearTimer(),!0)}expire(){"active"===this.status&&(this.status="expired",this.clearTimer())}dispose(){"active"===this.status&&(this.status="disposed"),this.clearTimer()}createTimeoutError(){return new ht("Login timeout",{code:ot.CONNECTION_LOGIN_TIMEOUT,details:{stage:"login",timeoutMs:this.timeoutMs,attemptId:this.attemptId,retryable:!0}})}clearTimer(){null!==this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null)}}const Nv=0,Ov=1,Mv=2,Uv=3,Lv=4,kv=5,Dv=0,Pv=0,xv=1,Fv=1001,Bv=1002,Gv=1003,qv=1004,$v=1005,jv=1101,Vv=bv(_v,{common:{},apis:{getSelfIdsOnOtherPlatform:{range:"202,300-303",errors:{}},getTokenExpireTimestamp:{range:"",errors:{}},getRtcTokenInfo:{range:"",errors:{}},getUserIdsWithRtcUids:{range:"",errors:{}}}}),Kv=class e{constructor(e){this.core=null,this.cacheManager=null,this.cacheUserId=null,this.state=t,this.loginAttempt=0,this.currentUserId=null,this.activeAppKey=null,this.logReportEnabled=!1,this.restBaseUrl=null,this.authToken=null,this.clientResource=null,this.platformAdapter=null,this.contactSyncController=null,this.groupSyncController=null,this.syncConversationListConfigController=null,this.syncWebSocketSession=null,this.contactSyncWsUrls=[],this.syncConversationListConfigWsUrls=[],this.contactSyncDnsResolved=!1,this.conversationListVersion=0,this.conversationListSnapshot=[],this.activeIncomingStreamMessageIds=new Set,this.managerSessionGeneration=0,this.activeManagerSessionContext=null,this.managerSessionEndingPromise=null,this.postLoginTaskContext=null,this.terminalSessionCleanupTask=null,this.config={appKey:e.appKey,appId:e.appId,enableUserInfoSync:e.enableUserInfoSync,enableSyncData:[...e.enableSyncData],enableDeliveryReceipt:e.enableDeliveryReceipt,deleteConversationOnGroupDestroyed:e.deleteConversationOnGroupDestroyed,syncConversationListConfig:{...e.syncConversationListConfig},useCustomAttachmentUpload:e.useCustomAttachmentUpload,enableMd5Check:e.enableMd5Check,serviceConfig:{mode:e.serviceConfig.mode,dnsConfigUrls:[...e.serviceConfig.dnsConfigUrls],hasCustomDnsConfigUrls:e.serviceConfig.hasCustomDnsConfigUrls,serverUrls:e.serviceConfig.serverUrls},useFixedDeviceId:e.useFixedDeviceId,deviceId:e.deviceId,useReplacedMessageContents:e.useReplacedMessageContents,customDeviceName:e.customDeviceName,customOSPlatform:e.customOSPlatform,uiKitVersion:e.uiKitVersion,loginExtensionInfo:e.loginExtensionInfo,cacheEncryptionMode:e.cacheEncryptionMode,profileSync:{...e.profileSync},platformAdapterOptions:e.platformAdapterOptions},this.activeAppKey=this.config.appKey??null,this.config.platformAdapterOptions&&(this.platformAdapter=Dd(this.config.platformAdapterOptions)),this.managerRegistry=new Map,this.managerCapabilities=new Map,this.eventHub=new Pm,Ls=e=>{this.eventHub.dispatch(V.LOG,e)},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 Rv({windowMs:this.config.profileSync.userInfoWindowMs,batchSize:this.config.profileSync.userInfoBatchSize,maxConcurrency:3,maxRetries:1,onFlush:async e=>{await this.flushUserInfoHydrationTargets(e)}}),this.groupNamecardHydrationQueue=new wv({windowMs:this.config.profileSync.groupNamecardWindowMs,minWindowMs:1e3,maxBatchSize:50,maxConcurrency:this.config.profileSync.groupNamecardMaxConcurrency,onFlushGroup:async e=>{await this.flushGroupNamecardHydrationBatch(e)}}),this.eventHub.addEventHandler("__internal:chat-client",{[o]:e=>{this.updateState(e.state)},[a]:e=>{this.updateState(e.state)},[c]:e=>{this.updateState(e.state),this.isTerminalManagerSessionDisconnect(e)&&this.startTerminalSessionCleanup(e)},[d]:e=>{this.updateState(e.state)},[M]:e=>{this.handleIncomingConversationMessage(e),this.handleIncomingMessageProfileSync(e)},[U]:e=>{this.handleIncomingConversationStreamMessage(e)},[I]:e=>{this.handleOutgoingConversationMessage(e)},[G]:e=>{this.handleMultiDeviceContactEvent(e)},[q]:e=>{if("CONVERSATION_DELETED"===e.operation)return this.handleMultiDeviceConversationEvent(e)},[W]:e=>this.handleIncomingContactRosterEvent("add",e),[Q]:e=>this.handleIncomingContactRosterEvent("add",e),[z]:e=>this.handleIncomingContactRosterEvent("none",e),[J]: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===ie&&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=Fy.validateOrThrow(Gy,t),s=r.customOSPlatform,n=e.normalizeServiceConfig(r.serviceConfig),i={appKey:r.appKey,appId:r.appId,enableUserInfoSync:r.enableUserInfoSync??!1,enableSyncData:e.normalizeSyncDataTypes(r.enableSyncData??["conversation"]),enableDeliveryReceipt:r.enableDeliveryReceipt??!1,deleteConversationOnGroupDestroyed:r.deleteConversationOnGroupDestroyed??!0,syncConversationListConfig:{includeEmpty:r.syncConversationListConfig?.includeEmpty??!1,includeMark:!0},useCustomAttachmentUpload:r.useCustomAttachmentUpload??!1,enableMd5Check:!1,serviceConfig:n,useFixedDeviceId:r.useFixedDeviceId??!0,deviceId:r.deviceId??"webim",useReplacedMessageContents:r.useReplacedMessageContents??!1,customDeviceName:void 0!==s?r.customDeviceName:void 0,customOSPlatform:s,uiKitVersion:r.uiKitVersion,loginExtensionInfo:r.loginExtensionInfo,cacheEncryptionMode:"auto",profileSync:{userInfoWindowMs:7e3,userInfoBatchSize:20,groupNamecardWindowMs:7e3,groupNamecardMaxConcurrency:5},platformAdapterOptions:r.platformAdapterOptions},o=t.managers??[];if(e.instance){if(!e.isSameConfig(e.instance.config,i))throw new mt("ChatClient already initialized with different config",{code:ot.VALIDATION_INVALID_FORMAT,details:{fields:[{path:"config",message:"ChatClient already initialized with different config",rule:"conflict"}],current:e.instance.config,next:i}});return o.length>0&&e.instance.registerManagers(o),e.instance.validateOptionalCapabilityDependencies(),e.instance}return e.instance=new e(i),o.length>0&&e.instance.registerManagers(o),e.instance.validateOptionalCapabilityDependencies(),e.instance}async login(n,i){if(e.instance!==this)throw new mt("ChatClient is not initialized",{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:"client",message:"ChatClient is not initialized",rule:"state"}]}});const o=Fy.validateOrThrow($y,n),a=Fy.validateOrThrow(jy,i??{});if(await this.waitForTerminalSessionCleanup(),this.state===r||this.state===s){const e=this.currentUserId&&this.currentUserId!==o.userId;throw new ht(e?"Another user is already logged in":"ChatClient is already connecting or connected",{code:e?ot.USER_ALREADY_LOGIN_ANOTHER:ot.AUTH_ALREADY_LOGIN,details:{stage:"auth",...e?{currentUserId:this.currentUserId,nextUserId:o.userId}:{}}})}const c=++this.loginAttempt,d=new Av(c,a.timeoutMs??3e4);try{let e=this.config.appKey??null;this.activeAppKey=e,Vs("Login started",{userId:o.userId,serviceConnectionMode:this.config.serviceConfig.mode,hasCustomDnsConfigUrls:this.config.serviceConfig.hasCustomDnsConfigUrls});const s=this.platformAdapter??Dd(this.config.platformAdapterOptions);this.platformAdapter=s,(e=>{Ah?.reset(),Ah=new Rh(e)})({requestAdapter:s.request,onDiagnostic:(e,t)=>{Vs(e,t)}});const n=(e=>Ah?.startSession(e))({appKey:e??"default#appkey",uid:o.userId,sdkVersion:Zy,platform:s.runtime.getPlatform(),deviceId:this.config.deviceId,os:this.config.customOSPlatform,uikitVersion:this.config.uiKitVersion,did:this.config.customDeviceName}),i=s.runtime.getNetworkType?.();i&&i.then(e=>{Mh(e)}).catch(()=>{Mh("unknown")});const a=Uh({operationName:"USER_LOGIN",operationType:"MANUALLOGIN",uid:o.userId});let h,p,m;this.updateState(r),this.logReportEnabled=!1,Bs("unknown");let f,g=!1,y=!1,v=!0;if("dns"===this.config.serviceConfig.mode){const r=a?.startRequest({requestName:"REST_DNSLIST",method:"GET",url:this.config.serviceConfig.dnsConfigUrls[0]});try{const t=await d.race(dv(void 0!==this.config.appId?{appId:this.config.appId,baseUrls:this.config.serviceConfig.dnsConfigUrls,requestAdapter:s.request,loginDeadline:d}:{appKey:this.requireConfiguredAppKey(),baseUrls:this.config.serviceConfig.dnsConfigUrls,requestAdapter:s.request,loginDeadline:d}));e=t.appKey,this.activeAppKey=e,Nh({appKey:e}),Vs("DNS resolved for login",{baseUrl:t.baseUrl,websocketUrl:t.websocketUrl,restBaseUrl:t.restBaseUrl,syncWebSocketSource:"rest"}),h=t.websocketUrl,p=t.websocketUrls;const n=uv(t.restBaseUrl);this.contactSyncWsUrls=[n],this.syncConversationListConfigWsUrls=[n],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,r?.finish({code:200,success:!0}),Oh(t.dnsConfig.enableDataReport),js("DNS report switch resolved",{enabled:g})}catch(l){const e=l instanceof ut?l.code:-1,s=l instanceof Error?l.message:String(l);throw r?.finish({code:e,success:!1,description:s}),a?.finish({code:e,success:!1,description:s}),Oh(void 0),Bs("disabled"),this.activeAppKey=this.config.appKey??null,this.updateState(t),d.dispose(),l}}else{const e=this.config.serviceConfig.serverUrls;if(!e?.wsUrl||!e.restApiUrl){const e=new mt("serviceConfig.serverUrls.restApiUrl and serviceConfig.serverUrls.wsUrl are required when serverUrls is configured",{code:ot.VALIDATION_REQUIRED,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 a?.finish({code:e.code,success:!1,description:e.message}),Oh(void 0),this.updateState(t),d.dispose(),e}h=e.wsUrl,m=e.restApiUrl;const r=uv(m);y=this.config.enableMd5Check,this.contactSyncWsUrls=[r],this.syncConversationListConfigWsUrls=[r],this.contactSyncDnsResolved=!1,Oh(void 0)}if(!e){const e=new mt("appKey is unavailable after service discovery",{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:"appKey",message:"appKey is unavailable after service discovery",rule:"required"}]}});throw this.updateState(t),Lh(),d.dispose(),e}Gs({restBaseUrl:m,appKey:e,userId:o.userId,token:o.token,requestAdapter:s.request}),u=f,Rs.updateReportInterval(u),this.logReportEnabled=g,Bs(g?"enabled":"disabled");const I=this.resetCore();if(I?.(),c!==this.loginAttempt){const e=new ht("Login cancelled",{code:ot.CONNECTION_CANCELLED,details:{stage:"auth"}});throw a?.finish({code:ot.CONNECTION_CANCELLED,success:!1,description:e.message}),this.updateState(t),this.activeAppKey=this.config.appKey??null,Lh(),d.dispose(),e}const b=new xp({serverUrl:h,serverUrls:p,userId:o.userId,token:o.token,appKey:e,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:n,platformAdapter:s,enableDeliveryReceipt:this.config.enableDeliveryReceipt},this.eventHub);this.core=b,Gs({resource:b.getClientResource()});const _=a?.startRequest({requestName:"CONNECT_WEBSOCKET",method:"",url:h});try{Vs("Connecting core websocket",{serverUrl:h,restBaseUrl:m,userId:o.userId});try{await d.race(b.connect(d))}finally{d.dispose()}this.throwIfLoginSessionCancelled(c,b),_?.finish({code:200,success:!0}),a?.finish({code:0,success:!0}),Vs("Core websocket connected",{userId:o.userId,resource:b.getClientResource()}),this.currentUserId=o.userId,Nh({uid:o.userId}),this.restBaseUrl=m??null,this.authToken=o.token,this.clientResource=b.getClientResource(),await this.initCacheManager(o.userId),this.throwIfLoginSessionCancelled(c,b),Vs("Cache initialized after login",{userId:o.userId}),this.loadCachedConversations(),this.loadCachedUserInfo(),this.notifyManagersSessionReady(o.userId,this.clientResource),this.startPostLoginTasks(o.userId,c)}catch(l){const e=l instanceof ut?l.code:-1,r=l instanceof Error?l.message:String(l);if(_?.finish({code:e,success:!1,description:r}),a?.finish({code:e,success:!1,description:r}),this.core===b){const e=this.resetCore();try{this.activeAppKey=this.config.appKey??null,this.updateState(t),Lh()}finally{e?.()}}throw l}}finally{d.dispose()}var u}startPostLoginTasks(e,t){this.cancelPostLoginTasks();const r={attemptId:t,userId:e,cancelled:!1};this.postLoginTaskContext=r,this.runPostLoginTasks(r).catch(e=>{this.isPostLoginTaskActive(r)&&Vs("Unexpected post-login task failure",{userId:r.userId,reason:e instanceof Error?e.message:String(e)})}).finally(()=>{this.postLoginTaskContext===r&&(this.postLoginTaskContext=null)})}cancelPostLoginTasks(){this.postLoginTaskContext&&(this.postLoginTaskContext.cancelled=!0,this.postLoginTaskContext=null)}isPostLoginTaskActive(e){return!e.cancelled&&this.postLoginTaskContext===e&&e.attemptId===this.loginAttempt&&this.currentUserId===e.userId}async runPostLoginTasks(e){if(!this.isPostLoginTaskActive(e))return;if(await this.runPostLoginTask(e,"self-user-info",async()=>{await this.syncSelfUserInfoAfterLogin()}),!this.isPostLoginTaskActive(e))return;if(this.config.enableSyncData.includes("conversation")&&await this.runPostLoginTask(e,"conversation",async()=>{await this.refreshSessionList(this.config.syncConversationListConfig)}),!this.isPostLoginTaskActive(e))return;const t=this.triggerConfiguredSyncDataAfterLogin(e.userId,e),r=this.logReportEnabled?this.runPostLoginTask(e,"log-report",async()=>{await qs()}):Promise.resolve();await Promise.all([t,r])}async runPostLoginTask(e,t,r){if(this.isPostLoginTaskActive(e))try{await r()}catch(s){if(!this.isPostLoginTaskActive(e))return;Vs("Post-login synchronization step failed",{userId:e.userId,task:t,reason:s instanceof Error?s.message:String(s)})}}async logout(){if(e.instance!==this)throw new mt("ChatClient is not initialized",{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:"client",message:"ChatClient is not initialized",rule:"state"}]}});for(this.loginAttempt+=1,this.cancelPostLoginTasks();this.terminalSessionCleanupTask;)await this.terminalSessionCleanupTask;if(this.loginAttempt+=1,this.cancelPostLoginTasks(),await this.notifyManagersSessionEnding("logout"),!this.core){const e=this.detachSessionListSyncController();try{this.contactSyncController?.cancel(),this.contactSyncController=null,this.groupSyncController?.cancel(),this.groupSyncController=null,this.syncWebSocketSession?.cancel("logout"),this.syncWebSocketSession=null,this.userInfoHydrationQueue.destroy(),this.groupNamecardHydrationQueue.destroy(),this.activeIncomingStreamMessageIds.clear(),this.resetManagerSessionRuntimes(),Bs("disabled"),$s(),Lh()}finally{this.contactSyncController=null,this.groupSyncController=null,this.syncWebSocketSession=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.activeAppKey=this.config.appKey??null,this.updateState(t),this.logReportEnabled=!1,e?.()}return}try{if(await(this.cacheManager?.flushPending()),this.logReportEnabled)try{await qs()}catch(r){Vs("Report logs on logout failed",r)}await this.core.disconnect()}finally{const e=this.resetCore();try{this.activeAppKey=this.config.appKey??null,this.updateState(t),this.logReportEnabled=!1,Bs("disabled"),$s(),Lh()}finally{e?.()}}}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 mt("restBaseUrl is required",{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:"restBaseUrl",message:"restBaseUrl is required",rule:"required"}]}});if(!this.authToken)throw new mt("token is required",{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:"token",message:"token is required",rule:"required"}]}});if(!this.currentUserId)throw new mt("userId is required",{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:"userId",message:"userId is required",rule:"required"}]}});const e=this.clientResource??this.core?.getClientResource();if(!e)throw new mt("clientResource is required",{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:"clientResource",message:"clientResource is required",rule:"required"}]}});return{restBaseUrl:this.restBaseUrl,appKey:this.requireActiveAppKey(),userId:this.currentUserId,token:this.authToken,clientResource:e}}async renewToken(e){const t=Fy.validateOrThrow(Vy,e);if(!this.core||!this.currentUserId||this.state!==s)throw new ht("ChatClient is not connected",{code:ot.AUTH_NOT_LOGIN,details:{stage:"token",state:this.state}});const r=this.getRestContext(),n={...r},i=new Vf(n.restBaseUrl,{errorMap:Vv,requestAdapter:this.platformAdapter?.request,includeRequestId:!0});i.setAuthToken(t),Vs("Renew token started",{userId:r.userId});const o=await gv(i,n);if(o<=Date.now())throw new ht("Token is expired",{code:ot.AUTH_TOKEN_EXPIRED,details:{stage:"token"}});const a=this.core.renewToken(t,o);return this.authToken=t,Gs({token:t}),Vs("Renew token succeeded",{userId:r.userId,expireAt:o}),a}async getRTCTokenInfo(e){const t=Fy.validateOrThrow(Ky,e),r=this.getRestContext(),s=new Vf(r.restBaseUrl,{errorMap:Vv,requestAdapter:this.platformAdapter?.request,includeRequestId:!0});return s.setAuthToken(r.token),Vs("Get RTC token info started",{userId:r.userId,hasChannelName:Boolean(t?.channelName)}),yv(s,r,t)}async getUserIdsWithRTCUids(e){const t=Fy.validateOrThrow(zy,e),r=this.getRestContext(),s=new Vf(r.restBaseUrl,{errorMap:Vv,requestAdapter:this.platformAdapter?.request,includeRequestId:!0});return s.setAuthToken(r.token),Vs("Get userIds with RTC UIDs started",{userId:r.userId,count:t.length}),vv(s,r,t)}async getSelfIdsOnOtherPlatform(){const e=this.getRestContext(),t=new Vf(e.restBaseUrl,{errorMap:Vv,requestAdapter:this.platformAdapter?.request,includeRequestId:!0});return t.setAuthToken(e.token),Vs("Get self ids on other platform started",{userId:e.userId,clientResource:e.clientResource}),Iv(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(){return this.buildAuthenticatedSessionListSyncUrls(this.syncConversationListConfigWsUrls)}hasSessionListSyncWsUrl(){return this.syncConversationListConfigWsUrls.length>0}getSharedSyncWebSocketSession(){return this.syncWebSocketSession||(this.syncWebSocketSession=new Ff({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===nt.START_COMPLETED||e.stream.status===nt.FULL||e.stream.status===nt.COMPLETED||e.stream.status===nt.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:Zu(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 Ev([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 Vs("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&&Vs("Self user info sync returned empty result after login",{userId:this.currentUserId})}catch(t){Vs("Self user info sync failed after login",{userId:this.currentUserId,error:t})}}handleIncomingMessageProfileSync(e){if("RECEIVE"!==e.direct||!this.isMessageProfileSyncEnabled())return;const t=Wu(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=>{zu.delete(e)})(e);const t={userInfoUpdateTime:this.resolveCurrentUserInfoUpdateTime(),namecardUpdateTime:"groupChat"===e.conversationType?this.resolveCurrentGroupNamecardUpdateTime(e.conversationId):void 0};Hu(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 Vs("User info hydration failed",{userIds:r,error:d}),d}const n=this.currentUserId,i=n?s.find(e=>e.userId===n):void 0,o=s.filter(e=>e.userId!==n);i&&this.dispatchOwnInfoUpdated(i),o.length>0&&this.dispatchUserInfoUpdated(o),s.length>0&&this.refreshConversationDisplayFromUserInfos(s.map(e=>({userId:e.userId})),"profile");const a=new Set(s.map(e=>e.userId)),c=r.filter(e=>!a.has(e));c.length>0&&Vs("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){Vs("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 mt("ChatClient is not initialized",{code:ot.VALIDATION_REQUIRED,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 mt("ChatClient is not initialized",{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:"client",message:"ChatClient is not initialized",rule:"state"}]}});if(!t?.sender?.userId)throw new mt("sender.userId is required",{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:"sender.userId",message:"sender.userId is required",rule:"required"}]}});if(this.currentUserId&&t.sender.userId!==this.currentUserId)throw new mt("sender.userId does not match current user",{code:ot.VALIDATION_INVALID_FORMAT,details:{fields:[{path:"sender.userId",message:"sender.userId does not match current user",rule:"conflict"}]}});if(it(t))throw new ft("Stream message send is not supported",{code:ot.STREAM_SEND_NOT_SUPPORTED,details:{msgLocalId:t.msgLocalId,retryable:!1}});if(this.core&&this.state!==s&&await this.waitForSendConnectionRecovery(this.core),!this.core||this.state!==s)throw new ft("ChatClient is not connected",{code:ot.MESSAGE_NOT_CONNECTED,details:{msgLocalId:t.msgLocalId,state:this.state,retryable:!0}});return this.attachOutgoingMessageProfileVersions(t),this.core.sendMessage(t,r)}async waitForSendConnectionRecovery(e){let t=null;const r=e.recoverConnectionForSend().then(()=>!0).catch(e=>(Vs("Send connection recovery failed",{error:e instanceof Error?e.message:String(e)}),!1)),s=new Promise(e=>{t=setTimeout(()=>{e(!1)},1e4)}),n=await Promise.race([r,s]);t&&clearTimeout(t),n||Vs("Send connection recovery wait timed out",{timeoutMs:1e4,state:this.state})}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 mt("ChatClient is not initialized",{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:"client",message:"ChatClient is not initialized",rule:"state"}]}});if(!this.core)throw new mt("ChatClient is not connected",{code:ot.AUTH_NOT_LOGIN,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 mt("ChatClient is not initialized",{code:ot.VALIDATION_REQUIRED});if(!this.core)throw new mt("ChatClient is not connected",{code:ot.AUTH_NOT_LOGIN});return this.core.sendMessageAction(t,r)}async sendChatRoomOperation(t,r){if(e.instance!==this)throw new mt("ChatClient is not initialized",{code:ot.VALIDATION_REQUIRED});if(!this.core)throw new mt("ChatClient is not connected",{code:ot.AUTH_NOT_LOGIN});return this.core.sendChatRoomOperation(t,r)}async downloadAttachment(t){if(e.instance!==this)throw new mt("ChatClient is not initialized",{code:ot.VALIDATION_REQUIRED});if(!this.core)throw new mt("ChatClient is not connected",{code:ot.AUTH_NOT_LOGIN});return this.core.downloadAttachment(t)}decodeServerMessageMeta(e){if(!this.core)throw new mt("ChatClient is not connected",{code:ot.AUTH_NOT_LOGIN});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.VALIDATION_INVALID_FORMAT,"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),this.notifyManagerSessionReady(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),this.notifyManagerSessionReady(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 mt(`${e} requires explicit manager capability: ${t}`,{code:ot.VALIDATION_REQUIRED,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.VALIDATION_INVALID_FORMAT,"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",ot.VALIDATION_REQUIRED,"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",ot.VALIDATION_REQUIRED,"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 mt(e,{code:t,details:{fields:[{path:r,message:e,rule:s}],...n}})}buildManagerConflictError(e,t,r,s){return this.buildManagerValidationError("Manager key conflict",ot.VALIDATION_INVALID_FORMAT,"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)}throwIfLoginSessionCancelled(e,t){if(e!==this.loginAttempt||this.core!==t)throw new ht("Login cancelled",{code:ot.CONNECTION_CANCELLED,details:{stage:"auth"}})}async initCacheManager(e){this.cacheManager&&this.cacheUserId===e||(this.cacheManager=new Dm({appKey:this.requireActiveAppKey(),userId:e,cacheEncryptionMode:this.config.cacheEncryptionMode,storageAdapter:this.platformAdapter?.storage}),this.cacheUserId=e),await this.cacheManager.prepare()}loadCachedConversations(){this.cacheManager&&this.emitConversationListUpdate("conversation",!0)}loadCachedUserInfo(){this.cacheManager&&this.cacheManager.loadUserInfoSummaries()}emitConversationListUpdate(e,t=!1){if(!this.cacheManager)return;const r=this.cacheManager.loadSessionList().map(Cf),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(L,{version:this.conversationListVersion,items:r,reason:e,patch:s}))}buildConversationListPatch(e,t,r){const s=new Map(e.map(e=>[this.buildConversationListKey(e),e])),n=new Map(t.map(e=>[this.buildConversationListKey(e),e])),i=new Set,o=[],a=[];for(const d of t){const e=this.buildConversationListKey(d),t=s.get(e);t&&this.isConversationListItemEqual(t,d)||(o.push(d),i.add(e))}for(const d of e){const e=this.buildConversationListKey(d);n.has(e)||(a.push({conversationId:d.conversationId,conversationType:d.conversationType}),i.add(e))}const c=e.map(e=>this.buildConversationListKey(e)).join("\n")!==t.map(e=>this.buildConversationListKey(e)).join("\n");if(c)for(const d of t)i.add(this.buildConversationListKey(d));return{reset:r,upserted:o,removed:a,affectedKeys:[...i],orderChanged:c}}buildConversationListKey(e){return`${e.conversationType}:${e.conversationId}`}isConversationListItemEqual(e,t){return e.conversationId===t.conversationId&&e.conversationType===t.conversationType&&e.unreadCount===t.unreadCount&&e.lastMessageAt===t.lastMessageAt&&e.isPinned===t.isPinned&&e.pinnedTimestamp===t.pinnedTimestamp&&e.readAt===t.readAt&&e.remindType===t.remindType&&e.conversationName===t.conversationName&&e.conversationAvatar===t.conversationAvatar&&e.marks.length===t.marks.length&&e.marks.every((e,r)=>e===t.marks[r])&&JSON.stringify(e.lastMessage)===JSON.stringify(t.lastMessage)}async triggerContactSync(){this.config.enableSyncData.includes("contact")&&await this.refreshContactSnapshot()}async triggerConfiguredSyncDataAfterLogin(e,t){const r=[];this.config.enableSyncData.includes("contact")&&(Vs("Triggering automatic contact sync after login",{userId:e}),r.push(this.runPostLoginTask(t,"contact",async()=>{await this.triggerContactSync()}))),this.config.enableSyncData.includes("group")&&(Vs("Triggering automatic group sync after login",{userId:e}),r.push(this.runPostLoginTask(t,"group",async()=>{await this.triggerGroupSync()}))),await Promise.all(r)}async triggerGroupSync(){if(!this.config.enableSyncData.includes("group"))return;const e=this.ensureGroupSyncController();await e.sync()}ensureSessionListSyncController(){return this.syncConversationListConfigController||(this.syncConversationListConfigController=new Uf(this)),this.syncConversationListConfigController}ensureContactSyncController(){if(this.contactSyncController)return this.contactSyncController;const e=this.managerRegistry.get("contactManager");if(!e?.createSyncController)throw new mt("ContactManager is required for contact sync",{code:ot.VALIDATION_REQUIRED,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 Kf(this.getRestContext(),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 mt("GroupManager is required for group sync",{code:ot.VALIDATION_REQUIRED,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($,{dataType:e})}emitSyncDataFinished(e){this.eventHub.dispatch(j,e)}requireCacheManager(){if(!this.cacheManager)throw new mt("cacheManager is required",{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:"cacheManager",message:"cacheManager is required",rule:"required"}]}});return this.cacheManager}async resolveContactSyncUrls(){if(this.contactSyncWsUrls.length>0)return this.buildAuthenticatedContactSyncUrls(this.contactSyncWsUrls);if(this.contactSyncDnsResolved)throw Vs("Derived contact sync websocket is unavailable after DNS precheck",{userId:this.currentUserId,serviceConnectionMode:this.config.serviceConfig.mode}),new ut("Contact sync websocket urls are unavailable",ot.CONTACT_SYNC_SOCKET_FAILED,{details:{stage:"socket_connect"}});if("dns"!==this.config.serviceConfig.mode)throw Vs("Derived contact sync websocket is unavailable for fixed service config",{userId:this.currentUserId,serviceConnectionMode:this.config.serviceConfig.mode}),new ut("Contact sync websocket urls are unavailable",ot.CONTACT_SYNC_SOCKET_FAILED,{details:{stage:"socket_connect"}});try{const e=await dv(void 0!==this.config.appId?{appId:this.config.appId,baseUrls:this.config.serviceConfig.dnsConfigUrls,requestAdapter:this.platformAdapter?.request}:{appKey:this.requireConfiguredAppKey(),baseUrls:this.config.serviceConfig.dnsConfigUrls,requestAdapter:this.platformAdapter?.request});this.contactSyncWsUrls=[uv(e.restBaseUrl)],this.contactSyncDnsResolved=!0}catch(e){throw Vs("Automatic contact sync REST endpoint DNS resolve failed",{userId:this.currentUserId,reason:e instanceof Error?e.message:String(e)}),new ut("Contact sync websocket dns resolve failed",ot.CONTACT_SYNC_SOCKET_FAILED,{details:{stage:"socket_connect",cause:e instanceof Error?e.message:String(e)}})}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 mt("token is required",{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:"token",message:"token is required",rule:"required"}]}})}buildContactSyncSocketUrl(e,t){const r=e.trim();if(!/^wss?:\/\/[^/?#]+/i.test(r))throw new mt("sync websocket URL must use ws or wss protocol");const s=r.indexOf("#"),n=s>=0?r.slice(s):"",i=s>=0?r.slice(0,s):r,o=i.indexOf("?"),a=o>=0?i.slice(0,o):i,c=o>=0?i.slice(o+1):"",d=a.indexOf("://")+3,u=a.indexOf("/",d),l=u<0||"/"===a.slice(u)?`${a}/ws`:a,h=c.split("&").filter(e=>e.length>0&&"token"!==e.split("=",1)[0]),p=encodeURIComponent(t).replace(/%20/g,"+");return h.push(`token=${p}`),`${l}?${h.join("&")}${n}`}shuffleContactSyncUrls(e){const t=[...e];for(let r=t.length-1;r>0;r-=1){const e=Math.floor(Math.random()*(r+1)),s=t[r],n=t[e];s&&n&&(t[r]=n,t[e]=s)}return t}buildContactRosterRequest(e){const t=this.getRestContext(),{orgName:r,appName:s}=fs(t.appKey);return{type:Uv,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}}detachSessionListSyncController(){const e=this.syncConversationListConfigController;return this.syncConversationListConfigController=null,e?.cancelForTeardown()??null}resetCore(){const e=this.detachSessionListSyncController();try{return this.cancelPostLoginTasks(),this.contactSyncController?.cancel(),this.contactSyncController=null,this.groupSyncController?.cancel(),this.groupSyncController=null,this.syncWebSocketSession?.cancel("reset-core"),this.syncWebSocketSession=null,this.userInfoHydrationQueue.destroy(),this.groupNamecardHydrationQueue.destroy(),this.activeIncomingStreamMessageIds.clear(),this.core?(this.core.destroy(),this.clearCoreSessionState(),this.resetManagerSessionRuntimes(),e):e}catch(r){throw this.clearCoreSessionState(),this.updateState(t),e?.(),r}}clearCoreSessionState(){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}requireConfiguredAppKey(){if(this.config.appKey)return this.config.appKey;throw new mt("appKey is unavailable before DNSConfig resolution",{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:"appKey",message:"appKey is unavailable before DNSConfig resolution",rule:"required"}]}})}requireActiveAppKey(){if(this.activeAppKey)return this.activeAppKey;throw new mt("appKey is unavailable for the current session",{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:"appKey",message:"appKey is unavailable for the current session",rule:"required"}]}})}resetManagerSessionRuntimes(){for(const t of this.managerRegistry.values())try{t.resetSessionRuntime?.()}catch(e){Vs("Manager session runtime reset failed",{manager:this.getManagerNameFromInstance(t),error:e instanceof Error?e.message:"unknown"})}this.activeManagerSessionContext=null,this.managerSessionEndingPromise=null}notifyManagersSessionReady(e,t){const r={generation:++this.managerSessionGeneration,userId:e,clientResource:t};this.activeManagerSessionContext=r,this.managerSessionEndingPromise=null;for(const s of this.managerRegistry.values())this.notifyManagerSessionReady(s)}notifyManagerSessionReady(e){const t=this.activeManagerSessionContext;if(t&&e.onSessionReady)try{e.onSessionReady(t)}catch(r){Vs("Manager session ready hook failed",{manager:this.getManagerNameFromInstance(e),error:r instanceof Error?r.message:"unknown"})}}notifyManagersSessionEnding(e){const t=this.activeManagerSessionContext;if(!t)return Promise.resolve();if(this.managerSessionEndingPromise)return this.managerSessionEndingPromise;const r={...t,reason:e},s=Array.from(this.managerRegistry.values(),e=>{if(!e.onSessionEnding)return Promise.resolve();try{return Promise.resolve(e.onSessionEnding(r)).catch(t=>{Vs("Manager session ending hook failed",{manager:this.getManagerNameFromInstance(e),error:t instanceof Error?t.message:"unknown"})})}catch(t){return Vs("Manager session ending hook failed",{manager:this.getManagerNameFromInstance(e),error:t instanceof Error?t.message:"unknown"}),Promise.resolve()}}),n=Promise.all(s).then(()=>{});let i=null;const o=new Promise(t=>{i=setTimeout(()=>{Vs("Manager session ending hooks timed out",{timeoutMs:6e3,reason:e}),t()},6e3)});return this.managerSessionEndingPromise=Promise.race([n,o]).then(()=>{null!==i&&clearTimeout(i),this.activeManagerSessionContext?.generation===t.generation&&(this.activeManagerSessionContext=null)}),this.managerSessionEndingPromise}isTerminalManagerSessionDisconnect(e){return e.reason===O||[ot.AUTH_TOKEN_EXPIRED,ot.AUTH_BIND_ANOTHER_DEVICE,ot.AUTH_LOGIN_TOO_MANY_DEVICES,ot.USER_LOGIN_ANOTHER_DEVICE,ot.USER_REMOVED,ot.USER_KICKED_BY_CHANGE_PASSWORD,ot.USER_KICKED_BY_OTHER_DEVICE].includes(e.errorCode??-1)}startTerminalSessionCleanup(e){if(this.terminalSessionCleanupTask)return;Vs("Terminal session cleanup started",{errorCode:e.errorCode,errorMessage:e.errorMessage,reason:e.reason});const t=this.finishTerminalSessionCleanup().catch(e=>{Ks("Terminal session cleanup failed",e instanceof Error?e:new Error(String(e)))}).finally(()=>{this.terminalSessionCleanupTask===t&&(this.terminalSessionCleanupTask=null)});this.terminalSessionCleanupTask=t}async waitForTerminalSessionCleanup(){await(this.terminalSessionCleanupTask??Promise.resolve())}async finishTerminalSessionCleanup(){this.loginAttempt+=1,this.cancelPostLoginTasks(),await this.notifyManagersSessionEnding("terminal-disconnect");try{try{await(this.cacheManager?.flushPending())}catch(e){Vs("Cache flush on terminal disconnect failed",{error:e instanceof Error?e.message:String(e)})}if(this.logReportEnabled)try{await qs()}catch(e){Vs("Report logs on terminal disconnect failed",e)}}finally{const e=this.resetCore();try{this.activeAppKey=this.config.appKey??null,this.updateState(t),this.logReportEnabled=!1,Bs("disabled"),$s(),Lh()}finally{e?.()}}Vs("Terminal session cleanup finished")}static isSameConfig(t,r){return t.appKey===r.appKey&&(t.appId===r.appId&&(!!e.isSameStringArray(t.enableSyncData,r.enableSyncData)&&(t.useCustomAttachmentUpload===r.useCustomAttachmentUpload&&(t.enableMd5Check===r.enableMd5Check&&(!!e.isSameServiceConfig(t.serviceConfig,r.serviceConfig)&&(t.useFixedDeviceId===r.useFixedDeviceId&&(t.deviceId===r.deviceId&&(t.useReplacedMessageContents===r.useReplacedMessageContents&&(t.customDeviceName===r.customDeviceName&&(t.customOSPlatform===r.customOSPlatform&&(t.platformAdapterOptions?.prefer===r.platformAdapterOptions?.prefer&&(t.platformAdapterOptions?.runtimeInput===r.platformAdapterOptions?.runtimeInput&&(t.platformAdapterOptions?.transportAdapter===r.platformAdapterOptions?.transportAdapter&&(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(t){const r=t?.serverUrls;return{mode:r?"fixed":"dns",dnsConfigUrls:t?.dnsConfigUrls??Yy,hasCustomDnsConfigUrls:Boolean(t?.dnsConfigUrls?.length),serverUrls:r?{restApiUrl:r.restApiUrl,wsUrl:r.wsUrl?e.normalizeFixedWebSocketUrl(r.wsUrl):void 0}:void 0}}static normalizeFixedWebSocketUrl(e){const t=e.search(/[?#]/),r=-1===t?e:e.slice(0,t),s=-1===t?"":e.slice(t),n=r.indexOf("://")+3,i=r.indexOf("/",n);if(-1===i)return`${r}/websocket${s}`;const o=r.slice(i);return/^\/+$/u.test(o)?`${r.slice(0,i)}/websocket${s}`:e}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)}};Kv.instance=null;let zv=Kv;const Hv=(e,t)=>new mt(t,{code:ot.VALIDATION_INVALID_FORMAT,details:{fields:[{path:e,message:t,rule:"invalid_format"}]}}),Wv=(e,t)=>{if("string"!=typeof e||0===e.trim().length)throw(e=>new mt(`${e} is required`,{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:e,message:`${e} is required`,rule:"required"}]}}))(t);return e.trim()},Jv=e=>`mark_${String(e)}`,Qv=(e,t)=>{if("singleChat"===e||"groupChat"===e||"chatRoom"===e)return e;throw Hv(t,`${t} must be one of singleChat, groupChat, chatRoom`)},Zv=e=>"singleChat"===e?"chat":"groupChat"===e?"groupchat":"chatroom",Yv=e=>"string"==typeof e&&e.length>0?e:void 0,Xv=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}},eI=e=>pu(e)?e:void 0,tI=(e,t)=>{const r=eI(e);if(!r)return;const s=(e=>"string"==typeof e?mu(e,{}):eI(e)??{})(r.payload),n=Array.isArray(s.bodies)?s.bodies:[],i=eI(n[0])??eI(s.body),o=(e=>"txt"===e||"text"===e?"text":"custom"===e?"custom":"cmd"===e?"cmd":"image"===e||"file"===e||"voice"===e||"video"===e||"location"===e||"combine"===e?e:null)(i?.type??s.type);if(!i||!o)return;const a=((e,t)=>{if("text"===e)return{content:Yv(t.msg)??Yv(t.content)??""};if("custom"===e){const e=eI(t.customExts)??eI(t.params)??{},r={};for(const[t,s]of Object.entries(e))"string"==typeof s&&(r[t]=s);return{event:Yv(t.customEvent)??Yv(t.event)??"",params:r}}if("cmd"===e)return{action:Yv(t.action)??""};if("image"===e){const e=Yv(t.url)??Yv(t.remotePath)??"";return{localUrl:"",filename:Yv(t.filename)??Yv(t.displayName),filetype:Yv(t.filetype)??"application/octet-stream",width:Xv(t.width),height:Xv(t.height),isGif:!0===t.isGif||1===t.subType,isOriginalImage:!0===t.isOriginalImage,originalImageUrl:e,bigImageUrl:Yv(t.bigImageUrl),thumbnailUrl:Yv(t.thumbnailUrl)??Yv(t.thumbnailRemotePath),secret:Yv(t.secret)??Yv(t.secretKey),fileLength:Xv(t.fileLength)}}return"file"===e?{url:Yv(t.url)??Yv(t.remotePath),filename:Yv(t.filename)??Yv(t.displayName),filetype:Yv(t.filetype)??"application/octet-stream",fileSize:Xv(t.fileSize),fileLength:Xv(t.fileLength),secret:Yv(t.secret)??Yv(t.secretKey)}:"voice"===e?{url:Yv(t.url)??Yv(t.remotePath),filename:Yv(t.filename)??Yv(t.displayName),filetype:Yv(t.filetype)??"application/octet-stream",duration:Xv(t.duration)??0,fileLength:Xv(t.fileLength),secret:Yv(t.secret)??Yv(t.secretKey)}:"video"===e?{url:Yv(t.url)??Yv(t.remotePath),filename:Yv(t.filename)??Yv(t.displayName),filetype:Yv(t.filetype)??"application/octet-stream",duration:Xv(t.duration)??0,width:Xv(t.width),height:Xv(t.height),fileLength:Xv(t.fileLength),secret:Yv(t.secret)??Yv(t.secretKey),thumbnailUrl:Yv(t.thumbnailUrl)??Yv(t.thumbnailRemotePath)}:"location"===e?{latitude:Xv(t.latitude)??0,longitude:Xv(t.longitude)??0,address:Yv(t.address),buildingName:Yv(t.buildingName)}:null})(o,i);if(!a)return;const c=Yv(s.from)??Yv(r.from)??"",d=Yv(s.to)??t.conversationId,u=eI(s.sender),l={userId:Yv(u?.userId)??c,nickname:Yv(u?.nickname),avatarUrl:Yv(u?.avatarUrl)},h=eI(s.ext)??{},p=(e=>{const t=eI(e);if(!t)return;const r=Yv(t.operatorId)??Yv(t.operator),s=Xv(t.operationCount)??Xv(t.count),n=Xv(t.operationTime)??Xv(t.edit_time);return r&&void 0!==s&&void 0!==n?{operatorId:r,operationCount:s,operationTime:n}:void 0})(s.modifiedInfo??eI(s.meta)?.edit_msg);return{msgServerId:Yv(r.id)??t.messageId,msgLocalId:Yv(r.msgLocalId)??"",from:c,to:d,sender:l,conversationId:t.conversationId,conversationType:t.conversationType,type:o,sendStatus:"sent",ext:h,timestamp:Xv(r.timestamp)??t.timestamp,body:a,direct:c===t.currentUserId?"SEND":"RECEIVE",...p?{modifiedInfo:p}:{}}},rI=e=>`${e.conversationType}:${e.conversationId}`,sI=e=>{const{orgName:t,appName:r}=fs(e.appKey);return{orgName:t,appName:r,encodedUserId:encodeURIComponent(e.userId),encodedResource:encodeURIComponent(e.clientResource)}},nI=async(e,t,r,s)=>{const n=sI(t),i=(e=>{const t=e,r=t.conversations;if(void 0!==r){if(!Array.isArray(r)||0===r.length)throw Hv("params.conversations","params.conversations must be a non-empty array");return r.map((e,t)=>{if(!pu(e))throw Hv(`params.conversations.${String(t)}`,`params.conversations.${String(t)} must be an object`);return{conversationId:Wv(e.conversationId,`params.conversations.${String(t)}.conversationId`),conversationType:Qv(e.conversationType,`params.conversations.${String(t)}.conversationType`)}})}return[{conversationId:Wv(t.conversationId,"params.conversationId"),conversationType:Qv(t.conversationType,"params.conversationType")}]})(r),o=((e,t)=>{if("number"!=typeof e||!Number.isInteger(e)||e<0||e>19)throw Hv(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:Jv(o),targets:i.map(e=>({to:e.conversationId,type:Zv(e.conversationType)}))},operation:s?"addConversationMark":"removeConversationMark"}),c=(e=>{if(!Array.isArray(e))return new Set;const t=new Set;return e.forEach(e=>{if(!pu(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(rI({conversationId:r,conversationType:s}))}),t})((pu(a)&&pu(a.data)?a.data:{}).ignore),d=[],u=[];for(const l of i){const e={conversationId:l.conversationId,conversationType:l.conversationType};c.has(rI(l))?u.push({...e,reason:"ignored_by_server"}):d.push(e)}return{succeeded:d,failed:u,mark:o,operation:s?"addMark":"removeMark"}},iI=async(e,t,r,s)=>{const n=sI(t),i=Wv(r.conversationId,"params.conversationId"),o=Qv(r.conversationType,"params.conversationType"),a=Wv(r.messageId,"params.messageId");return await e.request(`/${n.orgName}/${n.appName}/sdk/user/${n.encodedUserId}/user_channel/pin?resource=${n.encodedResource}`,{method:s?"POST":"DELETE",body:{to:i,type:Zv(o),pin_msg_id:a},operation:s?"pinMessage":"unpinMessage"}),{conversationId:i,conversationType:o,messageId:a,operation:s?"pin":"unpin"}},oI=["nickname","avatarUrl","mail","phone","gender","sign","birth","ext"],aI=(e,t)=>`${e}\0${t}`,cI=(e,t,r)=>{const s={userId:e};for(const n of oI){const e=r?.[n]??t?.[n];void 0!==e&&(s[n]=e)}return s},dI=e=>cI(e.userId,void 0,{userId:e.userId,nickname:e.nickname,avatarUrl:e.avatarUrl,sign:e.sign,ext:e.ext}),uI=(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(aI(n.groupId,n.user.userId),t.namecard)}return s},lI=async(e,t)=>{if(0===e.length||!t)return[];try{return await t({userIds:e})}catch(r){return Vs("Group user info hydration failed",{userIds:e,error:r}),[]}},hI=async(e,t)=>{t&&0!==e.size&&await Promise.all([...e.entries()].map(async([e,r])=>{try{await t(e,r)}catch(s){Vs("Group namecard hydration failed",{groupId:e,userIds:r,error:s})}}))},pI=async e=>{const t=(e=>{const t=[],r=new Set;for(const s of e){const e=s.groupId.trim(),n=s.user.userId.trim();if(!e||!n)continue;const i=aI(e,n);r.has(i)||(r.add(i),t.push({groupId:e,user:{...s.user,userId:n}}))}return t})(e.contexts),r=(e=>{const t=[],r=new Set;for(const s of e)r.has(s.user.userId)||(r.add(s.user.userId),t.push(s.user.userId));return t})(t),s=((e,t)=>{const r=new Map;if(!e)return r;for(const n of t){const t=e.getRuntimeUserInfo?.(n,!1)??null;t&&r.set(n,t)}const s=t.filter(e=>!r.has(e));for(const n of e.getUserInfoSummaries?.(s,!1)??[])r.set(n.userId,dI(n));return r})(e.cacheManager,r),n=r.filter(e=>!s.has(e)),i=new Set(n),o=uI(e.cacheManager,t,e.includeNameCard),a=e.includeNameCard?((e,t,r)=>{const s=new Map;for(const n of e){const e=n.user.userId,i=aI(n.groupId,e);if(!t.has(e)||r.has(i))continue;const o=s.get(n.groupId)??[];o.includes(e)||o.push(e),s.set(n.groupId,o)}return s})(t,i,o):new Map,[c]=await Promise.all([lI(n,e.fetchUserInfos),hI(a,e.hydrateGroupNamecards)]),d=new Map(c.map(e=>[e.userId,e])),u=uI(e.cacheManager,t,e.includeNameCard),l=new Map;for(const h of t){const e=h.user.userId,t=aI(h.groupId,e),r=cI(e,h.user,d.get(e)??s.get(e)),n=u.get(t)??o.get(t);l.set(t,void 0!==n?{...r,nameCard:n}:r)}return{usersByContextKey:l,fetchedUserInfos:c,missingUserIds:n.filter(e=>!d.has(e))}},mI=async e=>{const t=await pI({...e,contexts:e.users.map(t=>({groupId:e.groupId,user:t}))}),r=new Map;for(const s of e.users){const n=s.userId.trim();if(!n||r.has(n))continue;const i=t.usersByContextKey.get(aI(e.groupId.trim(),n));i&&r.set(n,i)}return{usersById:r,fetchedUserInfos:t.fetchedUserInfos,missingUserIds:t.missingUserIds}},fI=xy(["singleChat","groupChat","chatRoom"]),gI=Py(My()).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"),yI=ky({path:Ay().min(1,"data.path is required"),size:Ny().optional(),name:Ay().optional(),type:Ay().optional()}),vI=ky({uri:Ay().min(1,"data.uri is required"),size:Ny().optional(),name:Ay().optional(),type:Ay().optional()}),II=Dy(["undefined"!=typeof File?((e,t={message:`Input not instance of ${e.name}`})=>Ey(t=>t instanceof e,t))(File):Uy(),yI,vI]),bI=ky({conversationId:Ay().min(1,"conversationId is required"),conversationType:fI,ext:gI.optional(),timestamp:Ny().int().positive("timestamp must be a positive integer").optional(),receiverList:Ly(Ay().min(1,"receiverList item is required")).nonempty("receiverList must not be empty").optional(),deliverOnlineOnly:Oy().optional(),webhookEnv:Ay().optional(),priority:xy(["high","normal","low"]).optional(),needReadReceipt:Oy().optional(),isChatThread:Oy().optional()}),_I=ky({type:Ay().min(1,"messageList.type is required"),sender:ky({userId:Ay().min(1,"messageList.sender.userId is required"),nickname:Ay().optional(),avatarUrl:Ay().optional()}),conversationId:Ay().min(1,"messageList.conversationId is required"),conversationType:fI,timestamp:Ny().int().positive("messageList.timestamp must be positive"),body:Py(My()),combineLevel:Ny().int().min(0).max(10).optional()}).passthrough(),TI=e=>e.superRefine((e,t)=>{e.receiverList&&"singleChat"===e.conversationType&&t.addIssue({code:Zf.custom,message:"receiverList is only allowed for group or chat room conversation",path:["receiverList"]}),e.isChatThread&&"groupChat"!==e.conversationType&&t.addIssue({code:Zf.custom,message:"isChatThread is only allowed for group conversation",path:["isChatThread"]}),e.needReadReceipt&&"chatRoom"===e.conversationType&&t.addIssue({code:Zf.custom,message:"needReadReceipt is not allowed for chatRoom conversation",path:["needReadReceipt"]})}),CI=TI(bI.extend({content:Ay().min(1,"content is required"),targetLanguages:Ly(Ay().min(1)).optional()})),SI=TI(bI.extend({originalUrl:Ay().min(1,"originalUrl is required").optional(),filename:Ay().min(1,"filename is required").optional(),filetype:Ay().min(1,"filetype is required").optional(),width:Ny().positive("width must be positive").optional(),height:Ny().positive("height must be positive").optional(),isGif:Oy().optional(),isOriginalImage:Oy().optional(),fileLength:Ny().positive("fileLength must be positive").optional(),data:II.optional(),thumbnailUrl:Ay().min(1).optional()}).refine(e=>Boolean(e.originalUrl||e.data),{message:"originalUrl or data is required",path:["originalUrl"]})),EI=TI(bI.extend({originalUrl:Ay().min(1,"originalUrl is required").optional(),filename:Ay().min(1,"filename is required").optional(),filetype:Ay().min(1,"filetype is required").optional(),fileSize:Ny().positive("fileSize must be positive").optional(),fileLength:Ny().positive("fileLength must be positive").optional(),data:II.optional()}).refine(e=>Boolean(e.originalUrl||e.data),{message:"originalUrl or data is required",path:["originalUrl"]})),wI=TI(bI.extend({originalUrl:Ay().min(1,"originalUrl is required").optional(),filename:Ay().min(1,"filename is required").optional(),filetype:Ay().min(1,"filetype is required").optional(),duration:Ny().positive("duration must be positive"),fileLength:Ny().positive("fileLength must be positive").optional(),data:II.optional()}).refine(e=>Boolean(e.originalUrl||e.data),{message:"originalUrl or data is required",path:["originalUrl"]})),RI=TI(bI.extend({originalUrl:Ay().min(1,"originalUrl is required").optional(),filename:Ay().min(1,"filename is required").optional(),filetype:Ay().min(1,"filetype is required").optional(),duration:Ny().positive("duration must be positive"),width:Ny().positive("width must be positive").optional(),height:Ny().positive("height must be positive").optional(),fileLength:Ny().positive("fileLength must be positive").optional(),thumbnailUrl:Ay().min(1).optional(),data:II.optional()}).refine(e=>Boolean(e.originalUrl||e.data),{message:"originalUrl or data is required",path:["originalUrl"]})),AI=TI(bI.extend({latitude:Ny(),longitude:Ny(),address:Ay().min(1).optional(),buildingName:Ay().min(1).optional()})),NI=TI(bI.extend({action:Ay().min(1,"action is required")})),OI=TI(bI.extend({event:Ay().min(1,"event is required"),params:Py(Ay()).optional()})),MI=TI(bI.extend({title:Ay().min(1,"title is required"),summary:Ay().min(1,"summary is required"),compatibleText:Ay().min(1).optional(),messageList:Ly(_I).min(1,"messageList must not be empty").max(300,"messageList max length is 300")})),UI=e=>{const t=e?.userId?.trim();if(!t)throw new mt("sender.userId is required",{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:"sender.userId",message:"sender.userId is required",rule:"required"}]}});return{userId:t,nickname:e?.nickname,avatarUrl:e?.avatarUrl}},LI=()=>Bh(),kI=(e,t)=>{if(e)return e;if(!t)throw new mt("url or data is required",{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:"url",message:"url or data is required",rule:"required"}]}});const r=Fh(t);if(!r)throw new mt("Failed to resolve local url",{code:ot.VALIDATION_INVALID_FORMAT,details:{fields:[{path:"url",message:"Failed to resolve local url",rule:"invalid_format"}]}});return r},DI=e=>!!e.isGif||(e.isOriginalImage??!1),PI=(e,t,r,s,n)=>({msgServerId:"",msgLocalId:n??Bh(),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}),xI=(e,t)=>{const r=Fy.validateOrThrow(MI,e),s=r.messageList,n=UI(t);np(s);const i=ip(s);op(i);const o={title:r.title,summary:r.summary,messageList:s,filename:"combine",filetype:"application/octet-stream",combineLevel:i},a=PI(r,n,"combine",o);return((e,t)=>{t&&Yu.set(e,t)})(a,r.compatibleText),a},FI=e=>{const{orgName:t,appName:r}=fs(e.appKey);return`/${t}/${r}`},BI=e=>{const t=new Uint8Array(fa.util.base64.length(e));return fa.util.base64.decode(e,t,0),t},GI=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),qI=async e=>{try{return await e()}catch(t){if(!(t instanceof It))throw t;const e=(e=>{const t="string"==typeof e.details?.serverMessage?e.details.serverMessage:void 0;switch(e.code){case ot.SERVICE_NOT_ENABLED:case ot.TRANSLATE_SERVICE_NOT_ENABLED:return"Translation service is not enabled";case ot.TRANSLATE_PARAM_INVALID:return t?.includes("too long")?"Translation text is too long":t?.includes("target language")?"Invalid target language":"Invalid translation request";case ot.TRANSLATE_USAGE_LIMIT:return"Translation quota has been reached";case ot.TRANSLATE_FAILED:return"Translation service error";default:return}})(t);if(!e)throw t;throw new It(`REST business error: ${e}`,{code:t.code,details:t.details})}},$I=e=>"string"==typeof e?e:"number"==typeof e||"boolean"==typeof e||"bigint"==typeof e?String(e):"",jI=e=>{if("string"!=typeof e)return"";const t=e.trim();return t&&"undefined"!==t&&"null"!==t?t:""},VI=e=>({userId:e}),KI=(e,t)=>{if(!GI(e)||!GI(e.data))throw qf({apiName:t,message:`${t} response data is invalid`,mapped:!1});return e.data},zI=(e,t)=>{if(!GI(e)||!Array.isArray(e.data))throw qf({apiName:t,message:`${t} response data is invalid`,mapped:!1});return e.data},HI=(e,t)=>Array.isArray(e)?e:zI(e,t),WI={txt:"text",img:"image",video:"video",file:"file",loc:"location",custom:"custom",combine:"combine"},JI={text:"txt",image:"img",video:"video",file:"file",location:"loc",custom:"custom",combine:"combine"},QI={chat:"singleChat",chatroom:"chatRoom",groupchat:"groupChat",singleChat:"singleChat",chatRoom:"chatRoom",groupChat:"groupChat"},ZI=(e,t,r)=>{if(!t)return"";if(t.includes("em-redirect"))return t;const{orgName:s,appName:n}=fs(e.appKey),i=t.indexOf("/chatfiles/"),o=i>=0?t.slice(i):t,a=`${e.restBaseUrl}/${s}/${n}${o}`;return bs(a,r)},YI=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},XI=(e,t,r)=>{const s=$I(r.contentType??r.type),n=JI[s];if(!n)return null;const i=GI(r.content)?r.content:{},o=((e,t)=>{const r=$I(t.conversationType);if("groupchat"===r||"chatroom"===r)return $I(t.receiverId);const s=$I(t.senderId);return s===e?$I(t.receiverId):s})(t,r),a=QI[$I(r.conversationType)]??"singleChat",c={msgServerId:$I(r.messageId),msgLocalId:$I(r.messageId),from:$I(r.senderId),to:$I(r.receiverId),conversationId:o,conversationType:a,type:n,ext:GI(r.ext)?r.ext:{},timestamp:"number"==typeof r.sentTime?r.sentTime:new Date($I(r.sentTime)).getTime(),sender:{userId:$I(r.senderId)},highlight:YI(r.highlight),text:"string"==typeof r.text?r.text:void 0};let d;const u=$I(i.remotePath??i.url),l=$I(i.secret??i.secretKey);switch(n){case"txt":d={type:"txt",content:$I(i.message??r.text)};break;case"img":{const t=ZI(e,u,l);d={type:"img",url:t,thumb:i.thumb?ZI(e,$I(i.thumb),$I(i.thumb_secret??i.thumbnailSecretKey)):`${t}&thumbnail=true`,secret:l,width:Number(i.width??(GI(i.size)?i.size.width:0))||0,height:Number(i.height??(GI(i.size)?i.size.height:0))||0,fileLength:Number(i.file_length??i.fileLength??0)};break}case"video":d={type:"video",url:ZI(e,u,l),thumb:i.thumb||i.thumbnailRemotePath?ZI(e,$I(i.thumb??i.thumbnailRemotePath),$I(i.thumb_secret??i.thumbnailSecretKey)):"",secret:l,filename:$I(i.filename??i.displayName),duration:Number(i.length??i.duration??0),fileLength:Number(i.file_length??i.fileLength??0)};break;case"file":d={type:"file",url:ZI(e,u,l),secret:l,filename:$I(i.filename??i.displayName),fileLength:Number(i.file_length??i.fileLength??0)};break;case"loc":d={type:"loc",latitude:Number(i.lat??i.latitude??0),longitude:Number(i.lng??i.longitude??0),address:$I(i.addr??i.address),buildingName:$I(i.buildingName)};break;case"custom":d={type:"custom",customEvent:$I(i.customEvent),customExts:GI(i.customExts)?i.customExts:{}};break;default:return null}return{...c,body:d}},eb=async(e,t,r)=>{const s=`${FI(t)}/users/${t.userId}/messages/search/get`,n=((e,t)=>{const{option:r,pageNum:s=1,pageSize:n=20}=e,i=r.keywordList.map(e=>e.trim()).filter(e=>e.length>0),o={searchMode:"default",highlightEnable:!0,page:s,size:n};return 1===i.length?o.keyword=i[0]:(o.keywords=i,o.keywordMatch="and"===r.keywordListMatchType?"all":"any"),r.conversationId&&("singleChat"===r.conversationType?o.participantPairs=[{userId1:t,userId2:r.conversationId}]:"groupChat"===r.conversationType?o.groupIds=[r.conversationId]:"chatRoom"===r.conversationType&&(o.chatroomIds=[r.conversationId])),r.msgTypes&&r.msgTypes.length>0&&(o.contentType=r.msgTypes.map(e=>WI[e]??e).join(",")),void 0!==r.startTime&&(o.startTime=r.startTime),void 0!==r.endTime&&(o.endTime=r.endTime),r.searchScope&&(o.searchExt=r.searchScope),r.direction&&(o.sort="up"===r.direction?"sentTime:asc":"sentTime:desc"),{data:o}})(r,t.userId),i=await e.post(s,n,{operation:"searchMessages"}),o=GI(i)?i:{},a=GI(o.data)?o.data:o,c=GI(a.data)?a.data:a,d=Array.isArray(c.items)?c.items:Array.isArray(c.list)?c.list:[],u=GI(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(!GI(g))continue;const e=XI(t,t.userId,g);e&&f.push(e)}return{messages:f,pageNum:l,pageSize:h,totalPages:p,isLast:m}},tb=e=>{const{orgName:t,appName:r}=fs(e.appKey);return`/api/sdk/v1/${t}/${r}`},rb=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),sb=e=>rb(e)&&"string"==typeof e.path&&e.path.trim().length>0,nb=e=>(e=>"undefined"!=typeof File&&e instanceof File)(e)||sb(e),ib=e=>{if(!rb(e))return;return{data:rb(e.data)?e.data:void 0,error:rb(e.error)?e.error:void 0}},ob=(e,t)=>{const r=ib(e),s=r?.data?.text;if("string"!=typeof s)throw new ut(`${t} response data is invalid`,ot.REST_BUSINESS_UNKNOWN,{details:{api:t,response:e}});return s},ab=(e,t,r,s="sdk")=>"auth"===s?new pt(e,{code:t,details:r}):"validation"===s?new mt(e,{code:t,details:r}):new ut(e,t,{details:r}),cb=e=>!(void 0===e||rb(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))),db=e=>{if(!e)return;const t=(e.split("#")[0]?.split("?")[0]??"").split("/").filter(Boolean);return t.length>0?t[t.length-1]:void 0},ub=e=>{const{serviceCode:t,serviceMessage:r}=(e=>{const t=e instanceof ut&&rb(e.details)?e.details:void 0,r=ib(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 bt)return ab("File upload failed",ot.UPLOAD_REQUEST_FAILED,{cause:e.details});if(e instanceof ut&&!t)return e;if(t)switch(t){case"4041001":return ab("File not found",ot.VOICE_TO_TEXT_FILE_NOT_FOUND,{serviceCode:t,serviceMessage:r});case"4001002":return ab("Invalid file",ot.VOICE_TO_TEXT_FILE_INVALID,{serviceCode:t,serviceMessage:r},"validation");case"5021001":return ab("File upload failed",ot.UPLOAD_REQUEST_FAILED,{serviceCode:t,serviceMessage:r});case"4001003":return ab("Voice duration exceeds 60 seconds",ot.VOICE_TO_TEXT_FILE_DURATION_TOO_LONG,{serviceCode:t,serviceMessage:r},"validation");case"4031001":return ab("Voice-to-text service is not enabled",ot.SERVICE_NOT_ENABLED,{serviceCode:t,serviceMessage:r});case"4031002":return ab("Beta service usage limit exceeded",ot.SERVICE_LIMIT_EXCEEDED,{serviceCode:t,serviceMessage:r});case"4001001":return(e=>"string"==typeof e&&e.toLowerCase().includes("uploaded file exceeds"))(r)?ab("File too large",ot.VOICE_TO_TEXT_FILE_TOO_LARGE,{serviceCode:t,serviceMessage:r}):ab(r||"Missing or invalid request parameter",ot.VALIDATION_REQUIRED,{serviceCode:t,serviceMessage:r},"validation");case"5021003":case"5001003":return ab("Voice-to-text failed",ot.VOICE_TO_TEXT_FAILED,{serviceCode:t,serviceMessage:r});case"4011001":return ab(r||"Unauthorized or invalid token",ot.AUTH_UNAUTHORIZED,{serviceCode:t,serviceMessage:r},"auth");default:return ab(r||(e instanceof Error?e.message:"Voice-to-text failed"),ot.VOICE_TO_TEXT_FAILED,{serviceCode:t,serviceMessage:r})}return e instanceof ut?ab(e.message,e.code,e.details):ab(e instanceof Error?e.message:"Voice-to-text failed",ot.VOICE_TO_TEXT_FAILED)},lb=(e,t)=>{if(!rb(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 ab("Invalid file",ot.VOICE_TO_TEXT_FILE_INVALID,{path:"voiceMessageBody"},"validation");var r;if(cb(t))throw ab("Invalid file",ot.VOICE_TO_TEXT_FILE_INVALID,{path:"voiceParams"},"validation");if(!e.url)throw ab("File not found",ot.VOICE_TO_TEXT_FILE_NOT_FOUND,{path:"voiceMessageBody.url"});if(!db(e.url))throw ab("Invalid file",ot.VOICE_TO_TEXT_FILE_INVALID,{path:"voiceMessageBody.url"},"validation");return e},hb=(e,t)=>{if(cb(t))throw ab("Invalid file",ot.VOICE_TO_TEXT_FILE_INVALID,{path:"voiceParams"},"validation");if(!nb(e))throw ab("Invalid file",ot.VOICE_TO_TEXT_FILE_INVALID,{path:"file"},"validation");return e},pb=async(e,t,r,s)=>{const n=lb(r,s),i=db(n.url);if(!i)throw((e,t,r,s="invalid")=>new mt(e,{code:t,details:{fields:[{path:r,message:e,rule:s}]}}))("File not found",ot.VOICE_TO_TEXT_FILE_NOT_FOUND,"voiceMessageBody.url");try{const r=await e.post(`${tb(t)}/speech/transcriptions`,{data:{fileId:i,username:t.userId,...s?{audio:s}:{}}},{operation:"voiceMessageToText"});return{text:ob(r,"voiceMessageToText")}}catch(o){throw ub(o)}},mb=ky({keywordList:Ly(Ay()).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:xy(["or","and"]).optional(),conversationId:Ay().min(1).optional(),conversationType:xy(["singleChat","groupChat","chatRoom"]).optional(),msgTypes:Ly(xy(["txt","img","video","file","loc","custom","combine"])).optional(),startTime:Ny().optional(),endTime:Ny().optional(),searchScope:xy(["none","with","only"]).optional(),direction:xy(["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"}),fb=ky({option:mb,pageNum:Ny().int().min(1).default(1),pageSize:Ny().int().min(1).max(100).default(20)}),gb=bv(_v,{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"]}}}}}),yb=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=Fy.validateOrThrow(CI,e),s=UI(t),n=LI(),i={content:r.content};return r.targetLanguages&&(i.targetLanguages=r.targetLanguages),PI(r,s,"text",i,n)})(e,this.buildMessageSenderOrThrow())}createImageMessage(e){return((e,t,r)=>{const s=Fy.validateOrThrow(SI,e),n=UI(t),i=LI(),o=s.data?kI(void 0,s.data):"",a=s.originalUrl?Ts(s.originalUrl,{deriveVariants:!r?.useCustomAttachmentUpload}):void 0;s.data&&xh.set(i,s.data);const c=s.isGif??!1,d={localUrl:o,filename:s.filename,filetype:s.filetype,width:s.width,height:s.height,isGif:c,isOriginalImage:DI({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),PI(s,n,"image",d,i)})(e,this.buildMessageSenderOrThrow(),this.getClientOrThrow().getMessageCreationOptions())}createFileMessage(e){return((e,t)=>{const r=Fy.validateOrThrow(EI,e),s=UI(t),n=LI(),i=kI(r.originalUrl,r.data);r.data&&xh.set(n,r.data);const o={url:i,filename:r.filename,filetype:r.filetype};return void 0!==r.fileSize&&(o.fileSize=r.fileSize),void 0!==r.fileLength&&(o.fileLength=r.fileLength),PI(r,s,"file",o,n)})(e,this.buildMessageSenderOrThrow())}createVoiceMessage(e){return((e,t)=>{const r=Fy.validateOrThrow(wI,e),s=UI(t),n=LI(),i=kI(r.originalUrl,r.data);r.data&&xh.set(n,r.data);const o={url:i,filename:r.filename,filetype:r.filetype,duration:r.duration};return void 0!==r.fileLength&&(o.fileLength=r.fileLength),PI(r,s,"voice",o,n)})(e,this.buildMessageSenderOrThrow())}createVideoMessage(e){return((e,t)=>{const r=Fy.validateOrThrow(RI,e),s=UI(t),n=LI(),i=kI(r.originalUrl,r.data);r.data&&xh.set(n,r.data);const o={url:i,filename:r.filename,filetype:r.filetype,duration:r.duration};return void 0!==r.width&&(o.width=r.width),void 0!==r.height&&(o.height=r.height),void 0!==r.fileLength&&(o.fileLength=r.fileLength),r.thumbnailUrl&&(o.thumbnailUrl=r.thumbnailUrl),PI(r,s,"video",o,n)})(e,this.buildMessageSenderOrThrow())}createLocationMessage(e){return((e,t)=>{const r=Fy.validateOrThrow(AI,e),s=UI(t),n={latitude:r.latitude,longitude:r.longitude};return r.address&&(n.address=r.address),r.buildingName&&(n.buildingName=r.buildingName),PI(r,s,"location",n)})(e,this.buildMessageSenderOrThrow())}createCmdMessage(e){return((e,t)=>{const r=Fy.validateOrThrow(NI,e),s=UI(t),n={action:r.action};return void 0!==r.deliverOnlineOnly&&(n.deliverOnlineOnly=r.deliverOnlineOnly),PI(r,s,"cmd",n)})(e,this.buildMessageSenderOrThrow())}createCustomMessage(e){return((e,t)=>{const r=Fy.validateOrThrow(OI,e),s=UI(t),n={event:r.event};return r.params&&(n.params=r.params),PI(r,s,"custom",n)})(e,this.buildMessageSenderOrThrow())}createCombineMessage(e){return xI(e,this.buildMessageSenderOrThrow())}getConversationList(e){if(void 0!==e?.mark&&(!Number.isInteger(e.mark)||e.mark<0||e.mark>19))throw new mt("filter.mark must be an integer between 0 and 19",{code:ot.VALIDATION_INVALID_FORMAT,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(Cf);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=sI(t),n=Wv(r.conversationId,"params.conversationId"),i=Qv(r.conversationType,"params.conversationType"),o=r.deleteRoamingMessages??!1;if("boolean"!=typeof o)throw Hv("params.deleteRoamingMessages","params.deleteRoamingMessages must be a boolean");return await e.request(`/${s.orgName}/${s.appName}/user/${s.encodedUserId}/user_channel?resource=${s.encodedResource}`,{method:"DELETE",body:{channel:n,type:"groupChat"===i?"groupChat":Zv(i),delete_roam:o},operation:"deleteConversation"}),{conversationId:n,conversationType:i,operation:"delete"}})(this.getRestClient(t),t,e),s=this.getClientOrThrow(),n=s.getCacheManager()?.deleteConversation({conversationId:r.conversationId,type:r.conversationType});return n?.changed&&s.emitConversationListUpdate("local"),r}async setConversationPinned(e){const t=this.getRestContextOrThrow(),r=await(async(e,t,r)=>{const s=sI(t),n=Wv(r.conversationId,"params.conversationId"),i=Qv(r.conversationType,"params.conversationType");if("boolean"!=typeof r.pinned)throw Hv("params.pinned","params.pinned must be a boolean");const o="groupChat"===i?"groupChat":Zv(i),a=r.pinned?await e.post(`/${s.orgName}/${s.appName}/sdk/user/${s.encodedUserId}/user_channel/top?resource=${s.encodedResource}`,{type:o,to:n},{operation:"setConversationPinned"}):await e.delete(`/${s.orgName}/${s.appName}/sdk/user/${s.encodedUserId}/user_channel/top?type=${encodeURIComponent(o)}&to=${encodeURIComponent(n)}&resource=${s.encodedResource}`,{operation:"setConversationPinned"}),c=pu(a)&&pu(a.data)?a.data:{};return{conversationId:n,conversationType:i,operation:"setPinned",isPinned:"boolean"==typeof c.is_top?c.is_top:r.pinned,pinnedTime:"number"==typeof c.update_top_status_time?c.update_top_status_time:r.pinned?Date.now():0}})(this.getRestClient(t),t,e),s=this.getClientOrThrow().getCacheManager(),n=s?.applyConversationPinnedMutation({conversationId:r.conversationId,type:r.conversationType,isPinned:r.isPinned??e.pinned,pinnedTime:r.pinnedTime});return n?.changed&&this.getClientOrThrow().emitConversationListUpdate("local"),r}async addConversationMark(e){const t=this.getRestContextOrThrow(),r=await(async(e,t,r)=>nI(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)=>nI(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=sI(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)=>iI(e,t,r,!0))(this.getRestClient(t),t,e))}async unpinMessage(e){const t=this.getRestContextOrThrow();await this.executeRestOperation(()=>(async(e,t,r)=>iI(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=sI(t),n=Wv(r.conversationId,"params.conversationId"),i=Qv(r.conversationType,"params.conversationType"),o=await e.get(`/${s.orgName}/${s.appName}/sdk/user/${s.encodedUserId}/user_channel/pin?to=${encodeURIComponent(n)}&type=${encodeURIComponent(Zv(i))}&limit=${String(20)}`,{operation:"getPinnedMessageList"}),a=pu(o)&&pu(o.data)?o.data:{},c=(Array.isArray(a.msg_infos)?a.msg_infos:[]).reduce((e,r)=>{if(!pu(r))return e;const s="string"==typeof r.pin_msg_id?r.pin_msg_id:pu(r.message)&&"string"==typeof r.message.id?r.message.id:"";if(!s)return e;const o="number"==typeof r.pin_opt_at?r.pin_opt_at:0,a=tI(r.message,{messageId:s,conversationId:n,conversationType:i,currentUserId:t.userId,timestamp:o});return a?(e.push({messageId:s,conversationId:n,conversationType:i,operatorId:"string"==typeof r.pin_operator?r.pin_operator:void 0,pinnedAt:o,message:a}),e):e},[]);return{items:c}})(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;Vs("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 mt("only text and custom messages are editable",{code:ot.OPERATION_UNSUPPORTED});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=`${FI(t)}/users/${t.userId}/messageroaming`,i=await e.post(n,{queue:"singleChat"===r.conversationType?`${r.conversationId}@easemob.com`:`${r.conversationId}@conference.easemob.com`,start:r.cursor&&r.cursor.length>0?r.cursor:-1,pull_number:r.pageSize??20,is_positive:"down"===r.searchDirection,msgType:(r.messageTypes??[]).join(","),end:-1,startTime:r.startTime??null,endTime:r.endTime??null,userIds:"singleChat"===r.conversationType?null:r.senderIds&&r.senderIds.length>0?r.senderIds:null},{operation:"getHistoryMessages"}),o=KI(i,"getHistoryMessages"),a=Array.isArray(o.msgs)?o.msgs:[],c=[];for(const d of a){if(!GI(d)||"string"!=typeof d.msg||0===d.msg.length)continue;const e=s(BI(d.msg));e&&c.push(e)}return{items:c,cursor:jI(o.next_key),hasMore:!0!==o.is_last&&c.length>0}})(this.getRestClient(t),t,e,e=>this.getClientOrThrow().decodeServerMessageMeta(e)))}async searchMessages(e){const t=Fy.validateOrThrow(fb,e),r=this.getRestContextOrThrow();return this.executeRestOperation(()=>eb(this.getRestClient(r),r,t))}async downloadAttachment(e){return this.getClientOrThrow().downloadAttachment(e.message)}async downloadAndParseCombineMessage(e){return this.getClientOrThrow().downloadAndParseCombinePayload(this.resolveDownloadCombineMessageParams(e))}async removeHistoryMessages(e){if(this.validateConversationLocator(e),!e.messageIds&&!e.beforeTimestamp)throw this.buildValidationError("messageIds or beforeTimestamp is required","removeHistoryMessages");if(e.messageIds&&0===e.messageIds.length)throw this.buildValidationError("messageIds cannot be empty","messageIds");if(void 0!==e.beforeTimestamp&&(!Number.isInteger(e.beforeTimestamp)||e.beforeTimestamp<=0))throw this.buildValidationError("beforeTimestamp must be a positive integer","beforeTimestamp");const t=this.getRestContextOrThrow();await this.executeRestOperation(()=>(async(e,t,r)=>{const s="singleChat"===r.conversationType?"userId":"groupId",n="singleChat"===r.conversationType?"chat":"group",i=encodeURIComponent(t.clientResource),o=r.messageIds?`${FI(t)}/sdk/message/roaming/${n}/user/${t.userId}?${s}=${encodeURIComponent(r.conversationId)}&msgIdList=${encodeURIComponent(r.messageIds.join(","))}&resource=${i}`:`${FI(t)}/sdk/message/roaming/${n}/user/${t.userId}/time?${s}=${encodeURIComponent(r.conversationId)}&delTime=${r.beforeTimestamp}&resource=${i}`;await e.delete(o,{operation:"removeHistoryMessages"})})(this.getRestClient(t),t,e))}async getGroupMessageReadUsers(e){if(this.requireNonEmptyString(e.groupId,"groupId"),this.requireNonEmptyString(e.messageId,"messageId"),void 0!==e.pageSize&&(!Number.isInteger(e.pageSize)||e.pageSize<=0))throw this.buildValidationError("pageSize must be a positive integer","pageSize");const t=this.getRestContextOrThrow(),r=await this.executeRestOperation(()=>(async(e,t,r)=>{const s=Qy();s.set("limit",String(r.pageSize??10)),r.cursor&&s.set("key",r.cursor);const n=`${FI(t)}/chatgroups/${encodeURIComponent(r.groupId)}/acks/${encodeURIComponent(r.messageId)}?${s.toString()}`,i=await e.get(n,{operation:"getGroupMessageReadUsers"}),o=KI(i,"getGroupMessageReadUsers"),a=GI(o.group_ack)?o.group_ack:o,c=(Array.isArray(a.userlist)?a.userlist:[]).map(e=>GI(e)&&"string"==typeof e.username?{userId:e.username,user:VI(e.username),ackId:"string"==typeof e.meta_id?e.meta_id:void 0,timestamp:"number"==typeof e.timestamp?e.timestamp:void 0,ackContent:"string"==typeof e.ack_content?e.ack_content:void 0}:null).filter(e=>null!==e);return{groupId:r.groupId,messageId:"string"==typeof o.ackmid?o.ackmid:r.messageId,users:c,count:"number"==typeof a.total?a.total:c.length,cursor:jI(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=`${FI(t)}/chatgroups/${encodeURIComponent(r.groupId)}/acks/batch`,n=await e.post(s,{messageIds:r.messageIds},{operation:"getGroupMessageReadReceipts"});return zI(n,"getGroupMessageReadReceipts").map(e=>GI(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(`${FI(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=`${FI(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=Qy(),n="string"==typeof r.messageId?r.messageId:[...r.messageId].join(",");s.set("msgIdList",n),s.set("msgType","groupChat"===r.conversationType?"group":"chat"),r.groupId&&s.set("groupId",r.groupId);const i=await e.get(`${FI(t)}/reaction/user/${t.userId}?${s.toString()}`,{operation:"getReactionList"});return zI(i,"getReactionList").map(e=>{if(!GI(e)||"string"!=typeof e.msgId)return null;const t=Array.isArray(e.reactionList)?e.reactionList:[];return{messageId:e.msgId,reactions:t.map(e=>GI(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=Qy();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(`${FI(t)}/reaction/user/${t.userId}/detail?${s.toString()}`,{operation:"getReactionDetail"}),i=KI(n,"getReactionDetail"),o=Array.isArray(i.reactionUserList)?i.reactionUserList.map(e=>GI(e)&&"string"==typeof e.userId?{userId:e.userId,user:VI(e.userId),createdAt:"string"==typeof e.createdAt?e.createdAt:void 0}:null).filter(e=>null!==e):[],a=Array.isArray(i.userList)?i.userList.filter(e=>"string"==typeof e).map(e=>({userId:e,user:VI(e)})):[],c=o.length>0?o:a;return{reaction:"string"==typeof i.reaction?i.reaction:r.reaction,count:"number"==typeof i.count?i.count:c.length,isAddedBySelf:!0===i.state,reactionUsers:c,cursor:jI(i.cursor),hasMore:jI(i.cursor).length>0,createdAt:"string"==typeof i.createdAt?i.createdAt:void 0}})(this.getRestClient(t),t,e))}async getSupportedTranslationLanguages(){const e=this.getRestContextOrThrow();return this.executeRestOperation(()=>(async(e,t)=>{const r=await qI(()=>e.get(`${FI(t)}/users/${t.userId}/translate/support/language`,{operation:"getSupportedTranslationLanguages"}));return HI(r,"getSupportedTranslationLanguages").map(e=>GI(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 mt("only text messages can be translated",{code:ot.TRANSLATE_PARAM_INVALID,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 mt("message text is required",{code:ot.TRANSLATE_PARAM_INVALID,details:{fields:[{path:"message.body.content",message:"is required",rule:"required"}]}});if(!Array.isArray(e.targetLanguages)||0===e.targetLanguages.length)throw new mt("targetLanguages is required",{code:ot.TRANSLATE_PARAM_INVALID,details:{fields:[{path:"targetLanguages",message:"is required",rule:"required"}]}});if(e.targetLanguages.some(e=>"string"!=typeof e||0===e.trim().length))throw new mt("targetLanguages contains invalid language code",{code:ot.TRANSLATE_PARAM_INVALID,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 qI(()=>e.post(`${FI(t)}/users/${t.userId}/translate`,{text:r.text,to:[...r.targetLanguages]},{operation:"translateMessage"})),n=HI(s,"translateMessage"),i=GI(n[0])?n[0]:null;if(!i)throw qf({apiName:"translateMessage",message:"translateMessage response data is invalid",mapped:!1});const o=Array.isArray(i.translations)?i.translations:[],a=GI(i.detectedLanguage)?i.detectedLanguage:void 0;return{detectedLanguage:a&&"string"==typeof a.language?{language:a.language,score:"number"==typeof a.score?a.score:Number(a.score??0)}:void 0,translations:o.map(e=>GI(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){lb(e,t);const r=this.getRestContextOrThrow();return this.executeRestOperation(()=>pb(this.getRestClient(r),r,e,t))}async voiceFileToText(e,t){hb(e,t);const r=this.getRestContextOrThrow(),s=this.getClientOrThrow().getUploadAdapter();if(!s)throw new ut("Upload capability is missing for current platform",ot.UPLOAD_REQUIRED_FIELD_MISSING);return this.executeRestOperation(()=>(async(e,t,r,s)=>{const n=hb(r,s),i=os({file:n,fallbackName:sb(n)?"voice.amr":void 0,fallbackMimeType:"audio/amr"});try{const r=await e.upload({url:`${t.restBaseUrl}${tb(t)}/speech/recognitions`,headers:{Authorization:`Bearer ${t.token}`,Accept:"application/json",[ru]:tu()},source:i.source,fields:{username:t.userId,...s?.format?{format:s.format}:{},...void 0!==s?.sampleRate?{sampleRate:String(s.sampleRate)}:{},...void 0!==s?.bitsPerSample?{bitsPerSample:String(s.bitsPerSample)}:{},...void 0!==s?.channels?{channels:String(s.channels)}:{}}});let n=r.body;try{n=JSON.parse(r.body)}catch{n=r.body}if(r.status<200||r.status>=300)throw new ut("Voice-to-text failed",ot.VOICE_TO_TEXT_FAILED,{details:{httpStatus:r.status,rawResponse:n}});return{text:ob(n,"voiceFileToText")}}catch(o){if(o instanceof ut)throw ub(o);throw ub(Pd(o))}})(s,r,e,t))}validateConversationLocator(e){if(this.requireNonEmptyString(e.conversationId,"conversationId"),"singleChat"!==e.conversationType&&"groupChat"!==e.conversationType&&"chatRoom"!==e.conversationType)throw this.buildValidationError("conversationType is invalid","conversationType")}validateUnreadConversationLocator(e){if(this.requireNonEmptyString(e.conversationId,"conversationId"),"singleChat"!==e.conversationType&&"groupChat"!==e.conversationType)throw this.buildValidationError("conversationType must be singleChat or groupChat","conversationType")}validateSendMessageReadReceiptsParams(e){if(this.requireNonEmptyString(e.conversationId,"conversationId"),"singleChat"!==e.conversationType&&"groupChat"!==e.conversationType)throw this.buildValidationError("conversationType is invalid","conversationType");if(e.messageIds.length>50)throw this.buildValidationError("messageIds cannot contain more than 50 items","messageIds");return this.validateMessageIdList(e.messageIds,"messageIds")}validateMessageIdList(e,t){if(!Array.isArray(e)||0===e.length)throw this.buildValidationError(`${t} cannot be empty`,t);return e.map((e,r)=>{if("string"!=typeof e||0===e.trim().length)throw this.buildValidationError(`${t}.${r} is invalid`,`${t}.${r}`);return e.trim()})}resolveDownloadCombineMessageParams(e){if("message"in e){if("combine"!==e.message.type)throw new mt("message must be a combine message",{code:ot.VALIDATION_INVALID_FORMAT});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===ot.AUTH_NOT_LOGIN||e===ot.AUTH_UNAUTHORIZED?new pt(t??"authentication failed",{code:e}):e===ot.CONNECTION_WEBSOCKET_ERROR||e===ot.CONNECTION_TIMEOUT?new ht(t??"connection unavailable",{code:e}):107===e||110===e||205===e||500===e||e===ot.VALIDATION_REQUIRED||e===ot.VALIDATION_INVALID_FORMAT?new mt(t??"invalid parameter",{code:e}):e===ot.MESSAGE_RECALL_TIME_LIMIT?new ut(t??"message recall time limit reached",e):e===ot.MESSAGE_EDIT_FAILED?new ut(t??"message update failed",e):e===ot.OPERATION_UNSUPPORTED?new mt(t??"operation unsupported",{code:e}):new ut(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 mt(e,{code:ot.VALIDATION_INVALID_FORMAT,details:{fields:[{path:t,message:e,rule:"required"}]}})}getEventContextOrThrow(){if(!this.eventContext)throw new mt("ChatManager is not bound to event context",{code:ot.VALIDATION_REQUIRED});return this.eventContext}getClientOrThrow(){if(!this.client)throw new mt("ChatManager is not bound to client",{code:ot.VALIDATION_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 Vf(e.restBaseUrl,{errorMap:gb,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 ht("client is not connected",{code:ot.CONNECTION_WEBSOCKET_ERROR});return e}getCurrentUserIdOrThrow(){const e=this.getClientOrThrow().getCurrentUserId();if(!e)throw new pt("user is not logged in",{code:ot.AUTH_NOT_LOGIN});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 mI({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 mt||e instanceof pt||e instanceof ht||e instanceof lt?e:e instanceof vt?new lt(e.message,{code:e.code,details:e.details}):e instanceof It||e instanceof ut?e:new ut(String(e),ot.UNKNOWN)}};yb.key="chatManager";let vb=yb;class Ib{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 bb=e=>new mt(`${e} is required`,{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:e,message:`${e} is required`,rule:"required"}]}}),_b=(e,t)=>new mt(t,{code:ot.VALIDATION_INVALID_FORMAT,details:{fields:[{path:e,message:t,rule:"invalid_format"}]}}),Tb=(e,t)=>{if("string"!=typeof e||0===e.trim().length)throw bb(t);return e.trim()},Cb=(e,t)=>{if(void 0===e)return"";if("string"!=typeof e)throw _b(t,`${t} must be a string`);return e},Sb=(e,t)=>{if(void 0===e)return 20;if("number"!=typeof e||!Number.isInteger(e)||e<=0||e>50)throw _b(t,`${t} must be an integer between 1 and 50`);return e},Eb=e=>{const{orgName:t,appName:r}=fs(e.appKey);return{orgName:t,appName:r,encodedUserId:encodeURIComponent(e.userId),encodedResource:encodeURIComponent(e.clientResource)}},wb=e=>pu(e)?e:null,Rb=e=>{const t=wb(e);return t?.data??e},Ab=e=>{const t=wb(e);if(Array.isArray(t?.entities))return t.entities;const r=Rb(e);if(Array.isArray(r))return r;const s=wb(r);return Array.isArray(s?.entities)?s.entities:Array.isArray(s?.affiliations)?s.affiliations:[]},Nb=e=>{const t=wb(e),r=wb(t?.data),s=wb(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)??""},Ob=e=>{const t=wb(e);if(!t)return null;const r=("string"==typeof t.id?t.id:void 0)??("string"==typeof t.msgId?t.msgId:void 0);if(!r)return null;const s="number"==typeof t.timestamp?t.timestamp:0,n=t.payload,i="string"==typeof n?mu(n,{}):wb(n)??{},o=Array.isArray(i.bodies)?i.bodies:[],a=wb(o[0])??{};return{msgId:r,type:("string"==typeof a.type?a.type:void 0)??("string"==typeof i.type?i.type:void 0)??"",body:a,timestamp:s}},Mb=e=>{const t=wb(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:Ob(t.lastMessage??t.last_message)}:null},Ub=e=>({items:Ab(e).map(e=>Mb(e)).filter(e=>null!==e),cursor:Nb(e)}),Lb=async(e,t,r)=>{const s=Eb(t),n=Tb(r,"chatThreadId");return(e=>{const t=Rb(e),r=Array.isArray(t)?t[0]:t,s=Mb(r);if(!s)throw _b("response.data","response.data is invalid");return s})(await e.get(`/${s.orgName}/${s.appName}/thread/${encodeURIComponent(n)}`,{operation:"getChatThreadInfo"}))},kb=async(e,t,r)=>{const s=Eb(t),n=Tb(r.chatThreadId,"params.chatThreadId"),i=Sb(r.pageSize,"params.pageSize"),o=Cb(r.cursor,"params.cursor"),a=Qy({limit:String(i),cursor:o}),c=await e.get(`/${s.orgName}/${s.appName}/thread/${encodeURIComponent(n)}/users?${a.toString()}`,{operation:"getChatThreadMemberList"});return{items:Ab(d=c).map(e=>{if("string"==typeof e)return{memberId:e};const t=wb(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:Nb(d)};var d},Db=async(e,t,r)=>{const s=Eb(t);if(!Array.isArray(r.chatThreadIds)||0===r.chatThreadIds.length)throw bb("params.chatThreadIds");if(r.chatThreadIds.length>20)throw _b("params.chatThreadIds","params.chatThreadIds must contain at most 20 items");const n=r.chatThreadIds.map((e,t)=>Tb(e,`params.chatThreadIds[${t}]`)),i=await e.post(`/${s.orgName}/${s.appName}/thread/message`,{threadIds:n},{operation:"getChatThreadLastMessageList"});return{items:Ab(i).map(e=>{const t=wb(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:Ob(t.lastMessage??t.last_message)}:null}).filter(e=>null!==e)}},Pb=bv(_v,{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"]}}}}}),xb=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 mt("chatThreadId is required",{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:"chatThreadId",message:"chatThreadId is required",rule:"required"}]}});const r=this.registry.get(t);if(r)return r;const s=new Ib(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=Eb(t),n=Tb(r.parentId,"params.parentId"),i=Tb(r.name,"params.name"),o=Tb(r.messageId,"params.messageId"),a=await e.post(`/${s.orgName}/${s.appName}/thread?resource=${s.encodedResource}`,{name:i,msg_id:o,group_id:n,owner:t.userId},{operation:"createChatThread"}),c=wb(Rb(a)),d="string"==typeof c?.thread_id?c.thread_id:void 0;if(!d)throw _b("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=Eb(t),n=Tb(r.parentId,"params.parentId"),i=Sb(r.pageSize,"params.pageSize"),o=Cb(r.cursor,"params.cursor"),a=Qy({limit:String(i),cursor:o}),c=await e.get(`/${s.orgName}/${s.appName}/threads/chatgroups/${encodeURIComponent(n)}?${a.toString()}`,{operation:"getChatThreadList"});return Ub(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=Eb(t),n=Sb(r.pageSize,"params.pageSize"),i=Cb(r.cursor,"params.cursor"),o=Qy({limit:String(n),cursor:i}),a="string"==typeof r.parentId&&r.parentId.trim().length>0?`/${s.orgName}/${s.appName}/threads/chatgroups/${encodeURIComponent(r.parentId.trim())}/user/${s.encodedUserId}?${o.toString()}`:`/${s.orgName}/${s.appName}/threads/user/${s.encodedUserId}?${o.toString()}`,c=await e.get(a,{operation:"getJoinedChatThreadList"});return Ub(c)})(this.getRestClient(t),t,e)})}async getChatThreadInfo(e){return this.runOperation("getChatThreadInfo",async()=>{const t=this.getRestContextOrThrow();return Lb(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=Eb(t),n=Tb(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=Eb(t),n=Tb(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=Eb(t),n=Tb(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=Eb(t),n=Tb(r.chatThreadId,"params.chatThreadId"),i=Tb(r.name,"params.name");await e.put(`/${s.orgName}/${s.appName}/thread/${encodeURIComponent(n)}?resource=${s.encodedResource}`,{name:i},{operation:"updateChatThreadName"})})(this.getRestClient(t),t,e)})}async getChatThreadMemberList(e){return this.runOperation("getChatThreadMemberList",async()=>{const t=this.getRestContextOrThrow();return kb(this.getRestClient(t),t,e)})}async removeChatThreadMember(e){return this.runOperation("removeChatThreadMember",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=Eb(t),n=Tb(r.chatThreadId,"params.chatThreadId"),i=Tb(r.memberId,"params.memberId");await e.delete(`/${s.orgName}/${s.appName}/thread/${encodeURIComponent(n)}/users/${encodeURIComponent(i)}?resource=${s.encodedResource}`,{operation:"removeChatThreadMember"})})(this.getRestClient(t),t,e)})}async getChatThreadLastMessageList(e){return this.runOperation("getChatThreadLastMessageList",async()=>{const t=this.getRestContextOrThrow();return Db(this.getRestClient(t),t,e)})}getClientOrThrow(){if(!this.client)throw new mt("ChatThreadManager is not bound to client",{code:ot.VALIDATION_REQUIRED,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 mt("ChatThreadManager is not bound to event context",{code:ot.VALIDATION_REQUIRED,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 Vf(e.restBaseUrl,{errorMap:Pb,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 ut)throw r;const t=r instanceof Error?r.message:String(r);throw new ut(`ChatThreadManager ${e} failed: ${t}`,ot.UNKNOWN)}}buildChatThreadPublicEvent(e){const t=e.payload,r="string"==typeof t.id?t.id:"",s="string"==typeof t.muc_parent_id?t.muc_parent_id:"";if(!r||!s)return null;const n="string"==typeof t.msg_parent_id?t.msg_parent_id:void 0,i="string"==typeof t.name?t.name:void 0,o="number"==typeof t.message_count?t.message_count:void 0,a=t.last_message&&"object"==typeof t.last_message?this.tryBuildThreadMessageSnippet(t.last_message):void 0,c="number"==typeof t.timestamp?t.timestamp:0,d="string"==typeof t.from?t.from:void 0,u={chatThreadId:r,parentId:s,name:i??"",messageId:n,messageCount:o,lastMessage:a};switch(t.operation){case"create":return{eventName:"onChatThreadCreated",payload:{chatThreadId:r,parentId:s,operatorId:d,chatThreadName:i,messageId:n,thread:u,timestamp:c}};case"update":case"update_msg":return{eventName:"onChatThreadUpdated",payload:{chatThreadId:r,parentId:s,operatorId:d,chatThreadName:i,messageId:n,messageCount:o,lastMessage:a,thread:u,timestamp:c}};case"delete":return{eventName:"onChatThreadDestroyed",payload:{chatThreadId:r,parentId:s,operatorId:d,timestamp:c}};case"kick":return{eventName:"onChatThreadUserRemoved",payload:{chatThreadId:r,parentId:s,operatorId:d,memberId:t.userIds?.[0],timestamp:c}};default:return null}}tryBuildThreadMessageSnippet(e){const t=("string"==typeof e.id?e.id:void 0)??("string"==typeof e.msgId?e.msgId:void 0);if(!t)return null;const r=e.payload&&"object"==typeof e.payload?e.payload:{};return{msgId:t,type:"string"==typeof r.type?r.type:"",body:r,timestamp:"number"==typeof e.timestamp?e.timestamp:0}}};xb.key="chatThreadManager";let Fb=xb;class Bb{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 Gb=["nickname","avatarUrl","mail","phone","gender","sign","birth","ext"],qb=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},$b=e=>({userId:e.userId,nickname:e.nickname,avatarUrl:e.avatarUrl,sign:e.sign,ext:e.ext}),jb=e=>({userId:e}),Vb=(e,t,r)=>{const s={userId:r};for(const n of Gb){const r=t?.[n]??e?.[n];void 0!==r&&(s[n]=r)}return s},Kb=async(e,t)=>{const r=qb(e),s=new Map;if(0===r.length)return s;const n=t.cacheManager?.getUserInfoSummaries(r,!1)??[];for(const o of n)s.set(o.userId,$b(o));const i=r.filter(e=>!s.has(e));if(i.length>0&&t.fetchUserInfos){const e=await t.fetchUserInfos({userIds:i});for(const t of e)s.set(t.userId,t)}for(const o of r)s.has(o)||s.set(o,jb(o));return s},zb=e=>pu(e)?e:null,Hb=e=>"string"==typeof e?e:void 0,Wb=e=>{const t=Hb(e)?.trim();return t||void 0},Jb=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}},Qb=e=>{if("boolean"==typeof e)return e;if("string"==typeof e){if("true"===e)return!0;if("false"===e)return!1}},Zb=e=>{const t=zb(e);return t&&Array.isArray(t.data)?t.data:t&&Array.isArray(t.entities)?t.entities:Array.isArray(e)?e:[]},Yb=e=>{const t=zb(e);return t?zb(t.data)?t.data:t:null},Xb=(e,t)=>{const r=zb(e),s=r&&zb(r.params),n=s?.[t];if(Array.isArray(n)&&0!==n.length)return Jb(n[0])},e_=e=>Wb(e.chatRoomId)??Wb(e.chatroomid)??Wb(e.id)??"",t_=e=>Hb(e.name)??Hb(e.title)??Hb(e.groupname)??"",r_=e=>jb(e),s_=(e,t)=>{const r=(e=>{const t=Hb(e);return"owner"===t||"admin"===t||"member"===t||"none"===t?t:void 0})(e.permission);if(void 0!==r)return r;if(!t)return;if(Wb(e.owner)===t)return"owner";const s=Array.isArray(e.affiliations)?e.affiliations:[];for(const n of s){const e=zb(n);if(e){if(Wb(e.owner)===t)return"owner";if(Wb(e.admin)===t)return"admin";if(Wb(e.member)===t)return"member"}}},n_=(e,t)=>{const r=zb(e);if(!r)return null;const s=e_(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)})(Wb(r.owner)):Wb(r.owner);return{chatRoomId:s,name:t_(r),owner:n?r_(n):void 0,memberCount:Jb(r.memberCount)??Jb(r.affiliations_count),disabled:Qb(r.disabled)}},i_=(e,t)=>{const r=(e=>{const t=zb(e);return t?Jb(t.count):void 0})(e),s=Zb(e).map(e=>n_(e,t)).filter(e=>null!==e),n=Xb(e,"pagenum"),i=Xb(e,"pagesize");return{items:s,pageNum:n,pageSize:i,total:r,hasMore:void 0!==r&&void 0!==n&&void 0!==i?n*i<r:void 0}},o_=e=>Zb(e).map(e=>Wb(e)).filter(e=>Boolean(e)).map(e=>r_(e)),a_=(e,t)=>{const r=Yb(e)??{},s=Array.isArray(r.successKeys)?r.successKeys.filter(e=>"string"==typeof e):[],n=zb(r.errorKeys)??{},i={};for(const[o,a]of Object.entries(n))"string"==typeof a&&(i[o]={code:d_(a),message:a});return{chatRoomId:t,appliedKeys:s,failedKeys:i}},c_=e=>{const t=zb(e),r=t?.data,s=Array.isArray(r)?r:void 0!==r?[r]:[],n=[],i=[];return s.forEach(e=>{const t=zb(e),r=(e=>{const t=zb(e);if(!t)return null;const r=Wb(t.user),s=Wb(t.chatRoomId)??Wb(t.chatroomid)??Wb(t.id),n=Hb(t.action),i=Qb(t.result);return r&&s&&void 0!==n&&void 0!==i?{chatRoomId:s,user:r_(r),action:n,reason:Hb(t.reason),...i?{}:{reason:Hb(t.reason)??"failed"}}:null})(e);if(!r||!t)return;Qb(t.result)?n.push(r):i.push(r)}),{succeeded:n,failed:i}},d_=e=>e.includes("is exceeding maximum limit")||e.includes("size of metadata")&&e.includes("exceeds")?ot.SERVICE_LIMIT_EXCEEDED:e.includes("is not part of you")?ot.CHATROOM_PERMISSION_DENIED:e.includes("is not Legal")||e.includes("is not exist")?ot.VALIDATION_REQUIRED:ot.REST_BUSINESS_UNKNOWN,u_=e=>{const{orgName:t,appName:r}=fs(e.appKey);return{orgName:t,appName:r,encodedUserId:encodeURIComponent(e.userId),encodedResource:encodeURIComponent(e.clientResource)}},l_=e=>new mt(`${e} is required`,{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:e,message:`${e} is required`,rule:"required"}]}}),h_=(e,t)=>new mt(t,{code:ot.VALIDATION_INVALID_FORMAT,details:{fields:[{path:e,message:t,rule:"invalid_format"}]}}),p_=(e,t)=>`/${e.orgName}/${e.appName}${t}`,m_=(e,t)=>{if(void 0!==e){if("string"!=typeof e)throw h_(t,`${t} must be a string`);return e}},f_=(e,t)=>{if(void 0!==e){if("number"!=typeof e||Number.isNaN(e))throw h_(t,`${t} must be a number`);return e}},g_=(e,t)=>{const r=Qy();"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}`:""},y_=(e,t)=>{if("string"!=typeof e||0===e.trim().length)throw l_(t);return e.trim()},v_=(e,t)=>{if(!Array.isArray(e)||0===e.length)throw l_(t);const r=[],s=new Set;if(e.forEach((e,n)=>{if("string"!=typeof e)throw h_(`${t}[${n}]`,`${t}[${n}] must be a string`);const i=e.trim();i&&!s.has(i)&&(s.add(i),r.push(i))}),0===r.length)throw l_(t);return r},I_=(e,t)=>v_(e,t),b_=async(e,t,r)=>{const s=u_(t),n=y_(r.chatRoomId,"params.chatRoomId"),i=p_(s,`/chatrooms/${encodeURIComponent(n)}?joined_time=true&version=v3`);return((e,t)=>{const r=Zb(e),s=zb(r[0])??Yb(e)??{},n=n_(s)??{chatRoomId:e_(s),name:t_(s)},i=s_(s,t);return{...n,description:Hb(s.description),maxMembers:Jb(s.maxMembers)??Jb(s.maxusers)??Jb(s.max_users),createdAt:Jb(s.createdAt)??Jb(s.created),ext:Hb(s.ext)??Hb(s.custom),muteAllMembers:Qb(s.mute),permissionType:i}})(await e.get(i,{operation:"getChatRoomInfo"}),t.userId)},__=async(e,t,r)=>{const s=u_(t),n=y_(r.chatRoomId,"params.chatRoomId"),i={},o=m_(r.name,"params.name"),a=m_(r.description,"params.description"),c=f_(r.maxMembers,"params.maxMembers");if(void 0!==o&&(i.groupname=o),void 0!==a&&(i.description=a),void 0!==c&&(i.maxusers=c),0===Object.keys(i).length)throw l_("params");const d=p_(s,`/chatrooms/${encodeURIComponent(n)}?resource=${s.encodedResource}`);return(e=>{const t=Yb(e)??{};return{nameUpdated:Qb(t.groupname),descriptionUpdated:Qb(t.description),maxMembersUpdated:Qb(t.maxusers)}})(await e.put(d,i,{operation:"updateChatRoomInfo"}))},T_=async(e,t,r)=>{const s=u_(t),n=y_(r.chatRoomId,"params.chatRoomId"),i=p_(s,`/chatrooms/${encodeURIComponent(n)}/users${(e=>{const t=Qy();"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 Zb(e)){const e=zb(n);if(!e)continue;const r=Wb(e.owner),s=Wb(e.admin),i=Wb(e.member),o=r??s??i;o&&t.push({user:r_(o),role:r?"owner":s?"admin":"member",joinedAt:Jb(e.joinedAt)??Jb(e.joined_time)})}const r=zb(e),s=r?Wb(r.cursor):void 0;return{items:t,cursor:s,hasMore:"string"==typeof s&&s.length>0}})(await e.get(i,{operation:"getChatRoomMemberList"}))},C_=async(e,t,r)=>{const s=u_(t),n=y_(r.chatRoomId,"params.chatRoomId"),i=p_(s,`/chatrooms/${encodeURIComponent(n)}/admin`),o=await e.get(i,{operation:"getChatRoomAdminList"});return o_(o)},S_=async(e,t,r)=>{const s=u_(t),n=y_(r.chatRoomId,"params.chatRoomId"),i=Qy();i.set("version","v3"),"number"==typeof r.pageNum&&i.set("pagenum",String(r.pageNum)),"number"==typeof r.pageSize&&i.set("pagesize",String(r.pageSize));const o=p_(s,`/chatrooms/${encodeURIComponent(n)}/mute?${i.toString()}`);return(e=>{const t=Zb(e);if(t.every(e=>"string"==typeof e))return o_(e).map(e=>({user:e}));const r=[];for(const s of t){const e=zb(s);if(!e)continue;const t=Wb(e.user)??Wb(e.member)??Wb(e.owner)??Wb(e.admin);t&&r.push({user:r_(t),muteExpire:Jb(e.muteExpire)??Jb(e.expire)??Jb(e.expired)})}return r.map(e=>({user:e.user,muteExpire:e.muteExpire}))})(await e.get(o,{operation:"getChatRoomMuteList"}))},E_=async(e,t,r)=>{const s=u_(t),n=y_(r.chatRoomId,"params.chatRoomId"),i=p_(s,`/sdk/chatrooms/${encodeURIComponent(n)}/mute/${s.encodedUserId}?version=v3`);return(e=>{const t=Yb(e)??{};return{muted:Qb(t.muted)??Qb(t.value)??Boolean(t.data),muteExpireAt:Jb(t.muteExpireAt)??Jb(t.expire)??Jb(t.mute_expire)}})(await e.get(i,{operation:"isCurrentUserMutedInChatRoom"}))},w_=async(e,t,r)=>{const s=u_(t),n=y_(r.chatRoomId,"params.chatRoomId"),i=g_(r),o=i?"&":"",a=p_(s,`/chatrooms/${encodeURIComponent(n)}/blocks/users?version=v3${o}${i.replace("?","")}`),c=await e.get(a,{operation:"getChatRoomBlocklist"});return o_(c).map(e=>({user:e}))},R_=async(e,t,r)=>{const s=u_(t),n=y_(r.chatRoomId,"params.chatRoomId"),i=p_(s,`/chatrooms/${encodeURIComponent(n)}/white/users`),o=await e.get(i,{operation:"getChatRoomAllowlist"});return o_(o).map(e=>({user:e}))},A_=async(e,t,r)=>{const s=u_(t),n=y_(r.chatRoomId,"params.chatRoomId"),i=p_(s,`/chatrooms/${encodeURIComponent(n)}/white/users/${s.encodedUserId}?version=v3`);return(e=>{const t=Yb(e)??{};return Qb(t.value)??Qb(t.white)??!1})(await e.get(i,{operation:"checkIfInChatRoomAllowList"}))},N_=async(e,t,r)=>{const s=u_(t),n=y_(r.chatRoomId,"params.chatRoomId"),i=p_(s,`/chatrooms/${encodeURIComponent(n)}/announcement`);return(e=>{const t=Yb(e)??{};return{announcement:Hb(t.announcement)??""}})(await e.get(i,{operation:"getChatRoomAnnouncement"}))},O_=async(e,t,r)=>{const s=u_(t),n=y_(r.chatRoomId,"params.chatRoomId"),i=p_(s,`/metadata/chatroom/${encodeURIComponent(n)}`);return((e,t)=>{const r=Yb(e)??{};return{chatRoomId:t,attributes:Object.fromEntries(Object.entries(r).filter(e=>"string"==typeof e[1]))}})(await e.post(i,{keys:r.keys?I_(r.keys,"params.keys"):void 0},{operation:"getChatRoomAttributes"}),n)},M_=async(e,t,r)=>{const s=u_(t),n=y_(r.chatRoomId,"params.chatRoomId"),i=((e,t)=>{if(!e||"object"!=typeof e||Array.isArray(e))throw h_(t,`${t} must be an object`);const r=Object.entries(e);if(0===r.length)throw l_(t);return Object.fromEntries(r.map(([e,r])=>{if("string"!=typeof e||0===e.trim().length)throw h_(t,`${t} contains invalid key`);if("string"!=typeof r)throw h_(`${t}.${e}`,`${t}.${e} must be a string`);return[e,r]}))})(r.attributes,"params.attributes"),{autoDelete:o=!0,isForced:a=!1}=r,c=a?"/forced":"",d=p_(s,`/metadata/chatroom/${encodeURIComponent(n)}/user/${s.encodedUserId}${c}`),u=await e.put(d,{metaData:i,autoDelete:o?"DELETE":"NO_DELETE"},{operation:"setChatRoomAttributes"});return a_(u,n)},U_={nickname:"nickname",avatarUrl:"avatarurl",mail:"mail",phone:"phone",gender:"gender",sign:"sign",birth:"birth",ext:"ext"},L_=(e,t,r)=>new mt(e,{code:"required"===r?ot.VALIDATION_REQUIRED:ot.VALIDATION_INVALID_FORMAT,details:{fields:[{path:t,message:e,rule:r}]}}),k_=(e,t)=>{if("string"!=typeof e)throw L_(`${t} must be a string`,t,"invalid_format");return e},D_=(e,t)=>{if("string"==typeof e||"number"==typeof e||"boolean"==typeof e)return e;throw L_(`${t} must be a string, number, or boolean`,t,"invalid_format")},P_=(e,t="attribute")=>{const r=U_[e];if(!r)throw L_(`${t} is invalid`,t,"invalid_format");return r},x_=(e,t="params.userIds")=>{if(!Array.isArray(e)||0===e.length)throw L_(`${t} is required`,t,"required");const r=[],s=new Set;for(const[n,i]of e.entries()){const e=k_(i,`${t}[${n}]`).trim();e&&(s.has(e)||(s.add(e),r.push(e)))}if(0===r.length)throw L_(`${t} is required`,t,"required");return r},F_=(e,t="params.attributes")=>{if(!Array.isArray(e)||0===e.length)throw L_(`${t} is required`,t,"required");const r=[],s=new Set;for(const[n,i]of e.entries()){const e=k_(i,`${t}[${n}]`);if(!(e in U_))throw L_(`${t}[${n}] is invalid`,`${t}[${n}]`,"invalid_format");s.has(e)||(s.add(e),r.push(e))}if(0===r.length)throw L_(`${t} is required`,t,"required");return r},B_=e=>{const{orgName:t,appName:r}=fs(e.appKey);return`/${t}/${r}/metadata/user/get`},G_=e=>{const{orgName:t,appName:r}=fs(e.appKey);return`/${t}/${r}/metadata/user/${encodeURIComponent(e.userId)}`},q_=e=>({targets:x_(e)}),$_=e=>!!pu(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),j_=(e,t)=>{if(Array.isArray(e))for(const r of e){if(!pu(r))continue;const e="string"==typeof r.username?r.username:"";e&&t.set(e,r)}},V_=(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},K_=(e,t)=>{const r=(e=>{const t=new Map,r=pu(e)?e:null;if(r?.data&&pu(r.data))for(const[s,n]of Object.entries(r.data))$_(n)&&t.set(s,n);return j_(r?.entities,t),j_(r?.data&&pu(r.data)?r.data.entities:void 0,t),t})(e),s=(e=>{const t=new Map,r=pu(e)?e:null;if(!r?.lastModified||!pu(r.lastModified))return t;for(const[s,n]of Object.entries(r.lastModified))"number"==typeof n&&t.set(s,n);return t})(e),n=[];for(const i of t){const e=r.get(i);e&&n.push({profile:V_(i,e),lastModified:s.get(i)})}return n},z_=(e,t)=>K_(e,t).map(e=>e.profile),H_=(e,t,r,s)=>{void 0!==r&&("gender"!==t?e.push([t,k_(r,s)]):e.push([t,String(D_(r,s))]))},W_=e=>e.map(([e,t])=>`${encodeURIComponent(e)}=${encodeURIComponent(t)}`).join("&"),J_={onChatRoomDestroyed:Se,onMembersJoined:Ee,onMembersExited:we,onRemovedFromChatRoom:Re,onMuteListAdded:Ae,onMuteListRemoved:Ne,onAllowListAdded:Oe,onAllowListRemoved:Me,onAllMemberMuteStateChanged:Ue,onAdminAdded:Le,onAdminRemoved:ke,onOwnerChanged:De,onAnnouncementChanged:Pe,onChatRoomInfoChanged:xe,onAttributesUpdate:Fe,onAttributesRemoved:Be},Q_=bv(_v,{common:{},apis:{getChatRoomList:{range:"",errors:{}},getChatRoomInfo:{range:"705",errors:{resource_not_found:{code:705,runtimeMessage:"Chat room does not exist",httpStatus:404,retryable:!1,aliases:["service_resource_not_found"]}}},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,runtimeMessage:"Chat room does not exist",httpStatus:404,retryable:!1,aliases:["service_resource_not_found"]}}},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,runtimeMessage:"Chat room does not exist",httpStatus:404,retryable:!1,aliases:["30005"]}}},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}}}}}),Z_=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=J_[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=J_[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=u_(t),n=p_(s,`/chatrooms${g_(r)}`),i=await e.get(n,{operation:"getChatRoomList"});return i_(i)})(this.getRestClient(t),t,e);return{...r,items:await this.hydrateSummaryOwners(r.items)}})}getChatRoom(e){this.requireClient();const t=e.trim();if(0===t.length)throw new mt("chatRoomId is required",{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:"chatRoomId",message:"chatRoomId is required",rule:"required"}]}});const r=this.chatRoomRegistry.get(t);if(r)return r;const s=new Bb(t,this);return this.chatRoomRegistry.set(t,s),s}async getChatRoomInfo(e){return this.runOperation("getChatRoomInfo",async()=>{const t=this.getRestContextOrThrow(),r=await b_(this.getRestClient(t),t,e);return this.hydrateChatRoomDetailUsers(r)})}async updateChatRoomInfo(e){return this.runOperation("updateChatRoomInfo",async()=>{const t=this.getRestContextOrThrow();return __(this.getRestClient(t),t,e)})}async joinChatRoom(e){return this.runOperation("joinChatRoom",async()=>{const t=this.requireClient(),r=y_(e.chatRoomId,"params.chatRoomId"),s=this.normalizeOptionalString(e.ext,"params.ext"),n=this.normalizeOptionalBoolean(e.leaveOtherRooms,"params.leaveOtherRooms");try{return(await t.sendChatRoomOperation({operation:"join",chatRoomId:r,ext:s,leaveOtherRooms:n})).chatRoomInfo??{}}catch(i){throw this.remapChatRoomOperationError("joinChatRoom",i)}})}async leaveChatRoom(e){return this.runOperation("leaveChatRoom",async()=>{const t=this.requireClient(),r=y_(e.chatRoomId,"params.chatRoomId");try{await t.sendChatRoomOperation({operation:"leave",chatRoomId:r})}catch(s){throw this.remapChatRoomOperationError("leaveChatRoom",s)}})}async getMemberList(e){return this.runOperation("getMemberList",async()=>{const t=this.getRestContextOrThrow(),r=await T_(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=u_(t),n=y_(r.chatRoomId,"params.chatRoomId"),i=v_(r.userIds,"params.userIds"),o=p_(s,`/chatrooms/${encodeURIComponent(n)}/users/${i.map(e=>encodeURIComponent(e)).join(",")}?resource=${s.encodedResource}`),a=await e.delete(o,{operation:"removeChatRoomMembers"});return c_(a)})(this.getRestClient(t),t,e);return this.hydrateActionListResult(r)})}async getAdminList(e){return this.runOperation("getAdminList",async()=>{const t=this.getRestContextOrThrow(),r=await C_(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=u_(t),n=y_(r.chatRoomId,"params.chatRoomId"),i=y_(r.userId,"params.userId"),o=p_(s,`/chatrooms/${encodeURIComponent(n)}/admin?resource=${s.encodedResource}`);await e.post(o,{newadmin:i},{operation:"setChatRoomAdmin"})})(this.getRestClient(t),t,e)})}async removeAdmin(e){return this.runOperation("removeAdmin",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=u_(t),n=y_(r.chatRoomId,"params.chatRoomId"),i=y_(r.userId,"params.userId"),o=p_(s,`/chatrooms/${encodeURIComponent(n)}/admin/${encodeURIComponent(i)}?resource=${s.encodedResource}`);await e.delete(o,{operation:"removeChatRoomAdmin"})})(this.getRestClient(t),t,e)})}async getMuteList(e){return this.runOperation("getMuteList",async()=>{const t=this.getRestContextOrThrow(),r=await S_(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=u_(t),n=y_(r.chatRoomId,"params.chatRoomId"),i=v_(r.userIds,"params.userIds"),o=f_(r.duration,"params.duration"),a=p_(s,`/chatrooms/${encodeURIComponent(n)}/mute?resource=${s.encodedResource}`);await e.post(a,{usernames:i,mute_duration:o},{operation:"muteChatRoomMembers"})})(this.getRestClient(t),t,e)})}async unmuteMembers(e){return this.runOperation("unmuteMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=u_(t),n=y_(r.chatRoomId,"params.chatRoomId"),i=v_(r.userIds,"params.userIds"),o=p_(s,`/chatrooms/${encodeURIComponent(n)}/mute/${i.map(e=>encodeURIComponent(e)).join(",")}?resource=${s.encodedResource}`);await e.delete(o,{operation:"unmuteChatRoomMembers"})})(this.getRestClient(t),t,e)})}async muteAllMembers(e){return this.runOperation("muteAllMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=u_(t),n=y_(r.chatRoomId,"params.chatRoomId"),i=p_(s,`/chatrooms/${encodeURIComponent(n)}/ban?resource=${s.encodedResource}`);await e.post(i,void 0,{operation:"muteAllChatRoomMembers"})})(this.getRestClient(t),t,e)})}async unmuteAllMembers(e){return this.runOperation("unmuteAllMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=u_(t),n=y_(r.chatRoomId,"params.chatRoomId"),i=p_(s,`/chatrooms/${encodeURIComponent(n)}/ban?resource=${s.encodedResource}`);await e.delete(i,{operation:"unmuteAllChatRoomMembers"})})(this.getRestClient(t),t,e)})}async checkIfInMuteList(e){return this.runOperation("checkIfInMuteList",async()=>{const t=this.getRestContextOrThrow();return E_(this.getRestClient(t),t,e)})}async getBlocklist(e){return this.runOperation("getBlocklist",async()=>{const t=this.getRestContextOrThrow(),r=await w_(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=u_(t),n=y_(r.chatRoomId,"params.chatRoomId"),i=v_(r.userIds,"params.userIds"),o=1===i.length,a=p_(s,o?`/chatrooms/${encodeURIComponent(n)}/blocks/users/${encodeURIComponent(i[0]??"")}?resource=${s.encodedResource}`:`/chatrooms/${encodeURIComponent(n)}/blocks/users?resource=${s.encodedResource}`),c=await e.post(a,o?void 0:{usernames:i},{operation:"blockChatRoomMembers"});return c_(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=u_(t),n=y_(r.chatRoomId,"params.chatRoomId"),i=v_(r.userIds,"params.userIds"),o=p_(s,`/chatrooms/${encodeURIComponent(n)}/blocks/users/${i.map(e=>encodeURIComponent(e)).join(",")}?resource=${s.encodedResource}`),a=await e.delete(o,{operation:"unblockChatRoomMembers"});return c_(a)})(this.getRestClient(t),t,e);return this.hydrateActionListResult(r)})}async getAllowlist(e){return this.runOperation("getAllowlist",async()=>{const t=this.getRestContextOrThrow(),r=await R_(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=u_(t),n=y_(r.chatRoomId,"params.chatRoomId"),i=v_(r.userIds,"params.userIds"),o=p_(s,`/chatrooms/${encodeURIComponent(n)}/white/users?resource=${s.encodedResource}`),a=await e.post(o,{usernames:i},{operation:"addUsersToChatRoomAllowlist"});return c_(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=u_(t),n=y_(r.chatRoomId,"params.chatRoomId"),i=v_(r.userIds,"params.userIds"),o=p_(s,`/chatrooms/${encodeURIComponent(n)}/white/users/${i.map(e=>encodeURIComponent(e)).join(",")}?resource=${s.encodedResource}`),a=await e.delete(o,{operation:"removeUsersFromChatRoomAllowlist"});return c_(a)})(this.getRestClient(t),t,e);return this.hydrateActionListResult(r)})}async checkIfInAllowList(e){return this.runOperation("checkIfInAllowList",async()=>{const t=this.getRestContextOrThrow();return A_(this.getRestClient(t),t,e)})}async getAnnouncement(e){return this.runOperation("getAnnouncement",async()=>{const t=this.getRestContextOrThrow();return N_(this.getRestClient(t),t,e)})}async updateAnnouncement(e){return this.runOperation("updateAnnouncement",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=u_(t),n=y_(r.chatRoomId,"params.chatRoomId"),i=m_(r.announcement,"params.announcement");if(void 0===i)throw l_("params.announcement");const o=p_(s,`/chatrooms/${encodeURIComponent(n)}/announcement?resource=${s.encodedResource}`);await e.post(o,{announcement:i},{operation:"updateChatRoomAnnouncement"})})(this.getRestClient(t),t,e)})}async getAttributes(e){return this.runOperation("getAttributes",async()=>{const t=this.getRestContextOrThrow();return O_(this.getRestClient(t),t,e)})}async setAttributes(e){return this.runOperation("setAttributes",async()=>{const t=this.getRestContextOrThrow(),r=await M_(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=u_(t),n=y_(r.chatRoomId,"params.chatRoomId"),i=I_(r.keys,"params.keys"),{isForced:o=!1}=r,a=o?"/forced":"",c=p_(s,`/metadata/chatroom/${encodeURIComponent(n)}/user/${s.encodedUserId}${a}`),d=await e.request(c,{method:"DELETE",body:{keys:i},operation:"removeChatRoomAttributes"});return a_(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 Vs(`ChatRoomManager ${e} failed`,{code:t.code,message:t.message,details:t.details}),t}}normalizeSdkError(e,t){return t instanceof ut?t:t instanceof Error?new ut(`ChatRoomManager ${e} failed: ${t.message}`,ot.UNKNOWN):new ut(`ChatRoomManager ${e} failed`,ot.UNKNOWN)}remapChatRoomOperationError(e,t){return t instanceof ut&&t.code===ot.GROUP_NOT_EXIST?new ft("Chat room does not exist",{code:ot.CHATROOM_NOT_EXIST,details:{...t.details,api:e,originalCode:t.code,canonicalCode:ot.CHATROOM_NOT_EXIST,retryable:!1}}):t}checkAttributeMutationResult(e){const t=Object.values(e.failedKeys);if(t.length>0&&0===e.appliedKeys.length){const[e]=t;if(e)throw new ut(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 Vf(e.restBaseUrl,{errorMap:Q_,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 ut("ChatRoomManager is not bound to client",ot.VALIDATION_REQUIRED);return this.client}normalizeOptionalString(e,t){if(void 0!==e){if("string"!=typeof e)throw new mt(`${t} must be a string`,{code:ot.VALIDATION_INVALID_FORMAT,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 mt(`${t} must be a boolean`,{code:ot.VALIDATION_INVALID_FORMAT,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 Kb(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 Vs("ChatRoomManager user info fetch failed",{userIds:e,error:r}),[]}}})}async hydrateUserInfos(e){return(async(e,t)=>{const r=qb(e),s=await Kb(r,t);return r.map(e=>Vb(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 Vs("ChatRoomManager hydrate users failed",{userIds:e,error:r}),[]}}})}async fetchUserInfosFromRest(e){const t=this.getRestContextOrThrow(),r=q_(e),s=await this.getRestClient(t).request(B_(t),{method:"POST",body:r,operation:"getUserInfoByUserId"});return z_(s,r.targets)}collectEventUserIds(e){const t=e.payload,r=[t.participantId,t.memberId,...t.memberIds??[],t.adminId,t.oldOwnerId,t.newOwnerId,t.from,...t.userIds??[]],s=[],n=new Set;for(const i of r){if("string"!=typeof i)continue;const e=i.trim();e&&!n.has(e)&&(n.add(e),s.push(e))}return s}pickEventUser(e,t){if(e)return Vb(void 0,t.get(e),e)}pickEventUsers(e,t){return(e??[]).map(e=>Vb(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){Vs("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:Vb(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:Vb(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:Vb(e.owner,t.get(e.owner.userId),e.owner.userId)}}};Z_.key="chatRoomManager";let Y_=Z_;const X_={common:{},apis:{getContactList:{range:"",errors:{}},addContact:{range:"110,204,210,1000,1001,1002",localErrors:{addContact:{validation_invalid:{code:110,retryable:!1},cannot_add_self:{code:110,retryable:!1}}},errors:{USER_NOT_FOUND:{code:204,httpStatus:404,retryable:!1},ALREADY_FRIEND:{code:1e3,retryable:!1},BLOCKED_BY_USER:{code:210,retryable:!1},CONTACT_REACH_LIMIT:{code:1001,httpStatus:403,retryable:!1,matchField:"error_description",matchPattern:"Inviter's contact max count"},CONTACT_REACH_LIMIT_PEER:{code:1002,httpStatus:403,retryable:!1,matchField:"error_description",matchPattern:"Invitee's contact max count"}}},deleteContact:{range:"110,204",localErrors:{deleteContact:{validation_invalid:{code:110,retryable:!1}}},errors:{USER_NOT_FOUND:{code:204,httpStatus:404,retryable:!1,aliases:["service_resource_not_found"]}}},acceptContactInvite:{range:"110,204,1001,1002",localErrors:{acceptContactInvite:{validation_invalid:{code:110,retryable:!1}}},errors:{USER_NOT_FOUND:{code:204,httpStatus:404,retryable:!1},CONTACT_REACH_LIMIT:{code:1001,httpStatus:403,retryable:!1,matchField:"error_description",matchPattern:"Inviter's contact max count"},CONTACT_REACH_LIMIT_PEER:{code:1002,httpStatus:403,retryable:!1,matchField:"error_description",matchPattern:"Invitee's contact max count"}}},declineContactInvite:{range:"110,204",localErrors:{declineContactInvite:{validation_invalid:{code:110,retryable:!1}}},errors:{USER_NOT_FOUND:{code:204,httpStatus:404,retryable:!1}}},setContactRemark:{range:"4,110,221",localErrors:{setContactRemark:{validation_invalid:{code:110,retryable:!1}}},errors:{USER_NOT_ON_ROSTER:{code:221,httpStatus:400,retryable:!1,matchField:"error_description",matchPattern:"please add as a friend first"},remark_length_exceeded:{code:4,httpStatus:400,retryable:!1,matchField:"error_description",matchPattern:"remark length must less than"}}},getBlocklist:{range:"",errors:{}},addUsersToBlocklist:{range:"4,110,204",localErrors:{addUsersToBlocklist:{validation_invalid:{code:110,retryable:!1}}},errors:{service_resource_not_found:{code:204,httpStatus:404,retryable:!1},blocklist_limit_exceeded:{code:4,httpStatus:400,retryable:!1,matchField:"error_description",matchPattern:"almost reached or been greater than the upper range"}}},removeUserFromBlocklist:{range:"110",localErrors:{removeUserFromBlocklist:{validation_invalid:{code:110,retryable:!1}}},errors:{}}}},eT="User ID is invalid: cannot add yourself as a contact",tT=(e,t,r)=>{if(!pu(e)||!pu(e.data))return;const s=e.data[t];if(Array.isArray(s))for(const n of s)if(pu(n)&&"string"==typeof n.failReason&&n.failReason.toLowerCase().includes(r))return n.failReason},rT=e=>{const{orgName:t,appName:r}=fs(e.appKey);return{orgName:t,appName:r,encodedUserId:encodeURIComponent(e.userId),encodedResource:encodeURIComponent(e.clientResource)}},sT=e=>pu(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):[],nT=(e,t)=>{if(!Array.isArray(e.userIds)||0===e.userIds.length)throw new mt(`${t} is required`,{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:t,message:`${t} is required`,rule:"required"}]}});const r=e.userIds.map((e,r)=>{if("string"!=typeof e)throw new mt(`${t}[${r}] must be a string`,{code:ot.VALIDATION_INVALID_FORMAT,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 mt(`${t} is required`,{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:t,message:`${t} is required`,rule:"required"}]}});return s.length!==r.length&&pu(e),s},iT=async(e,t,r)=>{const s=rT(t),n=`/${s.orgName}/${s.appName}/users/${s.encodedUserId}/contacts/apply?resource=${s.encodedResource}`;(e=>{const t=tT(e,"applyYourselfUsers","user cannot apply to become a new friend");if(t)throw new mt(eT,{code:ot.VALIDATION_INVALID_FORMAT,details:{api:"addContact",mapped:!0,reasonKey:"cannot_add_self",serverMessage:t,retryable:!1,canonicalCode:ot.VALIDATION_INVALID_FORMAT,fields:[{path:"params.userId",message:eT,rule:"invalid_format"}]}});const r=tT(e,"notExistUsers","the users not exist");if(!r)return;const s=Gf(X_,"addContact",{error:"USER_NOT_FOUND"});if(!s)throw qf({apiName:"addContact",serverMessage:r,mapped:!1,reasonKey:"USER_NOT_FOUND"});throw qf({apiName:"addContact",entry:s.entry,serverMessage:r,mapped:!0,reasonKey:s.reasonKey,matchedBy:s.matchedBy})})(await e.post(n,{usernames:[r.userId],reason:r.message??""},{operation:"addContact"}))},oT=async(e,t)=>{const r=rT(t),s=`/${r.orgName}/${r.appName}/users/${r.encodedUserId}/blocks/users`,n=await e.get(s,{operation:"getBlocklist"});return sT(n).map(e=>({userId:e}))},aT=async(e,t,r)=>{const s=rT(t),n=`/${s.orgName}/${s.appName}/sdk/user/${s.encodedUserId}/blocks?resource=${s.encodedResource}`,i=await e.post(n,{usernames:r},{operation:"addUsersToBlocklist"});return{succeeded:sT(i).map(e=>({userId:e})),failed:[]}},cT={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 dT=!1,uT=null;const lT=()=>uT||(dT||(fa.util.Long=Dn,fa.configure(),dT=!0),Va(),uT=fa.Root.fromJSON(cT),ja(uT),uT),hT=e=>"number"==typeof e?e:Dn.isLong(e)?e.toNumber():0,pT=e=>{if(!e||"object"!=typeof e)return;const t=e;return{resource:"string"==typeof t.resource?t.resource:"",timestamp:hT(t.timestamp),requestId:"string"==typeof t.requestId?t.requestId:"",protocolVersion:hT(t.protocolVersion)}};class mT{encodeRequest(e){const t=lT().lookupType("easemob.imfusion.gateway.v1.GetRosterRequest");return t.encode(t.create(e)).finish()}encodePong(e=Dv){const t=lT().lookupType("easemob.imfusion.gateway.v1.PongResponse");return t.encode(t.create({type:Mv,status:e})).finish()}decode(e){const t=lT(),r=t.lookupType("easemob.imfusion.gateway.v1.BaseMessage").decode(e);switch(r.type){case Ov:return{type:Ov};case Mv:{const r=t.lookupType("easemob.imfusion.gateway.v1.PongResponse").decode(e);return{type:Mv,status:hT(r.status)}}case Lv:{const r=t.lookupType("easemob.imfusion.gateway.v1.GetRosterResponse").decode(e);return{type:Lv,header:pT(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:hT(t.createdAt),updatedAt:hT(t.updatedAt),metadataUpdatedAt:hT(t.metadataUpdatedAt)}})(e)):[],cursor:hT(r.cursor),version:"string"==typeof r.version?r.version:"",responseType:hT(r.responseType)||Pv}}case kv:{const r=t.lookupType("easemob.imfusion.gateway.v1.ErrorDetail").decode(e);return{type:kv,header:pT(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:Nv}}}}class fT{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 ut("Roster response requestId mismatched",ot.CONTACT_SYNC_PROTO_DECODE_FAILED,{details:{stage:"response_decode",expectedRequestId:this.requestId,receivedRequestId:t}});if(this.completed)throw new ut("Roster response received after completion",ot.CONTACT_SYNC_CURSOR_INVALID,{details:{cursor:e.cursor}});if(null!==this.responseType&&this.responseType!==e.responseType)throw new ut("Roster response type changed in same session",ot.CONTACT_SYNC_CURSOR_INVALID,{details:{expected:this.responseType,received:e.responseType}});if(this.pages.length>0&&0!==e.cursor&&e.cursor===this.pages[this.pages.length-1]?.cursor)throw new ut("Roster cursor duplicated",ot.CONTACT_SYNC_CURSOR_INVALID,{details:{cursor:e.cursor}});return this.responseType=e.responseType,this.version=e.version||this.version,this.pages.push(e),this.nextCursor=e.cursor,this.pageCount+=1,this.completed=0===e.cursor,{done:this.completed,nextCursor:this.nextCursor,pageCount:this.pageCount}}getNextCursor(){return this.nextCursor}getPageCount(){return this.pageCount}hasPages(){return this.pages.length>0}isCompleted(){return this.completed}buildResult(){return{mode:this.responseType===xv?"incremental":"full",version:this.version,pages:this.pages}}}const gT=e=>e.type===Lv,yT=e=>"message"in e&&"code"in e;class vT{constructor(e){this.codec=new mT,this.sharedSession=e}async sync(e){const t=new fT(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:gT(t)||yT(t)?t.header?.requestId:void 0,frame:t}},onFrame:async(e,r)=>{try{if(e.type===Ov)return void(await r.send(this.codec.encodePong()));if(gT(e)){if(!t.push(e).done)return;return{done:!0,result:t.buildResult()}}if(yT(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 Bv:return new pt(e.message,{code:ot.AUTH_UNAUTHORIZED,details:r(!1)});case Gv:return new ut(e.message,ot.SERVICE_LIMIT_EXCEEDED,{details:r(!0)});case Fv:return new ut(e.message,ot.VALIDATION_REQUIRED,{details:r(!1)});case qv:return new ut(e.message,ot.VALIDATION_INVALID_FORMAT,{details:r(!1)});case $v:return new ut(e.message,ot.REST_BUSINESS_UNKNOWN,{details:r(!0)});case jv:return new ut(e.message,ot.CONTACT_SYNC_SOCKET_FAILED,{details:r(!1)});default:return new ut(e.message,ot.CONTACT_SYNC_SOCKET_FAILED,{details:r(!0)})}})(e);return}catch(s){throw s instanceof ut?s:new ut("Roster frame decode failed",ot.CONTACT_SYNC_PROTO_DECODE_FAILED,{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 IT=e=>e.versionState.version?"incremental":"full",bT=e=>{const{metadata:t,metadataFailed:r,state:s}=e,n=s.versionState.version;return r||!t?{decision:"complete"===s.cacheMeta.cacheIntegrity?IT(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}},_T=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{}}},TT=e=>{const t=(e=>{if(!(e instanceof ut&&e.details))return null;const t=e.details.httpStatus;return"number"==typeof t?t:null})(e);return 401===t||403===t||404===t},CT=(e,t,r,s)=>({code:t,stage:e,message:`${e}: ${r}`,retryable:s}),ST=e=>{Vs("Contact sync duration",e)};class ET{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=bT({metadata:s,state:e}),"skip"===r.decision)return this.dependencies.onFinish(),void ST({outcome:"skip",decision:r.decision,durationMs:Date.now()-t,version:r.version,hasUsableSnapshot:e.cachedSnapshot.complete})}catch(s){if(TT(s)){const r=bT({metadataFailed:!0,state:e}),n=s instanceof ut?s:new ut("Contact metadata request failed",ot.CONTACT_SYNC_METADATA_FAILED,{details:{stage:"metadata"}});return this.dependencies.onFinish({error:CT("metadata",n.code,n.message,!1)}),void ST({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=bT({metadataFailed:!0,state:e}),e.cachedSnapshot.complete)return this.dependencies.onFinish({error:CT("metadata",ot.CONTACT_SYNC_METADATA_FAILED,s instanceof Error?s.message:String(s),!0)}),void ST({outcome:"fail",decision:r.decision,durationMs:Date.now()-t,version:r.version,stage:"metadata",hasUsableSnapshot:!0,source:e.cachedSnapshot.source})}try{const s=await this.dependencies.getSyncUrls(),n=this.dependencies.buildRosterRequest({decision:r.decision,version:e.versionState.version}),i=await new vT(this.dependencies.getSharedSyncSession()).sync({urls:s,request:n}),o=(e=>{const t=[];for(const r of e)for(const e of r.data){const r=_T(e.metadata);t.push({relation:{userId:e.contact,remark:e.remark,sign:r.sign??"",addTs:e.createdAt,updatedAt:e.updatedAt,metadataUpdatedAt:e.metadataUpdatedAt},userInfo:{userId:e.contact,nickname:r.nickname,avatarUrl:r.avatarUrl,sign:r.sign,ext:r.ext}})}return t})(i.pages),a=this.dependencies.applySyncResult({mode:i.mode,relations:o.map(e=>e.relation),userInfos:o.map(e=>e.userInfo),version:i.version,lastSyncTs:Date.now()});this.dependencies.onFinish(),ST({outcome:"finish",decision:r.decision,durationMs:Date.now()-t,version:i.version,source:"sync",changed:a.changed,hasUsableSnapshot:a.snapshot.complete})}catch(s){const n=s instanceof ut?s:new ut("Contact sync failed",ot.CONTACT_SYNC_SOCKET_FAILED,{details:{stage:"sync_page",cause:s instanceof Error?s.message:String(s)}}),i=n.details??{},o="string"==typeof i.stage?i.stage:"sync_page";this.dependencies.onFinish({error:CT(o,n.code,n.message,!0)}),ST({outcome:"fail",decision:r.decision,durationMs:Date.now()-t,version:r.version,stage:o,hasUsableSnapshot:e.cachedSnapshot.complete,source:e.cachedSnapshot.complete?e.cachedSnapshot.source:void 0})}}}const wT={items:[],loaded:!1,source:"server"},RT=bv(_v,X_),AT=class{constructor(){this.client=null,this.eventContext=null,this.restClient=null,this.restBaseUrl=null,this.restToken=null,this.blocklistSnapshot=wT,this.blocklistSessionKey=null}bind(e,t){this.client=e,this.eventContext=t??null,this.blocklistSnapshot=wT,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();if(t===s.userId)throw this.buildValidationError(eT,[{path:"params.userId",message:eT,rule:"invalid_format"}]);const n=this.getRestClient(s);js("ContactManager addContact",{userId:t,hasMessage:"string"==typeof r&&r.length>0}),await iT(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);js("ContactManager deleteContact",{userId:t}),await(async(e,t,r)=>{const s=rT(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);js("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);js("ContactManager acceptContactInvite",{userId:t}),await(async(e,t,r)=>{const s=rT(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);js("ContactManager declineContactInvite",{userId:t}),await(async(e,t,r)=>{const s=rT(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);js("ContactManager setContactRemark",{userId:t,remarkLength:r.length}),await(async(e,t,r)=>{const s=rT(t),n=`/${s.orgName}/${s.appName}/users/${s.encodedUserId}/contacts/users/${encodeURIComponent(r.userId)}?resource=${s.encodedResource}`;await e.put(n,{remark:r.remark},{operation:"setContactRemark"})})(n,s,{userId:t,remark:r});const i=this.client?.getCacheManager()?.updateContactRemark(t,r);this.client?.refreshConversationDisplayFromUserInfos([{userId:t}],"profile"),js("ContactManager setContactRemark patched cache",{userId:t,changed:i?.changed??!1})})}async getBlocklist(){return this.runOperation("getBlocklist",async()=>{const e=this.getRestContextOrThrow();this.ensureBlocklistSession(e);const t=this.getRestClient(e);if(this.blocklistSnapshot.loaded)return this.blocklistSnapshot.items;const r=await this.enrichBlocklistUsers(await oT(t,e));return this.blocklistSnapshot={items:r,loaded:!0,source:"server"},js("ContactManager getBlocklist",{count:r.length}),r})}async addUsersToBlocklist(e){return this.runOperation("addUsersToBlocklist",async()=>{const t=this.getRestContextOrThrow();this.ensureBlocklistSession(t);const r=nT(e,"params.userIds"),s=this.getRestClient(t);js("ContactManager addUsersToBlocklist",{userIds:r,inputCount:e.userIds.length,normalizedCount:r.length});const n=await aT(s,t,r),i=await this.enrichBlocklistUsers(n.succeeded);return this.blocklistSnapshot=this.patchBlocklistSnapshotWithAdditions(i),{succeeded:i,failed:await this.enrichBlocklistUsers(n.failed)}})}async removeUserFromBlocklist(e){return this.runOperation("removeUserFromBlocklist",async()=>{const t=this.getRestContextOrThrow();this.ensureBlocklistSession(t);const r=nT(e,"params.userIds"),s=this.getRestClient(t);js("ContactManager removeUserFromBlocklist",{userIds:r,inputCount:e.userIds.length,normalizedCount:r.length}),await(async(e,t,r)=>{const s=rT(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 Vs(`ContactManager ${e} failed`,{code:t.code,message:t.message,details:t.details}),t}}normalizeSdkError(e,t){return t instanceof ut?t:t instanceof Error?new ut(`ContactManager ${e} failed: ${t.message}`,ot.UNKNOWN):new ut(`ContactManager ${e} failed`,ot.UNKNOWN)}requireClient(){if(!this.client)throw this.buildValidationError("ContactManager is not bound to client",[{path:"contactManager.client",message:"ContactManager is not bound to client",rule:"required"}]);return this.client}getRestContextOrThrow(){return this.requireClient().getRestContext()}getRestClient(e){return this.restClient&&this.restBaseUrl===e.restBaseUrl&&this.restToken===e.token||(this.restClient=new Vf(e.restBaseUrl,{errorMap:RT,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=wT)}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.VALIDATION_INVALID_FORMAT:ot.VALIDATION_REQUIRED;return new mt(e,{code:r,details:{fields:t}})}async enrichBlocklistUsers(e){if(0===e.length||!this.requireClient().isUserInfoSyncEnabled())return e;const t=await Ev(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 Vs("ContactManager user info fetch failed",{userIds:e,error:t}),[]}}async fetchUserInfosFromRest(e){const t=this.getRestContextOrThrow(),r=q_(e),s=await this.getRestClient(t).request(B_(t),{method:"POST",body:r,operation:"getUserInfoByUserId"});return z_(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 ET(e)}};AT.key="contactManager";let NT=AT;class OT{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 MT=e=>{const{orgName:t,appName:r}=fs(e.appKey);return{orgName:t,appName:r,encodedUserId:encodeURIComponent(e.userId),encodedResource:encodeURIComponent(e.clientResource)}},UT=e=>new mt(`${e} is required`,{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:e,message:`${e} is required`,rule:"required"}]}}),LT=(e,t)=>new mt(t,{code:ot.VALIDATION_INVALID_FORMAT,details:{fields:[{path:e,message:t,rule:"invalid_format"}]}}),kT=(e,t)=>{if(!Array.isArray(e)||0===e.length)throw UT(t);const r=[],s=new Set;if(e.forEach((e,n)=>{if("string"!=typeof e)throw LT(`${t}[${n}]`,`${t}[${n}] must be a string`);const i=e.trim();i&&!s.has(i)&&(s.add(i),r.push(i))}),0===r.length)throw UT(t);return r},DT=(e,t)=>{if("string"!=typeof e||0===e.trim().length)throw UT(t);return e.trim()},PT=(e,t)=>{if(void 0!==e){if("string"!=typeof e)throw LT(t,`${t} must be a string`);return e}},xT=(e,t)=>{if(void 0!==e){if("boolean"!=typeof e)throw LT(t,`${t} must be a boolean`);return e}},FT=(e,t)=>`/${e.orgName}/${e.appName}${t}`,BT=new Set(["groupNamecard","group_namecard","group_name_card","namecard","nameCard"]),GT=e=>{const t=Qy();"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}`:""},qT=async(e,t,r)=>{const s=MT(t),n=FT(s,`/chatgroups?resource=${s.encodedResource}`);return(e=>{const t=Eu(e),r=bu(t[0]),s=wu(e)??r;return{groupId:s&&Nu(s)||r&&Nu(r)||""}})(await e.post(n,{owner:t.userId,groupname:r.name,desc:r.description,members:r.memberIds?kT(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"}))},$T=async(e,t,r)=>{const s=MT(t),n=DT(r.groupId,"params.groupId"),i=FT(s,`/chatgroups/${encodeURIComponent(n)}?joined_time=true&version=v3`),o=await e.get(i,{operation:"getGroupInfo"});return Mu(o)},jT=async(e,t,r)=>{const s=MT(t),n=DT(r.groupId,"params.groupId"),i={},o=PT(r.name,"params.name"),a=PT(r.description,"params.description"),c=PT(r.avatar,"params.avatar"),d=PT(r.ext,"params.ext"),u=xT(r.public,"params.public"),l=xT(r.joinApprovalRequired,"params.joinApprovalRequired"),h=xT(r.allowInvites,"params.allowInvites"),p=xT(r.inviteNeedConfirm,"params.inviteNeedConfirm"),m=((e,t)=>{if(void 0!==e){if("number"!=typeof e||Number.isNaN(e))throw LT(t,`${t} must be a number`);return e}})(r.maxMembers,"params.maxMembers");if(void 0!==o&&(i.groupname=o),void 0!==a&&(i.description=a),void 0!==c&&(i.avatar=c),void 0!==d&&(i.custom=d),void 0!==u&&(i.public=u),void 0!==l&&(i.membersonly=l),void 0!==h&&(i.allowinvites=h),void 0!==p&&(i.invite_need_confirm=p),void 0!==m&&(i.maxusers=m),0===Object.keys(i).length)throw UT("params");const f=FT(s,`/chatgroups/${encodeURIComponent(n)}?resource=${s.encodedResource}&version=v3`);await e.put(f,i,{operation:"updateGroupInfo"})},VT=async(e,t,r)=>{const s=MT(t),n=FT(s,`/chatgroups/${encodeURIComponent(DT(r.groupId,"params.groupId"))}/users${(e=>{const t=Qy();return"number"==typeof e?.pageSize&&t.set("pagesize",String(e.pageSize)),"string"==typeof e?.cursor&&e.cursor.length>0&&t.set("cursor",e.cursor),t.set("version","v3"),`?${t.toString()}`})(r)}`);return(e=>{const t=[];for(const i of Eu(e)){const e=bu(i);if(!e)continue;const r=Tu(e.owner),s=Tu(e.admin),n=Tu(e.member),o=r??s??n;if(!o)continue;const a=Cu(e.joinedAt)??Cu(e.joined_time);t.push({user:Uu(o),role:r?"owner":s?"admin":"member",...void 0===a?{}:{joinedAt:a}})}const r=Ru(e,"pagenum"),s=Ru(e,"pagesize"),n=Au(e,s);return{items:t,pageNum:r,pageSize:s,...void 0===n?{}:{hasMore:n}}})(await e.get(n,{operation:"getGroupMemberList"}))},KT=async(e,t,r)=>{const s=MT(t),n=FT(s,`/chatgroups/${encodeURIComponent(DT(r.groupId,"params.groupId"))}/admin`),i=await e.get(n,{operation:"getGroupAdminList"});return Lu(i)},zT=async(e,t,r)=>{const s=MT(t),n=DT(r.groupId,"params.groupId"),i=GT(r),o=i?"&":"",a=FT(s,`/chatgroups/${encodeURIComponent(n)}/mute?version=v3${o}${i.replace("?","")}`);return(e=>{const t=[];for(const r of Eu(e)){const e=Tu(r);if(e){t.push({user:Uu(e)});continue}const s=bu(r);if(!s)continue;const n=Tu(s.user);if(!n)continue;const i=Cu(s.expire);t.push({user:Uu(n),...void 0===i?{}:{muteExpire:i}})}return t})(await e.get(a,{operation:"getGroupMuteList"}))},HT=async(e,t,r)=>{const s=MT(t),n=DT(r.groupId,"params.groupId"),i=GT(r),o=i?"&":"",a=FT(s,`/chatgroups/${encodeURIComponent(n)}/blocks/users?version=v3${o}${i.replace("?","")}`),c=await e.get(a,{operation:"getGroupBlocklist"});return Lu(c).map(e=>({user:e}))},WT=async(e,t,r)=>{const s=MT(t),n=FT(s,`/chatgroups/${encodeURIComponent(DT(r.groupId,"params.groupId"))}/white/users`),i=await e.get(n,{operation:"getGroupAllowlist"});return Lu(i).map(e=>({user:e}))},JT=async(e,t,r)=>{const s=MT(t),n=FT(s,`/chatgroups/${encodeURIComponent(DT(r.groupId,"params.groupId"))}/announcement`);return(e=>{const t=wu(e)??{};return{announcement:_u(t.announcement)??""}})(await e.get(n,{operation:"getGroupAnnouncement"}))},QT=async(e,t,r)=>{const s=MT(t),n=Qy();n.set("pagenum",String(r.pageNum??1)),n.set("pagesize",String(r.pageSize??20));const i=FT(s,`/chatgroups/${encodeURIComponent(DT(r.groupId,"params.groupId"))}/share_files?${n.toString()}`);return(e=>{const t=Ru(e,"pagenum"),r=Ru(e,"pagesize"),s=Au(e,r);return{items:Eu(e).map(e=>ku(e)).filter(e=>null!==e),pageNum:t,pageSize:r,...void 0===s?{}:{hasMore:s}}})(await e.get(i,{operation:"getGroupSharedFileList"}))},ZT=(e,t)=>{const r=MT(e);return FT(r,`/chatgroups/${encodeURIComponent(DT(t.groupId,"params.groupId"))}/share_files/${encodeURIComponent(DT(t.fileId,"params.fileId"))}`)},YT=async(e,t,r)=>{const s=MT(t),n=DT(r.groupId,"params.groupId"),i=DT(r.userId,"params.userId"),o=((e,t,r)=>{if(t!==e.userId)return null;const s=Object.entries(r);if(0===s.length)return null;let n;for(const[i,o]of s){if(!BT.has(i)||"string"!=typeof o)return null;if(void 0!==n){if(n!==o)return null}else n=o}return void 0===n?null:{nameCard:n}})(t,i,r.memberAttributes);if(o){const t=FT(s,`/sdk/chatgroups/${encodeURIComponent(n)}/nameCard`);return await e.put(t,o,{operation:"setGroupMemberAttributes"})}const a=FT(s,`/sdk/metadata/chatgroup/${encodeURIComponent(n)}/user/${encodeURIComponent(i)}?resource=${s.encodedResource}`);return await e.put(a,{metaData:r.memberAttributes},{operation:"setGroupMemberAttributes"})},XT=async(e,t,r)=>{const s=MT(t),n=FT(s,`/sdk/metadata/chatgroup/${encodeURIComponent(DT(r.groupId,"params.groupId"))}/get`);return(e=>{const t=wu(e)??{},r=bu(t.data)??t,s={};for(const[n,i]of Object.entries(r)){const e=bu(i);e&&(s[n]=Object.fromEntries(Object.entries(e).filter(e=>"string"==typeof e[1])))}return{items:s}})(await e.post(n,{targets:kT(r.userIds,"params.userIds"),properties:r.keys??[]},{operation:"getGroupMembersAttributes"}))},eC=e=>{const t=pu(e)?e:{},r=t.data,s=pu(r)?r.data:void 0,n=Array.isArray(r)?r:Array.isArray(s)?s:null;if(Array.isArray(n))return tC(n);const i=pu(r)?r:t,o=pu(i.namecards)?i.namecards:i,a={};for(const[c,d]of Object.entries(o)){if("string"==typeof d){a[c]={namecard:d};continue}if(!pu(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:rC(d)})}return a},tC=e=>{const t={};return e.forEach(e=>{if(!pu(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:rC(e)})}),t},rC=e=>bl("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),sC=e=>{if(pu(e))return bl("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 nC{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 iC=e=>({...e}),oC=e=>({...e,owner:e.owner?{...e.owner}:void 0});class aC{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=iC({...this.summarySnapshot??{},...e,groupId:this.groupId}),this.loadedSummary=!0,this.lastPatchedAt=Date.now())}mergeDetail(e){e.groupId===this.groupId&&(this.detailSnapshot=oC({...this.detailSnapshot??this.summarySnapshot??{groupId:this.groupId,name:""},...e,groupId:this.groupId}),this.summarySnapshot=iC(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?iC(this.summarySnapshot):this.detailSnapshot?iC(this.toSummaryFromDetail(this.detailSnapshot)):null}getDetailSnapshot(){return this.detailSnapshot?oC(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 cC{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 dC{constructor(){this.groups=new Map,this.joinedGroupById=new Map,this.removedJoinedGroupIds=new Set,this.snapshotMapper=new cC,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 aC(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 uC=0,lC=5,hC=12,pC=13,mC=0,fC=1,gC=2,yC=0,vC=1,IC=2,bC=3,_C=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===mC?"owner":s===fC?"admin":s===gC?"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===yC?"DEFAULT":r===vC?"ALL":r===IC?"AT":r===bC?"NONE":void 0),createdAt:e.create_at,updatedAt:e.update_at,joinedAt:e.joined_timestamp}:null;var r,s},TC=e=>e.updatedAt??0,CC=(e,t)=>{if(!e)return!0;return TC(t)>=TC(e)},SC={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 EC=null,wC=!1;const RC=()=>EC||(wC||(fa.util.Long=Dn,fa.configure(),wC=!0),Va(),EC=fa.Root.fromJSON(SC),ja(EC),EC),AC=e=>RC().lookupType(e),NC=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(Dn.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}},OC=e=>{if(!e||"object"!=typeof e)return;const t=e;return{resource:"string"==typeof t.resource?t.resource:"",timestamp:NC(t.timestamp)??0,requestId:"string"==typeof t.request_id?t.request_id:"string"==typeof t.requestId?t.requestId:"",protocolVersion:NC(t.protocol_version)??NC(t.protocolVersion)??0}};class MC{constructor(){this.requestType=AC("easemob.joinedgroups.GetJoinedGroupsRequest"),this.responseType=AC("easemob.joinedgroups.GetJoinedGroupsResponse"),this.errorType=AC("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:uC}}tryDecodeRequest(e){try{const t=this.requestType.toObject(this.requestType.decode(e),{longs:String,bytes:Uint8Array}),r=NC(t.type);return r!==hC?null:{type:r,header:OC(t.header),org:"string"==typeof t.org?t.org:"",app:"string"==typeof t.app?t.app:"",username:"string"==typeof t.username?t.username:"",lastSyncTime:NC(t.last_sync_time)??NC(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=NC(t.type);return r!==pC?null:{type:r,header:OC(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:NC(t.members_count)??NC(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:NC(t.role),mute_expiration:NC(t.mute_expiration)??NC(t.muteExpiration),remind_type:NC(t.remind_type)??NC(t.remindType),create_at:NC(t.create_at)??NC(t.createAt),update_at:NC(t.update_at)??NC(t.updateAt),joined_timestamp:NC(t.joined_timestamp)??NC(t.joinedTimestamp)}})(e)):[],isLastBatch:!0===t.is_last_batch||!0===t.isLastBatch,lastSyncFinishedTs:NC(t.last_sync_finished_ts)??NC(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=NC(t.type);return r!==lC?null:{type:r,header:OC(t.header),code:NC(t.code)??0,message:"string"==typeof t.message?t.message:"Unknown joined groups sync error"}}catch{return null}}}class UC{constructor(e){this.batches=[],this.done=!1,this.requestId=e}getResumeCursor(){return this.latestCursor}push(e){if(e.type!==pC)return{done:!1};const t=e.header?.requestId;if(t!==this.requestId)return{done:!1};if(this.done)throw new ut("Joined groups response received after completion",ot.REST_BUSINESS_UNKNOWN,{details:{stage:"response_decode",requestId:this.requestId}});if(this.batches.push(e),e.cursor&&(this.latestCursor=e.cursor),e.isLastBatch){if("number"!=typeof e.lastSyncFinishedTs)throw new ut("Joined groups final batch missing lastSyncFinishedTs",ot.REST_BUSINESS_UNKNOWN,{details:{stage:"completion_meta",requestId:this.requestId}});this.done=!0,this.lastSyncFinishedTs=e.lastSyncFinishedTs}return{done:this.done}}buildResult(){return{batches:this.batches.map(e=>({...e,groups:e.groups.map(e=>({...e}))})),lastSyncFinishedTs:this.lastSyncFinishedTs}}}const LC=e=>e.type===pC,kC=e=>e.type===lC;class DC{constructor(e){this.codec=new MC,this.sharedSession=e}async sync(e){const t=e.request.header?.requestId??`group-sync-${Date.now()}`,r=new UC(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:LC(t)||kC(t)?t.header?.requestId:void 0,frame:t}},onFrame:e=>{try{if(LC(e)){if(!r.push(e).done)return;return{done:!0,result:r.buildResult()}}if(kC(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 ut(e.message,ot.VALIDATION_REQUIRED,{details:t("request_send",!1)});case 1602:return new ut(e.message,ot.REST_BUSINESS_UNKNOWN,{details:t("batch_merge",!0)});case 1002:return new pt(e.message,{code:ot.AUTH_UNAUTHORIZED,details:t("auth",!1)});case 1003:return new ut(e.message,ot.SERVICE_LIMIT_EXCEEDED,{details:t("server_limit",!0)});default:return new ut(e.message,ot.REST_BUSINESS_UNKNOWN,{details:t("response_decode",!0)})}})(e);return}catch(t){throw t instanceof ut?t:new ut("Joined groups frame decode failed",ot.CONTACT_SYNC_PROTO_DECODE_FAILED,{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 PC{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 ut("Group sync websocket urls are unavailable",ot.CONTACT_SYNC_SOCKET_FAILED,{details:{stage:"socket_connect",retryable:!0}});const s=this.buildRequest(),n=await new DC(this.dependencies.getSharedSyncSession()).sync({urls:r,request:s}),i=n.batches.flatMap(e=>(e=>{const t=[];for(const r of e){const e=_C(r);e&&t.push(e)}return t})(e.groups)),o=this.dependencies.getRuntimeSnapshot(),a=(e=>{const t=new Map(e.existingItems.map(e=>[e.groupId,e])),r=new Map;for(const n of e.incomingItems){const e=r.get(n.groupId)??t.get(n.groupId);CC(e,n)?r.set(n.groupId,{...e??{},...n,groupId:n.groupId}):e&&r.set(n.groupId,{...e})}const s=r.size>=lm;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:um,serverLimit:lm,source:"sync",lastSyncFinishedTs:e.lastSyncFinishedTs,lastSuccessfulAt:Date.now()}}})({existingItems:o?.items??[],incomingItems:i,lastSyncFinishedTs:n.lastSyncFinishedTs}),c=this.dependencies.getCacheManager();this.dependencies.applyRuntimeSnapshot(a);const d=this.dependencies.getRuntimeSnapshot()??a;try{await c.commitJoinedGroupPreviewSnapshot(d);const e=this.dependencies.getRuntimeSnapshot();e&&!this.hasSameMembership(d,e)&&await c.commitJoinedGroupPreviewSnapshot(e)}catch(t){throw o&&this.dependencies.applyRuntimeSnapshot(o),new yt("Joined-group preview persistence failed",{details:{stage:"preview_persist",cause:t instanceof Error?t.message:String(t)}})}Vs("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 ut?e:new ut("Group sync failed",ot.REST_BUSINESS_UNKNOWN,{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);Vs("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}=fs(e.appKey);return{type:hC,header:{resource:e.clientResource,timestamp:Date.now(),requestId:`group-sync-${Date.now()}`,protocolVersion:1},org:t,app:r,username:e.userId,lastSyncTime:0}}}const xC=bv(_v,{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:{}}}}),FC=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 dC,this.groupEventSync=new nC(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!==Te)return;if(!("attribute"in s)||!("user"in s))return;const n=this.extractGroupNamecard(s.attribute);if(void 0===n||!s.user?.userId)return;const i=this.client?.getCurrentUserId();s.user.userId!==i&&(this.getCacheManager()?.setGroupNamecards([{groupId:s.groupId,userId:s.user.userId,namecard:n,lastAccess:Date.now(),lastUpdate:Date.now()}]),this.eventContext?.dispatch?.(Ce,{groupId:s.groupId,userId:s.user.userId,namecard:n}))}async createGroup(e){return this.runOperation("createGroup",async()=>{const t=this.getRestContextOrThrow(),r=await qT(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 mt("groupId is required",{code:ot.VALIDATION_REQUIRED,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 OT(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 $T(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=MT(t),n=kT(r.groupIds,"params.groupIds"),i=FT(s,`/chatgroups/${n.map(e=>encodeURIComponent(e)).join(",")}?joined_time=true&version=v3`),o=await e.get(i,{operation:"getGroupInfoList"});return(pu(o)&&Array.isArray(o.data)?o.data:[]).map(e=>Mu({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===ie?this.resolveLocalGroupName(r.groupId):void 0,n=await this.resolveUserInfoMap(this.collectEventUserIds(t));switch(await this.syncRuntimeForEvent(e,r,n),e){case Y:return{groupId:r.groupId,groupName:r.groupName,inviter:this.pickEventUser(r.inviterId,n),reason:r.reason};case X:return{groupId:r.groupId,groupName:r.groupName,applicant:this.pickEventUser(r.applicantId,n),reason:r.reason};case ee:return{groupId:r.groupId,groupName:r.groupName,accepter:this.pickEventUser(r.accepterId,n)};case te:return{groupId:r.groupId,groupName:r.groupName,decliner:this.pickEventUser(r.declinerId,n),applicant:this.pickEventUser(r.applicantId,n),reason:r.reason};case re:case se:return{groupId:r.groupId,invitee:this.pickEventUser(r.inviteeId,n),reason:r.reason};case ne:return{groupId:r.groupId,groupName:r.groupName};case ie:return{groupId:r.groupId,groupName:r.groupName??s};case oe:return{groupId:r.groupId,inviter:this.pickEventUser(r.inviterId,n),inviteMessage:r.reason};case ae:return{groupId:r.groupId,mutes:this.pickEventUsers(r.userIds,n),muteExpire:r.muteExpire};case ce:return{groupId:r.groupId,mutes:this.pickEventUsers(r.userIds,n)};case de:case ue:return{groupId:r.groupId,allowlist:this.pickEventUsers(r.userIds,n)};case le:return{groupId:r.groupId,isMuted:Boolean(r.isMuted)};case he:case pe:return{groupId:r.groupId,administrator:this.pickEventUser(r.administratorId,n)};case me:return{groupId:r.groupId,newOwner:this.pickEventUser(r.newOwnerId,n),oldOwner:this.pickEventUser(r.oldOwnerId,n)};case fe:return{groupId:r.groupId,groupName:await this.resolveMembersJoinedGroupName(r),members:this.pickEventUsers(r.memberIds,n)};case ge:return{groupId:r.groupId,members:this.pickEventUsers(r.memberIds,n)};case ye:return{groupId:r.groupId,announcement:r.announcement??""};case ve:return{groupId:r.groupId,sharedFile:this.hydrateEventSharedFile(r.sharedFile,n)};case Ie:return{groupId:r.groupId,fileId:r.fileId??""};case be:return{groupId:r.groupId,groupInfo:await this.resolveGroupDetailForEvent(r)};case _e:{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 Te: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){Vs("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 jT(this.getRestClient(t),t,e)})}async changeGroupOwner(e){return this.runOperation("changeGroupOwner",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=MT(t),n=FT(s,`/chatgroups/${encodeURIComponent(DT(r.groupId,"params.groupId"))}?resource=${s.encodedResource}`);await e.put(n,{newowner:DT(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=MT(t),n=FT(s,`/chatgroups/${encodeURIComponent(DT(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=MT(t),n=FT(s,`/chatgroups/${encodeURIComponent(DT(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=MT(t),n=FT(s,`/chatgroups/${encodeURIComponent(DT(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=MT(t),n=FT(s,`/chatgroups/${encodeURIComponent(DT(r.groupId,"params.groupId"))}/invite?resource=${s.encodedResource}`);await e.post(n,{usernames:kT(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=MT(t),n=FT(s,`/chatgroups/${encodeURIComponent(DT(r.groupId,"params.groupId"))}/apply_verify?resource=${s.encodedResource}`);await e.post(n,{applicant:DT(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=MT(t),n=FT(s,`/chatgroups/${encodeURIComponent(DT(r.groupId,"params.groupId"))}/apply_verify?resource=${s.encodedResource}`);await e.post(n,{applicant:DT(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=MT(t),n=FT(s,`/chatgroups/${encodeURIComponent(DT(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=MT(t),n=FT(s,`/chatgroups/${encodeURIComponent(DT(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 VT(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=MT(t),n=kT(r.userIds,"params.userIds"),i=FT(s,`/chatgroups/${encodeURIComponent(DT(r.groupId,"params.groupId"))}/users/${n.map(e=>encodeURIComponent(e)).join(",")}?resource=${s.encodedResource}`);await e.delete(i,{operation:"removeGroupMembers"})})(this.getRestClient(t),t,e)})}async getGroupAdminList(e){return this.runOperation("getGroupAdminList",async()=>{const t=this.getRestContextOrThrow(),r=await KT(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=MT(t),n=FT(s,`/chatgroups/${encodeURIComponent(DT(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=MT(t),n=FT(s,`/chatgroups/${encodeURIComponent(DT(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 zT(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=MT(t),n=FT(s,`/chatgroups/${encodeURIComponent(DT(r.groupId,"params.groupId"))}/mute?resource=${s.encodedResource}`);await e.post(n,{usernames:kT(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=MT(t),n=kT(r.userIds,"params.userIds"),i=FT(s,`/chatgroups/${encodeURIComponent(DT(r.groupId,"params.groupId"))}/mute/${n.map(e=>encodeURIComponent(e)).join(",")}?resource=${s.encodedResource}`);await e.delete(i,{operation:"unmuteGroupMembers"})})(this.getRestClient(t),t,e)})}async muteAllGroupMembers(e){return this.runOperation("muteAllGroupMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=MT(t),n=FT(s,`/chatgroups/${encodeURIComponent(DT(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=MT(t),n=FT(s,`/chatgroups/${encodeURIComponent(DT(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 HT(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=MT(t),n=FT(s,`/chatgroups/${encodeURIComponent(DT(r.groupId,"params.groupId"))}/blocks/users?resource=${s.encodedResource}`);await e.post(n,{usernames:kT(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=MT(t),n=kT(r.userIds,"params.userIds"),i=FT(s,`/chatgroups/${encodeURIComponent(DT(r.groupId,"params.groupId"))}/blocks/users/${n.map(e=>encodeURIComponent(e)).join(",")}?resource=${s.encodedResource}`);await e.delete(i,{operation:"unblockGroupMembers"})})(this.getRestClient(t),t,e)})}async getGroupAllowlist(e){return this.runOperation("getGroupAllowlist",async()=>{const t=this.getRestContextOrThrow(),r=await WT(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=MT(t),n=FT(s,`/chatgroups/${encodeURIComponent(DT(r.groupId,"params.groupId"))}/white/users?resource=${s.encodedResource}`);await e.post(n,{usernames:kT(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=MT(t),n=kT(r.userIds,"params.userIds"),i=FT(s,`/chatgroups/${encodeURIComponent(DT(r.groupId,"params.groupId"))}/white/users/${n.map(e=>encodeURIComponent(e)).join(",")}?resource=${s.encodedResource}`);await e.delete(i,{operation:"removeUsersFromGroupAllowlist"})})(this.getRestClient(t),t,e)})}async checkIfInGroupAllowList(e){return this.runOperation("checkIfInGroupAllowList",async()=>{const t=this.getRestContextOrThrow();return(async(e,t,r)=>{const s=MT(t),n=FT(s,`/chatgroups/${encodeURIComponent(DT(r.groupId,"params.groupId"))}/white/users/${s.encodedUserId}?version=v3`),i=await e.get(n,{operation:"checkIfInGroupAllowList"});return"boolean"==typeof i?i:pu(i)&&"boolean"==typeof i.data?i.data:Boolean(i)})(this.getRestClient(t),t,e)})}async checkIfInGroupMuteList(e){return this.runOperation("checkIfInGroupMuteList",async()=>{const t=this.getRestContextOrThrow();return(async(e,t,r)=>{const s=MT(t),n=FT(s,`/sdk/chatgroups/${encodeURIComponent(DT(r.groupId,"params.groupId"))}/mute/${s.encodedUserId}?version=v3`),i=await e.get(n,{operation:"checkIfInGroupMuteList"});return"boolean"==typeof i?i:pu(i)&&"boolean"==typeof i.data?i.data:Boolean(i)})(this.getRestClient(t),t,e)})}async getGroupAnnouncement(e){return this.runOperation("getGroupAnnouncement",async()=>{const t=this.getRestContextOrThrow();return JT(this.getRestClient(t),t,e)})}async updateGroupAnnouncement(e){return this.runOperation("updateGroupAnnouncement",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=MT(t),n=FT(s,`/chatgroups/${encodeURIComponent(DT(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 QT(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=ZT(t,{groupId:e.groupId,fileId:"__upload__"}).replace(/\/share_files\/__upload__$/,"/share_files"),s=os({file:e.file}),n=Uh({operationName:"GROUP_UPLOAD_SHAREDFILE",operationType:"GROUP"}),i=n?.startRequest({requestName:"GROUP_UPLOAD_SHAREDFILE",method:"POST",url:`${t.restBaseUrl}${r}`});try{const o=await(this.requireClient().getUploadAdapter()?.upload({url:`${t.restBaseUrl}${r}?resource=${encodeURIComponent(t.clientResource)}`,headers:{Authorization:`Bearer ${t.token}`,[ru]:tu()},source:s.source,timeoutMs:3e5,onProgress:e.onFileUploadProgress}));if(!o)throw new Error("platform upload adapter is unavailable");if(o.status<200||o.status>=300)throw new ut("uploadGroupSharedFile failed",ot.REST_HTTP_ERROR,{details:{status:o.status}});i?.finish({code:o.status,success:!0}),n?.finish({code:0,success:!0}),e.onFileUploadComplete?.(o.body)}catch(o){const t=Pd(o);throw i?.finish({code:t.code,success:!1,description:t.message}),n?.finish({code:t.code,success:!1,description:t.message}),t.code===ot.UPLOAD_ABORTED&&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=MT(t),n=FT(s,`/chatgroups/${encodeURIComponent(DT(r.groupId,"params.groupId"))}/share_files/${encodeURIComponent(DT(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}${ZT(s,e)}`;t=Uh({operationName:"GROUP_DOWNLOAD_SHAREDFILE",operationType:"GROUP"}),r=t?.startRequest({requestName:"GROUP_DOWNLOAD_SHAREDFILE",method:"GET",url:n});const i=this.requireClient().getRequestAdapter();if(!i)throw new ut("downloadGroupSharedFile request adapter is unavailable",ot.REST_NETWORK_ERROR);const o=await i.request({url:n,method:"GET",headers:{Authorization:`Bearer ${s.token}`,...e.secret?{"Share-Secret":e.secret}:{},[ru]:tu()},responseType:"arraybuffer",timeoutMs:6e4});if(o.status<200||o.status>=300)throw r?.finish({code:o.status,success:!1,description:"downloadGroupSharedFile failed"}),t?.finish({code:o.status,success:!1,description:"downloadGroupSharedFile failed"}),new ut("downloadGroupSharedFile failed",ot.REST_HTTP_ERROR);r?.finish({code:o.status,success:!0}),t?.finish({code:0,success:!0});const a="undefined"!=typeof Blob?new Blob([o.data]):o.data;e.onFileDownloadComplete?.(a)}catch(s){const n=s instanceof ut?s.code:ot.REST_NETWORK_ERROR,i=s instanceof Error?s.message:String(s);throw r?.finish({code:n,success:!1,description:i}),t?.finish({code:n,success:!1,description:i}),e.onFileDownloadError?.(s),s}})}async setGroupMemberAttributes(e){return this.runOperation("setGroupMemberAttributes",async()=>{const t=this.getRestContextOrThrow(),r=await YT(this.getRestClient(t),t,e);this.writeSelfGroupNamecardCache(t.userId,e,r)})}async getGroupMembersAttributes(e){return this.runOperation("getGroupMembersAttributes",async()=>{const t=this.getRestContextOrThrow();return XT(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=MT(t),n=FT(s,`/sdk/chatgroups/${encodeURIComponent(DT(r.groupId,"params.groupId"))}/nameCard/batch/get`),i=await e.post(n,{members:kT(r.userIds,"params.userIds")},{operation:"getGroupNamecards"});return{items:eC(i),responseTimestamp:sC(i)}})(this.getRestClient(r),r,{groupId:e,userIds:s}),i=new Map(t.map(e=>[e.userId,e.namecardUpdateTime])),o=[],a=new Set;for(const[t,d]of Object.entries(n.items))a.add(t),o.push({groupId:e,userId:t,namecard:d.namecard,namecardUpdateTime:i.get(t)??d.namecardUpdateTime,lastSyncAt:Date.now(),lastAccess:Date.now(),lastUpdate:Date.now()});const c=s.filter(e=>!a.has(e));c.length>0&&"number"==typeof n.responseTimestamp&&o.push(...c.map(t=>({groupId:e,userId:t,namecard:"",namecardUpdateTime:n.responseTimestamp,lastSyncAt:Date.now(),lastAccess:Date.now(),lastUpdate:Date.now()}))),this.getCacheManager()?.setGroupNamecards(o);for(const e of o)e.userId!==r.userId&&""!==e.namecard&&this.eventContext?.dispatch?.(Ce,{groupId:e.groupId,userId:e.userId,namecard:e.namecard});c.length>0&&"number"!=typeof n.responseTimestamp&&Vs("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 Vs(`GroupManager ${e} failed`,{code:t.code,message:t.message,details:t.details}),t}}normalizeSdkError(e,t){return t instanceof ut?t:t instanceof Error?new ut(`GroupManager ${e} failed: ${t.message}`,ot.UNKNOWN):new ut(`GroupManager ${e} failed`,ot.UNKNOWN)}getRestContextOrThrow(){return this.requireClient().getRestContext()}getRestClient(e){return this.restClient&&this.restBaseUrl===e.restBaseUrl&&this.restToken===e.token||(this.restClient=new Vf(e.restBaseUrl,{errorMap:xC,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 ut("GroupManager is not bound to client",ot.VALIDATION_REQUIRED);return this.client}getGroupRepository(){return this.groupRepository||(this.groupRepository=new dC),this.groupRepository}getGroupEventSync(){return this.groupEventSync||(this.groupEventSync=new nC(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 $T(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 Vs("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&&Vs("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=bl("number"==typeof s?s:Number(s));if("number"==typeof e)return e}}collectUpdateTimeCandidates(e,t,r){if(!pu(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(pu(s)){this.collectUpdateTimeCandidates(s,t,r);const e=s[t];pu(e)&&this.collectUpdateTimeCandidates(e,t,r)}const n=e.lastModified??e.last_modified;pu(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 Iu(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 Vs("GroupManager user info fetch failed",{userIds:e,error:r}),[]}}})}collectEventUserIds(e){const t=e.payload,r=[t.inviterId,t.applicantId,t.accepterId,t.declinerId,t.inviteeId,t.administratorId,t.oldOwnerId,t.newOwnerId,t.userId,t.sharedFile?.fileOwner?.userId,...t.memberIds??[],...t.userIds??[]],s=[],n=new Set;for(const i of r){if("string"!=typeof i)continue;const e=i.trim();e&&!n.has(e)&&(n.add(e),s.push(e))}return s}pickEventUser(e,t){if(e)return vu(void 0,t.get(e),e)}pickEventUsers(e,t){return(e??[]).map(e=>vu(void 0,t.get(e),e))}hydrateEventSharedFile(e,t){return e?.fileOwner?.userId?{...e,fileOwner:vu(e.fileOwner,t.get(e.fileOwner.userId),e.fileOwner.userId)}:e}async syncRuntimeForEvent(e,t,r){switch(e){case le:return void this.getGroupEventSync().applyPatch({groupId:t.groupId,groupName:t.groupName,groupPatch:{muteAllMembers:Boolean(t.isMuted)}});case me:return void this.getGroupEventSync().applyPatch({groupId:t.groupId,groupName:t.groupName,groupPatch:{owner:this.pickEventUser(t.newOwnerId,r)}});case ee:case oe:return void this.addCurrentUserJoinedGroupFromEvent(t);case fe:{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 ge: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 ne:case ie:return void(await this.removeJoinedGroupLocal(t.groupId));case ae:case ce:case de:case ue:case he:case pe:return void this.getGroupEventSync().applyPatch({groupId:t.groupId,groupName:t.groupName,shouldMarkStale:!0});default:return}}getMemberEventDeltaCount(e,t){switch(e){case fe:case ge: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 Vs("Joined group detail enrichment skipped",{groupId:e.groupId,error:s}),!1}try{return await this.enrichJoinedGroupFromDetail(e.groupId,t,r)}catch(s){return Vs("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 $T(this.getRestClient(r),r,{groupId:e}),n=this.getGroupRepository();if(n.getSessionKey()!==t)return!1;n.mergeDetail(s);const i=n.getJoinedGroupSummarySnapshot(e);if(!i)return!1;const o=n.mergeJoinedGroupSummary(e,{...i.name||!s.name?{}:{name:s.name},...void 0!==i.description||void 0===s.description?{}:{description:s.description},...void 0!==i.memberCount||void 0===s.memberCount?{}:{memberCount:s.memberCount},...void 0!==i.role||void 0===s.role?{}:{role:s.role},...void 0!==i.disabled||void 0===s.disabled?{}:{disabled:s.disabled},...i.ownerId||!s.owner?.userId?{}:{ownerId:s.owner.userId},...void 0!==i.avatarUrl||void 0===s.avatarUrl?{}:{avatarUrl:s.avatarUrl},...void 0!==i.muteAllMembers||void 0===s.muteAllMembers?{}:{muteAllMembers:s.muteAllMembers},...void 0!==i.createdAt||void 0===s.createdAt?{}:{createdAt:s.createdAt},...void 0!==i.joinedAt||void 0===s.joinedAt?{}:{joinedAt:s.joinedAt}});if(o){this.persistJoinedGroupSnapshot(o);const t=n.getJoinedGroupSummarySnapshot(e);t&&this.requireClient().refreshConversationDisplayFromJoinedGroups([{...t,name:s.name||t.name,avatarUrl:s.avatarUrl??t.avatarUrl}],"profile",{onlyWhenNameMissing:!0})}return!0}persistJoinedGroupSnapshot(e){const t=this.getCacheManager();if(t&&"function"==typeof t.applyJoinedGroupPreviewSnapshot){try{t.applyJoinedGroupPreviewSnapshot(e)}catch(r){return void Vs("Joined group preview persistence failed",{error:r})}"function"==typeof t.flushPending&&t.flushPending().catch(e=>{Vs("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=q_(e),s=await this.getRestClient(t).request(B_(t),{method:"POST",body:r,operation:"getUserInfoByUserId"});return z_(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(aI(e.groupId,e.owner.userId))??e.owner}:e)}async resolveGroupContextUserInfoMap(e,t){const r=this.isGroupNamecardEnhancementEnabled(),s=await mI({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 pI({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 PC(e)}};FC.key="groupManager";let BC=FC;const GC=bv(_v,{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}}}}}),qC=class{constructor(){this.client=null,this.eventContext=null,this.restClient=null,this.restBaseUrl=null,this.restToken=null}bind(e,t){this.client=e,this.eventContext=t??null}addEventHandler(e,t){this.getEventContextOrThrow().addEventHandler(e,t)}removeEventHandler(e){this.getEventContextOrThrow().removeEventHandler(e)}async publishPresence(e){return this.runOperation("publishPresence",async()=>{this.validateDescription(e.customStatus);const t=this.getRestContextOrThrow(),r=this.getRestClient(t),{orgName:s,appName:n}=this.parseAppKey(t.appKey),i=`/${s}/${n}/users/${t.userId}/presence/${t.clientResource}/1`,o={ext:e.customStatus};js("Call publishPresence",{customStatus:e.customStatus}),await r.request(i,{method:"POST",body:o,operation:"publishPresence"})})}async subscribePresence(e){return this.runOperation("subscribePresence",async()=>{this.validateUserIds(e.userIds),this.validateExpiry(e.expiry);const t=this.getRestContextOrThrow(),r=this.getRestClient(t),{orgName:s,appName:n}=this.parseAppKey(t.appKey),i=`/${s}/${n}/users/${t.userId}/presence/${e.expiry}`,o={usernames:e.userIds};js("Call subscribePresence",{userIds:e.userIds,expiry:e.expiry});const a=await r.request(i,{method:"POST",body:o,operation:"subscribePresences"});return this.normalizeSubscribeResponse(a)})}async unsubscribePresence(e){return this.runOperation("unsubscribePresence",async()=>{this.validateUserIds(e.userIds);const t=this.getRestContextOrThrow(),r=this.getRestClient(t),{orgName:s,appName:n}=this.parseAppKey(t.appKey),i=`/${s}/${n}/users/${t.userId}/presence`;js("Call unsubscribePresence",{userIds:e.userIds}),await r.request(i,{method:"DELETE",body:e.userIds,operation:"unsubscribePresence"})})}async getSubscribedPresenceList(e){return this.runOperation("getSubscribedPresenceList",async()=>{this.validatePage(e.pageNum,e.pageSize);const t=this.getRestContextOrThrow(),r=this.getRestClient(t),{orgName:s,appName:n}=this.parseAppKey(t.appKey),i=`/${s}/${n}/users/${t.userId}/presence/sublist?pageNum=${e.pageNum}&pageSize=${e.pageSize}`;js("Call getSubscribedPresenceList",{pageNum:e.pageNum,pageSize:e.pageSize});const o=await r.request(i,{method:"GET",operation:"getSubscribedPresenceList"});return this.normalizeSubscribedListResponse(o)})}async getPresenceStatus(e){return this.runOperation("getPresenceStatus",async()=>{this.validateUserIds(e.userIds);const t=this.getRestContextOrThrow(),r=this.getRestClient(t),{orgName:s,appName:n}=this.parseAppKey(t.appKey),i=`/${s}/${n}/users/${t.userId}/presence`,o={usernames:e.userIds};js("Call getPresenceStatus",{userIds:e.userIds});const a=await r.request(i,{method:"POST",body:o,operation:"getPresenceStatus"});return this.normalizeSubscribeResponse(a)})}async runOperation(e,t){try{return await t()}catch(r){const t=this.normalizeSdkError(e,r);throw Vs(`PresenceManager ${e} failed`,{code:t.code,message:t.message,details:t.details}),t}}normalizeSdkError(e,t){return t instanceof ut?t:t instanceof Error?new ut(`PresenceManager ${e} failed: ${t.message}`,ot.UNKNOWN):new ut(`PresenceManager ${e} failed`,ot.UNKNOWN)}getEventContextOrThrow(){if(!this.eventContext)throw new mt("PresenceManager is not bound to event context",{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:"presenceManager.eventContext",message:"PresenceManager is not bound to event context",rule:"required"}]}});return this.eventContext}getClientOrThrow(){if(!this.client)throw new mt("PresenceManager is not bound to client",{code:ot.VALIDATION_REQUIRED,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 Vf(e.restBaseUrl,{errorMap:GC,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 mt("Invalid parameters",{code:ot.VALIDATION_INVALID_FORMAT,details:{fields:e}})}};qC.key="presenceManager";let $C=qC;const jC=["apns","fcm","huawei","xiaomi","meizu","vivo","oppo","honor"],VC=(e,t,r="invalid_format")=>new mt(t,{code:ot.VALIDATION_INVALID_FORMAT,details:{fields:[{path:e,message:t,rule:r}]}}),KC=(e,t)=>{if(void 0!==e){if("string"!=typeof e||0===e.trim().length)throw VC(t,`${t} must be a non-empty string`);return e.trim()}},zC=e=>8===e?"normal":jC[e]??"normal",HC=e=>{if(!e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.push_token&&"number"==typeof t.push_type&&Number.isInteger(t.push_type)&&t.push_type>=0&&t.push_type<=8&&"number"==typeof t.code&&"string"==typeof t.error};class WC{constructor(e){this.dependencies=e,this.config=null,this.session=null,this.state="unconfigured",this.disabledByUser=!1,this.registrationVersion=0,this.binding=null,this.lastAttemptedBinding=null,this.successfulKey=null,this.exhaustedKey=null,this.activeBindingKey=null,this.pendingCandidate=null,this.bindingPromise=null,this.lastBindingError=null,this.lastRemovalError=null,this.removalPromise=null,this.manualRemovalInProgress=!1,this.sessionEndingGeneration=null,this.pluginRegistered=!1,this.delays=new Set}configure(e){const t=(e=>{if(!e||"object"!=typeof e)throw VC("options","options is required","required");const t=e.plugin;if(!t||"object"!=typeof t)throw VC("plugin","plugin is required","required");const r=t;if("function"!=typeof r.onRegister)throw VC("plugin.onRegister","plugin.onRegister must be a function");if("function"!=typeof r.unRegister)throw VC("plugin.unRegister","plugin.unRegister must be a function");const s=e.certificates;if(!s||"object"!=typeof s)throw VC("certificates","certificates is required","required");const n=s,i={apns:KC(n.apns,"certificates.apns"),fcm:KC(n.fcm,"certificates.fcm"),huawei:KC(n.huawei,"certificates.huawei"),xiaomi:KC(n.xiaomi,"certificates.xiaomi"),meizu:KC(n.meizu,"certificates.meizu"),vivo:KC(n.vivo,"certificates.vivo"),oppo:KC(n.oppo,"certificates.oppo"),honor:KC(n.honor,"certificates.honor")};if(!jC.some(e=>void 0!==i[e]))throw VC("certificates","at least one native push certificate is required");return{plugin:t,certificates:i,signature:jC.map(e=>`${e}:${i[e]??""}`).join("|")}})(e),r=null!==this.config&&"disabled"!==this.state,s=this.config?.plugin===t.plugin&&this.config.signature===t.signature;if(r&&!s)throw new mt("Native push is enabled; call removePushToken() before replacing its configuration",{code:ot.VALIDATION_INVALID_FORMAT,details:{fields:[{path:"options",message:"removePushToken() must succeed before replacing native push config",rule:"conflict"}]}});r&&s&&"failed"!==this.state||(this.invalidateRegistration(),this.safeUnregister(),this.config=t,this.disabledByUser=!1,this.exhaustedKey=null,this.state="configured",this.session&&this.startRegistration())}onSessionReady(e){this.invalidateRegistration(),this.safeUnregister(),this.session=e,this.binding=null,this.lastAttemptedBinding=null,this.manualRemovalInProgress=!1,this.sessionEndingGeneration=null,this.successfulKey=null,this.exhaustedKey=null,this.config&&!this.disabledByUser&&(this.state="configured",this.startRegistration())}async onSessionEnding(e){if(this.session&&this.session.generation===e.generation){if(this.sessionEndingGeneration=e.generation,this.invalidateRegistration(),this.removalPromise)try{await this.removalPromise}catch{}if(this.isSessionGenerationActive(e.generation)&&(this.bindingPromise&&await this.bindingPromise,this.isSessionGenerationActive(e.generation))){for(const t of this.collectRemovalTargets(e.generation)){const r=await this.removeWithRetry(t,e.generation);if(!this.isSessionGenerationActive(e.generation))return;if(!r){this.emitFailure(Ge.TOKEN_REMOVE_FAILED,"remove",t.channel,t.notifierName,this.lastRemovalError??void 0);break}}this.isSessionGenerationActive(e.generation)&&(this.safeUnregister(),this.clearSessionRuntime())}}}resetSessionRuntime(){this.invalidateRegistration(),this.safeUnregister(),this.clearSessionRuntime()}removePushToken(){return this.session?(this.removalPromise||(this.removalPromise=this.performManualRemoval().finally(()=>{this.removalPromise=null})),this.removalPromise):Promise.reject(new ut("User is not logged in",ot.AUTH_NOT_LOGIN))}startRegistration(){if(!this.config||!this.session||this.disabledByUser)return;const e=this.config,t=this.session.generation,r=++this.registrationVersion;this.state="registering",this.pluginRegistered=!0;try{e.plugin.onRegister(s=>{if(!this.isRegistrationActive(t,r))return;const n=((e,t)=>{if(!HC(e)||200!==e.code||0===e.push_token.trim().length)return null;const r=zC(e.push_type);if("normal"===r)return null;const s=t.certificates[r];return s?{token:e.push_token,channel:r,notifierName:s}:null})(s,e);if(!n){this.state="failed";const t=HC(s)?zC(s.push_type):void 0,r=HC(s)&&200===s.code&&s.push_token.trim().length>0&&void 0!==t&&"normal"!==t&&void 0===e.certificates[t];return void this.emitFailure(Ge.TOKEN_BIND_FAILED,r?"bind":"register",t)}this.enqueueBinding(n)})}catch{this.safeUnregister(),this.state="failed",this.emitFailure(Ge.TOKEN_BIND_FAILED,"register")}}enqueueBinding(e){const t=this.createBindingKey(e);t!==this.successfulKey&&t!==this.exhaustedKey&&t!==this.activeBindingKey&&(this.pendingCandidate=e,this.manualRemovalInProgress||this.bindingPromise||(this.bindingPromise=this.drainBindingQueue().finally(()=>{this.bindingPromise=null,this.pendingCandidate&&this.session&&!this.disabledByUser&&!this.manualRemovalInProgress&&this.enqueueBinding(this.pendingCandidate)})))}async drainBindingQueue(){for(;this.pendingCandidate&&this.session&&!this.disabledByUser&&!this.manualRemovalInProgress;){const e=this.pendingCandidate;this.pendingCandidate=null;const t=this.session.generation,r=this.createBindingKey(e);this.activeBindingKey=r,this.state="binding";const s=await this.bindWithRetry(e,t);if(this.activeBindingKey=null,!this.session||this.session.generation!==t||this.disabledByUser)return;s?(this.binding={...e,generation:t,userId:this.session.userId,deviceId:this.session.clientResource},this.successfulKey=r,this.exhaustedKey=null,this.state="bound",this.sessionEndingGeneration===t||this.manualRemovalInProgress||this.dependencies.dispatch(Ge.TOKEN_BOUND,{channel:e.channel,notifierName:e.notifierName})):(this.exhaustedKey=r,this.state="failed",this.sessionEndingGeneration===t||this.manualRemovalInProgress||this.emitFailure(Ge.TOKEN_BIND_FAILED,"bind",e.channel,e.notifierName,this.lastBindingError??void 0))}}async bindWithRetry(e,t){this.lastBindingError=null;for(let s=0;s<=2;s+=1)try{const r=this.session;return!(!r||r.generation!==t)&&(this.lastAttemptedBinding={...e,generation:t,userId:r.userId,deviceId:r.clientResource},await this.dependencies.requestToken({deviceId:r.clientResource,deviceToken:e.token,notifierName:e.notifierName,timeout:5e3}),!0)}catch(r){if(this.lastBindingError=this.toSdkError(r),!this.session||this.session.generation!==t)return!1;if(!this.isRetryable(r)||2===s)return!1;const e=Yr[s]??0;if(!(await this.wait(e)))return!1}return!1}async performManualRemoval(){if(!this.session)throw new ut("User is not logged in",ot.AUTH_NOT_LOGIN);const e=this.session.generation;if(this.manualRemovalInProgress=!0,this.cancelDelays(),this.bindingPromise&&await this.bindingPromise,!this.isSessionGenerationActive(e))throw this.manualRemovalInProgress=!1,new ut("User is not logged in",ot.AUTH_NOT_LOGIN);const t=this.collectRemovalTargets(e);if(0!==t.length)try{for(const r of t)if(await this.dependencies.requestToken({deviceId:r.deviceId,deviceToken:"",notifierName:r.notifierName}),!this.isSessionGenerationActive(e))return;this.disableByUser()}catch(r){const s=this.toSdkError(r),n=t[0];throw n&&this.isSessionGenerationActive(e)&&this.emitFailure(Ge.TOKEN_REMOVE_FAILED,"remove",n.channel,n.notifierName,s),this.manualRemovalInProgress=!1,this.resumePendingBinding(e),s}else this.disableByUser()}async removeWithRetry(e,t){this.lastRemovalError=null;for(let s=0;s<=1;s+=1)try{return await this.dependencies.requestToken({deviceId:e.deviceId,deviceToken:"",notifierName:e.notifierName,timeout:2500}),!0}catch(r){if(this.lastRemovalError=this.toSdkError(r),!this.isSessionGenerationActive(t))return!1;if(!this.isRetryable(r)||1===s)return!1;if(!(await this.wait(500)))return!1}return!1}disableByUser(){this.disabledByUser=!0,this.manualRemovalInProgress=!1,this.invalidateRegistration(),this.safeUnregister(),this.binding=null,this.lastAttemptedBinding=null,this.successfulKey=null,this.exhaustedKey=null,this.state="disabled"}clearSessionRuntime(){this.session=null,this.binding=null,this.lastAttemptedBinding=null,this.manualRemovalInProgress=!1,this.sessionEndingGeneration=null,this.successfulKey=null,this.exhaustedKey=null,this.activeBindingKey=null,this.pendingCandidate=null,this.state=this.disabledByUser?"disabled":this.config?"configured":"unconfigured"}invalidateRegistration(){this.registrationVersion+=1,this.pendingCandidate=null,this.cancelDelays()}cancelDelays(){for(const e of this.delays)clearTimeout(e.timer),e.resolve(!1);this.delays.clear()}collectRemovalTargets(e){const t=[this.binding,this.lastAttemptedBinding].filter(t=>t?.generation===e);return t.filter((e,r)=>t.findIndex(t=>t.deviceId===e.deviceId&&t.notifierName===e.notifierName)===r)}resumePendingBinding(e){if(!this.pendingCandidate||!this.isSessionGenerationActive(e)||this.disabledByUser||this.sessionEndingGeneration===e)return;const t=this.pendingCandidate;this.pendingCandidate=null,this.enqueueBinding(t)}isSessionGenerationActive(e){return this.session?.generation===e}safeUnregister(){if(this.pluginRegistered){this.pluginRegistered=!1;try{this.config?.plugin.unRegister()}catch{Vs("Native push plugin unregister failed")}}}isRegistrationActive(e,t){return this.session?.generation===e&&this.registrationVersion===t&&!this.disabledByUser}createBindingKey(e){const t=this.session;return t?`${t.generation}\0${t.userId}\0${t.clientResource}\0${e.token}\0${e.notifierName}`:""}wait(e){return new Promise(t=>{const r={timer:setTimeout(()=>{this.delays.delete(r),t(!0)},e),resolve:t};this.delays.add(r)})}isRetryable(e){return!(e instanceof ut)||(!0===e.details?.retryable||[ot.REST_NETWORK_ERROR,ot.REST_TIMEOUT,ot.REST_HTTP_ERROR,ot.SERVER_BUSY].includes(e.code))}toSdkError(e){return e instanceof ut?e:new ut("Native push operation failed",ot.UNKNOWN)}emitFailure(e,t,r,s,n){const i=!!n&&this.isRetryable(n);this.dependencies.dispatchFailure(e,{stage:t,...r?{channel:r}:{},...s?{notifierName:s}:{},...n?{code:n.code}:{},retryable:i}),Vs("Native push operation failed",{stage:t,...r?{channel:r}:{},...s?{notifierName:s}:{},...n?{code:n.code}:{},retryable:i})}}const JC=bv(_v,{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,201,1500",localErrors:{uploadPushToken:{validation_invalid:{code:110,retryable:!1}},setNativePush:{validation_invalid:{code:110,retryable:!1}},removePushToken:{auth_not_login:{code:201,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}}}}}),QC=["singleChat","groupChat"],ZC=["ALL","AT","NONE","DEFAULT"],YC=["ALL","AT","NONE"],XC=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),eS=class{constructor(){this.client=null,this.restClient=null,this.restBaseUrl=null,this.restToken=null,this.eventContext=null,this.nativePushController=new WC({requestToken:async e=>{await this.requestNativePushToken(e)},dispatch:(e,t)=>{this.eventContext?.dispatch?.(e,t)},dispatchFailure:(e,t)=>{this.eventContext?.dispatch?.(e,t)}})}bind(e,t){this.client=e,this.eventContext=t??null}onSessionReady(e){this.nativePushController.onSessionReady(e)}async onSessionEnding(e){await this.nativePushController.onSessionEnding(e)}resetSessionRuntime(){this.nativePushController.resetSessionRuntime()}setNativePush(e){this.nativePushController.configure(e)}removePushToken(){return this.nativePushController.removePushToken()}addEventHandler(e,t){this.eventContext?.addEventHandler(e,t)}removeEventHandler(e){this.eventContext?.removeEventHandler(e)}async uploadPushToken(e){return this.runOperation(async()=>{this.validateUploadPushTokenParams(e),await this.requestNativePushToken(e)})}async requestNativePushToken(e){const t=this.getRestContextOrThrow(),r=this.getRestClient(t),{orgName:s,appName:n}=this.parseAppKey(t.appKey);js("Call native push token operation",{deviceId:e.deviceId,notifierName:e.notifierName,removing:0===e.deviceToken.length}),await r.request(`/${s}/${n}/users/${t.userId}`,{method:"PUT",body:{device_id:e.deviceId,device_token:e.deviceToken,notifier_name:e.notifierName},operation:"uploadPushToken",...void 0!==e.timeout?{timeout:e.timeout}:{}})}async setGlobalSilentMode(e){return this.runOperation(async()=>{this.validateRuleInput(e.rule,"rule");const t=this.getRestContextOrThrow(),r=this.getRestClient(t),{orgName:s,appName:n}=this.parseAppKey(t.appKey),i=`/${s}/${n}/users/${t.userId}/notification/user/${t.userId}?resource=${encodeURIComponent(t.clientResource)}`,o=this.buildSilentModePayload(e.rule);js("Call setGlobalSilentMode",{mode:e.rule.mode});const a=await r.request(i,{method:"PUT",body:o,operation:"setGlobalSilentMode"});return{scope:"global",rule:this.normalizeRuleView(this.resolveSilentModeRuleSource(a),e.rule)}})}async getGlobalSilentMode(e={}){return this.runOperation(async()=>{const e=this.getRestContextOrThrow(),t=this.getRestClient(e),{orgName:r,appName:s}=this.parseAppKey(e.appKey),n=`/${r}/${s}/users/${e.userId}/notification/user/${e.userId}`;js("Call getGlobalSilentMode");const i=await t.request(n,{method:"GET",operation:"getGlobalSilentMode"});return{scope:"global",rule:this.normalizeRuleView(this.resolveSilentModeRuleSource(i))}})}async setConversationSilentMode(e){return this.runOperation(async()=>{this.validateConversationId(e.conversationId,"conversationId"),this.validateConversationType(e.conversationType,"conversationType"),this.validateRuleInput(e.rule,"rule");const t=this.getRestContextOrThrow(),r=this.getRestClient(t),{orgName:s,appName:n}=this.parseAppKey(t.appKey),i=this.mapConversationTypeToPath(e.conversationType),o=`/${s}/${n}/users/${t.userId}/notification/${i}/${encodeURIComponent(e.conversationId)}?resource=${encodeURIComponent(t.clientResource)}`,a=this.buildSilentModePayload(e.rule);js("Call setConversationSilentMode",{conversationId:e.conversationId,conversationType:e.conversationType,mode:e.rule.mode});const c=await r.request(o,{method:"PUT",body:a,operation:"setConversationSilentMode"});return{conversationId:e.conversationId,conversationType:e.conversationType,rule:this.normalizeRuleView(this.resolveSilentModeRuleSource(c),e.rule)}})}async getConversationSilentMode(e){return this.runOperation(async()=>{this.validateConversationId(e.conversationId,"conversationId"),this.validateConversationType(e.conversationType,"conversationType");const t=this.getRestContextOrThrow(),r=this.getRestClient(t),{orgName:s,appName:n}=this.parseAppKey(t.appKey),i=this.mapConversationTypeToPath(e.conversationType),o=`/${s}/${n}/users/${t.userId}/notification/${i}/${encodeURIComponent(e.conversationId)}`;js("Call getConversationSilentMode",{conversationId:e.conversationId,conversationType:e.conversationType});const a=await r.request(o,{method:"GET",operation:"getConversationSilentMode"});return{conversationId:e.conversationId,conversationType:e.conversationType,rule:this.normalizeRuleView(this.resolveSilentModeRuleSource(a))}})}async clearConversationRemindType(e){return this.runOperation(async()=>{this.validateConversationId(e.conversationId,"conversationId"),this.validateConversationType(e.conversationType,"conversationType");const t=this.getRestContextOrThrow(),r=this.getRestClient(t),{orgName:s,appName:n}=this.parseAppKey(t.appKey),i=this.mapConversationTypeToPath(e.conversationType),o=`/${s}/${n}/users/${t.userId}/notification/${i}/${encodeURIComponent(e.conversationId)}?resource=${encodeURIComponent(t.clientResource)}`;js("Call clearConversationRemindType",{conversationId:e.conversationId,conversationType:e.conversationType});const a=await r.request(o,{method:"PUT",body:{type:"DEFAULT"},operation:"clearConversationRemindType"});return{conversationId:e.conversationId,conversationType:e.conversationType,rule:this.normalizeRuleView(this.resolveSilentModeRuleSource(a),{remindType:"DEFAULT"})}})}async getConversationSilentModes(e){return this.runOperation(async()=>{this.validateConversationList(e.conversationList,"conversationList");const t=this.getRestContextOrThrow(),r=this.getRestClient(t),{orgName:s,appName:n}=this.parseAppKey(t.appKey),i=e.conversationList.filter(e=>"singleChat"===e.conversationType).map(e=>encodeURIComponent(e.conversationId)).join(","),o=e.conversationList.filter(e=>"groupChat"===e.conversationType).map(e=>encodeURIComponent(e.conversationId)).join(","),a=`/${s}/${n}/users/${t.userId}/notification?user=${i}&group=${o}`;js("Call getConversationSilentModes",{count:e.conversationList.length});const c=await r.request(a,{method:"GET",operation:"getConversationSilentModes"}),d=this.resolveConversationRuleMap(c,"user"),u=this.resolveConversationRuleMap(c,"group");return{conversations:e.conversationList.map(e=>{const t="singleChat"===e.conversationType?d[e.conversationId]:u[e.conversationId];return{conversationId:e.conversationId,conversationType:e.conversationType,rule:this.normalizeRuleView(t)}})}})}async setPushLanguage(e){await this.runOperation(async()=>{this.validateLanguage(e.language,"language");const t=this.getRestContextOrThrow(),r=this.getRestClient(t),{orgName:s,appName:n}=this.parseAppKey(t.appKey),i=`/${s}/${n}/users/${t.userId}/notification/language`;js("Call setPushLanguage",{language:e.language}),await r.request(i,{method:"PUT",body:{translationLanguage:e.language},operation:"setPushLanguage"})})}async getPushLanguage(e={}){return this.runOperation(async()=>{const e=this.getRestContextOrThrow(),t=this.getRestClient(e),{orgName:r,appName:s}=this.parseAppKey(e.appKey),n=`/${r}/${s}/users/${e.userId}/notification/language`;js("Call getPushLanguage");const i=await t.request(n,{method:"GET",operation:"getPushLanguage"});return{language:this.resolvePushLanguage(i,"")}})}getConversationListByRemindType(e){return this.runOperation(()=>{js("Call getConversationListByRemindType",{pageSize:e.pageSize,hasCursor:Boolean(e.cursor)});const t=this.getClientOrThrow(),r=wf({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 ut?e:e instanceof Error?new ut(`PushManager operation failed: ${e.message}`,ot.UNKNOWN):new ut("PushManager operation failed",ot.UNKNOWN)}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 Vf(e.restBaseUrl,{errorMap:JC,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 ut("PushManager is not bound to client",ot.VALIDATION_REQUIRED);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||!QC.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(!XC(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(!YC.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(!XC(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(!XC(e))return null;const t={},r=this.normalizeRemindType(e.type);null!==r&&(t.remindType=r);const s=e.ignoreDuration;"number"==typeof s&&Number.isInteger(s)&&s>0&&(t.expireTimestamp=s);const n=e.ignoreInterval;if("string"==typeof n){const e=this.parseInterval(n);e&&(t.silentModeStartTime=e.startTime,t.silentModeEndTime=e.endTime)}return void 0!==t.remindType||void 0!==t.expireTimestamp||void 0!==t.silentModeStartTime&&void 0!==t.silentModeEndTime?t:null}parseInterval(e){const t=e.match(/^(\d{1,2}):(\d{1,2})-(\d{1,2}):(\d{1,2})$/);if(!t)return null;const r=Number(t[1]),s=Number(t[2]),n=Number(t[3]),i=Number(t[4]);return Number.isInteger(r)&&Number.isInteger(s)&&Number.isInteger(n)&&Number.isInteger(i)?r<0||r>23||n<0||n>23||s<0||s>59||i<0||i>59?null:{startTime:{hours:r,minutes:s},endTime:{hours:n,minutes:i}}:null}toRuleViewFromFallback(e){if("mode"in e)switch(e.mode){case"REMIND_TYPE":return{remindType:e.remindType};case"DURATION":return{};case"INTERVAL":return{silentModeStartTime:e.startTime,silentModeEndTime:e.endTime}}return e}formatIntervalSegment(e){return`${String(e.hours).padStart(2,"0")}:${String(e.minutes).padStart(2,"0")}`}resolveConversationRuleMap(e,t){if(XC(e.data)){const r=e.data[t];if(XC(r))return r}const r=e[t];return XC(r)?r:{}}resolveSilentModeRuleSource(e){if(!XC(e))return e;if(null!==this.parseRuleView(e))return e;const t=e.data;return XC(t)&&null!==this.parseRuleView(t)?t:e}normalizeRemindType(e){return"string"!=typeof e?null:"MENTION_ONLY"===e?"AT":ZC.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(XC(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 mt(e,{code:ot.VALIDATION_INVALID_FORMAT,details:{fields:t}})}};eS.key="pushManager";let tS=eS;const rS=e=>{const{orgName:t,appName:r}=fs(e.appKey);return`/${t}/${r}/user/${encodeURIComponent(e.userId)}/metadata/subscription`},sS=(e,t="params.userIds")=>x_(e,t),nS=e=>{const t=sS(e);if(t.length>100)throw((e,t,r,s=ot.VALIDATION_INVALID_FORMAT)=>new mt(e,{code:s,details:{fields:[{path:t,message:e,rule:r}]}}))("params.userIds must contain at most 100 unique users","params.userIds","range",ot.SERVICE_LIMIT_EXCEEDED);return{usernames:t}},iS=(e,t)=>{const r=(e=>sS(e))(t);return`${rS(e)}?usernames=${r.map(e=>encodeURIComponent(e)).join(",")}`},oS=(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}},aS=["nickname","avatarUrl","mail","phone","gender","sign","birth","ext"],cS=bv(_v,{common:{},apis:{updateOwnUserInfo:{range:"4,110,204,303,505,901",localErrors:{updateOwnInfo:{validation_invalid:{code:110,retryable:!1}},updateOwnInfoByAttribute:{validation_invalid:{code:110,retryable:!1}}},errors:{service_not_enabled:{code:505,httpStatus:403,retryable:!1,matchField:"desc",matchPattern:"user metadata service not allow"},data_length_exceed:{code:901,httpStatus:403,retryable:!1,matchField:"desc",matchPattern:"exceeds"},concurrent_update_conflict:{code:303,httpStatus:409,retryable:!0,matchField:"desc",matchPattern:"Concurrent"},resource_not_found:{code:204,httpStatus:404,retryable:!1},rate_limit:{code:4,httpStatus:429,retryable:!0}}},updateOwnInfo:{range:"4,110,204,303,505,901",localErrors:{updateOwnInfo:{validation_invalid:{code:110,retryable:!1}},updateOwnInfoByAttribute:{validation_invalid:{code:110,retryable:!1}}},errors:{service_not_enabled:{code:505,httpStatus:403,retryable:!1,matchField:"desc",matchPattern:"user metadata service not allow"},data_length_exceed:{code:901,httpStatus:403,retryable:!1,matchField:"desc",matchPattern:"exceeds"},concurrent_update_conflict:{code:303,httpStatus:409,retryable:!0,matchField:"desc",matchPattern:"Concurrent"},resource_not_found:{code:204,httpStatus:404,retryable:!1},rate_limit:{code:4,httpStatus:429,retryable:!0}}},updateOwnInfoByAttribute:{range:"4,110,204,303,505,901",localErrors:{updateOwnInfo:{validation_invalid:{code:110,retryable:!1}},updateOwnInfoByAttribute:{validation_invalid:{code:110,retryable:!1}}},errors:{service_not_enabled:{code:505,httpStatus:403,retryable:!1,matchField:"desc",matchPattern:"user metadata service not allow"},data_length_exceed:{code:901,httpStatus:403,retryable:!1,matchField:"desc",matchPattern:"exceeds"},concurrent_update_conflict:{code:303,httpStatus:409,retryable:!0,matchField:"desc",matchPattern:"Concurrent"},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}}}}}),dS=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=oS(r,s);e&&Object.assign(t,e)}return{userId:e.userId,attributes:t,lastModified:e.lastModified,source:"subscribe_metadata_updated"===e.notifyType?"subscription":"contact_metadata_updated"===e.notifyType?"contact":"own"}})(s);if(!n)return;const i=r.applyUserInfoNotifyPatch(n);if(!i.applied)return void js("User-info notify ignored",{userId:n.userId,notifyType:s.notifyType,reason:i.reason,lastModified:n.lastModified});if(r.updateUserInfoSummaryFromRuntime(n.userId),t.refreshConversationDisplayFromUserInfos?.([{userId:n.userId,lastModified:n.lastModified}]),"subscription"===n.source)return void this.eventContext?.dispatch?.("onUserInfoUpdated",[i.record.profile]);if("own"===n.source)return void this.eventContext?.dispatch?.("onOwnInfoUpdated",i.record.profile);const o=t.getContactSnapshot()?.items.find(e=>e.userId===n.userId);this.eventContext?.dispatch?.(Z,{userInfo:i.record.profile,contact:o})}async getUserInfoByUserId(e){return this.runOperation("getUserInfoByUserId",async()=>{const t=this.getRestContextOrThrow(),r=this.getRestClient(t),s=q_(x_(e.userIds,"params.userIds")),n=B_(t);js("UserInfoManager getUserInfoByUserId",{userIds:s.targets});const i=await r.request(n,{method:"POST",body:s,operation:"getUserInfoByUserId"}),o=this.normalizeFetchEnvelope(i,s.targets);return this.writeCache(o),this.completeFetchedProfiles(o,s.targets)})}async getUserInfoByAttribute(e){return this.runOperation("getUserInfoByAttribute",async()=>{const t=this.getRestContextOrThrow(),r=this.getRestClient(t),s=(n=x_(e.userIds,"params.userIds"),i=F_(e.attributes,"params.attributes"),{targets:x_(n),properties:F_(i).map(e=>P_(e,"params.attributes"))});var n,i;const o=B_(t);js("UserInfoManager getUserInfoByAttribute",{userIds:s.targets,attributes:s.properties});const a=await r.request(o,{method:"POST",body:s,operation:"getUserInfoByAttribute"}),c=this.normalizeFetchEnvelope(a,s.targets);return this.writeCache(c),this.completeFetchedProfiles(c,s.targets)})}async subscribeUsersInfo(e){return this.runOperation("subscribeUsersInfo",async()=>{const t=this.getRestContextOrThrow(),r=this.getRestClient(t),s=(e=>rS(e))(t),n=nS(e.userIds);js("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=iS(t,e.userIds);js("UserInfoManager unsubscribeUsersInfo",{userIds:x_(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=>rS(e))(e);js("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(H_(t,"nickname",e.nickname,"params.nickname"),H_(t,"avatarurl",e.avatarUrl,"params.avatarUrl"),H_(t,"mail",e.mail,"params.mail"),H_(t,"phone",e.phone,"params.phone"),H_(t,"gender",e.gender,"params.gender"),H_(t,"sign",e.sign,"params.sign"),H_(t,"birth",e.birth,"params.birth"),H_(t,"ext",e.ext,"params.ext"),0===t.length)throw L_("params must include at least one updatable field","params","required");return W_(t)})(e),n=G_(t);js("UserInfoManager updateOwnInfo",{userId:t.userId,fields:this.getUpdatedFieldNames(e)});const i=await r.request(n,{method:"PUT",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s,operation:"updateOwnInfo"}),o=this.normalizeUpdateEnvelope(i,t.userId,this.buildFallbackProfile(t.userId,e));return this.writeCache([o]),this.dispatchSelfUpdate(o.profile),o.profile})}async updateOwnInfoByAttribute(e,t){return this.runOperation("updateOwnInfoByAttribute",async()=>{const r=this.getRestContextOrThrow(),s=this.getRestClient(r),n=((e,t)=>{const r=P_(e,"attribute"),s=D_(t,"value");if("gender"!==r&&"string"!=typeof s)throw L_("value must be a string","value","invalid_format");return W_([[r,String(s)]])})(e,t),i=G_(r);js("UserInfoManager updateOwnInfoByAttribute",{userId:r.userId,attribute:e});const o=await s.request(i,{method:"PUT",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:n,operation:"updateOwnInfoByAttribute"}),a=this.normalizeUpdateEnvelope(o,r.userId,{userId:r.userId,[e]:t});return this.writeCache([a]),this.dispatchSelfUpdate(a.profile),a.profile})}async runOperation(e,t){try{return await t()}catch(r){throw this.normalizeOperationError(e,r)}}normalizeOperationError(e,t){return t instanceof ut?t:(Vs("UserInfoManager operation failed",{operation:e,message:t instanceof Error?t.message:String(t)}),new ut(`${e} failed`))}getRestContextOrThrow(){if(this.client)return this.client.getRestContext();throw new mt("UserInfoManager is not bound to client",{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:"userInfoManager.client",message:"client is required",rule:"required"}]}})}getRestClient(e){return this.restClient&&this.restBaseUrl===e.restBaseUrl&&this.restToken===e.token||(this.restClient=new Vf(e.restBaseUrl,{errorMap:cS,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 K_(e,t)}completeFetchedProfiles(e,t){const r=new Map(e.map(e=>[e.profile.userId,e.profile]));return t.map(e=>r.get(e)??{userId:e})}normalizeUpdateEnvelope(e,t,r){const s=pu(e)?e:null,n=(s&&pu(s.data)?s.data:null)??(s&&this.looksLikeUserInfoAttributes(s)?s:null),i=s&&"number"==typeof s.lastModified?s.lastModified:void 0;return{profile:n?this.toUserInfo(t,n):{userId:t,...r??{}},lastModified:i}}toUserInfo(e,t){const r={userId:e};return"string"==typeof t.nickname&&(r.nickname=t.nickname),"string"==typeof t.avatarurl?r.avatarUrl=t.avatarurl:"string"==typeof t.avatarUrl&&(r.avatarUrl=t.avatarUrl),"string"==typeof t.mail&&(r.mail=t.mail),"string"==typeof t.phone&&(r.phone=t.phone),"string"!=typeof t.gender&&"number"!=typeof t.gender&&"boolean"!=typeof t.gender||(r.gender=t.gender),"string"==typeof t.sign&&(r.sign=t.sign),"string"==typeof t.birth&&(r.birth=t.birth),"string"==typeof t.ext&&(r.ext=t.ext),r}looksLikeUserInfoAttributes(e){return!!pu(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 aS)n in t&&(s[n]=t[n]);return r}getUpdatedFieldNames(e){return aS.filter(t=>t in e)}projectToSummary(e){const t=Date.now(),r=bl(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)}};dS.key="userInfoManager";let uS=dS;return e.AuthenticationError=pt,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=Dm,e.ChatClient=zv,e.ChatManager=vb,e.ChatRoom=Bb,e.ChatRoomManager=Y_,e.ChatThread=Ib,e.ChatThreadManager=Fb,e.ConnectionError=ht,e.ContactManager=NT,e.Group=OT,e.GroupManager=BC,e.ImageType={ORIGINAL:"original",LARGE:"large"},e.LogEventName=V,e.MessageReceiveError=gt,e.MessageSendError=ft,e.NetworkError=lt,e.PresenceManager=$C,e.PushEventName=Ge,e.PushManager=tS,e.RUNTIME_PLATFORMS=Js,e.RestBusinessError=It,e.RestTransportError=vt,e.SDKError=ut,e.StorageError=yt,e.StreamMessageStatus=nt,e.UploadError=bt,e.UserInfoManager=uS,e.ValidationError=mt,e.createPlatformAdapter=Dd,e.detectRuntimePlatform=(e,t)=>On(t,e).platform,e.isSDKError=function(e){if(e instanceof ut)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.setConsoleLogEnabled=function(e){!function(e){Fs instanceof xs&&Fs.setConsoleEnabled(e)}(e)},e.setLogLevel=function(e){!function(e){Fs instanceof xs&&Fs.setLevel(e)}(e)},Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),e}({});