easemob-websdk 5.1.2 → 5.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/bundle/im-sdk-web.iife.js +1 -1
  2. package/cache/cache-manager.d.ts +11 -3
  3. package/cache/cache-types.d.ts +15 -4
  4. package/chat-client.d.ts +23 -2
  5. package/chunks/chat-manager-BB7wYWYG.js +2 -0
  6. package/chunks/chat-manager-auF_3s3R.cjs +1 -0
  7. package/chunks/common-Cg-lTASK.cjs +1 -0
  8. package/chunks/common-gbNWJrBc.js +1 -0
  9. package/chunks/{event-system-B62vbKqG.js → event-system-DguqwFpc.js} +1 -1
  10. package/chunks/{group-user-info-resolver-B-dyr__b.cjs → group-user-info-resolver-BNwtC7dY.cjs} +1 -1
  11. package/chunks/{group-user-info-resolver-DMccCqez.js → group-user-info-resolver-rs5Fnr0l.js} +1 -1
  12. package/chunks/index-BUNbI8gf.cjs +1 -0
  13. package/chunks/index-BxMCMoWN.js +1 -0
  14. package/chunks/index-C7fO2X0x.cjs +1 -0
  15. package/chunks/index-C_EMU0-3.js +1 -0
  16. package/chunks/index-CsqE2tfH.js +1 -0
  17. package/chunks/index-DeJuR3uW.cjs +1 -0
  18. package/chunks/index-Dknccp9Q.js +1 -0
  19. package/chunks/index-P1vnLSK2.cjs +1 -0
  20. package/chunks/multibody-content-BHb-Au8Q.js +1 -0
  21. package/chunks/multibody-content-BmdQukoX.cjs +1 -0
  22. package/chunks/push-manager-BO3xq-7O.js +1 -0
  23. package/chunks/push-manager-DMI0G9v9.cjs +1 -0
  24. package/chunks/reflection-proto-codec-B1apL0ws.js +1 -0
  25. package/chunks/reflection-proto-codec-CYglS_mx.cjs +1 -0
  26. package/chunks/session-list-query-DMe2GZ4v.cjs +1 -0
  27. package/chunks/session-list-query-Inseic9m.js +1 -0
  28. package/chunks/{user-info-DH3aE1gm.cjs → user-info-B5St7axd.cjs} +1 -1
  29. package/chunks/{user-info-AlshAvdy.js → user-info-BkqJHgja.js} +1 -1
  30. package/core/index.d.ts +1 -1
  31. package/core/message/attachment-downloader.d.ts +4 -1
  32. package/core/message/message-sender.d.ts +19 -4
  33. package/core/message/prepare-text-translation.d.ts +7 -0
  34. package/core/session-list-sync/session-list-message-events.d.ts +9 -0
  35. package/index.cjs +1 -1
  36. package/index.d.ts +3 -2
  37. package/index.js +2 -2
  38. package/managers/chat/index.cjs +1 -1
  39. package/managers/chat/index.js +1 -1
  40. package/managers/chat-manager.d.ts +128 -7
  41. package/managers/chat-thread/index.cjs +1 -1
  42. package/managers/chat-thread/index.js +1 -1
  43. package/managers/chatroom/index.cjs +1 -1
  44. package/managers/chatroom/index.js +1 -1
  45. package/managers/contact/index.cjs +1 -1
  46. package/managers/contact/index.js +1 -1
  47. package/managers/group/index.cjs +1 -1
  48. package/managers/group/index.js +1 -1
  49. package/managers/presence/index.cjs +1 -1
  50. package/managers/presence/index.js +1 -1
  51. package/managers/push/index.cjs +1 -1
  52. package/managers/push/index.js +1 -1
  53. package/managers/user-info/index.cjs +1 -1
  54. package/managers/user-info/index.js +1 -1
  55. package/message/combine-payload-codec.d.ts +2 -2
  56. package/message/combine-payload-file.d.ts +11 -0
  57. package/message/create-message.d.ts +16 -4
  58. package/message/create-multibody-message.d.ts +31 -0
  59. package/message/message-snapshot.d.ts +9 -0
  60. package/message/multibody-content.d.ts +35 -0
  61. package/message/translations.d.ts +7 -0
  62. package/package.json +1 -1
  63. package/platform/image/miniapp-image-processor.d.ts +10 -6
  64. package/protocol/msync/codec.d.ts +4 -21
  65. package/protocol/msync/message-identity.d.ts +2 -0
  66. package/protocol/msync/message-payload-decoder.d.ts +39 -0
  67. package/protocol/session-list/gateway.d.ts +8 -1
  68. package/protocol/session-list/payload-decoder.d.ts +13 -1
  69. package/types/chat-manager.d.ts +2 -2
  70. package/types/conversation.d.ts +28 -21
  71. package/types/index.d.ts +33 -9
  72. package/types/message-create.d.ts +130 -2
  73. package/upload/attachment-uploader.d.ts +8 -0
  74. package/utils/session-message-recipient.d.ts +11 -0
  75. package/validators/message-create.d.ts +25 -2
  76. package/chunks/chat-manager-BFd2Z4oY.cjs +0 -1
  77. package/chunks/chat-manager-CId_M_e5.js +0 -2
  78. package/chunks/common-BvlDAw4a.js +0 -1
  79. package/chunks/common-tHGz9VBk.cjs +0 -1
  80. package/chunks/index-BBFJYOM8.js +0 -1
  81. package/chunks/index-DJPAjXAp.cjs +0 -1
  82. package/chunks/index-DtWkVcfb.cjs +0 -1
  83. package/chunks/index-l_BUKi77.js +0 -1
  84. package/chunks/reflection-proto-codec-7r8Sei3y.js +0 -1
  85. package/chunks/reflection-proto-codec-CwrIKT1L.cjs +0 -1
  86. package/chunks/session-list-query-Cvr6rlme.js +0 -1
  87. package/chunks/session-list-query-Dslj2k3t.cjs +0 -1
@@ -0,0 +1 @@
1
+ import{g as e,O as t,Q as r,k as a,p as i,V as s,E as n,R as o,S as d,m as h,C as u}from"./common-gbNWJrBc.js";import{i as l,s as c}from"./cache-utils-B99glc0H.js";import{L as m}from"./index-CsqE2tfH.js";import{c as p,a as g,m as y}from"./multibody-content-BHb-Au8Q.js";import{c as f}from"./query-params-Bu3Xq4b6.js";const _={ORIGINAL:"original",LARGE:"large"},b={START:"STREAM_START",START_COMPLETED:"STREAM_START_COMPLETED",IN_PROGRESS:"STREAM_IN_PROGRESS",COMPLETED:"STREAM_COMPLETED",FULL:"STREAM_FULL",ERROR:"STREAM_ERROR"};function v(e){return"object"==typeof e.stream&&null!==e.stream}const T={SYNC:0,UNREAD:1,NOTICE:2,PROVISION:3,LOGOUT:4},I={NORMAL:0,SINGLECHAT:1,GROUPCHAT:2,CHATROOM:3,READ_ACK:4,DELIVER_ACK:5,RECALL:6,CHANNEL_ACK:7,EDIT:8},C={TEXT:0,IMAGE:1,VIDEO:2,LOCATION:3,VOICE:4,FILE:5,COMMAND:6,CUSTOM:7,COMBINE:8},N=0,S=1,R=2,O=3,E=4,A={STATISTIC:0,CHAT:1,MUC:2,ROSTER:3,NOTIFY:5},w={ROUTE_ALL:0,ROUTE_ONLINE:1,ROUTE_DIRECT:2},L={ENCRYPT_NONE:0},M={COMPRESS_NONE:0,COMPRESS_LZ4:2},U={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,RESOURCE_CHANGED:20},$=1,P=2,D=3,x=4,F=5,j=6,k=7,z=8,V=e=>{if("function"==typeof TextEncoder)return(new TextEncoder).encode(e);const t=[];for(let r=0;r<e.length;r+=1){let a=e.charCodeAt(r);if(a>=55296&&a<=56319&&r+1<e.length){const t=e.charCodeAt(r+1);t>=56320&&t<=57343&&(a=65536+(a-55296<<10)+(t-56320),r+=1)}a<=127?t.push(a):a<=2047?t.push(192|a>>6,128|63&a):a<=65535?t.push(224|a>>12,128|a>>6&63,128|63&a):t.push(240|a>>18,128|a>>12&63,128|a>>6&63,128|63&a)}return new Uint8Array(t)},B=e=>{if("function"==typeof TextDecoder)return(new TextDecoder).decode(e);let t="";for(let r=0;r<e.length;r+=1){const a=e[r]??0;if(a<128){t+=String.fromCharCode(a);continue}if(a>=192&&a<224){const i=e[r+1]??0;t+=String.fromCharCode((31&a)<<6|63&i),r+=1;continue}if(a>=224&&a<240){const i=e[r+1]??0,s=e[r+2]??0;t+=String.fromCharCode((15&a)<<12|(63&i)<<6|63&s),r+=2;continue}const i=((7&a)<<18|(63&(e[r+1]??0))<<12|(63&(e[r+2]??0))<<6|63&(e[r+3]??0))-65536;t+=String.fromCharCode(55296+(i>>10),56320+(1023&i)),r+=3}return t},q=e=>!e||"object"!=typeof e||Array.isArray(e)?[]:Object.entries(e).filter(([e,t])=>e.trim().length>0&&"string"==typeof t).map(([e,t])=>({code:e,text:t})),G=e=>{let t=e;if("string"==typeof t)try{t=JSON.parse(t)}catch{return}if(!t||"object"!=typeof t||!("translations"in t))return;const r=t.translations;if(!Array.isArray(r))return;const a=[];for(const i of r)i&&"object"==typeof i&&"code"in i&&"text"in i&&"string"==typeof i.code&&i.code.trim()&&"string"==typeof i.text&&a.push([i.code,i.text]);return a.length>0?Object.fromEntries(a):void 0},H="websdk2:device-info",K="webim",J="web",Y=t=>{const r=Date.now(),a=t.deviceId,i=t.customOSPlatform,s=void 0!==i?t.customDeviceName:void 0,n=e().localStorage,o=()=>{if(!n)return null;try{const t=n.getItem(H);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},d=e=>{if(n)try{n.setItem(H,JSON.stringify(e))}catch{}},h=e=>void 0===i?e:{deviceId:`custom${i}_${e.deviceUuid}`,deviceName:s??a,deviceUuid:e.deviceUuid};if(t.useFixedDeviceId){const e=o();if(e)return h(e);if(a===K){const e=`${J}_${r}`,t=h({deviceId:`${a}_${e}`,deviceName:a,deviceUuid:e});return d(t),t}if(void 0!==i){const e=h({deviceId:`webim_${J}_${a}`,deviceName:a,deviceUuid:`${J}_${r}`});return d(e),e}const t={deviceId:`webim_${J}_${a}`,deviceName:`webim_${J}_${a}`,deviceUuid:`webim_${J}_${a}`};return d(t),t}if(a===K){const e=`random_${J}_${r}`;return h({deviceId:`${a}_${e}`,deviceName:a,deviceUuid:e})}if(void 0!==i){return h({deviceId:`webim_${J}_${a}`,deviceName:a,deviceUuid:`random_${J}_${r}`})}return{deviceId:`webim_${J}_${a}`,deviceName:`webim_${J}_${a}`,deviceUuid:`webim_${J}_${a}`}},X=e=>({appKey:e.appKey,name:e.name,domain:e.domain,clientResource:e.clientResource}),Q=e=>{if(/^\d+$/.test(e))return e;const t=m.fromString("1099511628211",!0);let r=m.fromString("1469598103934665603",!0);for(let a=0;a<e.length;a+=1)r=r.xor(m.fromInt(e.charCodeAt(a),!0)).multiply(t).toUnsigned();return r.isZero()?"1":r.toString()},W=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 m(t.low,t.high,Boolean(t.unsigned)).toString()}return e&&"function"==typeof e.toString?e.toString():""},Z=e=>{const t=[];for(const[r,a]of Object.entries(e))if(void 0!==a)if("boolean"!=typeof a)if("number"!=typeof a)if("string"!=typeof a)try{t.push({key:r,type:z,stringValue:JSON.stringify(a)})}catch{t.push({key:r,type:k,stringValue:Object.prototype.toString.call(a)})}else t.push({key:r,type:k,stringValue:a});else Number.isInteger(a)?t.push({key:r,type:P,varintValue:a}):t.push({key:r,type:j,doubleValue:a});else t.push({key:r,type:$,varintValue:a?1:0});return t},ee=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 a="number"==typeof r.type?r.type:k;if(a!==$)if(a!==P&&a!==D&&a!==x)if(a!==F)if(a!==j){if(a!==z)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},te=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),re=e=>{const t=Array.isArray(e.contents)?e.contents[0]:void 0;return te(t)?t:void 0};class ae{constructor(e,t=!1){this.userId=e,this.useCustomAttachmentUpload=t}decodeMetadata(e,t,r,a){const i=this.resolveMessageMetaPayload(e.meta,a),s={},n={modifiedInfo:this.resolveModifiedInfo(i),reactions:this.resolveReactions(i),isContentReplaced:this.resolveContentReplaced(i),chatThread:this.resolveChatThreadMessageContext(i),chatThreadOverview:this.resolveChatThreadOverview(i),isPeerRead:this.resolvePeerRead(i,t,r),groupReadCount:this.resolveGroupReadCount(i,t),stream:this.decodeStreamMeta(e.stream,re(e))};for(const[o,d]of Object.entries(n))void 0!==d&&Object.assign(s,{[o]:d});return n.chatThread&&(s.isChatThread=!0),te(e.msgConfig)&&e.msgConfig.allowGroupAck&&(s.needReadReceipt=!0),s}decodeContent(e,i){const s="number"==typeof e.type?e.type:C.TEXT,n="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,o=Object.prototype.hasOwnProperty.call(e,"subType")&&0===e.subType;if(s===C.COMBINE||s===C.TEXT&&(o||n)){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(s===C.TEXT){const t=G(i);return{type:"text",body:{content:"string"==typeof e.text?e.text:"",...t?{translations:t}:{}}}}if(s===C.COMMAND)return{type:"cmd",body:{action:"string"==typeof e.action?e.action:""}};if(s===C.CUSTOM){const t=ee(e.customExts);return{type:"custom",body:{event:"string"==typeof e.customEvent?e.customEvent:"",params:t}}}if(s===C.LOCATION)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(s===C.IMAGE){const i=e.size??{},s="number"==typeof i.width?i.width:0,n="number"==typeof i.height?i.height:0,o=t(e.imageType)===r,d="string"==typeof e.remotePath?e.remotePath:"",h=a(d,{deriveVariants:!this.useCustomAttachmentUpload}),u="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:s,height:n,isGif:1===e.subType,isOriginalImage:o,originalImageUrl:h.originalImageUrl,bigImageUrl:h.bigImageUrl,secret:"string"==typeof e.secretKey?e.secretKey:void 0,fileLength:"number"==typeof e.fileLength?e.fileLength:void 0,thumbnailUrl:u??h.thumbnailUrl}}}if(s===C.VIDEO){const t=e.size??{},r="number"==typeof t.width?t.width:void 0,a="number"==typeof t.height?t.height:void 0,i="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:a,secret:"string"==typeof e.secretKey?e.secretKey:void 0,fileLength:"number"==typeof e.fileLength?e.fileLength:void 0,thumbnailUrl:i}}}if(s===C.VOICE){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(s===C.FILE){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}decodeStreamMeta(e,t){if(!e||"object"!=typeof e)return;const r=e,a=Number(W(r.streamSeq));if(!Number.isFinite(a))return;const i="number"==typeof r.streamStatus?r.streamStatus:R,s="number"==typeof r.streamError?r.streamError:0,n="number"==typeof r.streamFinishReason?r.streamFinishReason:void 0,o=this.resolveContentText(t),d=o;return{customType:"string"==typeof r.streamType?r.streamType:void 0,seq:a,status:this.mapStreamStatus(i,s),errorType:s,finishReason:n,deltaText:o,fullText:d}}mapStreamStatus(e,t){return t>0?b.ERROR:e===N?b.START:e===S?b.START_COMPLETED:e===O?b.COMPLETED:e===E?b.FULL:b.IN_PROGRESS}resolveContentText(e){return e&&"string"==typeof e.text?e.text:e&&"string"==typeof e.customEvent?e.customEvent:""}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),a=this.parseMetaPayload(t);return r&&a?{...a,...r}:r??a??e??t}resolvePeerRead(e,t,r){if("singleChat"!==t||"SEND"!==r)return;const a=this.parseMetaPayload(e);return"boolean"==typeof a?.isRead?a.isRead:void 0}resolveGroupReadCount(e,t){if("groupChat"!==t)return;const r=this.parseMetaPayload(e),a=r?.group_read_ack;return"number"==typeof a&&Number.isInteger(a)&&a>=0?a:void 0}resolveModifiedInfo(e){const t=this.parseMetaPayload(e),r=t?.edit_msg;if(!te(r))return;const a="string"==typeof r.operator?r.operator:"",i=this.toFiniteNumber(r.count),s=this.toFiniteNumber(r.edit_time);return a&&void 0!==i&&void 0!==s?{operatorId:a,operationCount:i,operationTime:s}:void 0}resolveChatThreadMessageContext(e){const t=this.parseMetaPayload(e),r=t?.thread;if(!te(r)||0===Object.keys(r).length)return;const a=this.readString(r.msg_parent_id??r.messageId),i=this.readString(r.muc_parent_id??r.parentId);if(!a||!i)return;const s=this.readString(r.thread_name??r.chatThreadName);return{messageId:a,parentId:i,...s?{chatThreadName:s}:{}}}resolveChatThreadOverview(e){const t=this.parseMetaPayload(e),r=t?.thread_overview??t?.threadOverview;if(!te(r)||0===Object.keys(r).length)return;const a=this.readString(r.id??r.thread_id??r.chatThreadId),i=this.readString(r.muc_parent_id??r.parentId);if(!a||!i)return;const s=this.readString(r.name),n=this.resolveChatThreadOverviewLastMessage(r.last_message??r.lastMessage,a);return{chatThreadId:a,parentId:i,...s?{name:s}:{},...void 0!==n?{lastMessage:n}:{},...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(!te(e)||0===Object.keys(e).length)return null;const r=this.readString(e.msgId??e.msg_id??e.id);if(!r)return null;const a=this.toFiniteNumber(e.timestamp)??0,i=this.resolveThreadLastMessagePayload(e),s=this.readString(i?.from)??this.readString(e.from)??"",n=this.readString(i?.to)??this.readString(e.to)??t,o=Array.isArray(i?.bodies)?i.bodies:[],d=o.length>=2?this.composeThreadBodies(o):null;if(o.length>=2&&!d)return null;const h=te(o[0])?o[0]:null,u=this.readString(h?.type)??this.readString(e.type),l=d?.type??this.mapThreadMessageType(u),c=d?.body??this.normalizeThreadLastMessageBody(l,h,e),m=t,p=s===this.userId?"SEND":"RECEIVE";return{msgServerId:r,msgLocalId:"",from:s,to:n,sender:{userId:s},conversationId:m,conversationType:"groupChat",type:l,sendStatus:"sent",ext:te(i?.ext)?i.ext:{},timestamp:a,body:c,direct:p}}resolveThreadLastMessagePayload(e){const t=e.payload;if(te(t))return t;if("string"==typeof t){const e=this.parseMetaPayload(t);if(e)return e}return null}composeThreadBodies(e){return p(e.map(e=>{if(!te(e))return null;if(g(e))return{type:"combine",body:this.normalizeThreadLastMessageBody("combine",e,e)};const t=y(this.readString(e.type));return t?{type:t,body:this.normalizeThreadLastMessageBody(t,e,e)}: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=a(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:te(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(B(t));return te(e)?e:null}catch{return null}}if(te(e))return e;if("string"==typeof e)try{const t=JSON.parse(e);return te(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(te).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}}class ie{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 se=e=>new s(`${e} is required`,{code:n.VALIDATION_REQUIRED,details:{fields:[{path:e,message:`${e} is required`,rule:"required"}]}}),ne=(e,t)=>new s(t,{code:n.VALIDATION_INVALID_FORMAT,details:{fields:[{path:e,message:t,rule:"invalid_format"}]}}),oe=(e,t)=>{if("string"!=typeof e||0===e.trim().length)throw se(t);return e.trim()},de=(e,t)=>{if(void 0===e)return"";if("string"!=typeof e)throw ne(t,`${t} must be a string`);return e},he=(e,t)=>{if(void 0===e)return 20;if("number"!=typeof e||!Number.isInteger(e)||e<=0||e>50)throw ne(t,`${t} must be an integer between 1 and 50`);return e},ue=e=>{const{orgName:t,appName:r}=i(e.appKey);return{orgName:t,appName:r,encodedUserId:encodeURIComponent(e.userId),encodedResource:encodeURIComponent(e.clientResource)}},le=e=>l(e)?e:null,ce=e=>{const t=le(e);return t?.data??e},me=e=>{const t=le(e);if(Array.isArray(t?.entities))return t.entities;const r=ce(e);if(Array.isArray(r))return r;const a=le(r);return Array.isArray(a?.entities)?a.entities:Array.isArray(a?.affiliations)?a.affiliations:[]},pe=e=>{const t=le(e),r=le(t?.data),a=le(t?.properties);return("string"==typeof r?.cursor?r.cursor:void 0)??("string"==typeof a?.cursor?a.cursor:void 0)??("string"==typeof t?.cursor?t.cursor:void 0)??""},ge=e=>{const t=le(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 a="number"==typeof t.timestamp?t.timestamp:0,i=t.payload,s="string"==typeof i?c(i,{}):le(i)??{},n=Array.isArray(s.bodies)?s.bodies:[];if(n.length>=2){const e=new ae("").composeThreadBodies(n);if("multi_body"===e?.type&&Array.isArray(e.body))return{msgId:r,type:"multi_body",body:e.body.map(e=>({...e})),timestamp:a}}const o=le(n[0])??{};return{msgId:r,type:("string"==typeof o.type?o.type:void 0)??("string"==typeof s.type?s.type:void 0)??"",body:o,timestamp:a}},ye=e=>{const t=le(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),a=("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),i="string"==typeof t.name?t.name:"";return r&&a&&i?{chatThreadId:r,parentId:a,name:i,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:ge(t.lastMessage??t.last_message)}:null},fe=e=>({items:me(e).map(e=>ye(e)).filter(e=>null!==e),cursor:pe(e)}),_e=async(e,t,r)=>{const a=ue(t),i=oe(r,"chatThreadId");return(e=>{const t=ce(e),r=Array.isArray(t)?t[0]:t,a=ye(r);if(!a)throw ne("response.data","response.data is invalid");return a})(await e.get(`/${a.orgName}/${a.appName}/thread/${encodeURIComponent(i)}`,{operation:"getChatThreadInfo"}))},be=async(e,t,r)=>{const a=ue(t),i=oe(r.chatThreadId,"params.chatThreadId"),s=he(r.pageSize,"params.pageSize"),n=de(r.cursor,"params.cursor"),o=f({limit:String(s),cursor:n}),d=await e.get(`/${a.orgName}/${a.appName}/thread/${encodeURIComponent(i)}/users?${o.toString()}`,{operation:"getChatThreadMemberList"});return{items:me(h=d).map(e=>{if("string"==typeof e)return{memberId:e};const t=le(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:pe(h)};var h},ve=async(e,t,r)=>{const a=ue(t);if(!Array.isArray(r.chatThreadIds)||0===r.chatThreadIds.length)throw se("params.chatThreadIds");if(r.chatThreadIds.length>20)throw ne("params.chatThreadIds","params.chatThreadIds must contain at most 20 items");const i=r.chatThreadIds.map((e,t)=>oe(e,`params.chatThreadIds[${t}]`)),s=await e.post(`/${a.orgName}/${a.appName}/thread/message`,{threadIds:i},{operation:"getChatThreadLastMessageList"});return{items:me(s).map(e=>{const t=le(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:ge(t.lastMessage??t.last_message)}:null}).filter(e=>null!==e)}},Te=h(u,{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"]}}}}}),Ie=class{constructor(){this.capabilities=["rawNotify:chatThread"],this.client=null,this.eventContext=null,this.restClient=null,this.restBaseUrl=null,this.restToken=null,this.registry=/* @__PURE__ */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 s("chatThreadId is required",{code:n.VALIDATION_REQUIRED,details:{fields:[{path:"chatThreadId",message:"chatThreadId is required",rule:"required"}]}});const r=this.registry.get(t);if(r)return r;const a=new ie(t,this);return this.registry.set(t,a),a}async createChatThread(e){return this.runOperation("createChatThread",async()=>{const t=this.getRestContextOrThrow();return(async(e,t,r)=>{const a=ue(t),i=oe(r.parentId,"params.parentId"),s=oe(r.name,"params.name"),n=oe(r.messageId,"params.messageId"),o=await e.post(`/${a.orgName}/${a.appName}/thread?resource=${a.encodedResource}`,{name:s,msg_id:n,group_id:i,owner:t.userId},{operation:"createChatThread"}),d=le(ce(o)),h="string"==typeof d?.thread_id?d.thread_id:void 0;if(!h)throw ne("response.data.thread_id","response.data.thread_id is invalid");return{chatThreadId:h}})(this.getRestClient(t),t,e)})}async getChatThreadList(e){return this.runOperation("getChatThreadList",async()=>{const t=this.getRestContextOrThrow();return(async(e,t,r)=>{const a=ue(t),i=oe(r.parentId,"params.parentId"),s=he(r.pageSize,"params.pageSize"),n=de(r.cursor,"params.cursor"),o=f({limit:String(s),cursor:n}),d=await e.get(`/${a.orgName}/${a.appName}/threads/chatgroups/${encodeURIComponent(i)}?${o.toString()}`,{operation:"getChatThreadList"});return fe(d)})(this.getRestClient(t),t,e)})}async getJoinedChatThreadList(e={}){return this.runOperation("getJoinedChatThreadList",async()=>{const t=this.getRestContextOrThrow();return(async(e,t,r={})=>{const a=ue(t),i=he(r.pageSize,"params.pageSize"),s=de(r.cursor,"params.cursor"),n=f({limit:String(i),cursor:s}),o="string"==typeof r.parentId&&r.parentId.trim().length>0?`/${a.orgName}/${a.appName}/threads/chatgroups/${encodeURIComponent(r.parentId.trim())}/user/${a.encodedUserId}?${n.toString()}`:`/${a.orgName}/${a.appName}/threads/user/${a.encodedUserId}?${n.toString()}`,d=await e.get(o,{operation:"getJoinedChatThreadList"});return fe(d)})(this.getRestClient(t),t,e)})}async getChatThreadInfo(e){return this.runOperation("getChatThreadInfo",async()=>{const t=this.getRestContextOrThrow();return _e(this.getRestClient(t),t,e.chatThreadId)})}async joinChatThread(e){return this.runOperation("joinChatThread",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const a=ue(t),i=oe(r,"chatThreadId");await e.post(`/${a.orgName}/${a.appName}/thread/${encodeURIComponent(i)}/user/${a.encodedUserId}/join?resource=${a.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 a=ue(t),i=oe(r,"chatThreadId");await e.delete(`/${a.orgName}/${a.appName}/thread/${encodeURIComponent(i)}/user/${a.encodedUserId}/quit?resource=${a.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 a=ue(t),i=oe(r,"chatThreadId");await e.delete(`/${a.orgName}/${a.appName}/thread/${encodeURIComponent(i)}?resource=${a.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 a=ue(t),i=oe(r.chatThreadId,"params.chatThreadId"),s=oe(r.name,"params.name");await e.put(`/${a.orgName}/${a.appName}/thread/${encodeURIComponent(i)}?resource=${a.encodedResource}`,{name:s},{operation:"updateChatThreadName"})})(this.getRestClient(t),t,e)})}async getChatThreadMemberList(e){return this.runOperation("getChatThreadMemberList",async()=>{const t=this.getRestContextOrThrow();return be(this.getRestClient(t),t,e)})}async removeChatThreadMember(e){return this.runOperation("removeChatThreadMember",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const a=ue(t),i=oe(r.chatThreadId,"params.chatThreadId"),s=oe(r.memberId,"params.memberId");await e.delete(`/${a.orgName}/${a.appName}/thread/${encodeURIComponent(i)}/users/${encodeURIComponent(s)}?resource=${a.encodedResource}`,{operation:"removeChatThreadMember"})})(this.getRestClient(t),t,e)})}async getChatThreadLastMessageList(e){return this.runOperation("getChatThreadLastMessageList",async()=>{const t=this.getRestContextOrThrow();return ve(this.getRestClient(t),t,e)})}getClientOrThrow(){if(!this.client)throw new s("ChatThreadManager is not bound to client",{code:n.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 s("ChatThreadManager is not bound to event context",{code:n.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 o(e.restBaseUrl,{errorMap:Te,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 d)throw r;const t=r instanceof Error?r.message:String(r);throw new d(`ChatThreadManager ${e} failed: ${t}`,n.UNKNOWN)}}buildChatThreadPublicEvent(e){const t=e.payload,r="string"==typeof t.id?t.id:"",a="string"==typeof t.muc_parent_id?t.muc_parent_id:"";if(!r||!a)return null;const i="string"==typeof t.msg_parent_id?t.msg_parent_id:void 0,s="string"==typeof t.name?t.name:void 0,n="number"==typeof t.message_count?t.message_count:void 0,o=t.last_message&&"object"==typeof t.last_message?this.tryBuildThreadMessageSnippet(t.last_message):void 0,d="number"==typeof t.timestamp?t.timestamp:0,h="string"==typeof t.from?t.from:void 0,u={chatThreadId:r,parentId:a,name:s??"",messageId:i,messageCount:n,lastMessage:o};switch(t.operation){case"create":return{eventName:"onChatThreadCreated",payload:{chatThreadId:r,parentId:a,operatorId:h,chatThreadName:s,messageId:i,thread:u,timestamp:d}};case"update":case"update_msg":return{eventName:"onChatThreadUpdated",payload:{chatThreadId:r,parentId:a,operatorId:h,chatThreadName:s,messageId:i,messageCount:n,lastMessage:o,thread:u,timestamp:d}};case"delete":return{eventName:"onChatThreadDestroyed",payload:{chatThreadId:r,parentId:a,operatorId:h,timestamp:d}};case"kick":return{eventName:"onChatThreadUserRemoved",payload:{chatThreadId:r,parentId:a,operatorId:h,memberId:t.userIds?.[0],timestamp:d}};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}}};Ie.key="chatThreadManager";let Ce=Ie;export{M as C,L as E,_ as I,ae as M,A as N,U as P,w as R,b as S,X as a,Y as b,I as c,B as d,ee as e,Z as f,V as g,q as h,C as i,T as j,v as k,W as l,ie as m,Ce as n,G as r,Q as t};
@@ -0,0 +1 @@
1
+ "use strict";var i=null;try{i=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 t(i,t,n){this.low=0|i,this.high=0|t,this.unsigned=!!n}function n(i){return!0===(i&&i.__isLong__)}function h(i){var t=Math.clz32(i&-i);return i?31-t:t}t.prototype.__isLong__,Object.defineProperty(t.prototype,"__isLong__",{value:!0}),t.isLong=n;var s={},e={};function r(i,t){var n,h,r;return t?(r=0<=(i>>>=0)&&i<256)&&(h=e[i])?h:(n=o(i,0,!0),r&&(e[i]=n),n):(r=-128<=(i|=0)&&i<128)&&(h=s[i])?h:(n=o(i,i<0?-1:0,!1),r&&(s[i]=n),n)}function u(i,t){if(isNaN(i))return t?m:v;if(t){if(i<0)return m;if(i>=d)return B}else{if(i<=-c)return I;if(i+1>=c)return b}return i<0?u(-i,t).neg():o(i%a|0,i/a|0,t)}function o(i,n,h){return new t(i,n,h)}t.fromInt=r,t.fromNumber=u,t.fromBits=o;var g=Math.pow;function f(i,t,n){if(0===i.length)throw Error("empty string");if("number"==typeof t?(n=t,t=!1):t=!!t,"NaN"===i||"Infinity"===i||"+Infinity"===i||"-Infinity"===i)return t?m:v;if((n=n||10)<2||36<n)throw RangeError("radix");var h;if((h=i.indexOf("-"))>0)throw Error("interior hyphen");if(0===h)return f(i.substring(1),t,n).neg();for(var s=u(g(n,8)),e=v,r=0;r<i.length;r+=8){var o=Math.min(8,i.length-r),l=parseInt(i.substring(r,r+o),n);if(o<8){var a=u(g(n,o));e=e.mul(a).add(u(l))}else e=(e=e.mul(s)).add(u(l))}return e.unsigned=t,e}function l(i,t){return"number"==typeof i?u(i,t):"string"==typeof i?f(i,t):o(i.low,i.high,"boolean"==typeof t?t:i.unsigned)}t.fromString=f,t.fromValue=l;var a=4294967296,d=a*a,c=d/2,w=r(1<<24),v=r(0);t.ZERO=v;var m=r(0,!0);t.UZERO=m;var N=r(1);t.ONE=N;var E=r(1,!0);t.UONE=E;var y=r(-1);t.NEG_ONE=y;var b=o(-1,2147483647,!1);t.MAX_VALUE=b;var B=o(-1,-1,!0);t.MAX_UNSIGNED_VALUE=B;var I=o(0,-2147483648,!1);t.MIN_VALUE=I;var p=t.prototype;p.toInt=function(){return this.unsigned?this.low>>>0:this.low},p.toNumber=function(){return this.unsigned?(this.high>>>0)*a+(this.low>>>0):this.high*a+(this.low>>>0)},p.toString=function(i){if((i=i||10)<2||36<i)throw RangeError("radix");if(this.isZero())return"0";if(this.isNegative()){if(this.eq(I)){var t=u(i),n=this.div(t),h=n.mul(t).sub(this);return n.toString(i)+h.toInt().toString(i)}return"-"+this.neg().toString(i)}for(var s=u(g(i,6),this.unsigned),e=this,r="";;){var o=e.div(s),f=(e.sub(o.mul(s)).toInt()>>>0).toString(i);if((e=o).isZero())return f+r;for(;f.length<6;)f="0"+f;r=""+f+r}},p.getHighBits=function(){return this.high},p.getHighBitsUnsigned=function(){return this.high>>>0},p.getLowBits=function(){return this.low},p.getLowBitsUnsigned=function(){return this.low>>>0},p.getNumBitsAbs=function(){if(this.isNegative())return this.eq(I)?64:this.neg().getNumBitsAbs();for(var i=0!=this.high?this.high:this.low,t=31;t>0&&!(i&1<<t);t--);return 0!=this.high?t+33:t+1},p.isSafeInteger=function(){var i=this.high>>21;return!i||!this.unsigned&&(-1===i&&!(0===this.low&&-2097152===this.high))},p.isZero=function(){return 0===this.high&&0===this.low},p.eqz=p.isZero,p.isNegative=function(){return!this.unsigned&&this.high<0},p.isPositive=function(){return this.unsigned||this.high>=0},p.isOdd=function(){return!(1&~this.low)},p.isEven=function(){return!(1&this.low)},p.equals=function(i){return n(i)||(i=l(i)),(this.unsigned===i.unsigned||this.high>>>31!=1||i.high>>>31!=1)&&(this.high===i.high&&this.low===i.low)},p.eq=p.equals,p.notEquals=function(i){return!this.eq(i)},p.neq=p.notEquals,p.ne=p.notEquals,p.lessThan=function(i){return this.comp(i)<0},p.lt=p.lessThan,p.lessThanOrEqual=function(i){return this.comp(i)<=0},p.lte=p.lessThanOrEqual,p.le=p.lessThanOrEqual,p.greaterThan=function(i){return this.comp(i)>0},p.gt=p.greaterThan,p.greaterThanOrEqual=function(i){return this.comp(i)>=0},p.gte=p.greaterThanOrEqual,p.ge=p.greaterThanOrEqual,p.compare=function(i){if(n(i)||(i=l(i)),this.eq(i))return 0;var t=this.isNegative(),h=i.isNegative();return t&&!h?-1:!t&&h?1:this.unsigned?i.high>>>0>this.high>>>0||i.high===this.high&&i.low>>>0>this.low>>>0?-1:1:this.sub(i).isNegative()?-1:1},p.comp=p.compare,p.negate=function(){return!this.unsigned&&this.eq(I)?I:this.not().add(N)},p.neg=p.negate,p.add=function(i){n(i)||(i=l(i));var t=this.high>>>16,h=65535&this.high,s=this.low>>>16,e=65535&this.low,r=i.high>>>16,u=65535&i.high,g=i.low>>>16,f=0,a=0,d=0,c=0;return d+=(c+=e+(65535&i.low))>>>16,a+=(d+=s+g)>>>16,f+=(a+=h+u)>>>16,f+=t+r,o((d&=65535)<<16|(c&=65535),(f&=65535)<<16|(a&=65535),this.unsigned)},p.subtract=function(i){return n(i)||(i=l(i)),this.add(i.neg())},p.sub=p.subtract,p.multiply=function(t){if(this.isZero())return this;if(n(t)||(t=l(t)),i)return o(i.mul(this.low,this.high,t.low,t.high),i.get_high(),this.unsigned);if(t.isZero())return this.unsigned?m:v;if(this.eq(I))return t.isOdd()?I:v;if(t.eq(I))return this.isOdd()?I:v;if(this.isNegative())return t.isNegative()?this.neg().mul(t.neg()):this.neg().mul(t).neg();if(t.isNegative())return this.mul(t.neg()).neg();if(this.lt(w)&&t.lt(w))return u(this.toNumber()*t.toNumber(),this.unsigned);var h=this.high>>>16,s=65535&this.high,e=this.low>>>16,r=65535&this.low,g=t.high>>>16,f=65535&t.high,a=t.low>>>16,d=65535&t.low,c=0,N=0,E=0,y=0;return E+=(y+=r*d)>>>16,N+=(E+=e*d)>>>16,E&=65535,N+=(E+=r*a)>>>16,c+=(N+=s*d)>>>16,N&=65535,c+=(N+=e*a)>>>16,N&=65535,c+=(N+=r*f)>>>16,c+=h*d+s*a+e*f+r*g,o((E&=65535)<<16|(y&=65535),(c&=65535)<<16|(N&=65535),this.unsigned)},p.mul=p.multiply,p.divide=function(t){if(n(t)||(t=l(t)),t.isZero())throw Error("division by zero");var h,s,e;if(i)return this.unsigned||-2147483648!==this.high||-1!==t.low||-1!==t.high?o((this.unsigned?i.div_u:i.div_s)(this.low,this.high,t.low,t.high),i.get_high(),this.unsigned):this;if(this.isZero())return this.unsigned?m:v;if(this.unsigned){if(t.unsigned||(t=t.toUnsigned()),t.gt(this))return m;if(t.gt(this.shru(1)))return E;e=m}else{if(this.eq(I))return t.eq(N)||t.eq(y)?I:t.eq(I)?N:(h=this.shr(1).div(t).shl(1)).eq(v)?t.isNegative()?N:y:(s=this.sub(t.mul(h)),e=h.add(s.div(t)));if(t.eq(I))return this.unsigned?m:v;if(this.isNegative())return t.isNegative()?this.neg().div(t.neg()):this.neg().div(t).neg();if(t.isNegative())return this.div(t.neg()).neg();e=v}for(s=this;s.gte(t);){h=Math.max(1,Math.floor(s.toNumber()/t.toNumber()));for(var r=Math.ceil(Math.log(h)/Math.LN2),f=r<=48?1:g(2,r-48),a=u(h),d=a.mul(t);d.isNegative()||d.gt(s);)d=(a=u(h-=f,this.unsigned)).mul(t);a.isZero()&&(a=N),e=e.add(a),s=s.sub(d)}return e},p.div=p.divide,p.modulo=function(t){return n(t)||(t=l(t)),i?o((this.unsigned?i.rem_u:i.rem_s)(this.low,this.high,t.low,t.high),i.get_high(),this.unsigned):this.sub(this.div(t).mul(t))},p.mod=p.modulo,p.rem=p.modulo,p.not=function(){return o(~this.low,~this.high,this.unsigned)},p.countLeadingZeros=function(){return this.high?Math.clz32(this.high):Math.clz32(this.low)+32},p.clz=p.countLeadingZeros,p.countTrailingZeros=function(){return this.low?h(this.low):h(this.high)+32},p.ctz=p.countTrailingZeros,p.and=function(i){return n(i)||(i=l(i)),o(this.low&i.low,this.high&i.high,this.unsigned)},p.or=function(i){return n(i)||(i=l(i)),o(this.low|i.low,this.high|i.high,this.unsigned)},p.xor=function(i){return n(i)||(i=l(i)),o(this.low^i.low,this.high^i.high,this.unsigned)},p.shiftLeft=function(i){return n(i)&&(i=i.toInt()),0==(i&=63)?this:i<32?o(this.low<<i,this.high<<i|this.low>>>32-i,this.unsigned):o(0,this.low<<i-32,this.unsigned)},p.shl=p.shiftLeft,p.shiftRight=function(i){return n(i)&&(i=i.toInt()),0==(i&=63)?this:i<32?o(this.low>>>i|this.high<<32-i,this.high>>i,this.unsigned):o(this.high>>i-32,this.high>=0?0:-1,this.unsigned)},p.shr=p.shiftRight,p.shiftRightUnsigned=function(i){return n(i)&&(i=i.toInt()),0==(i&=63)?this:i<32?o(this.low>>>i|this.high<<32-i,this.high>>>i,this.unsigned):o(32===i?this.high:this.high>>>i-32,0,this.unsigned)},p.shru=p.shiftRightUnsigned,p.shr_u=p.shiftRightUnsigned,p.rotateLeft=function(i){var t;return n(i)&&(i=i.toInt()),0==(i&=63)?this:32===i?o(this.high,this.low,this.unsigned):i<32?(t=32-i,o(this.low<<i|this.high>>>t,this.high<<i|this.low>>>t,this.unsigned)):(t=32-(i-=32),o(this.high<<i|this.low>>>t,this.low<<i|this.high>>>t,this.unsigned))},p.rotl=p.rotateLeft,p.rotateRight=function(i){var t;return n(i)&&(i=i.toInt()),0==(i&=63)?this:32===i?o(this.high,this.low,this.unsigned):i<32?(t=32-i,o(this.high<<t|this.low>>>i,this.low<<t|this.high>>>i,this.unsigned)):(t=32-(i-=32),o(this.low<<t|this.high>>>i,this.high<<t|this.low>>>i,this.unsigned))},p.rotr=p.rotateRight,p.toSigned=function(){return this.unsigned?o(this.low,this.high,!1):this},p.toUnsigned=function(){return this.unsigned?this:o(this.low,this.high,!0)},p.toBytes=function(i){return i?this.toBytesLE():this.toBytesBE()},p.toBytesLE=function(){var i=this.high,t=this.low;return[255&t,t>>>8&255,t>>>16&255,t>>>24,255&i,i>>>8&255,i>>>16&255,i>>>24]},p.toBytesBE=function(){var i=this.high,t=this.low;return[i>>>24,i>>>16&255,i>>>8&255,255&i,t>>>24,t>>>16&255,t>>>8&255,255&t]},t.fromBytes=function(i,n,h){return h?t.fromBytesLE(i,n):t.fromBytesBE(i,n)},t.fromBytesLE=function(i,n){return new t(i[0]|i[1]<<8|i[2]<<16|i[3]<<24,i[4]|i[5]<<8|i[6]<<16|i[7]<<24,n)},t.fromBytesBE=function(i,n){return new t(i[4]<<24|i[5]<<16|i[6]<<8|i[7],i[0]<<24|i[1]<<16|i[2]<<8|i[3],n)},"function"==typeof BigInt&&(t.fromBigInt=function(i,t){return o(Number(BigInt.asIntN(32,i)),Number(BigInt.asIntN(32,i>>BigInt(32))),t)},t.fromValue=function(i,n){return"bigint"==typeof i?t.fromBigInt(i,n):l(i,n)},p.toBigInt=function(){var i=BigInt(this.low>>>0);return BigInt(this.unsigned?this.high>>>0:this.high)<<BigInt(32)|i}),exports.Long=t;
@@ -0,0 +1 @@
1
+ import{S as e,l as t}from"./common-gbNWJrBc.js";const o=new Set(["text","image","file","voice","video","location","custom"]),n={txt:"text",text:"text",img:"image",image:"image",audio:"voice",voice:"voice",loc:"location",location:"location",video:"video",file:"file",custom:"custom",cmd:"cmd",combine:"combine"},i=/* @__PURE__ */new WeakMap,s=e=>o.has(e),a=(e,t)=>`${e}:${t}`,l=(e,t)=>{i.set(e,t)},r=e=>{const t=i.get(e);return t&&i.delete(e),t},m=e=>e?n[e]??null:null,c=e=>{const t="string"==typeof e.type?e.type:"";if("combine"===t)return!0;if("txt"!==t&&"text"!==t)return!1;if(0===e.subType)return!0;const o=e=>"string"==typeof e&&e.length>0;return o(e.remotePath)||o(e.title)||o(e.summary)||"number"==typeof e.combineLevel&&e.combineLevel>0},u=(e,t)=>({...t,type:e}),d=(e,o)=>(t.warn("Multi-segment message keeps the first body only",{operation:"message.multi_body.keep_first",segmentCount:e.length,reason:o}),e.slice(0,1)),y=e=>{if(0===e.length)return null;const t=e[0];if(1===e.length)return t??null;const o=[];for(const n of e){if(!n||!s(n.type))return d(e,"a segment is missing or is not allowed in a multi_body message"),t??null;o.push(u(n.type,n.body))}return{type:"multi_body",body:o}},f=(e,t)=>y(e.map(e=>{return"object"!=typeof(o=e)||null===o||Array.isArray(o)?null:t(e);var o})),g=e=>"image"===e||"voice"===e||"video"===e||"file"===e,p=(t,o)=>{if(!(t instanceof e))return;const n={...t.details??{},msgLocalId:o};delete n.bodyIndex,t.details=n};export{c as a,a as b,y as c,g as d,p as e,l as h,s as i,d as k,m,f as r,r as t};
@@ -0,0 +1 @@
1
+ "use strict";const e=require("./common-Cg-lTASK.cjs"),t=new Set(["text","image","file","voice","video","location","custom"]),o={txt:"text",text:"text",img:"image",image:"image",audio:"voice",voice:"voice",loc:"location",location:"location",video:"video",file:"file",custom:"custom",cmd:"cmd",combine:"combine"},n=new WeakMap,i=e=>t.has(e),s=(e,t)=>({...t,type:e}),r=(t,o)=>(e.logger.warn("Multi-segment message keeps the first body only",{operation:"message.multi_body.keep_first",segmentCount:t.length,reason:o}),t.slice(0,1)),l=e=>{if(0===e.length)return null;const t=e[0];if(1===e.length)return t??null;const o=[];for(const n of e){if(!n||!i(n.type))return r(e,"a segment is missing or is not allowed in a multi_body message"),t??null;o.push(s(n.type,n.body))}return{type:"multi_body",body:o}};exports.attachMultiBodyUploadDetails=(t,o)=>{if(!(t instanceof e.SDKError))return;const n={...t.details??{},msgLocalId:o};delete n.bodyIndex,t.details=n},exports.attachmentStoreKey=(e,t)=>`${e}:${t}`,exports.composeSegments=l,exports.holdAttachmentFile=(e,t)=>{n.set(e,t)},exports.isCombineRestSegment=e=>{const t="string"==typeof e.type?e.type:"";if("combine"===t)return!0;if("txt"!==t&&"text"!==t)return!1;if(0===e.subType)return!0;const o=e=>"string"==typeof e&&e.length>0;return o(e.remotePath)||o(e.title)||o(e.summary)||"number"==typeof e.combineLevel&&e.combineLevel>0},exports.isDownloadableSegmentType=e=>"image"===e||"voice"===e||"video"===e||"file"===e,exports.isMultiBodySegmentType=i,exports.keepFirstBody=r,exports.mapRestSegmentType=e=>e?o[e]??null:null,exports.resolvePublicMessageContent=(e,t)=>l(e.map(e=>{return"object"!=typeof(o=e)||null===o||Array.isArray(o)?null:t(e);var o})),exports.takeAttachmentFile=e=>{const t=n.get(e);return t&&n.delete(e),t};
@@ -0,0 +1 @@
1
+ import{V as e,E as t,S as i,N as n,b as s,c as r,d as o,e as a,f as l,l as u,R as d,m as h,C as c}from"./common-gbNWJrBc.js";import{P as g}from"./event-system-DguqwFpc.js";import{q as m}from"./session-list-query-Inseic9m.js";const p=["apns","fcm","huawei","xiaomi","meizu","vivo","oppo","honor"],v=(i,n,s="invalid_format")=>new e(n,{code:t.VALIDATION_INVALID_FORMAT,details:{fields:[{path:i,message:n,rule:s}]}}),y=(e,t)=>{if(void 0!==e){if("string"!=typeof e||0===e.trim().length)throw v(t,`${t} must be a non-empty string`);return e.trim()}},f=e=>8===e?"normal":p[e]??"normal",T=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 R{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=/* @__PURE__ */new Set}configure(i){const n=(e=>{if(!e||"object"!=typeof e)throw v("options","options is required","required");const t=e.plugin;if(!t||"object"!=typeof t)throw v("plugin","plugin is required","required");const i=t;if("function"!=typeof i.onRegister)throw v("plugin.onRegister","plugin.onRegister must be a function");if("function"!=typeof i.unRegister)throw v("plugin.unRegister","plugin.unRegister must be a function");const n=e.certificates;if(!n||"object"!=typeof n)throw v("certificates","certificates is required","required");const s=n,r={apns:y(s.apns,"certificates.apns"),fcm:y(s.fcm,"certificates.fcm"),huawei:y(s.huawei,"certificates.huawei"),xiaomi:y(s.xiaomi,"certificates.xiaomi"),meizu:y(s.meizu,"certificates.meizu"),vivo:y(s.vivo,"certificates.vivo"),oppo:y(s.oppo,"certificates.oppo"),honor:y(s.honor,"certificates.honor")};if(!p.some(e=>void 0!==r[e]))throw v("certificates","at least one native push certificate is required");return{plugin:t,certificates:r,signature:p.map(e=>`${e}:${r[e]??""}`).join("|")}})(i),s=null!==this.config&&"disabled"!==this.state,r=this.config?.plugin===n.plugin&&this.config.signature===n.signature;if(s&&!r)throw new e("Native push is enabled; call removePushToken() before replacing its configuration",{code:t.VALIDATION_INVALID_FORMAT,details:{fields:[{path:"options",message:"removePushToken() must succeed before replacing native push config",rule:"conflict"}]}});s&&r&&"failed"!==this.state||(this.invalidateRegistration(),this.safeUnregister(),this.config=n,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 i=await this.removeWithRetry(t,e.generation);if(!this.isSessionGenerationActive(e.generation))return;if(!i){this.emitFailure(g.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 i("User is not logged in",t.AUTH_NOT_LOGIN))}startRegistration(){if(!this.config||!this.session||this.disabledByUser)return;const e=this.config,t=this.session.generation,i=++this.registrationVersion;this.state="registering",this.pluginRegistered=!0;try{e.plugin.onRegister(n=>{if(!this.isRegistrationActive(t,i))return;const s=((e,t)=>{if(!T(e)||200!==e.code||0===e.push_token.trim().length)return null;const i=f(e.push_type);if("normal"===i)return null;const n=t.certificates[i];return n?{token:e.push_token,channel:i,notifierName:n}:null})(n,e);if(!s){this.state="failed";const t=T(n)?f(n.push_type):void 0,i=T(n)&&200===n.code&&n.push_token.trim().length>0&&void 0!==t&&"normal"!==t&&void 0===e.certificates[t];return void this.emitFailure(g.TOKEN_BIND_FAILED,i?"bind":"register",t)}this.enqueueBinding(s)})}catch{this.safeUnregister(),this.state="failed",this.emitFailure(g.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,i=this.createBindingKey(e);this.activeBindingKey=i,this.state="binding";const n=await this.bindWithRetry(e,t);if(this.activeBindingKey=null,!this.session||this.session.generation!==t||this.disabledByUser)return;n?(this.binding={...e,generation:t,userId:this.session.userId,deviceId:this.session.clientResource},this.successfulKey=i,this.exhaustedKey=null,this.state="bound",this.sessionEndingGeneration===t||this.manualRemovalInProgress||this.dependencies.dispatch(g.TOKEN_BOUND,{channel:e.channel,notifierName:e.notifierName})):(this.exhaustedKey=i,this.state="failed",this.sessionEndingGeneration===t||this.manualRemovalInProgress||this.emitFailure(g.TOKEN_BIND_FAILED,"bind",e.channel,e.notifierName,this.lastBindingError??void 0))}}async bindWithRetry(e,t){this.lastBindingError=null;for(let o=0;o<=n;o+=1)try{const i=this.session;return!(!i||i.generation!==t)&&(this.lastAttemptedBinding={...e,generation:t,userId:i.userId,deviceId:i.clientResource},await this.dependencies.requestToken({deviceId:i.clientResource,deviceToken:e.token,notifierName:e.notifierName,timeout:s}),!0)}catch(i){if(this.lastBindingError=this.toSdkError(i),!this.session||this.session.generation!==t)return!1;if(!this.isRetryable(i)||o===n)return!1;const e=r[o]??0;if(!(await this.wait(e)))return!1}return!1}async performManualRemoval(){if(!this.session)throw new i("User is not logged in",t.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 i("User is not logged in",t.AUTH_NOT_LOGIN);const n=this.collectRemovalTargets(e);if(0!==n.length)try{for(const t of n)if(await this.dependencies.requestToken({deviceId:t.deviceId,deviceToken:"",notifierName:t.notifierName}),!this.isSessionGenerationActive(e))return;this.disableByUser()}catch(s){const t=this.toSdkError(s),i=n[0];throw i&&this.isSessionGenerationActive(e)&&this.emitFailure(g.TOKEN_REMOVE_FAILED,"remove",i.channel,i.notifierName,t),this.manualRemovalInProgress=!1,this.resumePendingBinding(e),t}else this.disableByUser()}async removeWithRetry(e,t){this.lastRemovalError=null;for(let n=0;n<=o;n+=1)try{return await this.dependencies.requestToken({deviceId:e.deviceId,deviceToken:"",notifierName:e.notifierName,timeout:a}),!0}catch(i){if(this.lastRemovalError=this.toSdkError(i),!this.isSessionGenerationActive(t))return!1;if(!this.isRetryable(i)||n===o)return!1;if(!(await this.wait(l)))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,i)=>t.findIndex(t=>t.deviceId===e.deviceId&&t.notifierName===e.notifierName)===i)}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{u.warn("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 i={timer:setTimeout(()=>{this.delays.delete(i),t(!0)},e),resolve:t};this.delays.add(i)})}isRetryable(e){return!(e instanceof i)||(!0===e.details?.retryable||[t.REST_NETWORK_ERROR,t.REST_TIMEOUT,t.REST_HTTP_ERROR,t.SERVER_BUSY].includes(e.code))}toSdkError(e){return e instanceof i?e:new i("Native push operation failed",t.UNKNOWN)}emitFailure(e,t,i,n,s){const r=!!s&&this.isRetryable(s);this.dependencies.dispatchFailure(e,{stage:t,...i?{channel:i}:{},...n?{notifierName:n}:{},...s?{code:s.code}:{},retryable:r}),u.warn("Native push operation failed",{stage:t,...i?{channel:i}:{},...n?{notifierName:n}:{},...s?{code:s.code}:{},retryable:r})}}const b=h(c,{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}}}}}),I=["singleChat","groupChat"],N=["ALL","AT","NONE","DEFAULT"],E=["ALL","AT","NONE"],C=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),w=class{constructor(){this.client=null,this.restClient=null,this.restBaseUrl=null,this.restToken=null,this.eventContext=null,this.nativePushController=new R({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(),i=this.getRestClient(t),{orgName:n,appName:s}=this.parseAppKey(t.appKey);u.debug("Call native push token operation",{deviceId:e.deviceId,notifierName:e.notifierName,removing:0===e.deviceToken.length}),await i.request(`/${n}/${s}/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(),i=this.getRestClient(t),{orgName:n,appName:s}=this.parseAppKey(t.appKey),r=`/${n}/${s}/users/${t.userId}/notification/user/${t.userId}?resource=${encodeURIComponent(t.clientResource)}`,o=this.buildSilentModePayload(e.rule);u.debug("Call setGlobalSilentMode",{mode:e.rule.mode});const a=await i.request(r,{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:i,appName:n}=this.parseAppKey(e.appKey),s=`/${i}/${n}/users/${e.userId}/notification/user/${e.userId}`;u.debug("Call getGlobalSilentMode");const r=await t.request(s,{method:"GET",operation:"getGlobalSilentMode"});return{scope:"global",rule:this.normalizeRuleView(this.resolveSilentModeRuleSource(r))}})}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(),i=this.getRestClient(t),{orgName:n,appName:s}=this.parseAppKey(t.appKey),r=this.mapConversationTypeToPath(e.conversationType),o=`/${n}/${s}/users/${t.userId}/notification/${r}/${encodeURIComponent(e.conversationId)}?resource=${encodeURIComponent(t.clientResource)}`,a=this.buildSilentModePayload(e.rule);u.debug("Call setConversationSilentMode",{conversationId:e.conversationId,conversationType:e.conversationType,mode:e.rule.mode});const l=await i.request(o,{method:"PUT",body:a,operation:"setConversationSilentMode"});return{conversationId:e.conversationId,conversationType:e.conversationType,rule:this.normalizeRuleView(this.resolveSilentModeRuleSource(l),e.rule)}})}async getConversationSilentMode(e){return this.runOperation(async()=>{this.validateConversationId(e.conversationId,"conversationId"),this.validateConversationType(e.conversationType,"conversationType");const t=this.getRestContextOrThrow(),i=this.getRestClient(t),{orgName:n,appName:s}=this.parseAppKey(t.appKey),r=this.mapConversationTypeToPath(e.conversationType),o=`/${n}/${s}/users/${t.userId}/notification/${r}/${encodeURIComponent(e.conversationId)}`;u.debug("Call getConversationSilentMode",{conversationId:e.conversationId,conversationType:e.conversationType});const a=await i.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(),i=this.getRestClient(t),{orgName:n,appName:s}=this.parseAppKey(t.appKey),r=this.mapConversationTypeToPath(e.conversationType),o=`/${n}/${s}/users/${t.userId}/notification/${r}/${encodeURIComponent(e.conversationId)}?resource=${encodeURIComponent(t.clientResource)}`;u.debug("Call clearConversationRemindType",{conversationId:e.conversationId,conversationType:e.conversationType});const a=await i.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(),i=this.getRestClient(t),{orgName:n,appName:s}=this.parseAppKey(t.appKey),r=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=`/${n}/${s}/users/${t.userId}/notification?user=${r}&group=${o}`;u.debug("Call getConversationSilentModes",{count:e.conversationList.length});const l=await i.request(a,{method:"GET",operation:"getConversationSilentModes"}),d=this.resolveConversationRuleMap(l,"user"),h=this.resolveConversationRuleMap(l,"group");return{conversations:e.conversationList.map(e=>{const t="singleChat"===e.conversationType?d[e.conversationId]:h[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(),i=this.getRestClient(t),{orgName:n,appName:s}=this.parseAppKey(t.appKey),r=`/${n}/${s}/users/${t.userId}/notification/language`;u.debug("Call setPushLanguage",{language:e.language}),await i.request(r,{method:"PUT",body:{translationLanguage:e.language},operation:"setPushLanguage"})})}async getPushLanguage(e={}){return this.runOperation(async()=>{const e=this.getRestContextOrThrow(),t=this.getRestClient(e),{orgName:i,appName:n}=this.parseAppKey(e.appKey),s=`/${i}/${n}/users/${e.userId}/notification/language`;u.debug("Call getPushLanguage");const r=await t.request(s,{method:"GET",operation:"getPushLanguage"});return{language:this.resolvePushLanguage(r,"")}})}getConversationListByRemindType(e){return this.runOperation(()=>{u.debug("Call getConversationListByRemindType",{pageSize:e.pageSize,hasCursor:Boolean(e.cursor)});const t=this.getClientOrThrow(),i=m({items:t.getCacheManager()?.loadSessionList()??[],pageSize:e.pageSize,cursor:e.cursor});return Promise.resolve(i)})}async runOperation(e){try{return await e()}catch(t){throw this.normalizeSdkError(t)}}normalizeSdkError(e){return e instanceof i?e:e instanceof Error?new i(`PushManager operation failed: ${e.message}`,t.UNKNOWN):new i("PushManager operation failed",t.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 d(e.restBaseUrl,{errorMap:b,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 i("PushManager is not bound to client",t.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||!I.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,i)=>{this.validateConversationId(e.conversationId,`${t}[${i}].conversationId`),this.validateConversationType(e.conversationType,`${t}[${i}].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(!C(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(!E.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,i){const n=Object.keys(e).find(e=>!i.includes(e));if(n)throw this.buildValidationError("Silent mode rule contains conflicting fields",[{path:`${t}.${n}`,message:`${n} is not allowed when mode is ${e.mode}`,rule:"conflict"}])}validateTimePoint(e,t){if(!C(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 i=this.parseRuleView(e);return i?t?{...this.toRuleViewFromFallback(t),...i}:i:t?this.toRuleViewFromFallback(t):{}}parseRuleView(e){if(!C(e))return null;const t={},i=this.normalizeRemindType(e.type);null!==i&&(t.remindType=i);const n=e.ignoreDuration;"number"==typeof n&&Number.isInteger(n)&&n>0&&(t.expireTimestamp=n);const s=e.ignoreInterval;if("string"==typeof s){const e=this.parseInterval(s);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 i=Number(t[1]),n=Number(t[2]),s=Number(t[3]),r=Number(t[4]);return Number.isInteger(i)&&Number.isInteger(n)&&Number.isInteger(s)&&Number.isInteger(r)?i<0||i>23||s<0||s>23||n<0||n>59||r<0||r>59?null:{startTime:{hours:i,minutes:n},endTime:{hours:s,minutes:r}}: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(C(e.data)){const i=e.data[t];if(C(i))return i}const i=e[t];return C(i)?i:{}}resolveSilentModeRuleSource(e){if(!C(e))return e;if(null!==this.parseRuleView(e))return e;const t=e.data;return C(t)&&null!==this.parseRuleView(t)?t:e}normalizeRemindType(e){return"string"!=typeof e?null:"MENTION_ONLY"===e?"AT":N.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(C(e.data)){const t=e.data.translationLanguage;if("string"==typeof t&&t.length>0)return t;const i=e.data.language;if("string"==typeof i&&i.length>0)return i}return t}mapConversationTypeToPath(e){return"singleChat"===e?"user":"chatgroup"}buildValidationError(i,n){return new e(i,{code:t.VALIDATION_INVALID_FORMAT,details:{fields:n}})}};w.key="pushManager";let S=w;export{S as P};
@@ -0,0 +1 @@
1
+ "use strict";const e=require("./common-Cg-lTASK.cjs"),t=require("./event-system-TYhmgy4K.cjs"),i=require("./session-list-query-DMe2GZ4v.cjs"),n=["apns","fcm","huawei","xiaomi","meizu","vivo","oppo","honor"],s=(t,i,n="invalid_format")=>new e.ValidationError(i,{code:e.ERROR_CODES.VALIDATION_INVALID_FORMAT,details:{fields:[{path:t,message:i,rule:n}]}}),r=(e,t)=>{if(void 0!==e){if("string"!=typeof e||0===e.trim().length)throw s(t,`${t} must be a non-empty string`);return e.trim()}},o=e=>8===e?"normal":n[e]??"normal",a=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 l{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(t){const i=(e=>{if(!e||"object"!=typeof e)throw s("options","options is required","required");const t=e.plugin;if(!t||"object"!=typeof t)throw s("plugin","plugin is required","required");const i=t;if("function"!=typeof i.onRegister)throw s("plugin.onRegister","plugin.onRegister must be a function");if("function"!=typeof i.unRegister)throw s("plugin.unRegister","plugin.unRegister must be a function");const o=e.certificates;if(!o||"object"!=typeof o)throw s("certificates","certificates is required","required");const a=o,l={apns:r(a.apns,"certificates.apns"),fcm:r(a.fcm,"certificates.fcm"),huawei:r(a.huawei,"certificates.huawei"),xiaomi:r(a.xiaomi,"certificates.xiaomi"),meizu:r(a.meizu,"certificates.meizu"),vivo:r(a.vivo,"certificates.vivo"),oppo:r(a.oppo,"certificates.oppo"),honor:r(a.honor,"certificates.honor")};if(!n.some(e=>void 0!==l[e]))throw s("certificates","at least one native push certificate is required");return{plugin:t,certificates:l,signature:n.map(e=>`${e}:${l[e]??""}`).join("|")}})(t),o=null!==this.config&&"disabled"!==this.state,a=this.config?.plugin===i.plugin&&this.config.signature===i.signature;if(o&&!a)throw new e.ValidationError("Native push is enabled; call removePushToken() before replacing its configuration",{code:e.ERROR_CODES.VALIDATION_INVALID_FORMAT,details:{fields:[{path:"options",message:"removePushToken() must succeed before replacing native push config",rule:"conflict"}]}});o&&a&&"failed"!==this.state||(this.invalidateRegistration(),this.safeUnregister(),this.config=i,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 i of this.collectRemovalTargets(e.generation)){const n=await this.removeWithRetry(i,e.generation);if(!this.isSessionGenerationActive(e.generation))return;if(!n){this.emitFailure(t.PushEventName.TOKEN_REMOVE_FAILED,"remove",i.channel,i.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 e.SDKError("User is not logged in",e.ERROR_CODES.AUTH_NOT_LOGIN))}startRegistration(){if(!this.config||!this.session||this.disabledByUser)return;const e=this.config,i=this.session.generation,n=++this.registrationVersion;this.state="registering",this.pluginRegistered=!0;try{e.plugin.onRegister(s=>{if(!this.isRegistrationActive(i,n))return;const r=((e,t)=>{if(!a(e)||200!==e.code||0===e.push_token.trim().length)return null;const i=o(e.push_type);if("normal"===i)return null;const n=t.certificates[i];return n?{token:e.push_token,channel:i,notifierName:n}:null})(s,e);if(!r){this.state="failed";const i=a(s)?o(s.push_type):void 0,n=a(s)&&200===s.code&&s.push_token.trim().length>0&&void 0!==i&&"normal"!==i&&void 0===e.certificates[i];return void this.emitFailure(t.PushEventName.TOKEN_BIND_FAILED,n?"bind":"register",i)}this.enqueueBinding(r)})}catch{this.safeUnregister(),this.state="failed",this.emitFailure(t.PushEventName.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 i=this.session.generation,n=this.createBindingKey(e);this.activeBindingKey=n,this.state="binding";const s=await this.bindWithRetry(e,i);if(this.activeBindingKey=null,!this.session||this.session.generation!==i||this.disabledByUser)return;s?(this.binding={...e,generation:i,userId:this.session.userId,deviceId:this.session.clientResource},this.successfulKey=n,this.exhaustedKey=null,this.state="bound",this.sessionEndingGeneration===i||this.manualRemovalInProgress||this.dependencies.dispatch(t.PushEventName.TOKEN_BOUND,{channel:e.channel,notifierName:e.notifierName})):(this.exhaustedKey=n,this.state="failed",this.sessionEndingGeneration===i||this.manualRemovalInProgress||this.emitFailure(t.PushEventName.TOKEN_BIND_FAILED,"bind",e.channel,e.notifierName,this.lastBindingError??void 0))}}async bindWithRetry(t,i){this.lastBindingError=null;for(let s=0;s<=e.NATIVE_PUSH_BIND_MAX_RETRIES;s+=1)try{const n=this.session;return!(!n||n.generation!==i)&&(this.lastAttemptedBinding={...t,generation:i,userId:n.userId,deviceId:n.clientResource},await this.dependencies.requestToken({deviceId:n.clientResource,deviceToken:t.token,notifierName:t.notifierName,timeout:e.NATIVE_PUSH_BIND_REQUEST_TIMEOUT}),!0)}catch(n){if(this.lastBindingError=this.toSdkError(n),!this.session||this.session.generation!==i)return!1;if(!this.isRetryable(n)||s===e.NATIVE_PUSH_BIND_MAX_RETRIES)return!1;const t=e.NATIVE_PUSH_BIND_RETRY_DELAYS[s]??0;if(!(await this.wait(t)))return!1}return!1}async performManualRemoval(){if(!this.session)throw new e.SDKError("User is not logged in",e.ERROR_CODES.AUTH_NOT_LOGIN);const i=this.session.generation;if(this.manualRemovalInProgress=!0,this.cancelDelays(),this.bindingPromise&&await this.bindingPromise,!this.isSessionGenerationActive(i))throw this.manualRemovalInProgress=!1,new e.SDKError("User is not logged in",e.ERROR_CODES.AUTH_NOT_LOGIN);const n=this.collectRemovalTargets(i);if(0!==n.length)try{for(const e of n)if(await this.dependencies.requestToken({deviceId:e.deviceId,deviceToken:"",notifierName:e.notifierName}),!this.isSessionGenerationActive(i))return;this.disableByUser()}catch(s){const e=this.toSdkError(s),r=n[0];throw r&&this.isSessionGenerationActive(i)&&this.emitFailure(t.PushEventName.TOKEN_REMOVE_FAILED,"remove",r.channel,r.notifierName,e),this.manualRemovalInProgress=!1,this.resumePendingBinding(i),e}else this.disableByUser()}async removeWithRetry(t,i){this.lastRemovalError=null;for(let s=0;s<=e.NATIVE_PUSH_REMOVE_MAX_RETRIES;s+=1)try{return await this.dependencies.requestToken({deviceId:t.deviceId,deviceToken:"",notifierName:t.notifierName,timeout:e.NATIVE_PUSH_REMOVE_REQUEST_TIMEOUT}),!0}catch(n){if(this.lastRemovalError=this.toSdkError(n),!this.isSessionGenerationActive(i))return!1;if(!this.isRetryable(n)||s===e.NATIVE_PUSH_REMOVE_MAX_RETRIES)return!1;if(!(await this.wait(e.NATIVE_PUSH_REMOVE_RETRY_DELAY)))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,i)=>t.findIndex(t=>t.deviceId===e.deviceId&&t.notifierName===e.notifierName)===i)}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{e.logger.warn("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 i={timer:setTimeout(()=>{this.delays.delete(i),t(!0)},e),resolve:t};this.delays.add(i)})}isRetryable(t){return!(t instanceof e.SDKError)||(!0===t.details?.retryable||[e.ERROR_CODES.REST_NETWORK_ERROR,e.ERROR_CODES.REST_TIMEOUT,e.ERROR_CODES.REST_HTTP_ERROR,e.ERROR_CODES.SERVER_BUSY].includes(t.code))}toSdkError(t){return t instanceof e.SDKError?t:new e.SDKError("Native push operation failed",e.ERROR_CODES.UNKNOWN)}emitFailure(t,i,n,s,r){const o=!!r&&this.isRetryable(r);this.dependencies.dispatchFailure(t,{stage:i,...n?{channel:n}:{},...s?{notifierName:s}:{},...r?{code:r.code}:{},retryable:o}),e.logger.warn("Native push operation failed",{stage:i,...n?{channel:n}:{},...s?{notifierName:s}:{},...r?{code:r.code}:{},retryable:o})}}const u=e.mergeRuntimeErrorMaps(e.COMMON_ERROR_MAP,{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}}}}}),d=["singleChat","groupChat"],h=["ALL","AT","NONE","DEFAULT"],c=["ALL","AT","NONE"],g=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),m=class{constructor(){this.client=null,this.restClient=null,this.restBaseUrl=null,this.restToken=null,this.eventContext=null,this.nativePushController=new l({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(t){const i=this.getRestContextOrThrow(),n=this.getRestClient(i),{orgName:s,appName:r}=this.parseAppKey(i.appKey);e.logger.debug("Call native push token operation",{deviceId:t.deviceId,notifierName:t.notifierName,removing:0===t.deviceToken.length}),await n.request(`/${s}/${r}/users/${i.userId}`,{method:"PUT",body:{device_id:t.deviceId,device_token:t.deviceToken,notifier_name:t.notifierName},operation:"uploadPushToken",...void 0!==t.timeout?{timeout:t.timeout}:{}})}async setGlobalSilentMode(t){return this.runOperation(async()=>{this.validateRuleInput(t.rule,"rule");const i=this.getRestContextOrThrow(),n=this.getRestClient(i),{orgName:s,appName:r}=this.parseAppKey(i.appKey),o=`/${s}/${r}/users/${i.userId}/notification/user/${i.userId}?resource=${encodeURIComponent(i.clientResource)}`,a=this.buildSilentModePayload(t.rule);e.logger.debug("Call setGlobalSilentMode",{mode:t.rule.mode});const l=await n.request(o,{method:"PUT",body:a,operation:"setGlobalSilentMode"});return{scope:"global",rule:this.normalizeRuleView(this.resolveSilentModeRuleSource(l),t.rule)}})}async getGlobalSilentMode(t={}){return this.runOperation(async()=>{const t=this.getRestContextOrThrow(),i=this.getRestClient(t),{orgName:n,appName:s}=this.parseAppKey(t.appKey),r=`/${n}/${s}/users/${t.userId}/notification/user/${t.userId}`;e.logger.debug("Call getGlobalSilentMode");const o=await i.request(r,{method:"GET",operation:"getGlobalSilentMode"});return{scope:"global",rule:this.normalizeRuleView(this.resolveSilentModeRuleSource(o))}})}async setConversationSilentMode(t){return this.runOperation(async()=>{this.validateConversationId(t.conversationId,"conversationId"),this.validateConversationType(t.conversationType,"conversationType"),this.validateRuleInput(t.rule,"rule");const i=this.getRestContextOrThrow(),n=this.getRestClient(i),{orgName:s,appName:r}=this.parseAppKey(i.appKey),o=this.mapConversationTypeToPath(t.conversationType),a=`/${s}/${r}/users/${i.userId}/notification/${o}/${encodeURIComponent(t.conversationId)}?resource=${encodeURIComponent(i.clientResource)}`,l=this.buildSilentModePayload(t.rule);e.logger.debug("Call setConversationSilentMode",{conversationId:t.conversationId,conversationType:t.conversationType,mode:t.rule.mode});const u=await n.request(a,{method:"PUT",body:l,operation:"setConversationSilentMode"});return{conversationId:t.conversationId,conversationType:t.conversationType,rule:this.normalizeRuleView(this.resolveSilentModeRuleSource(u),t.rule)}})}async getConversationSilentMode(t){return this.runOperation(async()=>{this.validateConversationId(t.conversationId,"conversationId"),this.validateConversationType(t.conversationType,"conversationType");const i=this.getRestContextOrThrow(),n=this.getRestClient(i),{orgName:s,appName:r}=this.parseAppKey(i.appKey),o=this.mapConversationTypeToPath(t.conversationType),a=`/${s}/${r}/users/${i.userId}/notification/${o}/${encodeURIComponent(t.conversationId)}`;e.logger.debug("Call getConversationSilentMode",{conversationId:t.conversationId,conversationType:t.conversationType});const l=await n.request(a,{method:"GET",operation:"getConversationSilentMode"});return{conversationId:t.conversationId,conversationType:t.conversationType,rule:this.normalizeRuleView(this.resolveSilentModeRuleSource(l))}})}async clearConversationRemindType(t){return this.runOperation(async()=>{this.validateConversationId(t.conversationId,"conversationId"),this.validateConversationType(t.conversationType,"conversationType");const i=this.getRestContextOrThrow(),n=this.getRestClient(i),{orgName:s,appName:r}=this.parseAppKey(i.appKey),o=this.mapConversationTypeToPath(t.conversationType),a=`/${s}/${r}/users/${i.userId}/notification/${o}/${encodeURIComponent(t.conversationId)}?resource=${encodeURIComponent(i.clientResource)}`;e.logger.debug("Call clearConversationRemindType",{conversationId:t.conversationId,conversationType:t.conversationType});const l=await n.request(a,{method:"PUT",body:{type:"DEFAULT"},operation:"clearConversationRemindType"});return{conversationId:t.conversationId,conversationType:t.conversationType,rule:this.normalizeRuleView(this.resolveSilentModeRuleSource(l),{remindType:"DEFAULT"})}})}async getConversationSilentModes(t){return this.runOperation(async()=>{this.validateConversationList(t.conversationList,"conversationList");const i=this.getRestContextOrThrow(),n=this.getRestClient(i),{orgName:s,appName:r}=this.parseAppKey(i.appKey),o=t.conversationList.filter(e=>"singleChat"===e.conversationType).map(e=>encodeURIComponent(e.conversationId)).join(","),a=t.conversationList.filter(e=>"groupChat"===e.conversationType).map(e=>encodeURIComponent(e.conversationId)).join(","),l=`/${s}/${r}/users/${i.userId}/notification?user=${o}&group=${a}`;e.logger.debug("Call getConversationSilentModes",{count:t.conversationList.length});const u=await n.request(l,{method:"GET",operation:"getConversationSilentModes"}),d=this.resolveConversationRuleMap(u,"user"),h=this.resolveConversationRuleMap(u,"group");return{conversations:t.conversationList.map(e=>{const t="singleChat"===e.conversationType?d[e.conversationId]:h[e.conversationId];return{conversationId:e.conversationId,conversationType:e.conversationType,rule:this.normalizeRuleView(t)}})}})}async setPushLanguage(t){await this.runOperation(async()=>{this.validateLanguage(t.language,"language");const i=this.getRestContextOrThrow(),n=this.getRestClient(i),{orgName:s,appName:r}=this.parseAppKey(i.appKey),o=`/${s}/${r}/users/${i.userId}/notification/language`;e.logger.debug("Call setPushLanguage",{language:t.language}),await n.request(o,{method:"PUT",body:{translationLanguage:t.language},operation:"setPushLanguage"})})}async getPushLanguage(t={}){return this.runOperation(async()=>{const t=this.getRestContextOrThrow(),i=this.getRestClient(t),{orgName:n,appName:s}=this.parseAppKey(t.appKey),r=`/${n}/${s}/users/${t.userId}/notification/language`;e.logger.debug("Call getPushLanguage");const o=await i.request(r,{method:"GET",operation:"getPushLanguage"});return{language:this.resolvePushLanguage(o,"")}})}getConversationListByRemindType(t){return this.runOperation(()=>{e.logger.debug("Call getConversationListByRemindType",{pageSize:t.pageSize,hasCursor:Boolean(t.cursor)});const n=this.getClientOrThrow(),s=i.queryMutedConversationsFromSessionList({items:n.getCacheManager()?.loadSessionList()??[],pageSize:t.pageSize,cursor:t.cursor});return Promise.resolve(s)})}async runOperation(e){try{return await e()}catch(t){throw this.normalizeSdkError(t)}}normalizeSdkError(t){return t instanceof e.SDKError?t:t instanceof Error?new e.SDKError(`PushManager operation failed: ${t.message}`,e.ERROR_CODES.UNKNOWN):new e.SDKError("PushManager operation failed",e.ERROR_CODES.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(t){return this.restClient&&this.restBaseUrl===t.restBaseUrl&&this.restToken===t.token||(this.restClient=new e.RestClient(t.restBaseUrl,{errorMap:u,requestAdapter:this.getClientOrThrow().getRequestAdapter?.(),includeRequestId:!0}),this.restClient.setAuthToken(t.token),this.restBaseUrl=t.restBaseUrl,this.restToken=t.token),this.restClient}getClientOrThrow(){if(!this.client)throw new e.SDKError("PushManager is not bound to client",e.ERROR_CODES.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||!d.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,i)=>{this.validateConversationId(e.conversationId,`${t}[${i}].conversationId`),this.validateConversationType(e.conversationType,`${t}[${i}].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(!g(e))throw this.buildValidationError(`${t} must be an object`,[{path:t,message:`${t} must be an object`,rule:"invalid_format"}]);switch(e.mode){case"REMIND_TYPE":if(!c.includes(e.remindType))throw this.buildValidationError("rule.remindType is invalid",[{path:`${t}.remindType`,message:"remindType must be one of ALL/AT/NONE",rule:"invalid_format"}]);this.ensureNoConflictFields(e,t,["mode","remindType"]);break;case"DURATION":if(!Number.isInteger(e.duration)||e.duration<=0)throw this.buildValidationError("rule.duration must be a positive integer",[{path:`${t}.duration`,message:"duration must be a positive integer",rule:"range"}]);this.ensureNoConflictFields(e,t,["mode","duration"]);break;case"INTERVAL":this.validateTimePoint(e.startTime,`${t}.startTime`),this.validateTimePoint(e.endTime,`${t}.endTime`),this.ensureNoConflictFields(e,t,["mode","startTime","endTime"]);break;default:throw this.buildValidationError("rule.mode is invalid",[{path:`${t}.mode`,message:"mode must be one of REMIND_TYPE/DURATION/INTERVAL",rule:"invalid_format"}])}}ensureNoConflictFields(e,t,i){const n=Object.keys(e).find(e=>!i.includes(e));if(n)throw this.buildValidationError("Silent mode rule contains conflicting fields",[{path:`${t}.${n}`,message:`${n} is not allowed when mode is ${e.mode}`,rule:"conflict"}])}validateTimePoint(e,t){if(!g(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 i=this.parseRuleView(e);return i?t?{...this.toRuleViewFromFallback(t),...i}:i:t?this.toRuleViewFromFallback(t):{}}parseRuleView(e){if(!g(e))return null;const t={},i=this.normalizeRemindType(e.type);null!==i&&(t.remindType=i);const n=e.ignoreDuration;"number"==typeof n&&Number.isInteger(n)&&n>0&&(t.expireTimestamp=n);const s=e.ignoreInterval;if("string"==typeof s){const e=this.parseInterval(s);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 i=Number(t[1]),n=Number(t[2]),s=Number(t[3]),r=Number(t[4]);return Number.isInteger(i)&&Number.isInteger(n)&&Number.isInteger(s)&&Number.isInteger(r)?i<0||i>23||s<0||s>23||n<0||n>59||r<0||r>59?null:{startTime:{hours:i,minutes:n},endTime:{hours:s,minutes:r}}: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(g(e.data)){const i=e.data[t];if(g(i))return i}const i=e[t];return g(i)?i:{}}resolveSilentModeRuleSource(e){if(!g(e))return e;if(null!==this.parseRuleView(e))return e;const t=e.data;return g(t)&&null!==this.parseRuleView(t)?t:e}normalizeRemindType(e){return"string"!=typeof e?null:"MENTION_ONLY"===e?"AT":h.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(g(e.data)){const t=e.data.translationLanguage;if("string"==typeof t&&t.length>0)return t;const i=e.data.language;if("string"==typeof i&&i.length>0)return i}return t}mapConversationTypeToPath(e){return"singleChat"===e?"user":"chatgroup"}buildValidationError(t,i){return new e.ValidationError(t,{code:e.ERROR_CODES.VALIDATION_INVALID_FORMAT,details:{fields:i}})}};m.key="pushManager";let p=m;exports.PushManager=p;
@@ -0,0 +1 @@
1
+ import{L as e}from"./index-CsqE2tfH.js";import{l as t}from"./light-DImBnNes.js";const r=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),n=e=>{class r extends t.Message{constructor(e){super(),((e,t)=>{if(t)for(const r of Object.keys(t)){const n=t[r];null!=n&&(e[r]=n)}})(this,e)}}const n=r;return n.$type=e,n.prototype.$type=e,n},o=t=>e.isLong(t),s=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&"number"==typeof e.byteLength,i=e=>Object.prototype.hasOwnProperty.call(t.types.packed,e),a=e=>{const r=e.resolve();return r.resolvedType instanceof t.Enum||i(r.type)},u=(e,t)=>t in e?e[t]:void 0,c=e=>{const r=e.resolve();return r.resolvedType instanceof t.Enum?0:(n=r.type,Object.prototype.hasOwnProperty.call(t.types.basic,n)?t.types.basic[r.type]:2);var n},f=(t,n)=>o(t)||"number"==typeof t||"string"==typeof t?t:r(t)&&"number"==typeof t.low&&"number"==typeof t.high?new e(t.low,t.high,n):n?e.UZERO:e.ZERO,p=(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(f(r,!1));case"uint64":return e.uint64(f(r,!0));case"sint64":return e.sint64(f(r,!1));case"fixed64":return e.fixed64(f(r,!0));case"sfixed64":return e.sfixed64(f(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:s(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}`)}},y=(e,t,r)=>{if(t<0||e.pos+t>r)throw RangeError(`index out of range: ${e.pos} + ${t} > ${r}`)},l=(e,t)=>{const r=e.uint32();return y(e,r,t),r},d=(e,t,r)=>{const n=e.len;e.len=r;try{switch(t){case 0:return void e.skip();case 1:return y(e,8,r),void e.skip(8);case 2:{const t=l(e,r);return void e.skip(t)}case 5:return y(e,4,r),void e.skip(4);default:throw new Error(`Unsupported protobuf wire type: ${String(t)}`)}}finally{e.len=n}},m=(e,n,o)=>{const s=n.resolve(),i=s.resolvedType;if(i instanceof t.Type){const t=e.fork();return g(i,r(o)?o:{},t),t.ldelim(),e}return i instanceof t.Enum?(e.int32("number"==typeof o?o:Number(o)),e):p(e,s.type,o)},b=(e,t,r)=>{if(0===r.length)return e;const n=t.resolve();if(i(n.type)&&t.packed){e.uint32(t.id<<3|2).fork();for(const n of r)m(e,t,n);return e.ldelim(),e}const o=c(t);for(const s of r)e.uint32(t.id<<3|o),m(e,t,s);return e},g=(e,r,n=t.Writer.create())=>{const o=e.fieldsArray.slice().sort(t.util.compareFieldsById);for(const t of o){const e=u(r,t.name);null!=e&&(t.repeated?b(n,t,Array.isArray(e)?e:[]):(n.uint32(t.id<<3|c(t)),m(n,t,e)))}return n},v=(e,r,n,o)=>{const s=r.resolve(),i=s.resolvedType;return i instanceof t.Type?2!==n?void d(e,n,o):T(i,e,l(e,o)):i instanceof t.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,s.type)},T=(e,r,n)=>{const o=r instanceof t.Reader?r:t.Reader.create(r),s=void 0===n?o.len:o.pos+n,i=(e=>{const t={};for(const r of e.fieldsArray)r.repeated&&(t[r.name]=[]);return t})(e),u=e.fieldsById;for(;o.pos<s;){const t=o.pos,r=o.uint32(),n=u[r>>>3],f=7&r;try{if(!n){d(o,f,s);continue}if(n.repeated){const e=Array.isArray(i[n.name])?i[n.name]:[];if(a(n)&&2===f){const t=l(o,s)+o.pos;for(;o.pos<t;)e.push(v(o,n,0,t))}else{const t=v(o,n,f,s);void 0!==t&&e.push(t)}i[n.name]=e;continue}const e=v(o,n,f,s);void 0!==e&&(i[n.name]=e)}catch(c){if(c instanceof RangeError){const i=n?`${n.name}#${n.id}`:`unknown#${r>>>3}`;throw new RangeError(`${c.message}; protobufType=${e.fullName}; field=${i}; tag=${r}; wireType=${f}; tagPosition=${t}; readerPosition=${o.pos}; messageEnd=${s}`)}throw c}}return i},h=(e,t)=>t?.longs===String?e.toString():t?.longs===Number?e.toNumber():e,w=(e,r)=>{const n=e.resolve();if(n.resolvedType instanceof t.Type)return null;if(n.resolvedType instanceof t.Enum){if(r?.enums===String){return n.resolvedType.valuesById[n.typeDefault]??n.typeDefault}return n.typeDefault}return"bytes"===n.type?r?.bytes===String?"":r?.bytes===Array?[]:new Uint8Array:n.long&&o(n.typeDefault)?h(n.typeDefault,r):n.typeDefault},A=(e,n,i)=>{const a=e.resolve();if(void 0!==n)return a.resolvedType instanceof t.Type?r(n)?x(a.resolvedType,n,i):n:a.resolvedType instanceof t.Enum?i?.enums===String&&"number"==typeof n?a.resolvedType.valuesById[n]??n:n:a.long&&o(n)?h(n,i):"bytes"===a.type&&s(n)?((e,r)=>r?.bytes===String?t.util.base64.encode(e,0,e.length):r?.bytes===Array?Array.prototype.slice.call(e):e)(n,i):n},x=(e,r,n)=>{const o={};for(const s of e.fieldsArray.slice().sort(t.util.compareFieldsById)){const e=u(r,s.name);s.repeated?Array.isArray(e)?o[s.name]=e.map(e=>A(s,e,n)):(n?.arrays||n?.defaults)&&(o[s.name]=[]):null==e?n?.defaults&&(o[s.name]=w(s,n)):o[s.name]=A(s,e,n)}return o},$=e=>{const t=e;t.__reflectionCodecInstalled||(t.__reflectionCodecInstalled=!0,e.encode=(t,n)=>g(e,r(t)?t:{},n),e.decode=(t,r)=>T(e,t,r),e.fromObject=e=>r(e)?e:{},e.toObject=(t,n)=>x(e,r(t)?t:{},n),e.create=e=>e?{...e}:{},e.verify=()=>null)},E=e=>{$(e);for(const r of e.nestedArray)if(r instanceof t.Type)E(r);else if(r instanceof t.Namespace)for(const e of r.nestedArray)e instanceof t.Type&&E(e)},N=e=>{for(const r of e.nestedArray)r instanceof t.Type?E(r):r instanceof t.Namespace&&N(r)},O=()=>{const e=t.Type;e.__reflectionRuntimeInstalled||(e.generateConstructor=e=>()=>n(e),t.Type.prototype.setup=function(){return $(this),this},t.Type.prototype.create=function(e){return e?{...e}:{}},t.Type.prototype.encode=function(e,t){return g(this,r(e)?e:{},t)},t.Type.prototype.decode=function(e,t){return T(this,e,t)},t.Type.prototype.fromObject=function(e){return r(e)?e:{}},t.Type.prototype.toObject=function(e,t){return x(this,r(e)?e:{},t)},t.Type.prototype.verify=function(){return null},e.__reflectionRuntimeInstalled=!0)};export{O as a,N as b,g as e,E as i};
@@ -0,0 +1 @@
1
+ "use strict";const e=require("./index-P1vnLSK2.cjs"),t=require("./light-BcQg8h2W.cjs"),r=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),n=e=>{class r extends t.lightExports.Message{constructor(e){super(),((e,t)=>{if(t)for(const r of Object.keys(t)){const n=t[r];null!=n&&(e[r]=n)}})(this,e)}}const n=r;return n.$type=e,n.prototype.$type=e,n},o=t=>e.Long.isLong(t),s=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&"number"==typeof e.byteLength,i=e=>Object.prototype.hasOwnProperty.call(t.lightExports.types.packed,e),a=e=>{const r=e.resolve();return r.resolvedType instanceof t.lightExports.Enum||i(r.type)},p=(e,t)=>t in e?e[t]:void 0,l=e=>{const r=e.resolve();return r.resolvedType instanceof t.lightExports.Enum?0:(n=r.type,Object.prototype.hasOwnProperty.call(t.lightExports.types.basic,n)?t.lightExports.types.basic[r.type]:2);var n},u=(t,n)=>o(t)||"number"==typeof t||"string"==typeof t?t:r(t)&&"number"==typeof t.low&&"number"==typeof t.high?new e.Long(t.low,t.high,n):n?e.Long.UZERO:e.Long.ZERO,c=(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(u(r,!1));case"uint64":return e.uint64(u(r,!0));case"sint64":return e.sint64(u(r,!1));case"fixed64":return e.fixed64(u(r,!0));case"sfixed64":return e.sfixed64(u(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:s(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}`)}},f=(e,t,r)=>{if(t<0||e.pos+t>r)throw RangeError(`index out of range: ${e.pos} + ${t} > ${r}`)},y=(e,t)=>{const r=e.uint32();return f(e,r,t),r},d=(e,t,r)=>{const n=e.len;e.len=r;try{switch(t){case 0:return void e.skip();case 1:return f(e,8,r),void e.skip(8);case 2:{const t=y(e,r);return void e.skip(t)}case 5:return f(e,4,r),void e.skip(4);default:throw new Error(`Unsupported protobuf wire type: ${String(t)}`)}}finally{e.len=n}},g=(e,n,o)=>{const s=n.resolve(),i=s.resolvedType;if(i instanceof t.lightExports.Type){const t=e.fork();return x(i,r(o)?o:{},t),t.ldelim(),e}return i instanceof t.lightExports.Enum?(e.int32("number"==typeof o?o:Number(o)),e):c(e,s.type,o)},h=(e,t,r)=>{if(0===r.length)return e;const n=t.resolve();if(i(n.type)&&t.packed){e.uint32(t.id<<3|2).fork();for(const n of r)g(e,t,n);return e.ldelim(),e}const o=l(t);for(const s of r)e.uint32(t.id<<3|o),g(e,t,s);return e},x=(e,r,n=t.lightExports.Writer.create())=>{const o=e.fieldsArray.slice().sort(t.lightExports.util.compareFieldsById);for(const t of o){const e=p(r,t.name);null!=e&&(t.repeated?h(n,t,Array.isArray(e)?e:[]):(n.uint32(t.id<<3|l(t)),g(n,t,e)))}return n},b=(e,r,n,o)=>{const s=r.resolve(),i=s.resolvedType;return i instanceof t.lightExports.Type?2!==n?void d(e,n,o):m(i,e,y(e,o)):i instanceof t.lightExports.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,s.type)},m=(e,r,n)=>{const o=r instanceof t.lightExports.Reader?r:t.lightExports.Reader.create(r),s=void 0===n?o.len:o.pos+n,i=(e=>{const t={};for(const r of e.fieldsArray)r.repeated&&(t[r.name]=[]);return t})(e),p=e.fieldsById;for(;o.pos<s;){const t=o.pos,r=o.uint32(),n=p[r>>>3],u=7&r;try{if(!n){d(o,u,s);continue}if(n.repeated){const e=Array.isArray(i[n.name])?i[n.name]:[];if(a(n)&&2===u){const t=y(o,s)+o.pos;for(;o.pos<t;)e.push(b(o,n,0,t))}else{const t=b(o,n,u,s);void 0!==t&&e.push(t)}i[n.name]=e;continue}const e=b(o,n,u,s);void 0!==e&&(i[n.name]=e)}catch(l){if(l instanceof RangeError){const i=n?`${n.name}#${n.id}`:`unknown#${r>>>3}`;throw new RangeError(`${l.message}; protobufType=${e.fullName}; field=${i}; tag=${r}; wireType=${u}; tagPosition=${t}; readerPosition=${o.pos}; messageEnd=${s}`)}throw l}}return i},E=(e,t)=>t?.longs===String?e.toString():t?.longs===Number?e.toNumber():e,v=(e,r)=>{const n=e.resolve();if(n.resolvedType instanceof t.lightExports.Type)return null;if(n.resolvedType instanceof t.lightExports.Enum){if(r?.enums===String){return n.resolvedType.valuesById[n.typeDefault]??n.typeDefault}return n.typeDefault}return"bytes"===n.type?r?.bytes===String?"":r?.bytes===Array?[]:new Uint8Array:n.long&&o(n.typeDefault)?E(n.typeDefault,r):n.typeDefault},T=(e,n,i)=>{const a=e.resolve();if(void 0!==n)return a.resolvedType instanceof t.lightExports.Type?r(n)?w(a.resolvedType,n,i):n:a.resolvedType instanceof t.lightExports.Enum?i?.enums===String&&"number"==typeof n?a.resolvedType.valuesById[n]??n:n:a.long&&o(n)?E(n,i):"bytes"===a.type&&s(n)?((e,r)=>r?.bytes===String?t.lightExports.util.base64.encode(e,0,e.length):r?.bytes===Array?Array.prototype.slice.call(e):e)(n,i):n},w=(e,r,n)=>{const o={};for(const s of e.fieldsArray.slice().sort(t.lightExports.util.compareFieldsById)){const e=p(r,s.name);s.repeated?Array.isArray(e)?o[s.name]=e.map(e=>T(s,e,n)):(n?.arrays||n?.defaults)&&(o[s.name]=[]):null==e?n?.defaults&&(o[s.name]=v(s,n)):o[s.name]=T(s,e,n)}return o},A=e=>{const t=e;t.__reflectionCodecInstalled||(t.__reflectionCodecInstalled=!0,e.encode=(t,n)=>x(e,r(t)?t:{},n),e.decode=(t,r)=>m(e,t,r),e.fromObject=e=>r(e)?e:{},e.toObject=(t,n)=>w(e,r(t)?t:{},n),e.create=e=>e?{...e}:{},e.verify=()=>null)},$=e=>{A(e);for(const r of e.nestedArray)if(r instanceof t.lightExports.Type)$(r);else if(r instanceof t.lightExports.Namespace)for(const e of r.nestedArray)e instanceof t.lightExports.Type&&$(e)},R=e=>{for(const r of e.nestedArray)r instanceof t.lightExports.Type?$(r):r instanceof t.lightExports.Namespace&&R(r)};exports.encodeWithReflection=x,exports.installReflectionCodecInNamespace=R,exports.installReflectionCodecRecursive=$,exports.installReflectionRuntime=()=>{const e=t.lightExports.Type;e.__reflectionRuntimeInstalled||(e.generateConstructor=e=>()=>n(e),t.lightExports.Type.prototype.setup=function(){return A(this),this},t.lightExports.Type.prototype.create=function(e){return e?{...e}:{}},t.lightExports.Type.prototype.encode=function(e,t){return x(this,r(e)?e:{},t)},t.lightExports.Type.prototype.decode=function(e,t){return m(this,e,t)},t.lightExports.Type.prototype.fromObject=function(e){return r(e)?e:{}},t.lightExports.Type.prototype.toObject=function(e,t){return w(this,r(e)?e:{},t)},t.lightExports.Type.prototype.verify=function(){return null},e.__reflectionRuntimeInstalled=!0)};
@@ -0,0 +1 @@
1
+ "use strict";const e=require("zod"),t=require("./common-Cg-lTASK.cjs"),o=e.z.record(e.z.unknown()),n={text:e.z.object({content:e.z.string()}),image:e.z.object({isGif:e.z.boolean(),isOriginalImage:e.z.boolean()}),video:e.z.object({duration:e.z.number()}),voice:e.z.object({duration:e.z.number()}),file:o,location:e.z.object({latitude:e.z.number(),longitude:e.z.number()}),cmd:e.z.object({action:e.z.string()}),custom:e.z.object({event:e.z.string()}),combine:e.z.object({title:e.z.string(),summary:e.z.string(),filename:e.z.string(),filetype:e.z.string(),combineLevel:e.z.number()}),multi_body:e.z.array(e.z.object({type:e.z.string()}).passthrough()).min(2)},r=e.z.object({msgServerId:e.z.string(),msgLocalId:e.z.string(),from:e.z.string(),to:e.z.string(),sender:e.z.object({userId:e.z.string(),nickname:e.z.string().optional(),avatarUrl:e.z.string().optional()}),conversationId:e.z.string(),conversationType:e.z.enum(["singleChat","groupChat","chatRoom"]),type:e.z.enum(["text","image","video","voice","file","location","cmd","custom","combine","multi_body"]),sendStatus:e.z.enum(["sending","sent","failed"]),timestamp:e.z.number(),ext:o,body:e.z.union([o,e.z.array(e.z.object({type:e.z.string()}).passthrough()).min(2)])});const a=e.z.boolean().optional().catch(void 0),i=e.z.number().finite().optional().catch(void 0),s=e.z.string().optional().catch(void 0),c=e.z.object({msgLocalId:s,sendStatus:e.z.enum(["sending","sent","failed"]).optional().catch(void 0),direct:e.z.enum(["SEND","RECEIVE"]).optional().catch(void 0),isOnline:a,receiverList:e.z.array(e.z.string()).optional().catch(void 0),deliverOnlineOnly:a,webhookEnv:s,priority:e.z.enum(["high","normal","low"]).optional().catch(void 0),isBroadcast:a,isContentReplaced:a,combineLevel:i,modifiedInfo:e.z.object({operatorId:e.z.string(),operationCount:e.z.number().finite(),operationTime:e.z.number().finite()}).optional().catch(void 0),reactions:e.z.array(e.z.object({reaction:e.z.string(),count:e.z.number(),userList:e.z.array(e.z.string()),isAddedBySelf:e.z.boolean().optional(),op:e.z.array(e.z.object({operator:e.z.string(),reactionType:e.z.enum(["create","delete"])})).optional()})).optional().catch(void 0),groupReadCount:e.z.number().int().nonnegative().optional().catch(void 0),isPeerRead:a,needReadReceipt:a,isChatThread:a,chatThread:e.z.object({messageId:e.z.string(),parentId:e.z.string(),chatThreadName:e.z.string().optional()}).optional().catch(void 0),chatThreadOverview:e.z.object({chatThreadId:e.z.string(),parentId:e.z.string(),name:e.z.string().optional(),lastMessage:e.z.custom(e=>{const t=r.safeParse(e);return!!t.success&&("multi_body"===t.data.type?n.multi_body.safeParse(t.data.body).success:n[t.data.type].safeParse(t.data.body).success)}).transform(function(e){return{...r.parse(e),body:e.body,...d(e)}}).nullable().optional().catch(null),createdAt:e.z.number().optional(),updatedAt:e.z.number().optional(),messageCount:e.z.number().optional()}).optional().catch(void 0),stream:e.z.object({customType:e.z.string().optional(),seq:e.z.number(),status:e.z.enum(["STREAM_START","STREAM_START_COMPLETED","STREAM_IN_PROGRESS","STREAM_COMPLETED","STREAM_FULL","STREAM_ERROR"]),errorType:e.z.number(),finishReason:e.z.number().optional(),deltaText:e.z.string(),fullText:e.z.string()}).optional().catch(void 0),userInfoUpdateTime:i,namecardUpdateTime:i}),d=e=>{const t=c.safeParse(e);if(!t.success)return{};for(const[o,n]of Object.entries(t.data))void 0===n&&Reflect.deleteProperty(t.data,o);return t.data},l=e=>e.map(e=>{const t={...e};return"string"==typeof t.localUrl&&t.localUrl.startsWith("blob:")&&(t.localUrl=""),delete t.data,t}),m=e=>{if(Array.isArray(e))return l(e);const t={...e};return delete t.type,delete t.messageList,t},u=e=>new t.ValidationError(`${e} must be a local paging cursor returned by SDK`,{code:t.ERROR_CODES.VALIDATION_INVALID_FORMAT,details:{fields:[{path:e,message:`${e} must be a local paging cursor returned by SDK`,rule:"invalid_format"}]}}),p=(e,t,o)=>{const n=e+t;return n<o?String(n):""},z=e=>"AT"===e||"NONE"===e||"ALL"===e?e:null;exports.hasSessionMark=(e,t)=>e.marks.includes(t),exports.messageSnapshotSignature=e=>JSON.stringify(e,(e,t)=>t&&"object"==typeof t&&!Array.isArray(t)?Object.fromEntries(Object.entries(t).filter(([,e])=>void 0!==e).sort(([e],[t])=>e.localeCompare(t))):t),exports.projectMessageBody=m,exports.projectMessageMetadata=d,exports.projectMessageSegments=l,exports.queryMutedConversationsFromSessionList=e=>{if(!Number.isInteger(e.pageSize)||e.pageSize<=0)throw new t.ValidationError("pageSize must be a positive integer",{code:t.ERROR_CODES.VALIDATION_INVALID_FORMAT,details:{fields:[{path:"pageSize",message:"pageSize must be a positive integer",rule:"range"}]}});const o=((e,t)=>{if(void 0===e||""===e)return 0;if(!/^\d+$/.test(e))throw u(t);const o=Number.parseInt(e,10);if(!Number.isSafeInteger(o)||o<0)throw u(t);return o})(e.cursor,"cursor"),n=[];for(const t of e.items){if("chatRoom"===t.conversationType)continue;const e=z(t.remindType);e&&n.push({conversationId:t.conversationId,conversationType:t.conversationType,remindType:e})}return{conversations:n.slice(o,o+e.pageSize),cursor:p(o,e.pageSize,n.length)}},exports.toConversationItem=e=>({...e}),exports.toConversationSummary=e=>{const t=(e=>e?{...d(e),msgId:e.msgServerId,from:e.from,to:e.to,sender:{...e.sender},type:e.type??"unknown",body:m(e.body),ext:e.ext,timestamp:e.timestamp}:null)(e.lastMessage),o=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:o,lastUpdate:o}};
@@ -0,0 +1 @@
1
+ import{z as e}from"zod";import{V as t,E as o}from"./common-gbNWJrBc.js";const n=e.record(e.unknown()),a={text:e.object({content:e.string()}),image:e.object({isGif:e.boolean(),isOriginalImage:e.boolean()}),video:e.object({duration:e.number()}),voice:e.object({duration:e.number()}),file:n,location:e.object({latitude:e.number(),longitude:e.number()}),cmd:e.object({action:e.string()}),custom:e.object({event:e.string()}),combine:e.object({title:e.string(),summary:e.string(),filename:e.string(),filetype:e.string(),combineLevel:e.number()}),multi_body:e.array(e.object({type:e.string()}).passthrough()).min(2)},r=e.object({msgServerId:e.string(),msgLocalId:e.string(),from:e.string(),to:e.string(),sender:e.object({userId:e.string(),nickname:e.string().optional(),avatarUrl:e.string().optional()}),conversationId:e.string(),conversationType:e.enum(["singleChat","groupChat","chatRoom"]),type:e.enum(["text","image","video","voice","file","location","cmd","custom","combine","multi_body"]),sendStatus:e.enum(["sending","sent","failed"]),timestamp:e.number(),ext:n,body:e.union([n,e.array(e.object({type:e.string()}).passthrough()).min(2)])});const i=e.boolean().optional().catch(void 0),s=e.number().finite().optional().catch(void 0),c=e.string().optional().catch(void 0),d=e.object({msgLocalId:c,sendStatus:e.enum(["sending","sent","failed"]).optional().catch(void 0),direct:e.enum(["SEND","RECEIVE"]).optional().catch(void 0),isOnline:i,receiverList:e.array(e.string()).optional().catch(void 0),deliverOnlineOnly:i,webhookEnv:c,priority:e.enum(["high","normal","low"]).optional().catch(void 0),isBroadcast:i,isContentReplaced:i,combineLevel:s,modifiedInfo:e.object({operatorId:e.string(),operationCount:e.number().finite(),operationTime:e.number().finite()}).optional().catch(void 0),reactions:e.array(e.object({reaction:e.string(),count:e.number(),userList:e.array(e.string()),isAddedBySelf:e.boolean().optional(),op:e.array(e.object({operator:e.string(),reactionType:e.enum(["create","delete"])})).optional()})).optional().catch(void 0),groupReadCount:e.number().int().nonnegative().optional().catch(void 0),isPeerRead:i,needReadReceipt:i,isChatThread:i,chatThread:e.object({messageId:e.string(),parentId:e.string(),chatThreadName:e.string().optional()}).optional().catch(void 0),chatThreadOverview:e.object({chatThreadId:e.string(),parentId:e.string(),name:e.string().optional(),lastMessage:e.custom(e=>{const t=r.safeParse(e);return!!t.success&&("multi_body"===t.data.type?a.multi_body.safeParse(t.data.body).success:a[t.data.type].safeParse(t.data.body).success)}).transform(function(e){return{...r.parse(e),body:e.body,...l(e)}}).nullable().optional().catch(null),createdAt:e.number().optional(),updatedAt:e.number().optional(),messageCount:e.number().optional()}).optional().catch(void 0),stream:e.object({customType:e.string().optional(),seq:e.number(),status:e.enum(["STREAM_START","STREAM_START_COMPLETED","STREAM_IN_PROGRESS","STREAM_COMPLETED","STREAM_FULL","STREAM_ERROR"]),errorType:e.number(),finishReason:e.number().optional(),deltaText:e.string(),fullText:e.string()}).optional().catch(void 0),userInfoUpdateTime:s,namecardUpdateTime:s}),l=e=>{const t=d.safeParse(e);if(!t.success)return{};for(const[o,n]of Object.entries(t.data))void 0===n&&Reflect.deleteProperty(t.data,o);return t.data},m=e=>JSON.stringify(e,(e,t)=>t&&"object"==typeof t&&!Array.isArray(t)?Object.fromEntries(Object.entries(t).filter(([,e])=>void 0!==e).sort(([e],[t])=>e.localeCompare(t))):t),u=e=>e.map(e=>{const t={...e};return"string"==typeof t.localUrl&&t.localUrl.startsWith("blob:")&&(t.localUrl=""),delete t.data,t}),p=e=>{if(Array.isArray(e))return u(e);const t={...e};return delete t.type,delete t.messageList,t},g=e=>new t(`${e} must be a local paging cursor returned by SDK`,{code:o.VALIDATION_INVALID_FORMAT,details:{fields:[{path:e,message:`${e} must be a local paging cursor returned by SDK`,rule:"invalid_format"}]}}),b=(e,t,o)=>{const n=e+t;return n<o?String(n):""},y=e=>({...e}),f=e=>{const t=(e=>e?{...l(e),msgId:e.msgServerId,from:e.from,to:e.to,sender:{...e.sender},type:e.type??"unknown",body:p(e.body),ext:e.ext,timestamp:e.timestamp}:null)(e.lastMessage),o=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:o,lastUpdate:o}},v=e=>"AT"===e||"NONE"===e||"ALL"===e?e:null,h=e=>{if(!Number.isInteger(e.pageSize)||e.pageSize<=0)throw new t("pageSize must be a positive integer",{code:o.VALIDATION_INVALID_FORMAT,details:{fields:[{path:"pageSize",message:"pageSize must be a positive integer",rule:"range"}]}});const n=((e,t)=>{if(void 0===e||""===e)return 0;if(!/^\d+$/.test(e))throw g(t);const o=Number.parseInt(e,10);if(!Number.isSafeInteger(o)||o<0)throw g(t);return o})(e.cursor,"cursor"),a=[];for(const t of e.items){if("chatRoom"===t.conversationType)continue;const e=v(t.remindType);e&&a.push({conversationId:t.conversationId,conversationType:t.conversationType,remindType:e})}return{conversations:a.slice(n,n+e.pageSize),cursor:b(n,e.pageSize,a.length)}},T=(e,t)=>e.marks.includes(t);export{l as a,u as b,f as c,T as h,m,p,h as q,y as t};
@@ -1 +1 @@
1
- "use strict";const e=require("./cache-utils-gowrxNr8.cjs"),r=require("./common-tHGz9VBk.cjs"),t={nickname:"nickname",avatarUrl:"avatarurl",mail:"mail",phone:"phone",gender:"gender",sign:"sign",birth:"birth",ext:"ext"},n=(e,t,n)=>new r.ValidationError(e,{code:"required"===n?r.ERROR_CODES.VALIDATION_REQUIRED:r.ERROR_CODES.VALIDATION_INVALID_FORMAT,details:{fields:[{path:t,message:e,rule:n}]}}),a=(e,r)=>{if("string"!=typeof e)throw n(`${r} must be a string`,r,"invalid_format");return e},i=(e,r)=>{if("string"==typeof e||"number"==typeof e||"boolean"==typeof e)return e;throw n(`${r} must be a string, number, or boolean`,r,"invalid_format")},s=(e,r="attribute")=>{const a=t[e];if(!a)throw n(`${r} is invalid`,r,"invalid_format");return a},o=(e,r="params.userIds")=>{if(!Array.isArray(e)||0===e.length)throw n(`${r} is required`,r,"required");const t=[],i=new Set;for(const[n,s]of e.entries()){const e=a(s,`${r}[${n}]`).trim();e&&(i.has(e)||(i.add(e),t.push(e)))}if(0===t.length)throw n(`${r} is required`,r,"required");return t},d=(e,r="params.attributes")=>{if(!Array.isArray(e)||0===e.length)throw n(`${r} is required`,r,"required");const i=[],s=new Set;for(const[o,d]of e.entries()){const e=a(d,`${r}[${o}]`);if(!(e in t))throw n(`${r}[${o}] is invalid`,`${r}[${o}]`,"invalid_format");s.has(e)||(s.add(e),i.push(e))}if(0===i.length)throw n(`${r} is required`,r,"required");return i},p=r=>!!e.isRecord(r)&&("nickname"in r||"avatarurl"in r||"avatarUrl"in r||"mail"in r||"phone"in r||"gender"in r||"sign"in r||"birth"in r||"ext"in r),u=(r,t)=>{if(Array.isArray(r))for(const n of r){if(!e.isRecord(n))continue;const r="string"==typeof n.username?n.username:"";r&&t.set(r,n)}},l=(e,r)=>{const t={userId:e};return"string"==typeof r.nickname&&(t.nickname=r.nickname),"string"==typeof r.avatarurl?t.avatarUrl=r.avatarurl:"string"==typeof r.avatarUrl&&(t.avatarUrl=r.avatarUrl),"string"==typeof r.mail&&(t.mail=r.mail),"string"==typeof r.phone&&(t.phone=r.phone),"string"!=typeof r.gender&&"number"!=typeof r.gender&&"boolean"!=typeof r.gender||(t.gender=r.gender),"string"==typeof r.sign&&(t.sign=r.sign),"string"==typeof r.birth&&(t.birth=r.birth),"string"==typeof r.ext&&(t.ext=r.ext),t},m=(r,t)=>{const n=(r=>{const t=new Map,n=e.isRecord(r)?r:null;if(n?.data&&e.isRecord(n.data))for(const[e,a]of Object.entries(n.data))p(a)&&t.set(e,a);return u(n?.entities,t),u(n?.data&&e.isRecord(n.data)?n.data.entities:void 0,t),t})(r),a=(r=>{const t=new Map,n=e.isRecord(r)?r:null;if(!n?.lastModified||!e.isRecord(n.lastModified))return t;for(const[e,a]of Object.entries(n.lastModified))"number"==typeof a&&t.set(e,a);return t})(r),i=[];for(const e of t){const r=n.get(e);r&&i.push({profile:l(e,r),lastModified:a.get(e)})}return i},f=(e,r,t,n)=>{void 0!==t&&("gender"!==r?e.push([r,a(t,n)]):e.push([r,String(i(t,n))]))},c=e=>e.map(([e,r])=>`${encodeURIComponent(e)}=${encodeURIComponent(r)}`).join("&");exports.buildFetchUserInfoByAttributeRequest=(e,r)=>({targets:o(e),properties:d(r).map(e=>s(e,"params.attributes"))}),exports.buildFetchUserInfoByUserIdRequest=e=>({targets:o(e)}),exports.buildUpdateOwnInfoByAttributeFormBody=(e,r)=>{const t=s(e,"attribute"),a=i(r,"value");if("gender"!==t&&"string"!=typeof a)throw n("value must be a string","value","invalid_format");return c([[t,String(a)]])},exports.buildUpdateOwnInfoFormBody=e=>{const r=[];if(f(r,"nickname",e.nickname,"params.nickname"),f(r,"avatarurl",e.avatarUrl,"params.avatarUrl"),f(r,"mail",e.mail,"params.mail"),f(r,"phone",e.phone,"params.phone"),f(r,"gender",e.gender,"params.gender"),f(r,"sign",e.sign,"params.sign"),f(r,"birth",e.birth,"params.birth"),f(r,"ext",e.ext,"params.ext"),0===r.length)throw n("params must include at least one updatable field","params","required");return c(r)},exports.buildUserInfoFetchEndpoint=e=>{const{orgName:t,appName:n}=r.parseAppKey(e.appKey);return`/${t}/${n}/metadata/user/get`},exports.buildUserInfoUpdateEndpoint=e=>{const{orgName:t,appName:n}=r.parseAppKey(e.appKey);return`/${t}/${n}/metadata/user/${encodeURIComponent(e.userId)}`},exports.normalizeFetchedUserInfos=(e,r)=>m(e,r).map(e=>e.profile),exports.normalizeUserInfoAttributes=d,exports.normalizeUserInfoFetchRecords=m,exports.normalizeUserInfoTargetIds=o;
1
+ "use strict";const e=require("./cache-utils-gowrxNr8.cjs"),r=require("./common-Cg-lTASK.cjs"),t={nickname:"nickname",avatarUrl:"avatarurl",mail:"mail",phone:"phone",gender:"gender",sign:"sign",birth:"birth",ext:"ext"},n=(e,t,n)=>new r.ValidationError(e,{code:"required"===n?r.ERROR_CODES.VALIDATION_REQUIRED:r.ERROR_CODES.VALIDATION_INVALID_FORMAT,details:{fields:[{path:t,message:e,rule:n}]}}),a=(e,r)=>{if("string"!=typeof e)throw n(`${r} must be a string`,r,"invalid_format");return e},i=(e,r)=>{if("string"==typeof e||"number"==typeof e||"boolean"==typeof e)return e;throw n(`${r} must be a string, number, or boolean`,r,"invalid_format")},s=(e,r="attribute")=>{const a=t[e];if(!a)throw n(`${r} is invalid`,r,"invalid_format");return a},o=(e,r="params.userIds")=>{if(!Array.isArray(e)||0===e.length)throw n(`${r} is required`,r,"required");const t=[],i=new Set;for(const[n,s]of e.entries()){const e=a(s,`${r}[${n}]`).trim();e&&(i.has(e)||(i.add(e),t.push(e)))}if(0===t.length)throw n(`${r} is required`,r,"required");return t},d=(e,r="params.attributes")=>{if(!Array.isArray(e)||0===e.length)throw n(`${r} is required`,r,"required");const i=[],s=new Set;for(const[o,d]of e.entries()){const e=a(d,`${r}[${o}]`);if(!(e in t))throw n(`${r}[${o}] is invalid`,`${r}[${o}]`,"invalid_format");s.has(e)||(s.add(e),i.push(e))}if(0===i.length)throw n(`${r} is required`,r,"required");return i},p=r=>!!e.isRecord(r)&&("nickname"in r||"avatarurl"in r||"avatarUrl"in r||"mail"in r||"phone"in r||"gender"in r||"sign"in r||"birth"in r||"ext"in r),u=(r,t)=>{if(Array.isArray(r))for(const n of r){if(!e.isRecord(n))continue;const r="string"==typeof n.username?n.username:"";r&&t.set(r,n)}},l=(e,r)=>{const t={userId:e};return"string"==typeof r.nickname&&(t.nickname=r.nickname),"string"==typeof r.avatarurl?t.avatarUrl=r.avatarurl:"string"==typeof r.avatarUrl&&(t.avatarUrl=r.avatarUrl),"string"==typeof r.mail&&(t.mail=r.mail),"string"==typeof r.phone&&(t.phone=r.phone),"string"!=typeof r.gender&&"number"!=typeof r.gender&&"boolean"!=typeof r.gender||(t.gender=r.gender),"string"==typeof r.sign&&(t.sign=r.sign),"string"==typeof r.birth&&(t.birth=r.birth),"string"==typeof r.ext&&(t.ext=r.ext),t},m=(r,t)=>{const n=(r=>{const t=new Map,n=e.isRecord(r)?r:null;if(n?.data&&e.isRecord(n.data))for(const[e,a]of Object.entries(n.data))p(a)&&t.set(e,a);return u(n?.entities,t),u(n?.data&&e.isRecord(n.data)?n.data.entities:void 0,t),t})(r),a=(r=>{const t=new Map,n=e.isRecord(r)?r:null;if(!n?.lastModified||!e.isRecord(n.lastModified))return t;for(const[e,a]of Object.entries(n.lastModified))"number"==typeof a&&t.set(e,a);return t})(r),i=[];for(const e of t){const r=n.get(e);r&&i.push({profile:l(e,r),lastModified:a.get(e)})}return i},f=(e,r,t,n)=>{void 0!==t&&("gender"!==r?e.push([r,a(t,n)]):e.push([r,String(i(t,n))]))},c=e=>e.map(([e,r])=>`${encodeURIComponent(e)}=${encodeURIComponent(r)}`).join("&");exports.buildFetchUserInfoByAttributeRequest=(e,r)=>({targets:o(e),properties:d(r).map(e=>s(e,"params.attributes"))}),exports.buildFetchUserInfoByUserIdRequest=e=>({targets:o(e)}),exports.buildUpdateOwnInfoByAttributeFormBody=(e,r)=>{const t=s(e,"attribute"),a=i(r,"value");if("gender"!==t&&"string"!=typeof a)throw n("value must be a string","value","invalid_format");return c([[t,String(a)]])},exports.buildUpdateOwnInfoFormBody=e=>{const r=[];if(f(r,"nickname",e.nickname,"params.nickname"),f(r,"avatarurl",e.avatarUrl,"params.avatarUrl"),f(r,"mail",e.mail,"params.mail"),f(r,"phone",e.phone,"params.phone"),f(r,"gender",e.gender,"params.gender"),f(r,"sign",e.sign,"params.sign"),f(r,"birth",e.birth,"params.birth"),f(r,"ext",e.ext,"params.ext"),0===r.length)throw n("params must include at least one updatable field","params","required");return c(r)},exports.buildUserInfoFetchEndpoint=e=>{const{orgName:t,appName:n}=r.parseAppKey(e.appKey);return`/${t}/${n}/metadata/user/get`},exports.buildUserInfoUpdateEndpoint=e=>{const{orgName:t,appName:n}=r.parseAppKey(e.appKey);return`/${t}/${n}/metadata/user/${encodeURIComponent(e.userId)}`},exports.normalizeFetchedUserInfos=(e,r)=>m(e,r).map(e=>e.profile),exports.normalizeUserInfoAttributes=d,exports.normalizeUserInfoFetchRecords=m,exports.normalizeUserInfoTargetIds=o;
@@ -1 +1 @@
1
- import{i as e}from"./cache-utils-B99glc0H.js";import{p as r,V as t,E as a}from"./common-BvlDAw4a.js";const n={nickname:"nickname",avatarUrl:"avatarurl",mail:"mail",phone:"phone",gender:"gender",sign:"sign",birth:"birth",ext:"ext"},i=(e,r,n)=>new t(e,{code:"required"===n?a.VALIDATION_REQUIRED:a.VALIDATION_INVALID_FORMAT,details:{fields:[{path:r,message:e,rule:n}]}}),s=(e,r)=>{if("string"!=typeof e)throw i(`${r} must be a string`,r,"invalid_format");return e},o=(e,r)=>{if("string"==typeof e||"number"==typeof e||"boolean"==typeof e)return e;throw i(`${r} must be a string, number, or boolean`,r,"invalid_format")},p=(e,r="attribute")=>{const t=n[e];if(!t)throw i(`${r} is invalid`,r,"invalid_format");return t},m=(e,r="params.userIds")=>{if(!Array.isArray(e)||0===e.length)throw i(`${r} is required`,r,"required");const t=[],a=/* @__PURE__ */new Set;for(const[n,i]of e.entries()){const e=s(i,`${r}[${n}]`).trim();e&&(a.has(e)||(a.add(e),t.push(e)))}if(0===t.length)throw i(`${r} is required`,r,"required");return t},d=(e,r="params.attributes")=>{if(!Array.isArray(e)||0===e.length)throw i(`${r} is required`,r,"required");const t=[],a=/* @__PURE__ */new Set;for(const[o,p]of e.entries()){const e=s(p,`${r}[${o}]`);if(!(e in n))throw i(`${r}[${o}] is invalid`,`${r}[${o}]`,"invalid_format");a.has(e)||(a.add(e),t.push(e))}if(0===t.length)throw i(`${r} is required`,r,"required");return t},u=e=>{const{orgName:t,appName:a}=r(e.appKey);return`/${t}/${a}/metadata/user/get`},f=e=>{const{orgName:t,appName:a}=r(e.appKey);return`/${t}/${a}/metadata/user/${encodeURIComponent(e.userId)}`},l=e=>({targets:m(e)}),g=(e,r)=>({targets:m(e),properties:d(r).map(e=>p(e,"params.attributes"))}),c=r=>!!e(r)&&("nickname"in r||"avatarurl"in r||"avatarUrl"in r||"mail"in r||"phone"in r||"gender"in r||"sign"in r||"birth"in r||"ext"in r),h=(r,t)=>{if(Array.isArray(r))for(const a of r){if(!e(a))continue;const r="string"==typeof a.username?a.username:"";r&&t.set(r,a)}},b=(e,r)=>{const t={userId:e};return"string"==typeof r.nickname&&(t.nickname=r.nickname),"string"==typeof r.avatarurl?t.avatarUrl=r.avatarurl:"string"==typeof r.avatarUrl&&(t.avatarUrl=r.avatarUrl),"string"==typeof r.mail&&(t.mail=r.mail),"string"==typeof r.phone&&(t.phone=r.phone),"string"!=typeof r.gender&&"number"!=typeof r.gender&&"boolean"!=typeof r.gender||(t.gender=r.gender),"string"==typeof r.sign&&(t.sign=r.sign),"string"==typeof r.birth&&(t.birth=r.birth),"string"==typeof r.ext&&(t.ext=r.ext),t},y=(r,t)=>{const a=(r=>{const t=/* @__PURE__ */new Map,a=e(r)?r:null;if(a?.data&&e(a.data))for(const[e,n]of Object.entries(a.data))c(n)&&t.set(e,n);return h(a?.entities,t),h(a?.data&&e(a.data)?a.data.entities:void 0,t),t})(r),n=(r=>{const t=/* @__PURE__ */new Map,a=e(r)?r:null;if(!a?.lastModified||!e(a.lastModified))return t;for(const[e,n]of Object.entries(a.lastModified))"number"==typeof n&&t.set(e,n);return t})(r),i=[];for(const e of t){const r=a.get(e);r&&i.push({profile:b(e,r),lastModified:n.get(e)})}return i},v=(e,r)=>y(e,r).map(e=>e.profile),$=(e,r,t,a)=>{void 0!==t&&("gender"!==r?e.push([r,s(t,a)]):e.push([r,String(o(t,a))]))},w=e=>e.map(([e,r])=>`${encodeURIComponent(e)}=${encodeURIComponent(r)}`).join("&"),I=e=>{const r=[];if($(r,"nickname",e.nickname,"params.nickname"),$(r,"avatarurl",e.avatarUrl,"params.avatarUrl"),$(r,"mail",e.mail,"params.mail"),$(r,"phone",e.phone,"params.phone"),$(r,"gender",e.gender,"params.gender"),$(r,"sign",e.sign,"params.sign"),$(r,"birth",e.birth,"params.birth"),$(r,"ext",e.ext,"params.ext"),0===r.length)throw i("params must include at least one updatable field","params","required");return w(r)},A=(e,r)=>{const t=p(e,"attribute"),a=o(r,"value");if("gender"!==t&&"string"!=typeof a)throw i("value must be a string","value","invalid_format");return w([[t,String(a)]])};export{u as a,l as b,m as c,g as d,d as e,I as f,f as g,A as h,y as i,v as n};
1
+ import{i as e}from"./cache-utils-B99glc0H.js";import{p as r,V as t,E as a}from"./common-gbNWJrBc.js";const n={nickname:"nickname",avatarUrl:"avatarurl",mail:"mail",phone:"phone",gender:"gender",sign:"sign",birth:"birth",ext:"ext"},i=(e,r,n)=>new t(e,{code:"required"===n?a.VALIDATION_REQUIRED:a.VALIDATION_INVALID_FORMAT,details:{fields:[{path:r,message:e,rule:n}]}}),s=(e,r)=>{if("string"!=typeof e)throw i(`${r} must be a string`,r,"invalid_format");return e},o=(e,r)=>{if("string"==typeof e||"number"==typeof e||"boolean"==typeof e)return e;throw i(`${r} must be a string, number, or boolean`,r,"invalid_format")},p=(e,r="attribute")=>{const t=n[e];if(!t)throw i(`${r} is invalid`,r,"invalid_format");return t},m=(e,r="params.userIds")=>{if(!Array.isArray(e)||0===e.length)throw i(`${r} is required`,r,"required");const t=[],a=/* @__PURE__ */new Set;for(const[n,i]of e.entries()){const e=s(i,`${r}[${n}]`).trim();e&&(a.has(e)||(a.add(e),t.push(e)))}if(0===t.length)throw i(`${r} is required`,r,"required");return t},d=(e,r="params.attributes")=>{if(!Array.isArray(e)||0===e.length)throw i(`${r} is required`,r,"required");const t=[],a=/* @__PURE__ */new Set;for(const[o,p]of e.entries()){const e=s(p,`${r}[${o}]`);if(!(e in n))throw i(`${r}[${o}] is invalid`,`${r}[${o}]`,"invalid_format");a.has(e)||(a.add(e),t.push(e))}if(0===t.length)throw i(`${r} is required`,r,"required");return t},u=e=>{const{orgName:t,appName:a}=r(e.appKey);return`/${t}/${a}/metadata/user/get`},f=e=>{const{orgName:t,appName:a}=r(e.appKey);return`/${t}/${a}/metadata/user/${encodeURIComponent(e.userId)}`},l=e=>({targets:m(e)}),g=(e,r)=>({targets:m(e),properties:d(r).map(e=>p(e,"params.attributes"))}),c=r=>!!e(r)&&("nickname"in r||"avatarurl"in r||"avatarUrl"in r||"mail"in r||"phone"in r||"gender"in r||"sign"in r||"birth"in r||"ext"in r),h=(r,t)=>{if(Array.isArray(r))for(const a of r){if(!e(a))continue;const r="string"==typeof a.username?a.username:"";r&&t.set(r,a)}},b=(e,r)=>{const t={userId:e};return"string"==typeof r.nickname&&(t.nickname=r.nickname),"string"==typeof r.avatarurl?t.avatarUrl=r.avatarurl:"string"==typeof r.avatarUrl&&(t.avatarUrl=r.avatarUrl),"string"==typeof r.mail&&(t.mail=r.mail),"string"==typeof r.phone&&(t.phone=r.phone),"string"!=typeof r.gender&&"number"!=typeof r.gender&&"boolean"!=typeof r.gender||(t.gender=r.gender),"string"==typeof r.sign&&(t.sign=r.sign),"string"==typeof r.birth&&(t.birth=r.birth),"string"==typeof r.ext&&(t.ext=r.ext),t},y=(r,t)=>{const a=(r=>{const t=/* @__PURE__ */new Map,a=e(r)?r:null;if(a?.data&&e(a.data))for(const[e,n]of Object.entries(a.data))c(n)&&t.set(e,n);return h(a?.entities,t),h(a?.data&&e(a.data)?a.data.entities:void 0,t),t})(r),n=(r=>{const t=/* @__PURE__ */new Map,a=e(r)?r:null;if(!a?.lastModified||!e(a.lastModified))return t;for(const[e,n]of Object.entries(a.lastModified))"number"==typeof n&&t.set(e,n);return t})(r),i=[];for(const e of t){const r=a.get(e);r&&i.push({profile:b(e,r),lastModified:n.get(e)})}return i},v=(e,r)=>y(e,r).map(e=>e.profile),$=(e,r,t,a)=>{void 0!==t&&("gender"!==r?e.push([r,s(t,a)]):e.push([r,String(o(t,a))]))},w=e=>e.map(([e,r])=>`${encodeURIComponent(e)}=${encodeURIComponent(r)}`).join("&"),I=e=>{const r=[];if($(r,"nickname",e.nickname,"params.nickname"),$(r,"avatarurl",e.avatarUrl,"params.avatarUrl"),$(r,"mail",e.mail,"params.mail"),$(r,"phone",e.phone,"params.phone"),$(r,"gender",e.gender,"params.gender"),$(r,"sign",e.sign,"params.sign"),$(r,"birth",e.birth,"params.birth"),$(r,"ext",e.ext,"params.ext"),0===r.length)throw i("params must include at least one updatable field","params","required");return w(r)},A=(e,r)=>{const t=p(e,"attribute"),a=o(r,"value");if("gender"!==t&&"string"!=typeof a)throw i("value must be a string","value","invalid_format");return w([[t,String(a)]])};export{u as a,l as b,m as c,g as d,d as e,I as f,f as g,A as h,y as i,v as n};
package/core/index.d.ts CHANGED
@@ -93,7 +93,7 @@ export declare class CoreSDK {
93
93
  * 下载并解析合并消息详情
94
94
  */
95
95
  downloadAndParseCombineMessage(options: DownloadCombineMessageParams): Promise<ReadonlyArray<Message>>;
96
- downloadAttachment(message: Message, timeoutMs?: number): Promise<MessageAttachmentDownloadResult>;
96
+ downloadAttachment(message: Message, timeoutMs?: number): Promise<MessageAttachmentDownloadResult | ReadonlyArray<MessageAttachmentDownloadResult>>;
97
97
  decodeServerMessageMeta(metaPayload: Uint8Array): Message | null;
98
98
  /**
99
99
  * 销毁
@@ -3,5 +3,8 @@ import type { Message, MessageAttachmentDownloadResult } from '../../types';
3
3
  export declare class AttachmentDownloader {
4
4
  private readonly requestAdapter;
5
5
  constructor(requestAdapter?: RequestAdapter);
6
- download(message: Message, timeoutMs?: number): Promise<MessageAttachmentDownloadResult>;
6
+ private resolveMultiBodyTargets;
7
+ private assertHasDownloadUrl;
8
+ download(message: Message, timeoutMs?: number): Promise<MessageAttachmentDownloadResult | ReadonlyArray<MessageAttachmentDownloadResult>>;
9
+ private downloadSingle;
7
10
  }
@@ -29,24 +29,39 @@ export declare class MessageSender {
29
29
  constructor(msyncCodec: MsyncCodec, websocket: SocketLike | null, eventHub: EventHub, attachmentUploader?: AttachmentUploader);
30
30
  updateAuthToken(token: string): void;
31
31
  /**
32
- * 发送消息
32
+ * 发送一条消息。调用方看到的是这一个方法,实际分成准备和等待回执两段。
33
+ *
34
+ * 1. 流式消息,或 WebSocket 未连接:直接失败,不上传。
35
+ * 2. 合并消息先打成一个文件。其他类型跳过。
36
+ * 3. `prepareMessage` 上传本地附件,并把远端地址写回消息体。复合消息在这里按段串行上传。
37
+ * 4. 调用 `onSending`。这时消息还没写到网上。
38
+ * 5. `doSendMessage` 编码并写出,然后停在 Promise 上,直到下面三者之一:
39
+ * - `handleAck`:服务端接受,补上 `msgServerId`,清本地文件,再 `onSuccess`。
40
+ * - `handleSendError`:服务端拒绝或连接中断。
41
+ * - 超时:一直没有回执。
42
+ * 6. 第 3 步之后的失败也进下面的 catch。`onFailed` 拿到的是上传后的消息,
43
+ * 已成功的附件带远端地址,再次发送时会跳过。
33
44
  */
34
45
  sendMessage(message: Message, options?: SendMessageOptions): Promise<Message>;
35
46
  sendAction(action: MessageActionRequest, createAckError?: (statusCode: number, reason?: string) => Error): Promise<ActionAckResult>;
36
47
  sendChatRoomOperation(request: ChatRoomOperationRequest, createAckError?: (statusCode: number, reason?: string) => Error): Promise<ActionAckResult>;
37
48
  /**
38
- * 实际发送消息
49
+ * 把准备好的消息写到 WebSocket,并等待服务端回执。
50
+ * 这里先登记待确认消息,再发送。回执到达时用 protocolId 找回这条登记,
51
+ * 由 `handleAck` 或 `handleSendError` 结束这个 Promise。
39
52
  */
40
53
  private doSendMessage;
41
54
  private sendProtocolPayload;
42
55
  private prepareCombineMessage;
43
56
  /**
44
- * 处理 ACK
57
+ * 服务端接受了这条消息。用 protocolId 找到 `doSendMessage` 登记的待确认消息,
58
+ * 写入服务端 id,清掉本地附件,再 resolve,发送 Promise 才返回。
45
59
  */
46
60
  handleAck(protocolId: string, msgServerId?: string, replacedMessage?: Message, chatRoomInfo?: JoinChatRoomInfo): void;
47
61
  private resolveReplacedMessage;
48
62
  /**
49
- * 处理发送失败
63
+ * 消息已经写出,但服务端拒绝或连接中断。
64
+ * reject 之后回到 `sendMessage` 的 catch,由那里回调 `onFailed`。
50
65
  */
51
66
  handleSendError(protocolId: string, error: Error): void;
52
67
  handleAckFailure(protocolId: string, statusCode: number, reason: string | undefined, error: Error): void;
@@ -0,0 +1,7 @@
1
+ import type { Message } from '../../types';
2
+ import type { MessageTranslationResult } from '../../types/chat-manager';
3
+ /** 仅为本次发送准备消息快照,不回填调用方持有的消息对象。 */
4
+ export declare const prepareTextTranslation: (message: Message, translate: (params: {
5
+ readonly text: string;
6
+ readonly targetLanguages: ReadonlyArray<string>;
7
+ }) => Promise<MessageTranslationResult>) => Promise<Message>;
@@ -0,0 +1,9 @@
1
+ import type { ConversationItem, SessionMessageSnippet } from '../../types/conversation';
2
+ import type { ChatThreadRawNotifyPayload } from '../../types/chat-thread';
3
+ /** @internal Updates a parent message overview only when the notification identifies that message/thread. */
4
+ export declare const resolveThreadLastMessagePatch: (payload: ChatThreadRawNotifyPayload, items: ReadonlyArray<ConversationItem>, userId: string, useCustomAttachmentUpload?: boolean) => {
5
+ readonly conversationId: string;
6
+ readonly conversationType: "groupChat";
7
+ readonly messageId: string;
8
+ readonly patch: Partial<SessionMessageSnippet>;
9
+ } | null;