@amityco/ts-sdk 0.0.1-beta.42.3 → 0.0.1-beta.43

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 (296) hide show
  1. package/dist/@types/core/events.d.ts +11 -1
  2. package/dist/@types/core/events.d.ts.map +1 -1
  3. package/dist/@types/core/marker.d.ts +37 -0
  4. package/dist/@types/core/marker.d.ts.map +1 -0
  5. package/dist/@types/core/model.d.ts +10 -0
  6. package/dist/@types/core/model.d.ts.map +1 -1
  7. package/dist/@types/core/payload.d.ts +44 -0
  8. package/dist/@types/core/payload.d.ts.map +1 -1
  9. package/dist/@types/domains/channel.d.ts +5 -8
  10. package/dist/@types/domains/channel.d.ts.map +1 -1
  11. package/dist/@types/domains/client.d.ts +1 -0
  12. package/dist/@types/domains/client.d.ts.map +1 -1
  13. package/dist/@types/domains/marker.d.ts +15 -0
  14. package/dist/@types/domains/marker.d.ts.map +1 -0
  15. package/dist/@types/domains/message.d.ts +3 -0
  16. package/dist/@types/domains/message.d.ts.map +1 -1
  17. package/dist/@types/domains/partials.d.ts +3 -0
  18. package/dist/@types/domains/partials.d.ts.map +1 -1
  19. package/dist/@types/domains/subChannel.d.ts +2 -0
  20. package/dist/@types/domains/subChannel.d.ts.map +1 -1
  21. package/dist/channel/api/index.d.ts +0 -2
  22. package/dist/channel/api/index.d.ts.map +1 -1
  23. package/dist/channel/events/onChannelUpdated.d.ts.map +1 -1
  24. package/dist/channel/utils/index.d.ts +1 -2
  25. package/dist/channel/utils/index.d.ts.map +1 -1
  26. package/dist/channel/utils/prepareChannelPayload.d.ts +6 -0
  27. package/dist/channel/utils/prepareChannelPayload.d.ts.map +1 -0
  28. package/dist/channel/utils/tests/prepareChannelPayload.test.d.ts +5 -1
  29. package/dist/channel/utils/tests/prepareChannelPayload.test.d.ts.map +1 -1
  30. package/dist/client/api/activeUser.d.ts +2 -2
  31. package/dist/client/api/activeUser.d.ts.map +1 -1
  32. package/dist/client/api/connectClient.d.ts.map +1 -1
  33. package/dist/client/api/index.d.ts +2 -0
  34. package/dist/client/api/index.d.ts.map +1 -1
  35. package/dist/client/api/markerSync.d.ts +21 -0
  36. package/dist/client/api/markerSync.d.ts.map +1 -0
  37. package/dist/client/observers/getTotalUnreadCount.d.ts +18 -0
  38. package/dist/client/observers/getTotalUnreadCount.d.ts.map +1 -0
  39. package/dist/client/observers/index.d.ts +2 -0
  40. package/dist/client/observers/index.d.ts.map +1 -0
  41. package/dist/client/observers/tests/getTotalUnreadCount.test.d.ts +2 -0
  42. package/dist/client/observers/tests/getTotalUnreadCount.test.d.ts.map +1 -0
  43. package/dist/client/utils/index.d.ts +2 -0
  44. package/dist/client/utils/index.d.ts.map +1 -0
  45. package/dist/client/utils/markerSyncEngine.d.ts +46 -0
  46. package/dist/client/utils/markerSyncEngine.d.ts.map +1 -0
  47. package/dist/core/events.d.ts +3 -3
  48. package/dist/core/events.d.ts.map +1 -1
  49. package/dist/core/model/idResolvers.d.ts.map +1 -1
  50. package/dist/core/model/index.d.ts.map +1 -1
  51. package/dist/index.cjs.js +1921 -1185
  52. package/dist/index.d.ts +5 -0
  53. package/dist/index.d.ts.map +1 -1
  54. package/dist/index.esm.js +1891 -1186
  55. package/dist/index.umd.js +4 -4
  56. package/dist/marker/api/getChannelMarkers.d.ts +18 -0
  57. package/dist/marker/api/getChannelMarkers.d.ts.map +1 -0
  58. package/dist/marker/api/getMessageMarkers.d.ts +18 -0
  59. package/dist/marker/api/getMessageMarkers.d.ts.map +1 -0
  60. package/dist/marker/api/getSubChannelMarkers.d.ts +18 -0
  61. package/dist/marker/api/getSubChannelMarkers.d.ts.map +1 -0
  62. package/dist/marker/api/getUserMarker.d.ts +8 -0
  63. package/dist/marker/api/getUserMarker.d.ts.map +1 -0
  64. package/dist/marker/api/index.d.ts +5 -0
  65. package/dist/marker/api/index.d.ts.map +1 -0
  66. package/dist/marker/api/tests/getChannelMarkers.test.d.ts +2 -0
  67. package/dist/marker/api/tests/getChannelMarkers.test.d.ts.map +1 -0
  68. package/dist/marker/api/tests/getMessageMarkers.test.d.ts +2 -0
  69. package/dist/marker/api/tests/getMessageMarkers.test.d.ts.map +1 -0
  70. package/dist/marker/api/tests/getSubChannelMarkers.test.d.ts +2 -0
  71. package/dist/marker/api/tests/getSubChannelMarkers.test.d.ts.map +1 -0
  72. package/dist/marker/events/index.d.ts +7 -0
  73. package/dist/marker/events/index.d.ts.map +1 -0
  74. package/dist/marker/events/onChannelMarkerFetched.d.ts +17 -0
  75. package/dist/marker/events/onChannelMarkerFetched.d.ts.map +1 -0
  76. package/dist/marker/events/onFeedlMarkerFetched.d.ts +17 -0
  77. package/dist/marker/events/onFeedlMarkerFetched.d.ts.map +1 -0
  78. package/dist/marker/events/onMessageMarkerFetched.d.ts +17 -0
  79. package/dist/marker/events/onMessageMarkerFetched.d.ts.map +1 -0
  80. package/dist/marker/events/onSubChannelMarkerFetched.d.ts +17 -0
  81. package/dist/marker/events/onSubChannelMarkerFetched.d.ts.map +1 -0
  82. package/dist/marker/events/onSubChannelMarkerUpdated.d.ts +17 -0
  83. package/dist/marker/events/onSubChannelMarkerUpdated.d.ts.map +1 -0
  84. package/dist/marker/events/onUserMarkerFetched.d.ts +17 -0
  85. package/dist/marker/events/onUserMarkerFetched.d.ts.map +1 -0
  86. package/dist/message/api/getMessage.d.ts.map +1 -1
  87. package/dist/message/api/getMessages.d.ts.map +1 -1
  88. package/dist/message/api/index.d.ts +1 -0
  89. package/dist/message/api/index.d.ts.map +1 -1
  90. package/dist/message/api/markAsDelivered.d.ts +17 -0
  91. package/dist/message/api/markAsDelivered.d.ts.map +1 -0
  92. package/dist/message/api/queryMessages.d.ts.map +1 -1
  93. package/dist/message/api/tests/markAsDelivered.test.d.ts +2 -0
  94. package/dist/message/api/tests/markAsDelivered.test.d.ts.map +1 -0
  95. package/dist/message/api/updateMessage.d.ts.map +1 -1
  96. package/dist/message/events/index.d.ts +1 -0
  97. package/dist/message/events/index.d.ts.map +1 -1
  98. package/dist/message/events/onMessageCreated.d.ts +2 -1
  99. package/dist/message/events/onMessageCreated.d.ts.map +1 -1
  100. package/dist/message/events/onMessageUpdated.d.ts.map +1 -1
  101. package/dist/message/utils/index.d.ts +1 -18
  102. package/dist/message/utils/index.d.ts.map +1 -1
  103. package/dist/message/utils/prepareMessagePayload.d.ts +16 -0
  104. package/dist/message/utils/prepareMessagePayload.d.ts.map +1 -0
  105. package/dist/report/api/createReport.d.ts.map +1 -1
  106. package/dist/report/api/deleteReport.d.ts.map +1 -1
  107. package/dist/subChannel/api/getSubChannels.d.ts.map +1 -1
  108. package/dist/subChannel/api/index.d.ts +2 -0
  109. package/dist/subChannel/api/index.d.ts.map +1 -1
  110. package/dist/subChannel/api/startReadingAPI.d.ts +17 -0
  111. package/dist/subChannel/api/startReadingAPI.d.ts.map +1 -0
  112. package/dist/subChannel/api/stopReadingAPI.d.ts +17 -0
  113. package/dist/subChannel/api/stopReadingAPI.d.ts.map +1 -0
  114. package/dist/subChannel/events/onSubChannelUpdated.d.ts +1 -1
  115. package/dist/subChannel/events/onSubChannelUpdated.d.ts.map +1 -1
  116. package/dist/subChannel/observers/liveSubChannel.d.ts.map +1 -1
  117. package/dist/subChannel/utils/index.d.ts +2 -7
  118. package/dist/subChannel/utils/index.d.ts.map +1 -1
  119. package/dist/subChannel/utils/markReadEngine.d.ts +33 -0
  120. package/dist/subChannel/utils/markReadEngine.d.ts.map +1 -0
  121. package/dist/subChannel/utils/prepareSubChannelPayload.d.ts +15 -0
  122. package/dist/subChannel/utils/prepareSubChannelPayload.d.ts.map +1 -0
  123. package/dist/utils/liveObject.d.ts +1 -1
  124. package/dist/utils/liveObject.d.ts.map +1 -1
  125. package/dist/utils/tests/client.d.ts +1 -0
  126. package/dist/utils/tests/client.d.ts.map +1 -1
  127. package/dist/utils/tests/dummy/channel.d.ts +4 -0
  128. package/dist/utils/tests/dummy/channel.d.ts.map +1 -1
  129. package/dist/utils/tests/dummy/index.d.ts +1 -0
  130. package/dist/utils/tests/dummy/index.d.ts.map +1 -1
  131. package/dist/utils/tests/dummy/marker.d.ts +6 -0
  132. package/dist/utils/tests/dummy/marker.d.ts.map +1 -0
  133. package/dist/utils/tests/dummy/message.d.ts +2 -0
  134. package/dist/utils/tests/dummy/message.d.ts.map +1 -1
  135. package/dist/utils/tests/dummy/subChannel.d.ts +1 -0
  136. package/dist/utils/tests/dummy/subChannel.d.ts.map +1 -1
  137. package/dist/utils/tests/utils.d.ts.map +1 -1
  138. package/package.json +1 -1
  139. package/src/@types/core/events.ts +13 -1
  140. package/src/@types/core/marker.ts +42 -0
  141. package/src/@types/core/model.ts +12 -0
  142. package/src/@types/core/payload.ts +52 -0
  143. package/src/@types/domains/channel.ts +5 -16
  144. package/src/@types/domains/client.ts +2 -0
  145. package/src/@types/domains/marker.ts +15 -0
  146. package/src/@types/domains/message.ts +3 -0
  147. package/src/@types/domains/partials.ts +4 -0
  148. package/src/@types/domains/subChannel.ts +2 -0
  149. package/src/channel/api/addChannelMembers.ts +1 -1
  150. package/src/channel/api/addChannelMembersRole.ts +1 -1
  151. package/src/channel/api/banChannelMembers.ts +1 -1
  152. package/src/channel/api/createChannel.ts +1 -1
  153. package/src/channel/api/getChannel.ts +1 -1
  154. package/src/channel/api/getChannels.ts +1 -1
  155. package/src/channel/api/index.ts +0 -3
  156. package/src/channel/api/joinChannel.ts +1 -1
  157. package/src/channel/api/leaveChannel.ts +1 -1
  158. package/src/channel/api/queryChannelMembers.ts +1 -1
  159. package/src/channel/api/queryChannels.ts +1 -1
  160. package/src/channel/api/removeChannelMembers.ts +1 -1
  161. package/src/channel/api/removeChannelMembersRole.ts +1 -1
  162. package/src/channel/api/tests/addChannelMembers.test.ts +16 -0
  163. package/src/channel/api/tests/createChannel.test.ts +29 -8
  164. package/src/channel/api/tests/getChannel.test.ts +11 -4
  165. package/src/channel/api/tests/getChannels.test.ts +20 -12
  166. package/src/channel/api/tests/queryChannelMembers.test.ts +13 -4
  167. package/src/channel/api/tests/queryChannels.test.ts +19 -9
  168. package/src/channel/api/unbanChannelMembers.ts +1 -1
  169. package/src/channel/api/updateChannel.ts +1 -1
  170. package/src/channel/events/onChannelCreated.ts +2 -2
  171. package/src/channel/events/onChannelDeleted.ts +4 -4
  172. package/src/channel/events/onChannelJoined.ts +2 -2
  173. package/src/channel/events/onChannelLeft.ts +2 -2
  174. package/src/channel/events/onChannelMemberAdded.ts +2 -2
  175. package/src/channel/events/onChannelMemberBanned.ts +3 -3
  176. package/src/channel/events/onChannelMemberRemoved.ts +2 -2
  177. package/src/channel/events/onChannelMemberUnbanned.ts +2 -2
  178. package/src/channel/events/onChannelMuted.ts +2 -2
  179. package/src/channel/events/onChannelUpdated.ts +25 -4
  180. package/src/channel/events/tests/onChannelCreated.test.ts +4 -1
  181. package/src/channel/events/tests/onChannelJoined.test.ts +5 -1
  182. package/src/channel/events/tests/onChannelMemberAdded.test.ts +5 -1
  183. package/src/channel/events/tests/onChannelMemberBanned.test.ts +4 -1
  184. package/src/channel/events/tests/onChannelMemberRemoved.test.ts +5 -1
  185. package/src/channel/events/tests/onChannelMemberUnbanned.test.ts +10 -10
  186. package/src/channel/events/tests/onChannelUpdated.test.ts +5 -1
  187. package/src/channel/observers/tests/liveChannelMembers.test.ts +5 -11
  188. package/src/channel/observers/tests/liveChannels.test.ts +21 -24
  189. package/src/channel/utils/index.ts +1 -57
  190. package/src/channel/utils/prepareChannelPayload.ts +91 -0
  191. package/src/channel/utils/tests/prepareChannelPayload.test.ts +102 -104
  192. package/src/client/api/activeUser.ts +2 -2
  193. package/src/client/api/connectClient.ts +2 -1
  194. package/src/client/api/index.ts +3 -0
  195. package/src/client/api/markerSync.ts +42 -0
  196. package/src/client/observers/getTotalUnreadCount.ts +52 -0
  197. package/src/client/observers/index.ts +1 -0
  198. package/src/client/observers/tests/getTotalUnreadCount.test.ts +126 -0
  199. package/src/client/utils/index.ts +1 -0
  200. package/src/client/utils/markerSyncEngine.ts +179 -0
  201. package/src/comment/api/tests/queryComments.test.ts +2 -2
  202. package/src/core/model/idResolvers.ts +7 -0
  203. package/src/core/model/identifyModel.ts +1 -1
  204. package/src/core/model/index.ts +6 -0
  205. package/src/core/tests/query/query/runQuery.test.ts +3 -1
  206. package/src/group/utils/withUser.ts +2 -2
  207. package/src/index.ts +6 -0
  208. package/src/marker/api/getChannelMarkers.ts +53 -0
  209. package/src/marker/api/getMessageMarkers.ts +54 -0
  210. package/src/marker/api/getSubChannelMarkers.ts +54 -0
  211. package/src/marker/api/getUserMarker.ts +47 -0
  212. package/src/marker/api/index.ts +4 -0
  213. package/src/marker/api/tests/getChannelMarkers.test.ts +109 -0
  214. package/src/marker/api/tests/getMessageMarkers.test.ts +114 -0
  215. package/src/marker/api/tests/getSubChannelMarkers.test.ts +116 -0
  216. package/src/marker/events/index.ts +10 -0
  217. package/src/marker/events/onChannelMarkerFetched.ts +34 -0
  218. package/src/marker/events/onFeedlMarkerFetched.ts +34 -0
  219. package/src/marker/events/onMessageMarkerFetched.ts +34 -0
  220. package/src/marker/events/onSubChannelMarkerFetched.ts +34 -0
  221. package/src/marker/events/onSubChannelMarkerUpdated.ts +34 -0
  222. package/src/marker/events/onUserMarkerFetched.ts +34 -0
  223. package/src/message/api/createMessage.ts +1 -1
  224. package/src/message/api/getMessage.ts +6 -5
  225. package/src/message/api/getMessages.ts +7 -6
  226. package/src/message/api/index.ts +1 -0
  227. package/src/message/api/markAsDelivered.ts +36 -0
  228. package/src/message/api/queryMessages.ts +8 -6
  229. package/src/message/api/tests/createMessage.test.ts +13 -4
  230. package/src/message/api/tests/getMessage.test.ts +12 -3
  231. package/src/message/api/tests/getMessages.test.ts +14 -5
  232. package/src/message/api/tests/markAsDelivered.test.ts +83 -0
  233. package/src/message/api/tests/queryMessages.test.ts +14 -3
  234. package/src/message/api/updateMessage.ts +8 -7
  235. package/src/message/events/index.ts +2 -0
  236. package/src/message/events/onMessageCreated.ts +14 -41
  237. package/src/message/events/onMessageDeleted.ts +2 -2
  238. package/src/message/events/onMessageFlagCleared.ts +2 -2
  239. package/src/message/events/onMessageFlagged.ts +2 -2
  240. package/src/message/events/onMessageReactionAdded.ts +2 -2
  241. package/src/message/events/onMessageReactionRemoved.ts +2 -2
  242. package/src/message/events/onMessageUnflagged.ts +2 -2
  243. package/src/message/events/onMessageUpdated.ts +27 -5
  244. package/src/message/tests/events.test.ts +4 -2
  245. package/src/message/tests/observers/liveMessage.test.ts +22 -10
  246. package/src/message/tests/observers/liveMessages.test.ts +25 -18
  247. package/src/message/utils/index.ts +1 -140
  248. package/src/message/utils/prepareMessagePayload.ts +182 -0
  249. package/src/reaction/events/onReactionAdded.ts +2 -2
  250. package/src/reaction/events/onReactionRemoved.ts +2 -2
  251. package/src/reaction/events/onReactorAdded.ts +2 -2
  252. package/src/reaction/events/onReactorRemoved.ts +2 -2
  253. package/src/report/api/createReport.ts +2 -1
  254. package/src/report/api/deleteReport.ts +2 -1
  255. package/src/subChannel/api/createSubChannel.ts +1 -1
  256. package/src/subChannel/api/getSubChannel.ts +1 -1
  257. package/src/subChannel/api/getSubChannels.ts +2 -1
  258. package/src/subChannel/api/index.ts +3 -0
  259. package/src/subChannel/api/querySubChannels.ts +1 -1
  260. package/src/subChannel/api/startReadingAPI.ts +33 -0
  261. package/src/subChannel/api/stopReadingAPI.ts +33 -0
  262. package/src/subChannel/api/tests/createSubChannel.test.ts +6 -3
  263. package/src/subChannel/api/tests/deleteSubChannel.test.ts +7 -5
  264. package/src/subChannel/api/tests/getSubChannel.test.ts +6 -4
  265. package/src/subChannel/api/tests/getSubChannels.test.ts +6 -3
  266. package/src/subChannel/api/tests/updateSubChannel.test.ts +6 -3
  267. package/src/subChannel/api/updateSubChannel.ts +1 -1
  268. package/src/subChannel/events/onSubChannelCreated.ts +2 -2
  269. package/src/subChannel/events/onSubChannelDeleted.ts +2 -2
  270. package/src/subChannel/events/onSubChannelUpdated.ts +43 -4
  271. package/src/subChannel/observers/liveSubChannel.ts +2 -0
  272. package/src/subChannel/observers/tests/liveSubChannel.test.ts +15 -10
  273. package/src/subChannel/observers/tests/liveSubChannels.test.ts +21 -14
  274. package/src/subChannel/utils/index.ts +2 -50
  275. package/src/subChannel/utils/markReadEngine.ts +117 -0
  276. package/src/subChannel/utils/prepareSubChannelPayload.ts +132 -0
  277. package/src/utils/liveObject.ts +15 -4
  278. package/src/utils/tests/client.ts +3 -1
  279. package/src/utils/tests/dummy/channel.ts +38 -21
  280. package/src/utils/tests/dummy/index.ts +1 -0
  281. package/src/utils/tests/dummy/marker.ts +68 -0
  282. package/src/utils/tests/dummy/message.ts +43 -3
  283. package/src/utils/tests/dummy/subChannel.ts +16 -5
  284. package/src/utils/tests/utils.ts +4 -1
  285. package/dist/channel/api/startReading.d.ts +0 -17
  286. package/dist/channel/api/startReading.d.ts.map +0 -1
  287. package/dist/channel/api/stopReading.d.ts +0 -16
  288. package/dist/channel/api/stopReading.d.ts.map +0 -1
  289. package/dist/channel/api/tests/startReading.test.d.ts +0 -2
  290. package/dist/channel/api/tests/startReading.test.d.ts.map +0 -1
  291. package/dist/channel/api/tests/stopReading.test.d.ts +0 -2
  292. package/dist/channel/api/tests/stopReading.test.d.ts.map +0 -1
  293. package/src/channel/api/startReading.ts +0 -57
  294. package/src/channel/api/stopReading.ts +0 -53
  295. package/src/channel/api/tests/startReading.test.ts +0 -25
  296. package/src/channel/api/tests/stopReading.test.ts +0 -25
package/dist/index.esm.js CHANGED
@@ -81,8 +81,8 @@ const PostContentType = Object.freeze({
81
81
 
82
82
  function getVersion() {
83
83
  try {
84
- // the string ''v0.0.1-beta.42.3-esm'' should be replaced by actual value by @rollup/plugin-replace
85
- return 'v0.0.1-beta.42.3-esm';
84
+ // the string ''v0.0.1-beta.43-esm'' should be replaced by actual value by @rollup/plugin-replace
85
+ return 'v0.0.1-beta.43-esm';
86
86
  }
87
87
  catch (error) {
88
88
  return '__dev__';
@@ -500,6 +500,11 @@ const idResolvers = {
500
500
  subChannel: ({ subChannelId }) => subChannelId,
501
501
  channelUsers: ({ channelId, userId }) => `${channelId}#${userId}`,
502
502
  message: ({ messageId }) => messageId,
503
+ channelMarker: ({ entityId, userId }) => `${entityId}#${userId}`,
504
+ subChannelMarker: ({ entityId, feedId, userId }) => `${entityId}#${feedId}#${userId}`,
505
+ messageMarker: ({ feedId, contentId, creatorId }) => `${feedId}#${contentId}#${creatorId}`,
506
+ feedMarker: ({ feedId, entityId }) => `${feedId}#${entityId}`,
507
+ userMarker: ({ userId }) => userId,
503
508
  community: ({ communityId }) => communityId,
504
509
  category: ({ categoryId }) => categoryId,
505
510
  communityUsers: ({ communityId, userId }) => `${communityId}#${userId}`,
@@ -600,6 +605,11 @@ const PAYLOAD2MODEL = {
600
605
  messageFeeds: 'subChannel',
601
606
  channelUsers: 'channelUsers',
602
607
  messages: 'message',
608
+ userEntityMarkers: 'channelMarker',
609
+ userFeedMarkers: 'subChannelMarker',
610
+ contentMarkers: 'messageMarker',
611
+ feedMarkers: 'feedMarker',
612
+ userMarkers: 'userMarker',
603
613
  communities: 'community',
604
614
  categories: 'category',
605
615
  communityUsers: 'communityUsers',
@@ -20516,6 +20526,57 @@ const setClientToken = async (params) => {
20516
20526
  return { accessToken, users, refreshToken };
20517
20527
  };
20518
20528
 
20529
+ /**
20530
+ * Ingest a payload (v3) into the cache
20531
+ *
20532
+ * @param payload a "backend v3" payload object
20533
+ * @param options caching options like cachedAt or offline
20534
+ *
20535
+ * @category Cache
20536
+ * @hidden
20537
+ */
20538
+ const ingestInCache = (payload = {}, options) => {
20539
+ Object.entries(payload).forEach(([key, models]) => {
20540
+ const type = PAYLOAD2MODEL[key];
20541
+ if (!type)
20542
+ return;
20543
+ const resolver = getResolver(type);
20544
+ if (!resolver)
20545
+ return;
20546
+ models.forEach(model => {
20547
+ upsertInCache([type, 'get', resolver(model)], model, options);
20548
+ });
20549
+ });
20550
+ };
20551
+
20552
+ const createUserEventSubscriber = (event, callback) => {
20553
+ const client = getActiveClient();
20554
+ const filter = (payload) => {
20555
+ if (client.cache) {
20556
+ ingestInCache(payload);
20557
+ }
20558
+ callback(payload.users[0]);
20559
+ };
20560
+ return createEventSubscriber(client, event, event, filter);
20561
+ };
20562
+
20563
+ /**
20564
+ * ```js
20565
+ * import { onUserDeleted } from '@amityco/ts-sdk'
20566
+ * const dispose = onUserDeleted(user => {
20567
+ * // ...
20568
+ * })
20569
+ * ```
20570
+ *
20571
+ * Fired when a {@link Amity.User} has been deleted
20572
+ *
20573
+ * @param callback The function to call when the event was fired
20574
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
20575
+ *
20576
+ * @category User Events
20577
+ */
20578
+ const onUserDeleted = (callback) => createUserEventSubscriber('user.deleted', callback);
20579
+
20519
20580
  /* begin_public_function
20520
20581
  id: client.logout
20521
20582
  */
@@ -20570,57 +20631,6 @@ const disconnectClient = async () => {
20570
20631
  };
20571
20632
  /* end_public_function */
20572
20633
 
20573
- /**
20574
- * Ingest a payload (v3) into the cache
20575
- *
20576
- * @param payload a "backend v3" payload object
20577
- * @param options caching options like cachedAt or offline
20578
- *
20579
- * @category Cache
20580
- * @hidden
20581
- */
20582
- const ingestInCache = (payload = {}, options) => {
20583
- Object.entries(payload).forEach(([key, models]) => {
20584
- const type = PAYLOAD2MODEL[key];
20585
- if (!type)
20586
- return;
20587
- const resolver = getResolver(type);
20588
- if (!resolver)
20589
- return;
20590
- models.forEach(model => {
20591
- upsertInCache([type, 'get', resolver(model)], model, options);
20592
- });
20593
- });
20594
- };
20595
-
20596
- const createUserEventSubscriber = (event, callback) => {
20597
- const client = getActiveClient();
20598
- const filter = (payload) => {
20599
- if (client.cache) {
20600
- ingestInCache(payload);
20601
- }
20602
- callback(payload.users[0]);
20603
- };
20604
- return createEventSubscriber(client, event, event, filter);
20605
- };
20606
-
20607
- /**
20608
- * ```js
20609
- * import { onUserDeleted } from '@amityco/ts-sdk'
20610
- * const dispose = onUserDeleted(user => {
20611
- * // ...
20612
- * })
20613
- * ```
20614
- *
20615
- * Fired when a {@link Amity.User} has been deleted
20616
- *
20617
- * @param callback The function to call when the event was fired
20618
- * @returns an {@link Amity.Unsubscriber} function to stop listening
20619
- *
20620
- * @category User Events
20621
- */
20622
- const onUserDeleted = (callback) => createUserEventSubscriber('user.deleted', callback);
20623
-
20624
20634
  /**
20625
20635
  * Terminates {@link Amity.Client} instance
20626
20636
  *
@@ -21076,408 +21086,355 @@ const isConnected = () => {
21076
21086
 
21077
21087
  /**
21078
21088
  * ```js
21079
- * import { isInTombstone } from '@amityco/ts-sdk'
21080
- * const user = isInTombstone(["message", "messageId"])
21089
+ * import { markerSync } from '@amityco/ts-sdk'
21090
+ * const success = await markerSync()
21081
21091
  * ```
21082
21092
  *
21083
- * Checks if the {@link Amity.TombstoneCacheOptions} exists
21084
- * in cache and it's not expired means it's in tombstone
21085
- * and we throw an Error
21093
+ * Make all markers synced
21094
+ * * If response is empty means that the sync has ended.
21095
+ * * If response is not empty, the sync has not ended. You must call markerSync
21096
+ * again to continue syncing.
21086
21097
  *
21087
- * @param model the model to check
21088
- * @param modelId the object id to check
21089
- * @returns the matching cache entry, or undefined.
21098
+ * @return {hasMore} A success boolean if the marker sync was ended.
21090
21099
  *
21091
- * @category Cache API
21100
+ * @category Marker API
21101
+ * @async
21102
+ * @private
21092
21103
  */
21093
- const isInTombstone = (model, modelId) => {
21094
- const { log, cache } = getActiveClient();
21095
- const key = [model, CACHE_KEY_TOMBSTONE, modelId];
21096
- if (!cache)
21097
- return;
21098
- log('cache/api/isInTombstone', key);
21099
- const isInTombstone = pullFromCache(key);
21100
- const { lifeSpan } = queryOptions('cache_then_server', CACHE_LIFESPAN_TOMBSTONE);
21101
- if (isInTombstone && isFresh(isInTombstone.data, lifeSpan)) {
21102
- throw new ASCApiError('Item not found!', 400400 /* Amity.ServerError.ITEM_NOT_FOUND */, "error" /* Amity.ErrorLevel.ERROR */);
21103
- }
21104
+ const markerSync = async () => {
21105
+ const client = getActiveClient();
21106
+ client.log('channel/markerSync');
21107
+ const { data: payload } = await client.http.post(`/api/v1/markers/sync`);
21108
+ const { userEntityMarkers, userFeedMarkers, feedMarkers, userMarkers } = payload;
21109
+ const cachedAt = client.cache && Date.now();
21110
+ if (client.cache)
21111
+ ingestInCache(payload, { cachedAt });
21112
+ feedMarkers.length && fireEvent('local.feedMarker.fetched', { feedMarkers });
21113
+ userEntityMarkers.length && fireEvent('local.channelMarker.fetched', { userEntityMarkers });
21114
+ userFeedMarkers.length && fireEvent('local.subChannelMarker.fetched', { userFeedMarkers });
21115
+ userMarkers.length && fireEvent('local.userMarker.fetched', { userMarkers });
21116
+ return {
21117
+ hasMore: payload.feedMarkers.length > 0,
21118
+ };
21104
21119
  };
21105
21120
 
21121
+ /******************************************************************************
21122
+ Copyright (c) Microsoft Corporation.
21123
+
21124
+ Permission to use, copy, modify, and/or distribute this software for any
21125
+ purpose with or without fee is hereby granted.
21126
+
21127
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
21128
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
21129
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
21130
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
21131
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
21132
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
21133
+ PERFORMANCE OF THIS SOFTWARE.
21134
+ ***************************************************************************** */
21135
+
21136
+ function __rest(s, e) {
21137
+ var t = {};
21138
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
21139
+ t[p] = s[p];
21140
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
21141
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
21142
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
21143
+ t[p[i]] = s[p[i]];
21144
+ }
21145
+ return t;
21146
+ }
21147
+
21106
21148
  /**
21107
21149
  * ```js
21108
- * import { pushToTombstone } from '@amityco/ts-sdk'
21109
- * pushToTombstone(["message", "messageId"], { cachedAt: Date.now() })
21150
+ * import { getChannelMarker } from '@amityco/ts-sdk'
21151
+ * const channelMarkers = await getChannelMarkers(['ch1', 'ch2'])
21110
21152
  * ```
21111
21153
  *
21112
- * Removes an existing {@link Amity.CacheEntry} from the {@link Amity.Client}'s
21113
- * {@link Amity.Cache} from a given {@link Amity.CacheKey}
21154
+ * Fetches a paginable list of {@link Amity.ChannelMarker} objects
21114
21155
  *
21115
- * @param model the model to remove and push to Tombstone
21116
- * @param modelId the related model id
21156
+ * @param channelIds the IDs of the {@link Amity.RawChannel} marker to fetch
21157
+ * @param page
21158
+ * @returns A page of {@link Amity.ChannelMarker} objects
21117
21159
  *
21118
- * @category Cache API
21119
- * @hidden
21160
+ * @category Channel API
21161
+ * @async
21162
+ * @private
21120
21163
  */
21121
- const pushToTombstone = (model, modelId) => {
21122
- const { log, cache } = getActiveClient();
21123
- const cacheKey = [model, CACHE_KEY_TOMBSTONE, modelId];
21124
- const data = { cachedAt: Date.now() };
21125
- if (!cache)
21126
- return;
21127
- log('cache/api/pushToTombstone', { cacheKey, data });
21128
- dropFromCache([model, CACHE_KEY_GET, modelId], true);
21129
- pushToCache(cacheKey, data);
21164
+ const getChannelMarkers = async (channelIds, page = { limit: 100 }) => {
21165
+ const client = getActiveClient();
21166
+ client.log('channel/getChannelMarkers', channelIds, page);
21167
+ const { data: queryPayload } = await client.http.get(`/api/v1/markers/channels`, {
21168
+ params: {
21169
+ channelIds,
21170
+ options: {
21171
+ token: toToken(page, 'skiplimit'),
21172
+ },
21173
+ },
21174
+ });
21175
+ const { paging } = queryPayload, payload = __rest(queryPayload, ["paging"]);
21176
+ const { userEntityMarkers, userMarkers } = payload;
21177
+ const cachedAt = client.cache && Date.now();
21178
+ if (client.cache)
21179
+ ingestInCache(payload, { cachedAt });
21180
+ userEntityMarkers.length && fireEvent('local.channelMarker.fetched', { userEntityMarkers });
21181
+ userMarkers.length && fireEvent('local.userMarker.fetched', { userMarkers });
21182
+ const nextPage = toPage(paging.next);
21183
+ const prevPage = toPage(paging.previous);
21184
+ return { data: userEntityMarkers, cachedAt, prevPage, nextPage };
21130
21185
  };
21131
21186
 
21132
- /* begin_public_function
21133
- id: user.get
21134
- */
21135
21187
  /**
21136
21188
  * ```js
21137
- * import { getUser } from '@amityco/ts-sdk'
21138
- * const { data: user } = await getUser('foobar')
21189
+ * import { getMessageMarkers } from '@amityco/ts-sdk'
21190
+ * const messageMarkers = await getMessageMarkers(['sch1', 'sch2'])
21139
21191
  * ```
21140
21192
  *
21141
- * Fetches a {@link Amity.User} object
21193
+ * Fetches a paginable list of {@link Amity.MessageMarker} objects
21142
21194
  *
21143
- * @param userId the ID of the {@link Amity.User} to fetch
21144
- * @returns the associated {@link Amity.User} object
21195
+ * @param messageIds the feed IDs of the {@link Amity.RawMessage} marker to fetch
21196
+ * @param page
21197
+ * @returns A page of {@link Amity.MessageMarker} objects
21145
21198
  *
21146
- * @category User API
21199
+ * @category Channel API
21147
21200
  * @async
21201
+ * @private
21148
21202
  */
21149
- const getUser = async (userId, isLive = false) => {
21203
+ const getMessageMarkers = async (messageIds, page = { limit: 100 }) => {
21150
21204
  const client = getActiveClient();
21151
- client.log('user/getUser', userId);
21152
- if (!isLive) {
21153
- console.log('getUser will be deprecated on 25th November 2022, please use liveUser instead.');
21154
- }
21155
- isInTombstone('user', userId);
21156
- let data;
21157
- try {
21158
- const response = await client.http.get(`/api/v3/users/${encodeURIComponent(userId)}`);
21159
- data = response.data;
21160
- }
21161
- catch (error) {
21162
- if (checkIfShouldGoesToTombstone(error === null || error === void 0 ? void 0 : error.code)) {
21163
- pushToTombstone('user', userId);
21164
- }
21165
- throw error;
21166
- }
21205
+ client.log('channel/getMessageMarkers', messageIds, page);
21206
+ const { data: queryPayload } = await client.http.get(`/api/v1/markers/messages`, {
21207
+ params: {
21208
+ messageIds,
21209
+ options: {
21210
+ token: toToken(page, 'skiplimit'),
21211
+ },
21212
+ },
21213
+ });
21214
+ const { paging } = queryPayload, payload = __rest(queryPayload, ["paging"]);
21215
+ const { contentMarkers, feedMarkers, userMarkers } = payload;
21167
21216
  const cachedAt = client.cache && Date.now();
21168
21217
  if (client.cache)
21169
- ingestInCache(data, { cachedAt });
21170
- const { users } = data;
21171
- fireEvent('user.fetched', data);
21172
- return {
21173
- data: users.find(user => user.userId === userId),
21174
- cachedAt,
21175
- };
21176
- };
21177
- /* end_public_function */
21218
+ ingestInCache(payload, { cachedAt });
21219
+ feedMarkers.length && fireEvent('local.feedMarker.fetched', { feedMarkers });
21220
+ contentMarkers.length && fireEvent('local.messageMarker.fetched', { contentMarkers });
21221
+ userMarkers.length && fireEvent('local.userMarker.fetched', { userMarkers });
21222
+ const nextPage = toPage(paging.next);
21223
+ const prevPage = toPage(paging.previous);
21224
+ return { data: contentMarkers, cachedAt, prevPage, nextPage };
21225
+ };
21226
+
21178
21227
  /**
21179
21228
  * ```js
21180
- * import { getUser } from '@amityco/ts-sdk'
21181
- * const { data: user } = getUser.locally('foobar')
21229
+ * import { getSubChannelMarkers } from '@amityco/ts-sdk'
21230
+ * const subChannelMarkers = await getSubChannelMarkers(['sch1', 'sch2'])
21182
21231
  * ```
21183
21232
  *
21184
- * Fetches a {@link Amity.User} object from cache
21233
+ * Fetches a paginable list of {@link Amity.SubChannelMarker} objects
21185
21234
  *
21186
- * @param userId the ID of the {@link Amity.User} to fetch
21187
- * @returns the associated {@link Amity.User} object
21235
+ * @param messageFeedIds the feed IDs of the {@link Amity.RawSubChannel} marker to fetch
21236
+ * @param page
21237
+ * @returns A page of {@link Amity.SubChannelMarker} objects
21188
21238
  *
21189
- * @category User API
21239
+ * @category Channel API
21240
+ * @async
21241
+ * @private
21190
21242
  */
21191
- getUser.locally = (userId) => {
21243
+ const getSubChannelMarkers = async (messageFeedIds, page = { limit: 100 }) => {
21192
21244
  const client = getActiveClient();
21193
- client.log('user/getUser.locally', userId);
21194
- return client.cache && pullFromCache(['user', 'get', userId]);
21245
+ client.log('channel/getSubChannelMarkers', messageFeedIds, page);
21246
+ const { data: queryPayload } = await client.http.get(`/api/v1/markers/message-feeds`, {
21247
+ params: {
21248
+ messageFeedIds,
21249
+ options: {
21250
+ token: toToken(page, 'skiplimit'),
21251
+ },
21252
+ },
21253
+ });
21254
+ const { paging } = queryPayload, payload = __rest(queryPayload, ["paging"]);
21255
+ const { userEntityMarkers, userFeedMarkers, userMarkers } = payload;
21256
+ const cachedAt = client.cache && Date.now();
21257
+ if (client.cache)
21258
+ ingestInCache(payload, { cachedAt });
21259
+ userEntityMarkers.length && fireEvent('local.channelMarker.fetched', { userEntityMarkers });
21260
+ userFeedMarkers.length && fireEvent('local.subChannelMarker.fetched', { userFeedMarkers });
21261
+ userMarkers.length && fireEvent('local.userMarker.fetched', { userMarkers });
21262
+ const nextPage = toPage(paging.next);
21263
+ const prevPage = toPage(paging.previous);
21264
+ return { data: userFeedMarkers, cachedAt, prevPage, nextPage };
21195
21265
  };
21196
21266
 
21197
- /* begin_public_function
21198
- id: user.get_by_ids
21199
- */
21200
- /**
21201
- * ```js
21202
- * import { getUsers } from '@amityco/ts-sdk'
21203
- * const { data: users } = await getUsers(['foo', 'bar'])
21204
- * ```
21205
- *
21206
- * Fetches a collection of {@link Amity.User} objects
21207
- *
21208
- * @param userIds the IDs of the {@link Amity.User} to fetch
21209
- * @returns the associated collection of {@link Amity.User} objects
21210
- *
21211
- * @category User API
21212
- * @async
21213
- */
21214
- const getUsers = async (userIds) => {
21267
+ const locally = () => {
21268
+ var _a, _b;
21215
21269
  const client = getActiveClient();
21216
- client.log('user/getUsers', userIds);
21217
- const encodedUserIds = userIds.map(userId => encodeURIComponent(userId));
21218
- // API-FIX: endpoint should not be /list, parameters should be querystring.
21219
- const { data } = await client.http.get(`/api/v3/users/list`, {
21220
- params: { userIds: encodedUserIds },
21221
- });
21270
+ const user = getActiveUser();
21271
+ client.log('marker/getUserMarker.locally');
21272
+ const { _id: userId } = user;
21273
+ if (!userId)
21274
+ throw new ASCError('The userId has not been defined in active client', 800000 /* Amity.ClientError.UNKNOWN_ERROR */, "error" /* Amity.ErrorLevel.ERROR */);
21275
+ const createdTime = new Date().toISOString();
21222
21276
  const cachedAt = client.cache && Date.now();
21223
- if (client.cache)
21224
- ingestInCache(data, { cachedAt });
21225
- fireEvent('user.fetched', data);
21277
+ const data = (_b = (_a = pullFromCache([
21278
+ 'userMarker',
21279
+ 'get',
21280
+ getResolver('userMarker')({ userId }),
21281
+ ])) === null || _a === void 0 ? void 0 : _a.data) !== null && _b !== void 0 ? _b : {
21282
+ userId,
21283
+ unreadCount: 0,
21284
+ lastSyncAt: createdTime,
21285
+ createdAt: createdTime,
21286
+ updatedAt: createdTime,
21287
+ };
21226
21288
  return {
21227
- data: data.users,
21289
+ data,
21228
21290
  cachedAt,
21229
21291
  };
21230
21292
  };
21231
- /**
21232
- * ```js
21233
- * import { getUsers } from '@amityco/ts-sdk'
21234
- * const { data: users } = getUsers.locally!(['foo', 'bar'])
21235
- * ```
21236
- *
21237
- * Fetches a collection of {@link Amity.User} objects from cache
21238
- *
21239
- * @param userIds the IDs of the {@link Amity.User} to fetch
21240
- * @returns the associated collection of {@link Amity.User} objects
21241
- *
21242
- * @category User API
21243
- */
21244
- getUsers.locally = (userIds) => {
21245
- var _a;
21246
- const client = getActiveClient();
21247
- client.log('user/getUsers.locally', userIds);
21248
- if (!client.cache)
21249
- return;
21250
- const cached = userIds
21251
- .map(userId => pullFromCache(['user', 'get', userId]))
21252
- .filter(Boolean);
21253
- const users = cached.map(({ data }) => data);
21254
- const oldest = (_a = cached.sort((a, b) => (a.cachedAt < b.cachedAt ? -1 : 1))) === null || _a === void 0 ? void 0 : _a[0];
21255
- if ((cached === null || cached === void 0 ? void 0 : cached.length) < userIds.length)
21256
- return;
21257
- return {
21258
- data: users,
21259
- cachedAt: oldest.cachedAt,
21260
- };
21261
- };
21262
-
21263
- /******************************************************************************
21264
- Copyright (c) Microsoft Corporation.
21265
-
21266
- Permission to use, copy, modify, and/or distribute this software for any
21267
- purpose with or without fee is hereby granted.
21268
-
21269
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
21270
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
21271
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
21272
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
21273
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
21274
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
21275
- PERFORMANCE OF THIS SOFTWARE.
21276
- ***************************************************************************** */
21277
-
21278
- function __rest(s, e) {
21279
- var t = {};
21280
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
21281
- t[p] = s[p];
21282
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
21283
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
21284
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
21285
- t[p[i]] = s[p[i]];
21286
- }
21287
- return t;
21288
- }
21289
-
21290
- /* begin_public_function
21291
- id: user.query, user.search
21292
- */
21293
- /**
21294
- * ```js
21295
- * import { queryUsers } from '@amityco/ts-sdk'
21296
- * const { data: users, prevPage, nextPage } = await queryUsers({ displayName: 'foo' })
21297
- * ```
21298
- *
21299
- * Queries a paginable list of {@link Amity.User} objects
21300
- * Search is performed by displayName such as `.startsWith(search)`
21301
- *
21302
- * @param query The query parameters
21303
- * @returns A page of {@link Amity.User} objects
21304
- *
21305
- * @category User API
21306
- * @async
21307
- */
21308
- const queryUsers = async (query = {}) => {
21309
- const client = getActiveClient();
21310
- client.log('user/queryUsers', query);
21311
- const { page = { limit: 10 }, displayName, filter = 'all', sortBy = 'displayName' } = query, params = __rest(query, ["page", "displayName", "filter", "sortBy"]);
21312
- const { data } = await client.http.get(`/api/v3/users`, {
21313
- params: Object.assign(Object.assign({}, params), { keyword: displayName, filter,
21314
- sortBy, options: {
21315
- token: toToken(page, 'skiplimit'),
21316
- } }),
21317
- });
21318
- // unpacking
21319
- const { paging } = data, payload = __rest(data, ["paging"]);
21320
- const { users } = payload;
21321
- const cachedAt = client.cache && Date.now();
21322
- if (client.cache) {
21323
- ingestInCache(payload, { cachedAt });
21324
- /*
21325
- * using query as cache key over params because if the keyword, filter, sort
21326
- * change the API will NOT cache results, when it should
21327
- */
21328
- const cacheKey = ['user', 'query', Object.assign(Object.assign({}, query), { options: Object.assign({}, page) })];
21329
- pushToCache(cacheKey, { users: users.map(getResolver('user')), paging });
21330
- }
21331
- fireEvent('user.fetched', data);
21332
- const prevPage = toPage(paging.previous);
21333
- const nextPage = toPage(paging.next);
21334
- return { data: users, cachedAt, prevPage, nextPage };
21293
+ const getUserMarker = () => {
21294
+ // API-FIX: backend should implement user marker get API
21295
+ return Promise.resolve(locally());
21335
21296
  };
21336
- /* end_public_function */
21297
+ getUserMarker.locally = locally;
21298
+
21337
21299
  /**
21338
21300
  * ```js
21339
- * import { queryUsers } from '@amityco/ts-sdk'
21340
- * const { data: users } = queryUsers.locally({ keyword: 'foo' })
21301
+ * import { onChannelMarkerFetched } from '@amityco/ts-sdk'
21302
+ * const dispose = onChannelMarkerFetched(channelMarker => {
21303
+ * // ...
21304
+ * })
21341
21305
  * ```
21342
21306
  *
21343
- * Queries a paginable list of {@link Amity.User} objects from cache
21344
- * Search is performed by displayName such as `.startsWith(search)`
21307
+ * Fired when an {@link Amity.ChannelMarker} has been fetched
21345
21308
  *
21346
- * @param query The query parameters
21347
- * @returns A page of {@link Amity.User} objects
21309
+ * @param callback The function to call when the event was fired
21310
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
21348
21311
  *
21349
- * @category User API
21312
+ * @category ChannelMarker Events
21350
21313
  */
21351
- queryUsers.locally = (query = {}) => {
21352
- var _a, _b, _c;
21314
+ const onChannelMarkerFetched = (callback) => {
21353
21315
  const client = getActiveClient();
21354
- client.log('user/queryUsers.locally', query);
21355
- if (!client.cache)
21356
- return;
21357
- const { page = { limit: 10 } } = query !== null && query !== void 0 ? query : {};
21358
- const cacheKey = [
21359
- 'user',
21360
- 'query',
21361
- Object.assign(Object.assign({}, query), { options: Object.assign({}, page) }),
21362
- ];
21363
- const { data, cachedAt } = (_a = pullFromCache(cacheKey)) !== null && _a !== void 0 ? _a : {};
21364
- const users = (_b = data === null || data === void 0 ? void 0 : data.users.map(userId => pullFromCache(['user', 'get', userId])).filter(Boolean).map(({ data }) => data)) !== null && _b !== void 0 ? _b : [];
21365
- const prevPage = toPage(data === null || data === void 0 ? void 0 : data.paging.previous);
21366
- const nextPage = toPage(data === null || data === void 0 ? void 0 : data.paging.next);
21367
- return users.length > 0 && users.length === ((_c = data === null || data === void 0 ? void 0 : data.users) === null || _c === void 0 ? void 0 : _c.length)
21368
- ? { data: users, cachedAt, prevPage, nextPage }
21369
- : undefined;
21316
+ const filter = (payload) => {
21317
+ callback(payload.userEntityMarkers[0]);
21318
+ };
21319
+ return createEventSubscriber(client, 'channelMarker/onChannelMarkerFetched', 'local.channelMarker.fetched', filter);
21370
21320
  };
21371
21321
 
21372
- /* begin_public_function
21373
- id: client.update_user
21374
- */
21375
21322
  /**
21376
21323
  * ```js
21377
- * import { updateUser } from '@amityco/ts-sdk'
21378
- * const updated = await updateUser(userId, { displayName: 'foobar' })
21324
+ * import { onSubChannelMarkerFetched } from '@amityco/ts-sdk'
21325
+ * const dispose = onSubChannelMarkerFetched(subChannelMarker => {
21326
+ * // ...
21327
+ * })
21379
21328
  * ```
21380
21329
  *
21381
- * Updates an {@link Amity.User}
21330
+ * Fired when an {@link Amity.SubChannelMarker} has been fetched
21382
21331
  *
21383
- * @param userId The ID of the {@link Amity.User} to update
21384
- * @param patch The patch data to apply
21385
- * @returns the updated {@link Amity.User} object
21332
+ * @param callback The function to call when the event was fired
21333
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
21386
21334
  *
21387
- * @category User API
21388
- * @async
21335
+ * @category SubChannelMarker Events
21389
21336
  */
21390
- const updateUser = async (userId, patch) => {
21337
+ const onSubChannelMarkerFetched = (callback) => {
21391
21338
  const client = getActiveClient();
21392
- client.log('user/updateUser', userId, patch);
21393
- // API-FIX: Endpoint is malformed, userId should be a url param.
21394
- /*
21395
- const { data } = await client.http.put<Amity.Response<UserPayload>>(
21396
- `/api/v3/users/${userId}`, patch,
21397
- )
21398
- */
21399
- const { data } = await client.http.put(`/api/v3/users/`, Object.assign(Object.assign({ userId }, patch), { createNewUserWhenNotFound: false }));
21400
- const cachedAt = client.cache && Date.now();
21401
- if (client.cache)
21402
- ingestInCache(data, { cachedAt });
21403
- const { users } = data;
21404
- fireEvent('user.updated', data);
21405
- return {
21406
- data: users.find(user => user.userId === userId),
21407
- cachedAt,
21339
+ const filter = (payload) => {
21340
+ callback(payload.userFeedMarkers[0]);
21408
21341
  };
21409
- };
21410
- /* end_public_function */
21342
+ return createEventSubscriber(client, 'subChannelMarker/onSubChannelMarkerFetched', 'local.subChannelMarker.fetched', filter);
21343
+ };
21411
21344
 
21412
21345
  /**
21413
21346
  * ```js
21414
- * import { onUserUpdated } from '@amityco/ts-sdk'
21415
- * const dispose = onUserUpdated(user => {
21347
+ * import { onSubChannelMarkerUpdated } from '@amityco/ts-sdk'
21348
+ * const dispose = onSubChannelMarkerUpdated(subChannelMarker => {
21416
21349
  * // ...
21417
21350
  * })
21418
21351
  * ```
21419
21352
  *
21420
- * Fired when a {@link Amity.User} has been updated
21353
+ * Fired when an {@link Amity.SubChannelMarker} has been updated
21421
21354
  *
21422
21355
  * @param callback The function to call when the event was fired
21423
21356
  * @returns an {@link Amity.Unsubscriber} function to stop listening
21424
21357
  *
21425
- * @category User Events
21358
+ * @category SubChannelMarker Events
21426
21359
  */
21427
- const onUserUpdated = (callback) => createUserEventSubscriber('user.updated', callback);
21360
+ const onSubChannelMarkerUpdated = (callback) => {
21361
+ const client = getActiveClient();
21362
+ const filter = (payload) => {
21363
+ callback(payload.userFeedMarkers[0]);
21364
+ };
21365
+ return createEventSubscriber(client, 'subChannelMarker/onSubChannelMarkerUpdated', 'local.subChannelMarker.updated', filter);
21366
+ };
21428
21367
 
21429
21368
  /**
21430
21369
  * ```js
21431
- * import { onUserFlagged } from '@amityco/ts-sdk'
21432
- * const dispose = onUserFlagged(user => {
21370
+ * import { onFeedMarkerFetched } from '@amityco/ts-sdk'
21371
+ * const dispose = onFeedMarkerFetched(feedMarker => {
21433
21372
  * // ...
21434
21373
  * })
21435
21374
  * ```
21436
21375
  *
21437
- * Fired when a {@link Amity.User} has been flagged
21376
+ * Fired when an {@link Amity.FeedMarker} has been fetched
21438
21377
  *
21439
21378
  * @param callback The function to call when the event was fired
21440
21379
  * @returns an {@link Amity.Unsubscriber} function to stop listening
21441
21380
  *
21442
- * @category User Events
21381
+ * @category FeedMarker Events
21443
21382
  */
21444
- const onUserFlagged = (callback) => createUserEventSubscriber('user.flagged', callback);
21383
+ const onFeedMarkerFetched = (callback) => {
21384
+ const client = getActiveClient();
21385
+ const filter = (payload) => {
21386
+ callback(payload.feedMarkers[0]);
21387
+ };
21388
+ return createEventSubscriber(client, 'feedMarker/onFeedMarkerFetched', 'local.feedMarker.fetched', filter);
21389
+ };
21445
21390
 
21446
21391
  /**
21447
21392
  * ```js
21448
- * import { onUserUnflagged } from '@amityco/ts-sdk'
21449
- * const dispose = onUserUnflagged(user => {
21393
+ * import { onUserMarkerFetched } from '@amityco/ts-sdk'
21394
+ * const dispose = onUserMarkerFetched(userMarker => {
21450
21395
  * // ...
21451
21396
  * })
21452
21397
  * ```
21453
21398
  *
21454
- * Fired when a flag has been removed from a {@link Amity.User}
21399
+ * Fired when an {@link Amity.UserMarker} has been fetched
21455
21400
  *
21456
21401
  * @param callback The function to call when the event was fired
21457
21402
  * @returns an {@link Amity.Unsubscriber} function to stop listening
21458
21403
  *
21459
- * @category User Events
21404
+ * @category UserMarker Events
21460
21405
  */
21461
- const onUserUnflagged = (callback) => createUserEventSubscriber('user.unflagged', callback);
21406
+ const onUserMarkerFetched = (callback) => {
21407
+ const client = getActiveClient();
21408
+ const filter = (payload) => {
21409
+ callback(payload.userMarkers[0]);
21410
+ };
21411
+ return createEventSubscriber(client, 'userMarker/onUserMarkerFetched', 'local.userMarker.fetched', filter);
21412
+ };
21462
21413
 
21463
21414
  /**
21464
21415
  * ```js
21465
- * import { onUserFlagCleared } from '@amityco/ts-sdk'
21466
- * const dispose = onUserFlagCleared(user => {
21416
+ * import { onMessageMarkerFetched } from '@amityco/ts-sdk'
21417
+ * const dispose = onMessageMarkerFetched(messageMarker => {
21467
21418
  * // ...
21468
21419
  * })
21469
21420
  * ```
21470
21421
  *
21471
- * Fired when flags have been cleared for a {@link Amity.User}
21422
+ * Fired when an {@link Amity.MessageMarker} has been fetched
21472
21423
  *
21473
21424
  * @param callback The function to call when the event was fired
21474
21425
  * @returns an {@link Amity.Unsubscriber} function to stop listening
21475
21426
  *
21476
- * @category User Events
21427
+ * @category MessageMarker Events
21477
21428
  */
21478
- const onUserFlagCleared = (callback) => createUserEventSubscriber('user.flagCleared', callback);
21429
+ const onMessageMarkerFetched = (callback) => {
21430
+ const client = getActiveClient();
21431
+ const filter = (payload) => {
21432
+ callback(payload.contentMarkers[0]);
21433
+ };
21434
+ return createEventSubscriber(client, 'messageMarker/onMessageMarkerFetched', 'local.messageMarker.fetched', filter);
21435
+ };
21479
21436
 
21480
- const liveObject = (id, callback, key, fetcher, eventHandlers) => {
21437
+ const liveObject = (id, callback, key, fetcher, eventHandlers, callbackDataSelector = data => data, callbackFilter) => {
21481
21438
  const { cache } = getActiveClient();
21482
21439
  if (!cache) {
21483
21440
  console.log(LIVE_OBJECT_ENABLE_CACHE_MESSAGE);
@@ -21486,8 +21443,11 @@ const liveObject = (id, callback, key, fetcher, eventHandlers) => {
21486
21443
  let isUnsyncedModel = false; // for messages
21487
21444
  const disposers = [];
21488
21445
  const dispatcher = (data) => {
21489
- model = data.data;
21490
- callback(data);
21446
+ const { data: newModel } = data, rest = __rest(data, ["data"]);
21447
+ if (!callbackFilter || callbackFilter(newModel, model)) {
21448
+ callback(Object.assign({ data: callbackDataSelector(newModel) }, rest));
21449
+ }
21450
+ model = newModel;
21491
21451
  };
21492
21452
  const realtimeRouter = (eventModel) => {
21493
21453
  if (id !== eventModel[key]) {
@@ -21531,22 +21491,1255 @@ const liveObject = (id, callback, key, fetcher, eventHandlers) => {
21531
21491
 
21532
21492
  /**
21533
21493
  * ```js
21534
- * import { onUserFetched } from '@amityco/ts-sdk'
21535
- * const dispose = onUserFetched(user => {
21536
- * // ...
21537
- * })
21494
+ * import { getTotalUnreadCount } from '@amityco/ts-sdk';
21495
+ *
21496
+ * const unsubscribe = getTotalUnreadCount(response => {
21497
+ * totalUnreadCount = response.data;
21498
+ * });
21538
21499
  * ```
21539
21500
  *
21540
- * Fired when a {@link Amity.User} has been fetched
21501
+ * Observe current user's unread count from {@link Amity.UserMarker}
21541
21502
  *
21542
- * @param callback The function to call when the event was fired
21543
- * @returns an {@link Amity.Unsubscriber} function to stop listening
21503
+ * @param callback the function to call when new data are available
21504
+ * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the events
21544
21505
  *
21545
- * @category User Events
21506
+ * @category Message Live Object
21546
21507
  */
21547
- const onUserFetched = (callback) => createUserEventSubscriber('user.fetched', callback);
21508
+ const getTotalUnreadCount = (callback) => {
21509
+ const { _id: userId } = getActiveUser();
21510
+ if (!userId)
21511
+ throw new ASCError('The _id has not been defined in ActiveUser', 800000 /* Amity.ClientError.UNKNOWN_ERROR */, "error" /* Amity.ErrorLevel.ERROR */);
21512
+ const callbackPayloadSelector = (data) => { var _a; return (_a = data === null || data === void 0 ? void 0 : data.unreadCount) !== null && _a !== void 0 ? _a : 0; };
21513
+ // based on the mobile specs, unreadCount will not trigger observer when userMarker
21514
+ // is re-fetched, so apply this filter to ensure the behavior is the same.
21515
+ const callbackFilter = (newModel, oldModel) => (newModel === null || newModel === void 0 ? void 0 : newModel.unreadCount) !== (oldModel === null || oldModel === void 0 ? void 0 : oldModel.unreadCount);
21516
+ return liveObject(userId, callback, 'userId', getUserMarker, [onUserMarkerFetched], callbackPayloadSelector, callbackFilter);
21517
+ };
21548
21518
 
21549
- /**
21519
+ /** @hidden */
21520
+ /*
21521
+ * @param message payload from http request without myReactions
21522
+ * add myReactions to http response if the event was a reaction event
21523
+ */
21524
+ const prepareMessagePayloadForCache = (payload) => {
21525
+ const client = getActiveClient();
21526
+ const cached = pullFromCache(['message', 'get', payload.messageId]);
21527
+ // '[]' in cases where the new reaction is the first one
21528
+ const myReactions = (cached === null || cached === void 0 ? void 0 : cached.data.myReactions) || [];
21529
+ // add myReactions to the payload
21530
+ Object.assign(payload, { myReactions });
21531
+ // check if there are any updates to the reactions
21532
+ const latestReaction = payload === null || payload === void 0 ? void 0 : payload.latestReaction;
21533
+ const isLatestReactionMine = latestReaction && latestReaction.userId === client.userId;
21534
+ if (!isLatestReactionMine) {
21535
+ return;
21536
+ }
21537
+ // new reaction added
21538
+ if (latestReaction.eventName === 'add' && !myReactions.includes(latestReaction.reactionName)) {
21539
+ Object.assign(payload, {
21540
+ myReactions: [...myReactions, latestReaction.reactionName],
21541
+ });
21542
+ }
21543
+ // existing reaction removed
21544
+ if (latestReaction.eventName === 'remove' && myReactions.includes(latestReaction.reactionName)) {
21545
+ Object.assign(payload, {
21546
+ myReactions: myReactions.filter(x => x !== latestReaction.reactionName),
21547
+ });
21548
+ }
21549
+ };
21550
+
21551
+ const getCachedMarker$1 = (message) => {
21552
+ var _a, _b;
21553
+ const key = {
21554
+ creatorId: message.creatorId,
21555
+ feedId: (_a = message.messageFeedId) !== null && _a !== void 0 ? _a : message.subChannelId,
21556
+ contentId: message.messageId,
21557
+ };
21558
+ return (_b = pullFromCache([
21559
+ 'messageMarker',
21560
+ 'get',
21561
+ getResolver('messageMarker')(key),
21562
+ ])) === null || _b === void 0 ? void 0 : _b.data;
21563
+ };
21564
+ const getReadCount = (message, marker) => {
21565
+ var _a;
21566
+ // Look in the marker param first
21567
+ return (_a = marker !== null && marker !== void 0 ? marker :
21568
+ // If the marker param is not set, look in the cache
21569
+ getCachedMarker$1(message)) !== null && _a !== void 0 ? _a : { readCount: 0, deliveredCount: 0 };
21570
+ }; // and if not found in cache use default value `0`
21571
+ function convertFromRaw$2(message, marker) {
21572
+ const { channelPublicId, childCount, creatorPublicId, mentionedUsers, messageFeedId, myReactions, reactionCount, reactions, referenceId, segment, messageId } = message, rest = __rest(message, ["channelPublicId", "childCount", "creatorPublicId", "mentionedUsers", "messageFeedId", "myReactions", "reactionCount", "reactions", "referenceId", "segment", "messageId"]);
21573
+ const { readCount, deliveredCount } = getReadCount(message, marker);
21574
+ let cache;
21575
+ if (referenceId) {
21576
+ cache = pullFromCache(['message', 'get', referenceId]);
21577
+ }
21578
+ if (!cache) {
21579
+ cache = pullFromCache(['message', 'get', messageId]);
21580
+ }
21581
+ const out = Object.assign(Object.assign({}, rest), { messageId, channelId: channelPublicId, channelSegment: segment, childrenNumber: childCount, creatorId: creatorPublicId, reactions: reactions !== null && reactions !== void 0 ? reactions : {}, reactionsCount: reactionCount, subChannelId: messageFeedId, uniqueId: cache ? cache.data.uniqueId : messageId, readCount,
21582
+ deliveredCount });
21583
+ if (mentionedUsers) {
21584
+ out.mentionees = mentionedUsers.map(mention => {
21585
+ if (mention.type === 'channel') {
21586
+ return mention;
21587
+ }
21588
+ return { type: 'user', userIds: mention.userPublicIds };
21589
+ });
21590
+ }
21591
+ if (myReactions) {
21592
+ // http response
21593
+ out.myReactions = myReactions;
21594
+ }
21595
+ else {
21596
+ // mqtt event
21597
+ prepareMessagePayloadForCache(out);
21598
+ }
21599
+ return out;
21600
+ }
21601
+ function updateMessageMarker(message, marker) {
21602
+ const { readCount, deliveredCount } = getReadCount(message, marker);
21603
+ return Object.assign(Object.assign({}, message), { readCount,
21604
+ deliveredCount, updatedAt: new Date().toISOString() });
21605
+ }
21606
+ const prepareMessagePayload = async (payload) => {
21607
+ // make a fetch marker to prepare it for merging with the raw message payload.
21608
+ let markers = [];
21609
+ const markerIds = payload.messages.map(({ messageId }) => messageId);
21610
+ if (markerIds.length > 0)
21611
+ // from the spec, allow marker fetch to fail
21612
+ try {
21613
+ ({ data: markers } = await getMessageMarkers(markerIds));
21614
+ }
21615
+ catch (e) {
21616
+ // empty block
21617
+ }
21618
+ return Object.assign(Object.assign({}, payload), { messages: payload.messages.map(message => {
21619
+ const marker = markers === null || markers === void 0 ? void 0 : markers.find(({ contentId }) => contentId === message.messageId);
21620
+ return convertFromRaw$2(message, marker);
21621
+ }) });
21622
+ };
21623
+ function convertParams(_a) {
21624
+ var { subChannelId, mentionees } = _a, rest = __rest(_a, ["subChannelId", "mentionees"]);
21625
+ return Object.assign({ messageFeedId: subChannelId, mentionedUsers: mentionees }, rest);
21626
+ }
21627
+ function convertQueryParams$1(_a) {
21628
+ var { page, sortBy, subChannelId, tags, includeDeleted } = _a, rest = __rest(_a, ["page", "sortBy", "subChannelId", "tags", "includeDeleted"]);
21629
+ const out = Object.assign(Object.assign({}, rest), { messageFeedId: subChannelId, isDeleted: includeDeleted === false ? false : undefined, options: { token: toToken(page || { limit: 10 }, 'afterbeforeraw') } });
21630
+ if (sortBy !== undefined) {
21631
+ out.options.sortBy = sortBy;
21632
+ }
21633
+ if (tags) {
21634
+ out.includeTags = tags;
21635
+ }
21636
+ return out;
21637
+ }
21638
+
21639
+ /**
21640
+ * ```js
21641
+ * import { onMessageCreated } from '@amityco/ts-sdk'
21642
+ * const dispose = onMessageCreated(message => {
21643
+ * // ...
21644
+ * })
21645
+ * ```
21646
+ *
21647
+ * Fired when an {@link Amity.Message} has been created
21648
+ *
21649
+ * @param callback The function to call when the event was fired
21650
+ * @param local Trigger when an event occurs from a local event or not
21651
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
21652
+ *
21653
+ * @category Message Events
21654
+ */
21655
+ const onMessageCreated = (callback, local = true) => {
21656
+ const client = getActiveClient();
21657
+ const filter = async (rawPayload) => {
21658
+ const payload = await prepareMessagePayload(rawPayload);
21659
+ const message = payload.messages[0];
21660
+ ingestInCache(payload);
21661
+ callback(message);
21662
+ };
21663
+ const disposers = [
21664
+ createEventSubscriber(client, 'message/onMessageCreated', 'message.created', filter),
21665
+ ];
21666
+ if (local) {
21667
+ createEventSubscriber(client, 'message/onMessageCreated', 'local.message.created', payload => callback(payload.messages[0]));
21668
+ }
21669
+ return () => {
21670
+ disposers.forEach(fn => fn());
21671
+ };
21672
+ };
21673
+
21674
+ /**
21675
+ * ```js
21676
+ * import { onMessageUpdated } from '@amityco/ts-sdk'
21677
+ * const dispose = onMessageUpdated(message => {
21678
+ * // ...
21679
+ * })
21680
+ * ```
21681
+ *
21682
+ * Fired when an {@link Amity.Message} has been updated
21683
+ *
21684
+ * @param callback The function to call when the event was fired
21685
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
21686
+ *
21687
+ * @category Message Events
21688
+ */
21689
+ const onMessageUpdated = (callback) => {
21690
+ const client = getActiveClient();
21691
+ const filter = async (rawPayload) => {
21692
+ const payload = await prepareMessagePayload(rawPayload);
21693
+ ingestInCache(payload);
21694
+ callback(payload.messages[0]);
21695
+ };
21696
+ const messageMarkerChangeHandler = async (rawPayload) => {
21697
+ var _a;
21698
+ const marker = rawPayload.contentMarkers[0];
21699
+ const cacheKey = ['message', 'get', marker.contentId];
21700
+ const message = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
21701
+ if (!message)
21702
+ return;
21703
+ const updated = updateMessageMarker(message, marker);
21704
+ upsertInCache(cacheKey, updated);
21705
+ callback(updated);
21706
+ };
21707
+ const disposers = [
21708
+ createEventSubscriber(client, 'onMessageUpdated', 'message.updated', filter),
21709
+ createEventSubscriber(client, 'onMessageUpdated', 'local.message.updated', payload => callback(payload.messages[0])),
21710
+ createEventSubscriber(client, 'onMessageUpdated', 'local.messageMarker.fetched', messageMarkerChangeHandler),
21711
+ ];
21712
+ return () => {
21713
+ disposers.forEach(fn => fn());
21714
+ };
21715
+ };
21716
+
21717
+ /**
21718
+ * ```js
21719
+ * import { onMessageDeleted } from '@amityco/ts-sdk'
21720
+ * const dispose = onMessageDeleted(message => {
21721
+ * // ...
21722
+ * })
21723
+ * ```
21724
+ *
21725
+ * Fired when an {@link Amity.Message} was deleted
21726
+ *
21727
+ * @param callback The function to call when the event was fired
21728
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
21729
+ *
21730
+ * @category Message Events
21731
+ */
21732
+ const onMessageDeleted = (callback) => {
21733
+ const client = getActiveClient();
21734
+ const filter = async (rawPayload) => {
21735
+ const payload = await prepareMessagePayload(rawPayload);
21736
+ ingestInCache(payload);
21737
+ callback(payload.messages[0]);
21738
+ };
21739
+ const disposers = [
21740
+ createEventSubscriber(client, 'message/onMessageDeleted', 'message.deleted', filter),
21741
+ createEventSubscriber(client, 'local.message.deleted', 'local.message.deleted', payload => callback(payload.messages[0])),
21742
+ ];
21743
+ return () => {
21744
+ disposers.forEach(fn => fn());
21745
+ };
21746
+ };
21747
+
21748
+ /**
21749
+ * ```js
21750
+ * import { onMessageFlagged } from '@amityco/ts-sdk'
21751
+ * const dispose = onMessageFlagged(message => {
21752
+ * // ...
21753
+ * })
21754
+ * ```
21755
+ *
21756
+ * Fired when a {@link Amity.Message} has been flagged
21757
+ *
21758
+ * @param callback The function to call when the event was fired
21759
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
21760
+ *
21761
+ * @category Message Events
21762
+ */
21763
+ const onMessageFlagged = (callback) => {
21764
+ const client = getActiveClient();
21765
+ const filter = async (rawPayload) => {
21766
+ const payload = await prepareMessagePayload(rawPayload);
21767
+ ingestInCache(payload);
21768
+ callback(payload.messages[0]);
21769
+ };
21770
+ return createEventSubscriber(client, 'onMessageFlagged', 'message.flagged', filter);
21771
+ };
21772
+
21773
+ /**
21774
+ * ```js
21775
+ * import { onMessageUnflagged } from '@amityco/ts-sdk'
21776
+ * const dispose = onMessageUnflagged(message => {
21777
+ * // ...
21778
+ * })
21779
+ * ```
21780
+ *
21781
+ * Fired when a flag has been removed from a {@link Amity.Message}
21782
+ *
21783
+ * @param callback The function to call when the event was fired
21784
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
21785
+ *
21786
+ * @category Message Events
21787
+ */
21788
+ const onMessageUnflagged = (callback) => {
21789
+ const client = getActiveClient();
21790
+ const filter = async (rawPayload) => {
21791
+ const payload = await prepareMessagePayload(rawPayload);
21792
+ ingestInCache(payload);
21793
+ callback(payload.messages[0]);
21794
+ };
21795
+ return createEventSubscriber(client, 'onMessageUnflagged', 'message.unflagged', filter);
21796
+ };
21797
+
21798
+ /**
21799
+ * ```js
21800
+ * import { onMessageFlagCleared } from '@amityco/ts-sdk'
21801
+ * const dispose = onMessageFlagCleared(message => {
21802
+ * // ...
21803
+ * })
21804
+ * ```
21805
+ *
21806
+ * Fired when flags have been cleared for a {@link Amity.Message}
21807
+ *
21808
+ * @param callback The function to call when the event was fired
21809
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
21810
+ *
21811
+ * @category Message Events
21812
+ */
21813
+ const onMessageFlagCleared = (callback) => {
21814
+ const client = getActiveClient();
21815
+ const filter = async (rawPayload) => {
21816
+ const payload = await prepareMessagePayload(rawPayload);
21817
+ ingestInCache(payload);
21818
+ callback(payload.messages[0]);
21819
+ };
21820
+ return createEventSubscriber(client, 'onMessageFlagCleared', 'message.flagCleared', filter);
21821
+ };
21822
+
21823
+ /**
21824
+ * ```js
21825
+ * import { onMessageReactionAdded } from '@amityco/ts-sdk';
21826
+ *
21827
+ * const unsubscribe = onMessageReactionAdded(message => {
21828
+ * // ...
21829
+ * });
21830
+ * ```
21831
+ *
21832
+ * Fired when a {@link Amity.Message} has been reacted
21833
+ *
21834
+ * @param callback The function to call when the event was fired
21835
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
21836
+ *
21837
+ * @category Post Events
21838
+ */
21839
+ const onMessageReactionAdded = (callback) => {
21840
+ const client = getActiveClient();
21841
+ const filter = async (rawPayload) => {
21842
+ const payload = await prepareMessagePayload(rawPayload);
21843
+ ingestInCache(payload);
21844
+ callback(payload.messages[0]);
21845
+ };
21846
+ return createEventSubscriber(client, 'onMessageReactionAdded', 'message.reactionAdded', filter);
21847
+ };
21848
+
21849
+ /**
21850
+ * ```js
21851
+ * import { onMessageReactionRemoved } from '@amityco/ts-sdk';
21852
+ *
21853
+ * const unsubscribe = onMessageReactionRemoved(message => {
21854
+ * // ...
21855
+ * });
21856
+ * ```
21857
+ *
21858
+ * Fired when a reaction has been removed from a {@link Amity.Message}
21859
+ *
21860
+ * @param callback The function to call when the event was fired
21861
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
21862
+ *
21863
+ * @category Post Events
21864
+ */
21865
+ const onMessageReactionRemoved = (callback) => {
21866
+ const client = getActiveClient();
21867
+ const filter = async (rawPayload) => {
21868
+ const payload = await prepareMessagePayload(rawPayload);
21869
+ ingestInCache(payload);
21870
+ callback(payload.messages[0]);
21871
+ };
21872
+ return createEventSubscriber(client, 'onMessageReactionRemoved', 'message.reactionRemoved', filter);
21873
+ };
21874
+
21875
+ /**
21876
+ * ```js
21877
+ * import { onMessageFetched } from '@amityco/ts-sdk'
21878
+ * const dispose = onMessageFetched(message => {
21879
+ * // ...
21880
+ * })
21881
+ * ```
21882
+ *
21883
+ * Fired when an {@link Amity.Message} has been fetched
21884
+ *
21885
+ * @param callback The function to call when the event was fired
21886
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
21887
+ *
21888
+ * @category Message Events
21889
+ */
21890
+ const onMessageFetched = (callback) => {
21891
+ const client = getActiveClient();
21892
+ const filter = (payload) => {
21893
+ ingestInCache(payload);
21894
+ callback(payload.messages[0]);
21895
+ };
21896
+ return createEventSubscriber(client, 'message/onMessageFetched', 'local.message.fetched', filter);
21897
+ };
21898
+
21899
+ const MARKER_INCLUDED_SUB_CHANNEL_TYPE = ['broadcast', 'conversation', 'community'];
21900
+ /**
21901
+ * Filter sub channel by type. Only conversation, community and broadcast type are included.
21902
+ */
21903
+ const isUnreadCountSupport$1 = ({ channelType }) => MARKER_INCLUDED_SUB_CHANNEL_TYPE.includes(channelType);
21904
+ function getUnreadCount$1(channelId, subChannelId, marker) {
21905
+ var _a;
21906
+ // Look for `unreadCount` in the marker param first
21907
+ if (marker) {
21908
+ return marker.unreadCount;
21909
+ }
21910
+ const key = {
21911
+ entityId: channelId,
21912
+ feedId: subChannelId,
21913
+ userId: getActiveUser()._id,
21914
+ };
21915
+ // If the marker param is not set, look in the cache
21916
+ const cachedMarker = (_a = pullFromCache([
21917
+ 'subChannelMarker',
21918
+ 'get',
21919
+ getResolver('subChannelMarker')(key),
21920
+ ])) === null || _a === void 0 ? void 0 : _a.data;
21921
+ if (cachedMarker) {
21922
+ return cachedMarker.unreadCount;
21923
+ }
21924
+ // and if not found in cache use default value `0`
21925
+ return 0;
21926
+ }
21927
+ function convertFromRaw$1(_a, marker) {
21928
+ var { channelId, channelPublicId, channelType, childCount, creatorId, creatorPublicId, lastMessageId, lastMessageTimestamp, messageFeedId, name } = _a, rest = __rest(_a, ["channelId", "channelPublicId", "channelType", "childCount", "creatorId", "creatorPublicId", "lastMessageId", "lastMessageTimestamp", "messageFeedId", "name"]);
21929
+ return Object.assign(Object.assign({}, rest), { channelId: channelPublicId, creatorId: creatorPublicId, displayName: name, lastActivity: lastMessageTimestamp, latestMessageId: lastMessageId, messageCount: childCount, subChannelId: messageFeedId, isUnreadCountSupport: isUnreadCountSupport$1({ channelType }), unreadCount: getUnreadCount$1(channelId, messageFeedId, marker) });
21930
+ }
21931
+ function updateSubChannelMarker(subChannel, marker) {
21932
+ return Object.assign(Object.assign({}, subChannel), { unreadCount: getUnreadCount$1(subChannel.channelId, subChannel.subChannelId, marker), updatedAt: new Date().toISOString() });
21933
+ }
21934
+ const prepareSubChannelPayload = async (rawPayload) => {
21935
+ // make a fetch marker to prepare it for merging with the raw channel payload.
21936
+ let markers = [];
21937
+ const markerIds = rawPayload.messageFeeds
21938
+ .filter(isUnreadCountSupport$1)
21939
+ .map(({ messageFeedId }) => messageFeedId);
21940
+ if (markerIds.length > 0)
21941
+ // from the spec, allow marker fetch to fail
21942
+ try {
21943
+ ({ data: markers } = await getSubChannelMarkers(markerIds));
21944
+ }
21945
+ catch (e) {
21946
+ // empty block
21947
+ }
21948
+ // attach marker to sub channel
21949
+ const messageFeeds = rawPayload.messageFeeds.map(messageFeed => {
21950
+ const marker = markers === null || markers === void 0 ? void 0 : markers.find(({ feedId }) => feedId === messageFeed.messageFeedId);
21951
+ return convertFromRaw$1(messageFeed, marker);
21952
+ });
21953
+ return Object.assign(Object.assign({}, rawPayload), { messageFeeds });
21954
+ };
21955
+ function convertQueryParams(_a) {
21956
+ var { excludeDefaultSubChannel } = _a, rest = __rest(_a, ["excludeDefaultSubChannel"]);
21957
+ const out = Object.assign({}, rest);
21958
+ if (excludeDefaultSubChannel !== undefined) {
21959
+ out.excludeDefaultMessageFeed = excludeDefaultSubChannel;
21960
+ }
21961
+ return out;
21962
+ }
21963
+
21964
+ /**
21965
+ * ```js
21966
+ * import { SubChannel } from '@amityco/ts-sdk'
21967
+ * const success = await SubChannel('foo')
21968
+ * ```
21969
+ *
21970
+ * Mark all messages as read and start reading message inside channel
21971
+ *
21972
+ * @param messageFeedId - The sub channel ID to start reading.
21973
+ * @return A success boolean if reading of the sub channel had begun.
21974
+ *
21975
+ * @category Channel API
21976
+ * @async
21977
+ * @private
21978
+ */
21979
+ const startReadingAPI = async (messageFeedId) => {
21980
+ const client = getActiveClient();
21981
+ client.log('channel/startReadingAPI', messageFeedId);
21982
+ const { data: payload } = await client.http.post(`/api/v1/markers/message-feeds/${messageFeedId}/start-reading`);
21983
+ const cachedAt = client.cache && Date.now();
21984
+ if (client.cache)
21985
+ ingestInCache(payload, { cachedAt });
21986
+ return true;
21987
+ };
21988
+
21989
+ /**
21990
+ * ```js
21991
+ * import { stopReading } from '@amityco/ts-sdk'
21992
+ * const success = await stopReading('foo')
21993
+ * ```
21994
+ *
21995
+ * Mark all messages as read and stop reading message inside channel
21996
+ *
21997
+ * @param messageFeedId - The sub channel ID to stop reading.
21998
+ * @return A success boolean if reading of the sub channel had begun.
21999
+ *
22000
+ * @category Channel API
22001
+ * @async
22002
+ * @private
22003
+ */
22004
+ const stopReadingAPI = async (messageFeedId) => {
22005
+ const client = getActiveClient();
22006
+ client.log('channel/stopReadingAPI', messageFeedId);
22007
+ const { data: payload } = await client.http.post(`/api/v1/markers/message-feeds/${messageFeedId}/stop-reading`);
22008
+ const cachedAt = client.cache && Date.now();
22009
+ if (client.cache)
22010
+ ingestInCache(payload, { cachedAt });
22011
+ return true;
22012
+ };
22013
+
22014
+ let disposers$1 = [];
22015
+ const isReadingMap = {};
22016
+ const updateReadToSegment = (message) => {
22017
+ var _a;
22018
+ if (!isReadingMap[message.subChannelId])
22019
+ return;
22020
+ const client = getActiveClient();
22021
+ if (!client.cache)
22022
+ return;
22023
+ const key = {
22024
+ entityId: message.channelId,
22025
+ feedId: message.subChannelId,
22026
+ userId: getActiveUser()._id,
22027
+ };
22028
+ const currentValue = (_a = pullFromCache([
22029
+ 'subChannelMarker',
22030
+ 'get',
22031
+ getResolver('subChannelMarker')(key),
22032
+ ])) === null || _a === void 0 ? void 0 : _a.data;
22033
+ if (!currentValue)
22034
+ return;
22035
+ const userFeedMarkers = [Object.assign(Object.assign({}, currentValue), { readToSegment: message.channelSegment })];
22036
+ fireEvent('local.subChannelMarker.updated', { userFeedMarkers });
22037
+ };
22038
+ /**
22039
+ * the event callback when app is back to online
22040
+ */
22041
+ const onOnline$1 = () => {
22042
+ const callback = () => {
22043
+ // Start reading the reading subChannel again when resume from offline state
22044
+ Object.entries(isReadingMap).forEach(([subChannelId, isReading]) => {
22045
+ if (isReading)
22046
+ startReadingAPI(subChannelId);
22047
+ });
22048
+ };
22049
+ window.addEventListener('online', callback);
22050
+ return () => window.removeEventListener('online', callback);
22051
+ };
22052
+ const registerEventListeners$1 = () => {
22053
+ disposers$1.push(onOnline$1(), onMessageCreated(updateReadToSegment));
22054
+ };
22055
+ const unRegisterEventListeners$1 = () => {
22056
+ disposers$1.forEach(fn => fn());
22057
+ disposers$1 = [];
22058
+ };
22059
+ /* begin_public_function
22060
+ id: channel.start_reading
22061
+ */
22062
+ /**
22063
+ * ```js
22064
+ * import { startReading } from '@amityco/ts-sdk'
22065
+ * const success = await startReading('foo')
22066
+ * ```
22067
+ *
22068
+ * Set local reading state of channel to `true` and then call mark all
22069
+ * messages as read API.
22070
+ *
22071
+ * @param subChannelId - The sub channel ID to start reading.
22072
+ * @return A success boolean if reading of the sub channel had begun.
22073
+ *
22074
+ * @category Channel API
22075
+ * @async
22076
+ */
22077
+ const startReading = (subChannelId) => {
22078
+ isReadingMap[subChannelId] = true;
22079
+ if (disposers$1.length === 0) {
22080
+ registerEventListeners$1();
22081
+ }
22082
+ return startReadingAPI(subChannelId);
22083
+ };
22084
+ /* end_public_function */
22085
+ /* begin_public_function
22086
+ id: channel.stop_reading
22087
+ */
22088
+ /**
22089
+ * ```js
22090
+ * import { stopReading } from '@amityco/ts-sdk'
22091
+ * const success = await stopReading('foo')
22092
+ * ```
22093
+ *
22094
+ * Set local reading state of channel to `false` and then call mark all
22095
+ * messages as unread API.
22096
+ *
22097
+ * @param subChannelId - The sub channel ID to stop reading.
22098
+ * @return A success boolean if reading of the sub channel had begun.
22099
+ *
22100
+ * @category Channel API
22101
+ * @async
22102
+ */
22103
+ const stopReading = (subChannelId) => {
22104
+ isReadingMap[subChannelId] = false;
22105
+ unRegisterEventListeners$1();
22106
+ return stopReadingAPI(subChannelId);
22107
+ };
22108
+ /* end_public_function */
22109
+
22110
+ /**
22111
+ * ```js
22112
+ * import { onChannelSubCreated } from '@amityco/ts-sdk'
22113
+ * const dispose = onSubChannelCreated(subChannel => {
22114
+ * // ...
22115
+ * })
22116
+ * ```
22117
+ *
22118
+ * Fired when any {@link Amity.SubChannel} have been created
22119
+ *
22120
+ * @param callback The function to call when the event was fired
22121
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
22122
+ *
22123
+ * @category Channel Events
22124
+ */
22125
+ const onSubChannelCreated = (callback) => {
22126
+ const client = getActiveClient();
22127
+ const filter = async (rawPayload) => {
22128
+ const payload = await prepareSubChannelPayload(rawPayload);
22129
+ ingestInCache(payload);
22130
+ callback(payload.messageFeeds[0]);
22131
+ };
22132
+ return createEventSubscriber(client, 'onSubChannelCreated', 'message-feed.created', filter);
22133
+ };
22134
+
22135
+ /**
22136
+ * ```js
22137
+ * import { onSubChannelUpdated } from '@amityco/ts-sdk'
22138
+ * const dispose = onSubChannelUpdated(subChannel => {
22139
+ * // ...
22140
+ * })
22141
+ * ```
22142
+ *
22143
+ * Fired when any {@link Amity.SubChannel} have been updated
22144
+ *
22145
+ * @param callback The function to call when the event was fired
22146
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
22147
+ *
22148
+ * @category Channel Events
22149
+ */
22150
+ const onSubChannelUpdated = (callback) => {
22151
+ const client = getActiveClient();
22152
+ const subChannelChangeHandler = async (rawPayload) => {
22153
+ const payload = await prepareSubChannelPayload(rawPayload);
22154
+ ingestInCache(payload);
22155
+ callback(payload.messageFeeds[0]);
22156
+ };
22157
+ const subChannelMarkerChangeHandler = async (rawPayload) => {
22158
+ var _a;
22159
+ const marker = rawPayload.userFeedMarkers[0];
22160
+ const cacheKey = ['subChannel', 'get', marker.feedId];
22161
+ const subChannel = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
22162
+ if (!subChannel)
22163
+ return;
22164
+ const updated = updateSubChannelMarker(subChannel, marker);
22165
+ upsertInCache(cacheKey, updated);
22166
+ callback(updated);
22167
+ };
22168
+ const disposers = [
22169
+ createEventSubscriber(client, 'onSubChannelUpdated', 'message-feed.updated', subChannelChangeHandler),
22170
+ createEventSubscriber(client, 'onSubChannelUpdated', 'local.subChannelMarker.fetched', subChannelMarkerChangeHandler),
22171
+ createEventSubscriber(client, 'onSubChannelUpdated', 'local.subChannelMarker.updated', subChannelMarkerChangeHandler),
22172
+ ];
22173
+ return () => {
22174
+ disposers.forEach(fn => fn());
22175
+ };
22176
+ };
22177
+
22178
+ /**
22179
+ * ```js
22180
+ * import { onSubChannelDeleted } from '@amityco/ts-sdk'
22181
+ * const dispose = onSubChannelDeleted(subChannel => {
22182
+ * // ...
22183
+ * })
22184
+ * ```
22185
+ *
22186
+ * Fired when any {@link Amity.SubChannel} have been deleted
22187
+ *
22188
+ * @param callback The function to call when the event was fired
22189
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
22190
+ *
22191
+ * @category Channel Events
22192
+ */
22193
+ const onSubChannelDeleted = (callback) => {
22194
+ const client = getActiveClient();
22195
+ const filter = async (rawPayload) => {
22196
+ const payload = await prepareSubChannelPayload(rawPayload);
22197
+ ingestInCache(payload);
22198
+ callback(payload.messageFeeds[0]);
22199
+ };
22200
+ const disposers = [
22201
+ createEventSubscriber(client, 'onSubChannelDeleted', 'message-feed.deleted', filter),
22202
+ createEventSubscriber(client, 'local.message-feed.deleted', 'local.message-feed.deleted', payload => callback(payload.messageFeeds[0])),
22203
+ ];
22204
+ return () => {
22205
+ disposers.forEach(fn => fn());
22206
+ };
22207
+ };
22208
+
22209
+ const FORCE_SYNC_INTERVAL_TIME = 8000;
22210
+ const SYNC_TRIGGER_INTERVAL_TIME = 2000;
22211
+ let clearSyncTrigger;
22212
+ let disposers = [];
22213
+ let isWaitingForResponse = false;
22214
+ /**
22215
+ * list of conditions that make timer still trigger the syncing process.
22216
+ * If it's empty, it means sync is stopped.
22217
+ * if it's not empty, sync will resume.
22218
+ */
22219
+ let events = [];
22220
+ /**
22221
+ * get current marker sync event list
22222
+ * @private
22223
+ */
22224
+ const getMarkerSyncEvents = () => events;
22225
+ /**
22226
+ * set marker sync events
22227
+ * @private
22228
+ */
22229
+ const setMarkerSyncEvents = (newEvents) => {
22230
+ events = newEvents;
22231
+ };
22232
+ /**
22233
+ * push new event to marker sync events
22234
+ * @private
22235
+ */
22236
+ const pushMarkerSyncEvent = (event) => events.push(event);
22237
+ /**
22238
+ * interval task
22239
+ * @private
22240
+ */
22241
+ const markerSyncTrigger = async (markerSync) => {
22242
+ if (isWaitingForResponse) {
22243
+ // waiting for the response no need to make another API call
22244
+ return;
22245
+ }
22246
+ if (events.length === 0) {
22247
+ // no event that require to call marker sync API
22248
+ return;
22249
+ }
22250
+ isWaitingForResponse = true;
22251
+ // any past events are considered processed here.
22252
+ // however during waiting for the response, RTE could add the new message event;
22253
+ // which will make the engine trigger another call next round.
22254
+ events = [];
22255
+ const response = await markerSync();
22256
+ if (response.hasMore) {
22257
+ events.push("has_more" /* Amity.MarkerSyncEvent.HAS_MORE */);
22258
+ }
22259
+ // eslint-disable-next-line require-atomic-updates
22260
+ isWaitingForResponse = false;
22261
+ };
22262
+ /**
22263
+ * the event callback when app is back to online
22264
+ */
22265
+ const onOnline = () => {
22266
+ // should add RESUME to the event to trigger marker syncing again
22267
+ const callback = () => events.push("resume" /* Amity.MarkerSyncEvent.RESUME */);
22268
+ window.addEventListener('online', callback);
22269
+ return () => window.removeEventListener('online', callback);
22270
+ };
22271
+ const setIntervalTask = (handler, timeout) => {
22272
+ const timer = setInterval(handler, timeout);
22273
+ return () => clearInterval(timer);
22274
+ };
22275
+ const registerEventListeners = () => {
22276
+ // based on the tech spec design, we designed a fetch marker in case of these events
22277
+ // - new message
22278
+ // - create channel
22279
+ // - remove channel
22280
+ // - app going to online again after offline
22281
+ disposers.push(onOnline(), onMessageCreated(message => {
22282
+ // only conversation, community and broadcast types can sync
22283
+ if (isUnreadCountSupport$1(message))
22284
+ events.push("new message" /* Amity.MarkerSyncEvent.NEW_MESSAGE */);
22285
+ },
22286
+ // only trigger sync from remote events to prevent an unread count equal `-1`
22287
+ // when an optimistic message creation is performed.
22288
+ false), onSubChannelCreated(() => events.push("subchannel is created" /* Amity.MarkerSyncEvent.SUB_CHANNEL_CREATED */)), onSubChannelDeleted(() => events.push("subchannel is deleted" /* Amity.MarkerSyncEvent.SUBCHANNEL_IS_DELETED */)),
22289
+ // In real-world use, we've encountered some cases where BE returns empty result
22290
+ // even if a marker changes in the database, causing the SDK to mistakenly believe that
22291
+ // no changes have been made in the database and end the sync prematurely.
22292
+ // Did miss update the unread count
22293
+ //
22294
+ // We found that some time BE loads were too high, causing the calculation
22295
+ // marker not to finish within the sync time, so it returned an empty value.
22296
+ //
22297
+ // Therefore, solve this problem by creating a second interval loop that
22298
+ // runs every 8 seconds regardless of whether an event occurs or not so that
22299
+ // the unread count is always updated in case of an error like the above.
22300
+ setIntervalTask(() => events.push("force sync" /* Amity.MarkerSyncEvent.FORCE_SYNC */), FORCE_SYNC_INTERVAL_TIME));
22301
+ };
22302
+ const unRegisterEventListeners = () => {
22303
+ disposers.forEach(fn => fn());
22304
+ disposers = [];
22305
+ };
22306
+ /**
22307
+ ```js
22308
+ * import { startUnreadSync } from '@amityco/ts-sdk'
22309
+ * startUnreadSync()
22310
+ * ```
22311
+ *
22312
+ * start syncing to keep feed markers, channel markers and user makers cache
22313
+ * update to the server.
22314
+ *
22315
+ * @category Marker API
22316
+ */
22317
+ const startUnreadSync = () => {
22318
+ pushMarkerSyncEvent("start syncing" /* Amity.MarkerSyncEvent.START_SYNCING */);
22319
+ if (!clearSyncTrigger) {
22320
+ // it is possible to repeatedly call the API when multiple events occur at the same time.
22321
+ // This is very burdensome to the BE Server, so we have an interval loop for
22322
+ // grouping every event that occurs within 2 seconds into a single API call.
22323
+ //
22324
+ // interval loop is also useful for fetching large results. Because if the result
22325
+ // is more than 20 records, the API will split the result into multiple pages
22326
+ // and the SDK will need to fetch it repeatedly until all the results are available.
22327
+ // So we need an interval loop for repeat fetch.
22328
+ clearSyncTrigger = setIntervalTask(() => markerSyncTrigger(markerSync), SYNC_TRIGGER_INTERVAL_TIME);
22329
+ }
22330
+ registerEventListeners();
22331
+ };
22332
+ /**
22333
+ ```js
22334
+ * import { stopUnreadSyncing } from '@amityco/ts-sdk'
22335
+ * stopUnreadSyncing()
22336
+ * ```
22337
+ *
22338
+ * stop unread syncing
22339
+ *
22340
+ * @category Marker API
22341
+ */
22342
+ const stopUnreadSyncing = () => {
22343
+ clearSyncTrigger === null || clearSyncTrigger === void 0 ? void 0 : clearSyncTrigger();
22344
+ clearSyncTrigger = undefined;
22345
+ setMarkerSyncEvents([]);
22346
+ unRegisterEventListeners();
22347
+ };
22348
+
22349
+ /**
22350
+ * ```js
22351
+ * import { isInTombstone } from '@amityco/ts-sdk'
22352
+ * const user = isInTombstone(["message", "messageId"])
22353
+ * ```
22354
+ *
22355
+ * Checks if the {@link Amity.TombstoneCacheOptions} exists
22356
+ * in cache and it's not expired means it's in tombstone
22357
+ * and we throw an Error
22358
+ *
22359
+ * @param model the model to check
22360
+ * @param modelId the object id to check
22361
+ * @returns the matching cache entry, or undefined.
22362
+ *
22363
+ * @category Cache API
22364
+ */
22365
+ const isInTombstone = (model, modelId) => {
22366
+ const { log, cache } = getActiveClient();
22367
+ const key = [model, CACHE_KEY_TOMBSTONE, modelId];
22368
+ if (!cache)
22369
+ return;
22370
+ log('cache/api/isInTombstone', key);
22371
+ const isInTombstone = pullFromCache(key);
22372
+ const { lifeSpan } = queryOptions('cache_then_server', CACHE_LIFESPAN_TOMBSTONE);
22373
+ if (isInTombstone && isFresh(isInTombstone.data, lifeSpan)) {
22374
+ throw new ASCApiError('Item not found!', 400400 /* Amity.ServerError.ITEM_NOT_FOUND */, "error" /* Amity.ErrorLevel.ERROR */);
22375
+ }
22376
+ };
22377
+
22378
+ /**
22379
+ * ```js
22380
+ * import { pushToTombstone } from '@amityco/ts-sdk'
22381
+ * pushToTombstone(["message", "messageId"], { cachedAt: Date.now() })
22382
+ * ```
22383
+ *
22384
+ * Removes an existing {@link Amity.CacheEntry} from the {@link Amity.Client}'s
22385
+ * {@link Amity.Cache} from a given {@link Amity.CacheKey}
22386
+ *
22387
+ * @param model the model to remove and push to Tombstone
22388
+ * @param modelId the related model id
22389
+ *
22390
+ * @category Cache API
22391
+ * @hidden
22392
+ */
22393
+ const pushToTombstone = (model, modelId) => {
22394
+ const { log, cache } = getActiveClient();
22395
+ const cacheKey = [model, CACHE_KEY_TOMBSTONE, modelId];
22396
+ const data = { cachedAt: Date.now() };
22397
+ if (!cache)
22398
+ return;
22399
+ log('cache/api/pushToTombstone', { cacheKey, data });
22400
+ dropFromCache([model, CACHE_KEY_GET, modelId], true);
22401
+ pushToCache(cacheKey, data);
22402
+ };
22403
+
22404
+ /* begin_public_function
22405
+ id: user.get
22406
+ */
22407
+ /**
22408
+ * ```js
22409
+ * import { getUser } from '@amityco/ts-sdk'
22410
+ * const { data: user } = await getUser('foobar')
22411
+ * ```
22412
+ *
22413
+ * Fetches a {@link Amity.User} object
22414
+ *
22415
+ * @param userId the ID of the {@link Amity.User} to fetch
22416
+ * @returns the associated {@link Amity.User} object
22417
+ *
22418
+ * @category User API
22419
+ * @async
22420
+ */
22421
+ const getUser = async (userId, isLive = false) => {
22422
+ const client = getActiveClient();
22423
+ client.log('user/getUser', userId);
22424
+ if (!isLive) {
22425
+ console.log('getUser will be deprecated on 25th November 2022, please use liveUser instead.');
22426
+ }
22427
+ isInTombstone('user', userId);
22428
+ let data;
22429
+ try {
22430
+ const response = await client.http.get(`/api/v3/users/${encodeURIComponent(userId)}`);
22431
+ data = response.data;
22432
+ }
22433
+ catch (error) {
22434
+ if (checkIfShouldGoesToTombstone(error === null || error === void 0 ? void 0 : error.code)) {
22435
+ pushToTombstone('user', userId);
22436
+ }
22437
+ throw error;
22438
+ }
22439
+ const cachedAt = client.cache && Date.now();
22440
+ if (client.cache)
22441
+ ingestInCache(data, { cachedAt });
22442
+ const { users } = data;
22443
+ fireEvent('user.fetched', data);
22444
+ return {
22445
+ data: users.find(user => user.userId === userId),
22446
+ cachedAt,
22447
+ };
22448
+ };
22449
+ /* end_public_function */
22450
+ /**
22451
+ * ```js
22452
+ * import { getUser } from '@amityco/ts-sdk'
22453
+ * const { data: user } = getUser.locally('foobar')
22454
+ * ```
22455
+ *
22456
+ * Fetches a {@link Amity.User} object from cache
22457
+ *
22458
+ * @param userId the ID of the {@link Amity.User} to fetch
22459
+ * @returns the associated {@link Amity.User} object
22460
+ *
22461
+ * @category User API
22462
+ */
22463
+ getUser.locally = (userId) => {
22464
+ const client = getActiveClient();
22465
+ client.log('user/getUser.locally', userId);
22466
+ return client.cache && pullFromCache(['user', 'get', userId]);
22467
+ };
22468
+
22469
+ /* begin_public_function
22470
+ id: user.get_by_ids
22471
+ */
22472
+ /**
22473
+ * ```js
22474
+ * import { getUsers } from '@amityco/ts-sdk'
22475
+ * const { data: users } = await getUsers(['foo', 'bar'])
22476
+ * ```
22477
+ *
22478
+ * Fetches a collection of {@link Amity.User} objects
22479
+ *
22480
+ * @param userIds the IDs of the {@link Amity.User} to fetch
22481
+ * @returns the associated collection of {@link Amity.User} objects
22482
+ *
22483
+ * @category User API
22484
+ * @async
22485
+ */
22486
+ const getUsers = async (userIds) => {
22487
+ const client = getActiveClient();
22488
+ client.log('user/getUsers', userIds);
22489
+ const encodedUserIds = userIds.map(userId => encodeURIComponent(userId));
22490
+ // API-FIX: endpoint should not be /list, parameters should be querystring.
22491
+ const { data } = await client.http.get(`/api/v3/users/list`, {
22492
+ params: { userIds: encodedUserIds },
22493
+ });
22494
+ const cachedAt = client.cache && Date.now();
22495
+ if (client.cache)
22496
+ ingestInCache(data, { cachedAt });
22497
+ fireEvent('user.fetched', data);
22498
+ return {
22499
+ data: data.users,
22500
+ cachedAt,
22501
+ };
22502
+ };
22503
+ /**
22504
+ * ```js
22505
+ * import { getUsers } from '@amityco/ts-sdk'
22506
+ * const { data: users } = getUsers.locally!(['foo', 'bar'])
22507
+ * ```
22508
+ *
22509
+ * Fetches a collection of {@link Amity.User} objects from cache
22510
+ *
22511
+ * @param userIds the IDs of the {@link Amity.User} to fetch
22512
+ * @returns the associated collection of {@link Amity.User} objects
22513
+ *
22514
+ * @category User API
22515
+ */
22516
+ getUsers.locally = (userIds) => {
22517
+ var _a;
22518
+ const client = getActiveClient();
22519
+ client.log('user/getUsers.locally', userIds);
22520
+ if (!client.cache)
22521
+ return;
22522
+ const cached = userIds
22523
+ .map(userId => pullFromCache(['user', 'get', userId]))
22524
+ .filter(Boolean);
22525
+ const users = cached.map(({ data }) => data);
22526
+ const oldest = (_a = cached.sort((a, b) => (a.cachedAt < b.cachedAt ? -1 : 1))) === null || _a === void 0 ? void 0 : _a[0];
22527
+ if ((cached === null || cached === void 0 ? void 0 : cached.length) < userIds.length)
22528
+ return;
22529
+ return {
22530
+ data: users,
22531
+ cachedAt: oldest.cachedAt,
22532
+ };
22533
+ };
22534
+
22535
+ /* begin_public_function
22536
+ id: user.query, user.search
22537
+ */
22538
+ /**
22539
+ * ```js
22540
+ * import { queryUsers } from '@amityco/ts-sdk'
22541
+ * const { data: users, prevPage, nextPage } = await queryUsers({ displayName: 'foo' })
22542
+ * ```
22543
+ *
22544
+ * Queries a paginable list of {@link Amity.User} objects
22545
+ * Search is performed by displayName such as `.startsWith(search)`
22546
+ *
22547
+ * @param query The query parameters
22548
+ * @returns A page of {@link Amity.User} objects
22549
+ *
22550
+ * @category User API
22551
+ * @async
22552
+ */
22553
+ const queryUsers = async (query = {}) => {
22554
+ const client = getActiveClient();
22555
+ client.log('user/queryUsers', query);
22556
+ const { page = { limit: 10 }, displayName, filter = 'all', sortBy = 'displayName' } = query, params = __rest(query, ["page", "displayName", "filter", "sortBy"]);
22557
+ const { data } = await client.http.get(`/api/v3/users`, {
22558
+ params: Object.assign(Object.assign({}, params), { keyword: displayName, filter,
22559
+ sortBy, options: {
22560
+ token: toToken(page, 'skiplimit'),
22561
+ } }),
22562
+ });
22563
+ // unpacking
22564
+ const { paging } = data, payload = __rest(data, ["paging"]);
22565
+ const { users } = payload;
22566
+ const cachedAt = client.cache && Date.now();
22567
+ if (client.cache) {
22568
+ ingestInCache(payload, { cachedAt });
22569
+ /*
22570
+ * using query as cache key over params because if the keyword, filter, sort
22571
+ * change the API will NOT cache results, when it should
22572
+ */
22573
+ const cacheKey = ['user', 'query', Object.assign(Object.assign({}, query), { options: Object.assign({}, page) })];
22574
+ pushToCache(cacheKey, { users: users.map(getResolver('user')), paging });
22575
+ }
22576
+ fireEvent('user.fetched', data);
22577
+ const prevPage = toPage(paging.previous);
22578
+ const nextPage = toPage(paging.next);
22579
+ return { data: users, cachedAt, prevPage, nextPage };
22580
+ };
22581
+ /* end_public_function */
22582
+ /**
22583
+ * ```js
22584
+ * import { queryUsers } from '@amityco/ts-sdk'
22585
+ * const { data: users } = queryUsers.locally({ keyword: 'foo' })
22586
+ * ```
22587
+ *
22588
+ * Queries a paginable list of {@link Amity.User} objects from cache
22589
+ * Search is performed by displayName such as `.startsWith(search)`
22590
+ *
22591
+ * @param query The query parameters
22592
+ * @returns A page of {@link Amity.User} objects
22593
+ *
22594
+ * @category User API
22595
+ */
22596
+ queryUsers.locally = (query = {}) => {
22597
+ var _a, _b, _c;
22598
+ const client = getActiveClient();
22599
+ client.log('user/queryUsers.locally', query);
22600
+ if (!client.cache)
22601
+ return;
22602
+ const { page = { limit: 10 } } = query !== null && query !== void 0 ? query : {};
22603
+ const cacheKey = [
22604
+ 'user',
22605
+ 'query',
22606
+ Object.assign(Object.assign({}, query), { options: Object.assign({}, page) }),
22607
+ ];
22608
+ const { data, cachedAt } = (_a = pullFromCache(cacheKey)) !== null && _a !== void 0 ? _a : {};
22609
+ const users = (_b = data === null || data === void 0 ? void 0 : data.users.map(userId => pullFromCache(['user', 'get', userId])).filter(Boolean).map(({ data }) => data)) !== null && _b !== void 0 ? _b : [];
22610
+ const prevPage = toPage(data === null || data === void 0 ? void 0 : data.paging.previous);
22611
+ const nextPage = toPage(data === null || data === void 0 ? void 0 : data.paging.next);
22612
+ return users.length > 0 && users.length === ((_c = data === null || data === void 0 ? void 0 : data.users) === null || _c === void 0 ? void 0 : _c.length)
22613
+ ? { data: users, cachedAt, prevPage, nextPage }
22614
+ : undefined;
22615
+ };
22616
+
22617
+ /* begin_public_function
22618
+ id: client.update_user
22619
+ */
22620
+ /**
22621
+ * ```js
22622
+ * import { updateUser } from '@amityco/ts-sdk'
22623
+ * const updated = await updateUser(userId, { displayName: 'foobar' })
22624
+ * ```
22625
+ *
22626
+ * Updates an {@link Amity.User}
22627
+ *
22628
+ * @param userId The ID of the {@link Amity.User} to update
22629
+ * @param patch The patch data to apply
22630
+ * @returns the updated {@link Amity.User} object
22631
+ *
22632
+ * @category User API
22633
+ * @async
22634
+ */
22635
+ const updateUser = async (userId, patch) => {
22636
+ const client = getActiveClient();
22637
+ client.log('user/updateUser', userId, patch);
22638
+ // API-FIX: Endpoint is malformed, userId should be a url param.
22639
+ /*
22640
+ const { data } = await client.http.put<Amity.Response<UserPayload>>(
22641
+ `/api/v3/users/${userId}`, patch,
22642
+ )
22643
+ */
22644
+ const { data } = await client.http.put(`/api/v3/users/`, Object.assign(Object.assign({ userId }, patch), { createNewUserWhenNotFound: false }));
22645
+ const cachedAt = client.cache && Date.now();
22646
+ if (client.cache)
22647
+ ingestInCache(data, { cachedAt });
22648
+ const { users } = data;
22649
+ fireEvent('user.updated', data);
22650
+ return {
22651
+ data: users.find(user => user.userId === userId),
22652
+ cachedAt,
22653
+ };
22654
+ };
22655
+ /* end_public_function */
22656
+
22657
+ /**
22658
+ * ```js
22659
+ * import { onUserUpdated } from '@amityco/ts-sdk'
22660
+ * const dispose = onUserUpdated(user => {
22661
+ * // ...
22662
+ * })
22663
+ * ```
22664
+ *
22665
+ * Fired when a {@link Amity.User} has been updated
22666
+ *
22667
+ * @param callback The function to call when the event was fired
22668
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
22669
+ *
22670
+ * @category User Events
22671
+ */
22672
+ const onUserUpdated = (callback) => createUserEventSubscriber('user.updated', callback);
22673
+
22674
+ /**
22675
+ * ```js
22676
+ * import { onUserFlagged } from '@amityco/ts-sdk'
22677
+ * const dispose = onUserFlagged(user => {
22678
+ * // ...
22679
+ * })
22680
+ * ```
22681
+ *
22682
+ * Fired when a {@link Amity.User} has been flagged
22683
+ *
22684
+ * @param callback The function to call when the event was fired
22685
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
22686
+ *
22687
+ * @category User Events
22688
+ */
22689
+ const onUserFlagged = (callback) => createUserEventSubscriber('user.flagged', callback);
22690
+
22691
+ /**
22692
+ * ```js
22693
+ * import { onUserUnflagged } from '@amityco/ts-sdk'
22694
+ * const dispose = onUserUnflagged(user => {
22695
+ * // ...
22696
+ * })
22697
+ * ```
22698
+ *
22699
+ * Fired when a flag has been removed from a {@link Amity.User}
22700
+ *
22701
+ * @param callback The function to call when the event was fired
22702
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
22703
+ *
22704
+ * @category User Events
22705
+ */
22706
+ const onUserUnflagged = (callback) => createUserEventSubscriber('user.unflagged', callback);
22707
+
22708
+ /**
22709
+ * ```js
22710
+ * import { onUserFlagCleared } from '@amityco/ts-sdk'
22711
+ * const dispose = onUserFlagCleared(user => {
22712
+ * // ...
22713
+ * })
22714
+ * ```
22715
+ *
22716
+ * Fired when flags have been cleared for a {@link Amity.User}
22717
+ *
22718
+ * @param callback The function to call when the event was fired
22719
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
22720
+ *
22721
+ * @category User Events
22722
+ */
22723
+ const onUserFlagCleared = (callback) => createUserEventSubscriber('user.flagCleared', callback);
22724
+
22725
+ /**
22726
+ * ```js
22727
+ * import { onUserFetched } from '@amityco/ts-sdk'
22728
+ * const dispose = onUserFetched(user => {
22729
+ * // ...
22730
+ * })
22731
+ * ```
22732
+ *
22733
+ * Fired when a {@link Amity.User} has been fetched
22734
+ *
22735
+ * @param callback The function to call when the event was fired
22736
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
22737
+ *
22738
+ * @category User Events
22739
+ */
22740
+ const onUserFetched = (callback) => createUserEventSubscriber('user.fetched', callback);
22741
+
22742
+ /**
21550
22743
  * ```js
21551
22744
  * import { liveUser } from '@amityco/ts-sdk';
21552
22745
  *
@@ -22066,139 +23259,45 @@ const getRole = async (roleId) => {
22066
23259
  cachedAt,
22067
23260
  };
22068
23261
  };
22069
- /**
22070
- * ```js
22071
- * import { getRole } from '@amityco/ts-sdk'
22072
- * const role = getRole.locally('foobar')
22073
- * ```
22074
- *
22075
- * Fetches a {@link Amity.Role} object from cache
22076
- *
22077
- * @param roleId the ID of the {@link Amity.Role} to fetch
22078
- * @returns the associated {@link Amity.Role} object
22079
- *
22080
- * @category Role API
22081
- */
22082
- getRole.locally = (roleId) => {
22083
- const client = getActiveClient();
22084
- client.log('role/getRole.locally', roleId);
22085
- if (!client.cache)
22086
- return;
22087
- const cached = pullFromCache(['role', 'get', roleId]);
22088
- if (!cached)
22089
- return;
22090
- return {
22091
- data: cached.data,
22092
- cachedAt: cached.cachedAt,
22093
- };
22094
- };
22095
-
22096
- /** @hidden */
22097
- const dispatchReactable = (referenceType, model) => {
22098
- if (referenceType === 'message')
22099
- // @ts-ignore: refactor later
22100
- fireEvent('local.message.updated', { messages: [model] });
22101
- else if (referenceType === 'post')
22102
- // @ts-ignore: refactor later
22103
- fireEvent('post.updated', { posts: [model] });
22104
- else if (referenceType === 'comment')
22105
- // @ts-ignore: refactor later
22106
- fireEvent('comment.updated', { comments: [model] });
22107
- };
22108
-
22109
- /** @hidden */
22110
- /*
22111
- * @param message payload from http request without myReactions
22112
- * add myReactions to http response if the event was a reaction event
22113
- */
22114
- const prepareMessagePayloadForCache = (payload) => {
22115
- const client = getActiveClient();
22116
- const cached = pullFromCache(['message', 'get', payload.messageId]);
22117
- // '[]' in cases where the new reaction is the first one
22118
- const myReactions = (cached === null || cached === void 0 ? void 0 : cached.data.myReactions) || [];
22119
- // add myReactions to the payload
22120
- Object.assign(payload, { myReactions });
22121
- // check if there are any updates to the reactions
22122
- const latestReaction = payload === null || payload === void 0 ? void 0 : payload.latestReaction;
22123
- const isLatestReactionMine = latestReaction && latestReaction.userId === client.userId;
22124
- if (!isLatestReactionMine) {
22125
- return;
22126
- }
22127
- // new reaction added
22128
- if (latestReaction.eventName === 'add' && !myReactions.includes(latestReaction.reactionName)) {
22129
- Object.assign(payload, {
22130
- myReactions: [...myReactions, latestReaction.reactionName],
22131
- });
22132
- }
22133
- // existing reaction removed
22134
- if (latestReaction.eventName === 'remove' && myReactions.includes(latestReaction.reactionName)) {
22135
- Object.assign(payload, {
22136
- myReactions: myReactions.filter(x => x !== latestReaction.reactionName),
22137
- });
22138
- }
22139
- };
22140
-
22141
- function convertFromRaw$2(_a) {
22142
- var { channelPublicId, childCount, creatorPublicId, mentionedUsers, messageFeedId, myReactions, reactionCount, reactions, referenceId, segment } = _a, rest = __rest(_a, ["channelPublicId", "childCount", "creatorPublicId", "mentionedUsers", "messageFeedId", "myReactions", "reactionCount", "reactions", "referenceId", "segment"]);
22143
- let cache;
22144
- if (referenceId) {
22145
- try {
22146
- cache = pullFromCache(['message', 'get', referenceId]);
22147
- // eslint-disable-next-line no-empty
22148
- }
22149
- catch (_b) { }
22150
- }
22151
- if (!cache) {
22152
- try {
22153
- cache = pullFromCache(['message', 'get', rest.messageId]);
22154
- // eslint-disable-next-line no-empty
22155
- }
22156
- catch (_c) { }
22157
- }
22158
- const out = Object.assign(Object.assign({}, rest), { channelId: channelPublicId, channelSegment: segment, childrenNumber: childCount, creatorId: creatorPublicId, reactions: reactions !== null && reactions !== void 0 ? reactions : {}, reactionsCount: reactionCount, subChannelId: messageFeedId, uniqueId: cache ? cache.data.uniqueId : rest.messageId });
22159
- if (mentionedUsers) {
22160
- out.mentionees = mentionedUsers.map(mention => {
22161
- if (mention.type === 'channel') {
22162
- return mention;
22163
- }
22164
- return { type: 'user', userIds: mention.userPublicIds };
22165
- });
22166
- }
22167
- if (myReactions) {
22168
- // http response
22169
- out.myReactions = myReactions;
22170
- }
22171
- else {
22172
- // mqtt event
22173
- try {
22174
- prepareMessagePayloadForCache(out);
22175
- // eslint-disable-next-line no-empty
22176
- }
22177
- catch (_d) { }
22178
- }
22179
- return out;
22180
- }
22181
- const prepareMessagePayload = (payload) => {
22182
- return Object.assign(Object.assign({}, payload), { messages: payload.messages.map(convertFromRaw$2) });
22183
- };
22184
- const convertResponseFromRaw = (response) => {
22185
- return Object.assign(Object.assign({}, response), { data: Object.assign(Object.assign({}, response.data), { messages: response.data.messages.map(convertFromRaw$2) }) });
22186
- };
22187
- function convertParams(_a) {
22188
- var { subChannelId, mentionees } = _a, rest = __rest(_a, ["subChannelId", "mentionees"]);
22189
- return Object.assign({ messageFeedId: subChannelId, mentionedUsers: mentionees }, rest);
22190
- }
22191
- function convertQueryParams$1(_a) {
22192
- var { page, sortBy, subChannelId, tags, includeDeleted } = _a, rest = __rest(_a, ["page", "sortBy", "subChannelId", "tags", "includeDeleted"]);
22193
- const out = Object.assign(Object.assign({}, rest), { messageFeedId: subChannelId, isDeleted: includeDeleted === false ? false : undefined, options: { token: toToken(page || { limit: 10 }, 'afterbeforeraw') } });
22194
- if (sortBy !== undefined) {
22195
- out.options.sortBy = sortBy;
22196
- }
22197
- if (tags) {
22198
- out.includeTags = tags;
22199
- }
22200
- return out;
22201
- }
23262
+ /**
23263
+ * ```js
23264
+ * import { getRole } from '@amityco/ts-sdk'
23265
+ * const role = getRole.locally('foobar')
23266
+ * ```
23267
+ *
23268
+ * Fetches a {@link Amity.Role} object from cache
23269
+ *
23270
+ * @param roleId the ID of the {@link Amity.Role} to fetch
23271
+ * @returns the associated {@link Amity.Role} object
23272
+ *
23273
+ * @category Role API
23274
+ */
23275
+ getRole.locally = (roleId) => {
23276
+ const client = getActiveClient();
23277
+ client.log('role/getRole.locally', roleId);
23278
+ if (!client.cache)
23279
+ return;
23280
+ const cached = pullFromCache(['role', 'get', roleId]);
23281
+ if (!cached)
23282
+ return;
23283
+ return {
23284
+ data: cached.data,
23285
+ cachedAt: cached.cachedAt,
23286
+ };
23287
+ };
23288
+
23289
+ /** @hidden */
23290
+ const dispatchReactable = (referenceType, model) => {
23291
+ if (referenceType === 'message')
23292
+ // @ts-ignore: refactor later
23293
+ fireEvent('local.message.updated', { messages: [model] });
23294
+ else if (referenceType === 'post')
23295
+ // @ts-ignore: refactor later
23296
+ fireEvent('post.updated', { posts: [model] });
23297
+ else if (referenceType === 'comment')
23298
+ // @ts-ignore: refactor later
23299
+ fireEvent('comment.updated', { comments: [model] });
23300
+ };
22202
23301
 
22203
23302
  /* begin_public_function
22204
23303
  id: message.get
@@ -22227,10 +23326,8 @@ const getMessage = async (messageId, isLive = false) => {
22227
23326
  let data;
22228
23327
  try {
22229
23328
  // API-FIX: endpoint should not be /list, parameters should be querystring.
22230
- const response = await client.http
22231
- .get(`/api/v5/messages/${encodeURIComponent(messageId)}`)
22232
- .then(convertResponseFromRaw);
22233
- data = response.data;
23329
+ const { data: payload } = await client.http.get(`/api/v5/messages/${encodeURIComponent(messageId)}`);
23330
+ data = await prepareMessagePayload(payload);
22234
23331
  }
22235
23332
  catch (error) {
22236
23333
  if (checkIfShouldGoesToTombstone(error === null || error === void 0 ? void 0 : error.code)) {
@@ -22293,11 +23390,10 @@ getMessage.locally = (messageId) => {
22293
23390
  const getMessages = async (messageIds) => {
22294
23391
  const client = getActiveClient();
22295
23392
  client.log('message/getMessages', messageIds);
22296
- const { data } = await client.http
22297
- .get(`/api/v5/messages/list`, {
23393
+ const { data: payload } = await client.http.get(`/api/v5/messages/list`, {
22298
23394
  params: { messageIds: messageIds.map(encodeURIComponent) },
22299
- })
22300
- .then(convertResponseFromRaw);
23395
+ });
23396
+ const data = await prepareMessagePayload(payload);
22301
23397
  const cachedAt = client.cache && Date.now();
22302
23398
  if (client.cache)
22303
23399
  ingestInCache(data, { cachedAt });
@@ -22365,12 +23461,11 @@ const queryMessages = async (query) => {
22365
23461
  // API-FIX: backend should answer Amity.Response (2)
22366
23462
  // API-FIX: pagination should not be indexed on channelSegment (3)
22367
23463
  // const { data } = await client.http.get<Amity.Response<Amity.Paged<Amity.MessagePayload>>>(
22368
- const response = await client.http
22369
- .get(`/api/v5/messages`, { params })
22370
- .then(convertResponseFromRaw);
23464
+ const { data: queryPayload } = await client.http.get(`/api/v5/messages`, { params });
22371
23465
  // API-FIX: backend should answer Amity.Response (2)
22372
23466
  // const { paging, messages } = unwrapPayload(data)
22373
- const _a = response.data, { paging } = _a, data = __rest(_a, ["paging"]);
23467
+ const { paging } = queryPayload, payload = __rest(queryPayload, ["paging"]);
23468
+ const data = await prepareMessagePayload(payload);
22374
23469
  const { messages } = data;
22375
23470
  const cachedAt = client.cache && Date.now();
22376
23471
  if (client.cache) {
@@ -22455,7 +23550,7 @@ const createMessage = async (bundle) => {
22455
23550
  const referenceId = bundle.referenceId || uniqueId || getLocalId();
22456
23551
  uniqueId = undefined;
22457
23552
  const { data: payload } = await client.http.post('/api/v5/messages', Object.assign(Object.assign({}, convertParams(bundle)), { referenceId }));
22458
- const data = prepareMessagePayload(payload);
23553
+ const data = await prepareMessagePayload(payload);
22459
23554
  const { messages } = data;
22460
23555
  const cachedAt = client.cache && Date.now();
22461
23556
  if (client.cache) {
@@ -22547,9 +23642,8 @@ createMessage.optimistically = (_a) => {
22547
23642
  const updateMessage = async (messageId, patch) => {
22548
23643
  const client = getActiveClient();
22549
23644
  client.log('message/updateMessage', patch);
22550
- const { data } = await client.http
22551
- .put(`/api/v5/messages/${encodeURIComponent(messageId)}`, convertParams(patch))
22552
- .then(convertResponseFromRaw);
23645
+ const { data: payload } = await client.http.put(`/api/v5/messages/${encodeURIComponent(messageId)}`, convertParams(patch));
23646
+ const data = await prepareMessagePayload(payload);
22553
23647
  const cachedAt = client.cache && Date.now();
22554
23648
  if (client.cache)
22555
23649
  ingestInCache(data, { cachedAt });
@@ -22651,6 +23745,31 @@ deleteMessage.optimistically = (messageId) => {
22651
23745
  };
22652
23746
  /* end_public_function */
22653
23747
 
23748
+ /**
23749
+ * ```js
23750
+ * import { markAsDelivered } from '@amityco/ts-sdk'
23751
+ * const success = await markAsDelivered('subChannelId', 'messageId')
23752
+ * ```
23753
+ *
23754
+ * Update `deliveredToSegment` in {@link Amity.SubChannelMarker}
23755
+ *
23756
+ * @param subChannelId the ID of the {@link Amity.SubChannel} of message
23757
+ * @param messageId the ID of the {@link Amity.Message} to mark delivered
23758
+ * @returns A success boolean if the {@link Amity.SubChannel} was updated
23759
+ *
23760
+ * @category Message API
23761
+ * @async
23762
+ */
23763
+ const markAsDelivered = async (subChannelId, messageId) => {
23764
+ const client = getActiveClient();
23765
+ client.log('message/markAsDelivered', subChannelId, messageId);
23766
+ const { data } = await client.http.put(`/api/v1/markers/message-feeds/${subChannelId}/mark-delivering`, { messageId });
23767
+ const cachedAt = client.cache && Date.now();
23768
+ if (client.cache)
23769
+ ingestInCache(data, { cachedAt });
23770
+ return true;
23771
+ };
23772
+
22654
23773
  /**
22655
23774
  * Attach user object to membership model
22656
23775
  * - If cache is not enabled, set user to undefined ({..., user: undefined})
@@ -24960,9 +26079,9 @@ const onReactionAdded = (referenceType, referenceId, callback) => {
24960
26079
  */
24961
26080
  if (referenceType === 'message') {
24962
26081
  const client = getActiveClient();
24963
- const filter = (rawPayload) => {
26082
+ const filter = async (rawPayload) => {
24964
26083
  var _a;
24965
- const payload = prepareMessagePayload(rawPayload);
26084
+ const payload = await prepareMessagePayload(rawPayload);
24966
26085
  const cached = pullFromCache([
24967
26086
  'message',
24968
26087
  'get',
@@ -25007,9 +26126,9 @@ const onReactionRemoved = (referenceType, referenceId, callback) => {
25007
26126
  };
25008
26127
  if (referenceType === 'message') {
25009
26128
  const client = getActiveClient();
25010
- const filter = (rawPayload) => {
26129
+ const filter = async (rawPayload) => {
25011
26130
  var _a;
25012
- const payload = prepareMessagePayload(rawPayload);
26131
+ const payload = await prepareMessagePayload(rawPayload);
25013
26132
  const cached = pullFromCache([
25014
26133
  'message',
25015
26134
  'get',
@@ -25054,8 +26173,8 @@ const onReactorAdded = (referenceType, referenceId, callback) => {
25054
26173
  }
25055
26174
  };
25056
26175
  if (referenceType === 'message') {
25057
- const filter = (rawPayload) => {
25058
- const payload = prepareMessagePayload(rawPayload);
26176
+ const filter = async (rawPayload) => {
26177
+ const payload = await prepareMessagePayload(rawPayload);
25059
26178
  if (!payload.messages[0].latestReaction)
25060
26179
  return;
25061
26180
  const _a = payload.messages[0].latestReaction, { eventName, referenceId, referenceType, userDisplayName } = _a, reactor = __rest(_a, ["eventName", "referenceId", "referenceType", "userDisplayName"]);
@@ -25116,8 +26235,8 @@ const onReactorRemoved = (referenceType, referenceId, callback) => {
25116
26235
  }
25117
26236
  };
25118
26237
  if (referenceType === 'message') {
25119
- const filter = (rawPayload) => {
25120
- const payload = prepareMessagePayload(rawPayload);
26238
+ const filter = async (rawPayload) => {
26239
+ const payload = await prepareMessagePayload(rawPayload);
25121
26240
  if (!payload.messages[0].latestReaction)
25122
26241
  return;
25123
26242
  const _a = payload.messages[0].latestReaction, { eventName, referenceId, referenceType } = _a, reactor = __rest(_a, ["eventName", "referenceId", "referenceType"]);
@@ -25303,7 +26422,8 @@ const createReport = async (referenceType, referenceId) => {
25303
26422
  const { data: payload } = await client.http.post(getAPIUrl());
25304
26423
  if (client.cache) {
25305
26424
  if (referenceType === 'message') {
25306
- ingestInCache(prepareMessagePayload(payload));
26425
+ const messagePayload = await prepareMessagePayload(payload);
26426
+ ingestInCache(messagePayload);
25307
26427
  }
25308
26428
  else if (referenceType === 'post') {
25309
26429
  ingestInCache(prepareMembershipPayload(payload, 'communityUsers'));
@@ -25349,7 +26469,8 @@ const deleteReport = async (referenceType, referenceId) => {
25349
26469
  const { data: payload } = await client.http.delete(getAPIUrl());
25350
26470
  if (client.cache) {
25351
26471
  if (referenceType === 'message') {
25352
- ingestInCache(prepareMessagePayload(payload));
26472
+ const messagePayload = await prepareMessagePayload(payload);
26473
+ ingestInCache(messagePayload);
25353
26474
  }
25354
26475
  else if (referenceType === 'post') {
25355
26476
  ingestInCache(prepareMembershipPayload(payload, 'communityUsers'));
@@ -25396,37 +26517,60 @@ const isReportedByMe = async (referenceType, referenceId) => {
25396
26517
  };
25397
26518
  /* end_public_function */
25398
26519
 
25399
- function convertFromRaw$1(_a, params) {
25400
- var { _id } = _a, rest = __rest(_a, ["_id"]);
25401
- return Object.assign(Object.assign(Object.assign({}, rest), params), { defaultSubChannelId: _id });
25402
- }
25403
- function getSegmentParams(rawChannel) {
25404
- let cached;
25405
- try {
25406
- cached = pullFromCache(['channel', 'get', rawChannel.channelId]);
25407
- // eslint-disable-next-line no-empty
25408
- }
25409
- catch (_a) { }
25410
- if (cached) {
25411
- return {
25412
- defaultSubChannelHasUnreadMention: cached.data.defaultSubChannelHasUnreadMention,
25413
- defaultSubChannelUnreadCount: cached.data.defaultSubChannelUnreadCount,
25414
- localReadToSegment: cached.data.localReadToSegment,
25415
- localLastMentionSegment: cached.data.localLastMentionSegment,
25416
- };
25417
- }
25418
- return {
25419
- defaultSubChannelHasUnreadMention: false,
25420
- defaultSubChannelUnreadCount: 0,
25421
- // @ts-ignore
25422
- localReadToSegment: rawChannel.messageCount > 0 ? rawChannel.messageCount - 1 : 0,
25423
- localLastMentionSegment: 0,
26520
+ const MARKER_INCLUDED_CHANNEL_TYPE = ['broadcast', 'conversation', 'community'];
26521
+ const isUnreadCountSupport = ({ type }) => MARKER_INCLUDED_CHANNEL_TYPE.includes(type);
26522
+ const getCachedMarker = (entityId) => {
26523
+ var _a;
26524
+ const key = {
26525
+ entityId,
26526
+ userId: getActiveUser()._id,
25424
26527
  };
26528
+ return (_a = pullFromCache([
26529
+ 'channelMarker',
26530
+ 'get',
26531
+ getResolver('channelMarker')(key),
26532
+ ])) === null || _a === void 0 ? void 0 : _a.data;
26533
+ };
26534
+ const getUnreadCount = (channel, marker) => {
26535
+ var _a, _b, _c;
26536
+ if (marker === null || marker === void 0 ? void 0 : marker.isDeleted) {
26537
+ // NOTE: This is a temporary solution to handle the channel marker when the user is forced to
26538
+ // leave the channel because currently backend can't handle this, so every time a user is banned
26539
+ // from a channel or the channel is deleted the channel's unread count will reset to zero
26540
+ return 0;
26541
+ }
26542
+ return (_c = (_a = marker === null || marker === void 0 ? void 0 : marker.unreadCount) !== null && _a !== void 0 ? _a : (_b = getCachedMarker(channel.channelId)) === null || _b === void 0 ? void 0 : _b.unreadCount) !== null && _c !== void 0 ? _c : 0;
26543
+ };
26544
+ function convertFromRaw(channel, marker) {
26545
+ return Object.assign(Object.assign({}, channel), { isUnreadCountSupport: isUnreadCountSupport(channel), unreadCount: getUnreadCount(channel, marker) });
26546
+ }
26547
+ function updateChannelMarker(channel, marker) {
26548
+ return Object.assign(Object.assign({}, channel), { unreadCount: getUnreadCount(channel, marker), updatedAt: new Date().toISOString() });
25425
26549
  }
25426
- const prepareChannelPayload = (rawPayload) => {
25427
- const channels = rawPayload.channels.map(channel => convertFromRaw$1(channel, getSegmentParams(channel)));
26550
+ const prepareChannelPayload = async (rawPayload) => {
26551
+ // make a fetch marker to prepare it for merging with the raw channel payload.
26552
+ let markers = [];
26553
+ const markerIds = rawPayload.channels
26554
+ // filter channel by type. Only conversation, community and broadcast type are included.
26555
+ .filter(isUnreadCountSupport)
26556
+ .map(({ channelId }) => channelId);
26557
+ if (markerIds.length > 0)
26558
+ // from the spec, allow marker fetch to fail
26559
+ try {
26560
+ ({ data: markers } = await getChannelMarkers(markerIds));
26561
+ }
26562
+ catch (e) {
26563
+ // empty block
26564
+ }
26565
+ // attach marker to channel
26566
+ const channels = rawPayload.channels.map(channel => {
26567
+ const marker = markers === null || markers === void 0 ? void 0 : markers.find(({ entityId }) => entityId === channel.channelId);
26568
+ return convertFromRaw(channel, marker);
26569
+ });
26570
+ // user marker to channel users
25428
26571
  const channelUsers = withUsers(rawPayload.channelUsers);
25429
- return Object.assign(Object.assign({}, rawPayload), { channels, channelUsers });
26572
+ return Object.assign(Object.assign({}, rawPayload), { channels,
26573
+ channelUsers });
25430
26574
  };
25431
26575
 
25432
26576
  /* begin_public_function
@@ -25461,7 +26605,7 @@ const queryChannels = async (query) => {
25461
26605
  } }),
25462
26606
  });
25463
26607
  const { paging } = queryPayload, payload = __rest(queryPayload, ["paging"]);
25464
- const data = prepareChannelPayload(payload);
26608
+ const data = await prepareChannelPayload(payload);
25465
26609
  const { channels } = data;
25466
26610
  const cachedAt = client.cache && Date.now();
25467
26611
  if (client.cache) {
@@ -25546,7 +26690,7 @@ const getChannels = async (channelIds) => {
25546
26690
  });
25547
26691
  throw error;
25548
26692
  }
25549
- const data = prepareChannelPayload(payload);
26693
+ const data = await prepareChannelPayload(payload);
25550
26694
  const cachedAt = client.cache && Date.now();
25551
26695
  if (client.cache)
25552
26696
  ingestInCache(data, { cachedAt });
@@ -25611,7 +26755,7 @@ const getChannel = async (channelId) => {
25611
26755
  let data;
25612
26756
  try {
25613
26757
  const { data: payload } = await client.http.get(`/api/v3/channels/${encodeURIComponent(channelId)}`);
25614
- data = prepareChannelPayload(payload);
26758
+ data = await prepareChannelPayload(payload);
25615
26759
  }
25616
26760
  catch (error) {
25617
26761
  if (checkIfShouldGoesToTombstone(error === null || error === void 0 ? void 0 : error.code)) {
@@ -25683,7 +26827,7 @@ const createChannel = async (bundle) => {
25683
26827
  else {
25684
26828
  payload = await client.http.post('/api/v3/channels', bundle);
25685
26829
  }
25686
- const data = prepareChannelPayload(payload.data);
26830
+ const data = await prepareChannelPayload(payload.data);
25687
26831
  const cachedAt = client.cache && Date.now();
25688
26832
  if (client.cache)
25689
26833
  ingestInCache(data, { cachedAt });
@@ -25717,7 +26861,7 @@ const updateChannel = async (channelId, patch) => {
25717
26861
  const client = getActiveClient();
25718
26862
  client.log('channel/updateChannel', channelId, patch);
25719
26863
  const { data: payload } = await client.http.put(`/api/v3/channels/${encodeURIComponent(channelId)}`, patch);
25720
- const data = prepareChannelPayload(payload);
26864
+ const data = await prepareChannelPayload(payload);
25721
26865
  const cachedAt = client.cache && Date.now();
25722
26866
  if (client.cache)
25723
26867
  ingestInCache(data, { cachedAt });
@@ -25773,7 +26917,7 @@ const joinChannel = async (channelId) => {
25773
26917
  const client = getActiveClient();
25774
26918
  client.log('channel/joinChannel', channelId);
25775
26919
  const { data: payload } = await client.http.post(`/api/v3/channels/${encodeURIComponent(channelId)}/join`);
25776
- const data = prepareChannelPayload(payload);
26920
+ const data = await prepareChannelPayload(payload);
25777
26921
  if (client.cache)
25778
26922
  ingestInCache(data);
25779
26923
  const { channelUsers } = data;
@@ -25802,7 +26946,7 @@ const leaveChannel = async (channelId) => {
25802
26946
  const client = getActiveClient();
25803
26947
  client.log('channel/leaveChannel', channelId);
25804
26948
  const { data: payload } = await client.http.delete(`/api/v3/channels/${encodeURIComponent(channelId)}/leave`);
25805
- const data = prepareChannelPayload(payload);
26949
+ const data = await prepareChannelPayload(payload);
25806
26950
  if (client.cache)
25807
26951
  ingestInCache(data);
25808
26952
  const { channelUsers } = data;
@@ -25837,7 +26981,7 @@ const queryChannelMembers = async (query) => {
25837
26981
  } }),
25838
26982
  });
25839
26983
  const { paging } = queryPayload, payload = __rest(queryPayload, ["paging"]);
25840
- const preparedPayload = prepareChannelPayload(payload);
26984
+ const preparedPayload = await prepareChannelPayload(payload);
25841
26985
  const { channelUsers } = preparedPayload;
25842
26986
  const cachedAt = client.cache && Date.now();
25843
26987
  if (client.cache) {
@@ -25928,7 +27072,7 @@ const addChannelMembers = async (channelId, userIds) => {
25928
27072
  * should fire event for each user that was added
25929
27073
  */
25930
27074
  userIds.forEach(id => fireEvent('channel.membersAdded', Object.assign(Object.assign({}, payload), { channelUsers: payload.channelUsers.filter(u => u.userId === id) })));
25931
- const data = prepareChannelPayload(payload);
27075
+ const data = await prepareChannelPayload(payload);
25932
27076
  if (client.cache)
25933
27077
  ingestInCache(data);
25934
27078
  const { channelUsers } = data;
@@ -25962,7 +27106,7 @@ const removeChannelMembers = async (channelId, userIds) => {
25962
27106
  * should fire event for each user that was removed
25963
27107
  */
25964
27108
  userIds.forEach(id => fireEvent('channel.membersRemoved', Object.assign(Object.assign({}, payload), { channelUsers: payload.channelUsers.filter(u => u.userId === id) })));
25965
- const data = prepareChannelPayload(payload);
27109
+ const data = await prepareChannelPayload(payload);
25966
27110
  if (client.cache)
25967
27111
  ingestInCache(data);
25968
27112
  const { channelUsers } = data;
@@ -25993,7 +27137,7 @@ const addChannelMembersRole = async (channelId, roleId, userIds) => {
25993
27137
  const client = getActiveClient();
25994
27138
  client.log('channel/addChannelMembersRole', channelId, roleId, userIds);
25995
27139
  const { data: payload } = await client.http.post(`/api/v3/channels/${encodeURIComponent(channelId)}/users/roles`, { channelId, role: roleId, userIds });
25996
- const data = prepareChannelPayload(payload);
27140
+ const data = await prepareChannelPayload(payload);
25997
27141
  if (client.cache)
25998
27142
  ingestInCache(data);
25999
27143
  const { channelUsers } = data;
@@ -26024,7 +27168,7 @@ const removeChannelMembersRole = async (channelId, roleId, userIds) => {
26024
27168
  const client = getActiveClient();
26025
27169
  client.log('channel/removeChannelMembersRole', channelId, roleId, userIds);
26026
27170
  const { data: payload } = await client.http.delete(`/api/v3/channels/${encodeURIComponent(channelId)}/users/roles`, { data: { channelId, role: roleId, userIds } });
26027
- const data = prepareChannelPayload(payload);
27171
+ const data = await prepareChannelPayload(payload);
26028
27172
  if (client.cache)
26029
27173
  ingestInCache(data);
26030
27174
  const { channelUsers } = data;
@@ -26055,7 +27199,7 @@ const banChannelMembers = async (channelId, userIds) => {
26055
27199
  const { data: payload } = await client.http.put(`/api/v3/channels/${channelId}/users/ban`, {
26056
27200
  userIds,
26057
27201
  });
26058
- const preparedPayload = prepareChannelPayload(payload);
27202
+ const preparedPayload = await prepareChannelPayload(payload);
26059
27203
  const { channelUsers } = preparedPayload;
26060
27204
  const cachedAt = client.cache && Date.now();
26061
27205
  if (client.cache)
@@ -26090,7 +27234,7 @@ const unbanChannelMembers = async (channelId, userIds) => {
26090
27234
  const { data: payload } = await client.http.put(`/api/v3/channels/${encodeURIComponent(channelId)}/users/unban`, {
26091
27235
  userIds,
26092
27236
  });
26093
- const preparedPayload = prepareChannelPayload(payload);
27237
+ const preparedPayload = await prepareChannelPayload(payload);
26094
27238
  const cachedAt = client.cache && Date.now();
26095
27239
  if (client.cache)
26096
27240
  ingestInCache(preparedPayload, { cachedAt });
@@ -26102,88 +27246,6 @@ const unbanChannelMembers = async (channelId, userIds) => {
26102
27246
  };
26103
27247
  /* end_public_function */
26104
27248
 
26105
- /* begin_public_function
26106
- id: channel.start_reading
26107
- */
26108
- /**
26109
- * ```js
26110
- * import { startReading } from '@amityco/ts-sdk'
26111
- * const success = await startReading('foo')
26112
- * ```
26113
- *
26114
- * Mark all messages as read and start reading message inside channel
26115
- *
26116
- * @param subChannelId - The channel ID to start reading.
26117
- * @param userId - The user ID of channel member.
26118
- * @return A success boolean if the channel reading of the sub channel had begun.
26119
- *
26120
- * @category Message API
26121
- * @async
26122
- */
26123
- const startReading = async (subChannelId, userId = getActiveClient().userId) => {
26124
- const client = getActiveClient();
26125
- client.log('message/startReading', { subChannelId });
26126
- const subChannel = pullFromCache(['subChannel', 'get', subChannelId]);
26127
- if (!subChannel) {
26128
- return;
26129
- }
26130
- const { channelId } = subChannel.data;
26131
- const channel = pullFromCache(['channel', 'get', channelId]);
26132
- if (!channel || channel.data.defaultSubChannelId !== subChannelId) {
26133
- return;
26134
- }
26135
- const update = Object.assign(Object.assign({}, channel.data), {
26136
- // @ts-ignore
26137
- localReading: true, defaultSubChannelUnreadCount: 0, defaultSubChannelHasUnreadMention: false });
26138
- pushToCache(['channel', 'get', channelId], update);
26139
- client.emitter.emit('local.channel.updated', { channels: [update] });
26140
- const result = await synchronousWSCall(client, 'channel.startReading', {
26141
- channelId,
26142
- });
26143
- return !!result;
26144
- };
26145
- /* end_public_function */
26146
-
26147
- /* begin_public_function
26148
- id: channel.stop_reading
26149
- */
26150
- /**
26151
- * ```js
26152
- * import { stopReading } from '@amityco/ts-sdk'
26153
- * const success = await stopReading('foo')
26154
- * ```
26155
- *
26156
- * Stop reading message inside channel
26157
- *
26158
- * @param subChannelId - The channel ID to stop reading.
26159
- * @return A success boolean if the sub channel reading was halted.
26160
- *
26161
- * @category Message API
26162
- * @async
26163
- */
26164
- const stopReading = async (subChannelId) => {
26165
- const client = getActiveClient();
26166
- client.log('message/stopReading', { subChannelId });
26167
- const subChannel = pullFromCache(['subChannel', 'get', subChannelId]);
26168
- if (!subChannel) {
26169
- return;
26170
- }
26171
- const { channelId } = subChannel.data;
26172
- const channel = pullFromCache(['channel', 'get', channelId]);
26173
- if (!channel || channel.data.defaultSubChannelId !== subChannelId) {
26174
- return;
26175
- }
26176
- const update = Object.assign(Object.assign({}, channel.data), {
26177
- // @ts-ignore
26178
- localReading: false });
26179
- pushToCache(['channel', 'get', channelId], update);
26180
- const result = await synchronousWSCall(client, 'channel.stopReading', {
26181
- channelId,
26182
- });
26183
- return !!result;
26184
- };
26185
- /* end_public_function */
26186
-
26187
27249
  /**
26188
27250
  * ```js
26189
27251
  * import { onChannelCreated } from '@amityco/ts-sdk'
@@ -26192,602 +27254,345 @@ const stopReading = async (subChannelId) => {
26192
27254
  * })
26193
27255
  * ```
26194
27256
  *
26195
- * Fired when any {@link Amity.Channel} have been created
26196
- *
26197
- * @param callback The function to call when the event was fired
26198
- * @returns an {@link Amity.Unsubscriber} function to stop listening
26199
- *
26200
- * @category Channel Events
26201
- */
26202
- const onChannelCreated = (callback) => {
26203
- const client = getActiveClient();
26204
- const filter = (payload) => {
26205
- const data = prepareChannelPayload(payload);
26206
- ingestInCache(data);
26207
- callback(data.channels[0]);
26208
- };
26209
- return createEventSubscriber(client, 'onChannelCreated', 'channel.created', filter);
26210
- };
26211
-
26212
- /**
26213
- * ```js
26214
- * import { onChannelUpdated } from '@amityco/ts-sdk'
26215
- * const dispose = onChannelUpdated(channel => {
26216
- * // ...
26217
- * })
26218
- * ```
26219
- *
26220
- * Fired when any {@link Amity.Channel} have been updated
26221
- *
26222
- * @param callback The function to call when the event was fired
26223
- * @returns an {@link Amity.Unsubscriber} function to stop listening
26224
- *
26225
- * @category Channel Events
26226
- */
26227
- const onChannelUpdated = (callback) => {
26228
- const client = getActiveClient();
26229
- const filter = (payload) => {
26230
- const data = prepareChannelPayload(payload);
26231
- ingestInCache(data);
26232
- callback(data.channels[0]);
26233
- };
26234
- const disposers = [
26235
- createEventSubscriber(client, 'onChannelUpdated', 'channel.updated', filter),
26236
- createEventSubscriber(client, 'local.channel.updated', 'local.channel.updated', payload => callback(payload.channels[0])),
26237
- ];
26238
- return () => {
26239
- disposers.forEach(fn => fn());
26240
- };
26241
- };
26242
-
26243
- /**
26244
- * ```js
26245
- * import { onChannelDeleted } from '@amityco/ts-sdk'
26246
- * const dispose = onChannelDeleted(channel => {
26247
- * // ...
26248
- * })
26249
- * ```
26250
- *
26251
- * Fired when any {@link Amity.Channel} have been deleted
26252
- *
26253
- * @param callback The function to call when the event was fired
26254
- * @returns an {@link Amity.Unsubscriber} function to stop listening
26255
- *
26256
- * @category Channel Events
26257
- */
26258
- const onChannelDeleted = (callback) => {
26259
- const client = getActiveClient();
26260
- const filter = (payload) => {
26261
- const data = prepareChannelPayload(payload);
26262
- ingestInCache(data);
26263
- callback(data.channels[0]);
26264
- };
26265
- return createEventSubscriber(client, 'onChannelDeleted', 'channel.deleted', filter);
26266
- };
26267
-
26268
- /**
26269
- * ```js
26270
- * import { onChannelJoined } from '@amityco/ts-sdk'
26271
- * const dispose = onChannelJoined((channel, member) => {
26272
- * // ...
26273
- * })
26274
- * ```
26275
- *
26276
- * Fired when any {@link Amity.Channel} was joined
26277
- *
26278
- * @param callback The function to call when the event was fired
26279
- * @returns an {@link Amity.Unsubscriber} function to stop listening
26280
- *
26281
- * @category Channel Events
26282
- */
26283
- const onChannelJoined = (callback) => {
26284
- const client = getActiveClient();
26285
- const filter = (payload) => {
26286
- const preparedPayload = prepareChannelPayload(payload);
26287
- const { channels, channelUsers } = preparedPayload;
26288
- ingestInCache(preparedPayload);
26289
- callback(channels[0], channelUsers[0]);
26290
- };
26291
- return createEventSubscriber(client, 'onChannelJoined', 'channel.joined', filter);
26292
- };
26293
-
26294
- /**
26295
- * ```js
26296
- * import { onChannelLeft } from '@amityco/ts-sdk'
26297
- * const dispose = onChannelLeft((channel, member) => {
26298
- * // ...
26299
- * })
26300
- * ```
26301
- *
26302
- * Fired when any {@link Amity.Channel} was left
26303
- *
26304
- * @param callback The function to call when the event was fired
26305
- * @returns an {@link Amity.Unsubscriber} function to stop listening
26306
- *
26307
- * @category Channel Events
26308
- */
26309
- const onChannelLeft = (callback) => {
26310
- const client = getActiveClient();
26311
- const filter = (payload) => {
26312
- const preparedPayload = prepareChannelPayload(payload);
26313
- const { channels, channelUsers } = preparedPayload;
26314
- ingestInCache(preparedPayload);
26315
- callback(channels[0], channelUsers[0]);
26316
- };
26317
- return createEventSubscriber(client, 'onChannelLeft', 'channel.left', filter);
26318
- };
26319
-
26320
- /**
26321
- * ```js
26322
- * import { onChannelMuted } from '@amityco/ts-sdk'
26323
- * const dispose = onChannelMuted(channel => {
26324
- * // ...
26325
- * })
26326
- * ```
26327
- *
26328
- * Fired when any {@link Amity.Channel} have been muted
27257
+ * Fired when any {@link Amity.Channel} have been created
26329
27258
  *
26330
27259
  * @param callback The function to call when the event was fired
26331
27260
  * @returns an {@link Amity.Unsubscriber} function to stop listening
26332
27261
  *
26333
27262
  * @category Channel Events
26334
27263
  */
26335
- const onChannelMuted = (callback) => {
27264
+ const onChannelCreated = (callback) => {
26336
27265
  const client = getActiveClient();
26337
- const filter = (payload) => {
26338
- const data = prepareChannelPayload(payload);
27266
+ const filter = async (payload) => {
27267
+ const data = await prepareChannelPayload(payload);
26339
27268
  ingestInCache(data);
26340
27269
  callback(data.channels[0]);
26341
27270
  };
26342
- return createEventSubscriber(client, 'onChannelMuted', 'channel.setMuted', filter);
27271
+ return createEventSubscriber(client, 'onChannelCreated', 'channel.created', filter);
26343
27272
  };
26344
27273
 
26345
27274
  /**
26346
27275
  * ```js
26347
- * import { onChannelMemberAdded } from '@amityco/ts-sdk'
26348
- * const dispose = onChannelMemberAdded((channel, member) => {
27276
+ * import { onChannelUpdated } from '@amityco/ts-sdk'
27277
+ * const dispose = onChannelUpdated(channel => {
26349
27278
  * // ...
26350
27279
  * })
26351
27280
  * ```
26352
27281
  *
26353
- * Fired when any {@link Amity.User} has been added to any {@link Amity.Channel}
27282
+ * Fired when any {@link Amity.Channel} have been updated
26354
27283
  *
26355
27284
  * @param callback The function to call when the event was fired
26356
27285
  * @returns an {@link Amity.Unsubscriber} function to stop listening
26357
27286
  *
26358
27287
  * @category Channel Events
26359
27288
  */
26360
- const onChannelMemberAdded = (callback) => {
27289
+ const onChannelUpdated = (callback) => {
26361
27290
  const client = getActiveClient();
26362
- const filter = (payload) => {
26363
- const preparedPayload = prepareChannelPayload(payload);
26364
- const { channels, channelUsers } = preparedPayload;
26365
- ingestInCache(preparedPayload);
26366
- callback(channels[0], channelUsers.find(cu => cu.membership === 'member'));
27291
+ const filter = async (payload) => {
27292
+ const data = await prepareChannelPayload(payload);
27293
+ ingestInCache(data);
27294
+ callback(data.channels[0]);
27295
+ };
27296
+ const channelMarkerChangeHandler = async (rawPayload) => {
27297
+ var _a;
27298
+ const marker = rawPayload.userEntityMarkers[0];
27299
+ const cacheKey = ['channel', 'get', marker.entityId];
27300
+ const channel = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
27301
+ if (!channel)
27302
+ return;
27303
+ const updated = updateChannelMarker(channel, marker);
27304
+ upsertInCache(cacheKey, updated);
27305
+ callback(updated);
27306
+ };
27307
+ const disposers = [
27308
+ createEventSubscriber(client, 'onChannelUpdated', 'channel.updated', filter),
27309
+ createEventSubscriber(client, 'onChannelUpdated', 'local.channel.updated', payload => callback(payload.channels[0])),
27310
+ createEventSubscriber(client, 'onChannelUpdated', 'local.channelMarker.fetched', channelMarkerChangeHandler),
27311
+ ];
27312
+ return () => {
27313
+ disposers.forEach(fn => fn());
26367
27314
  };
26368
- return createEventSubscriber(client, 'onChannelMemberAdded', 'channel.membersAdded', filter);
26369
27315
  };
26370
27316
 
26371
27317
  /**
26372
27318
  * ```js
26373
- * import { onChannelMemberRemoved } from '@amityco/ts-sdk'
26374
- * const dispose = onChannelMemberRemoved((channel, member) => {
27319
+ * import { onChannelDeleted } from '@amityco/ts-sdk'
27320
+ * const dispose = onChannelDeleted(channel => {
26375
27321
  * // ...
26376
27322
  * })
26377
27323
  * ```
26378
27324
  *
26379
- * Fired when any {@link Amity.User} has been removed from any {@link Amity.Channel}
27325
+ * Fired when any {@link Amity.Channel} have been deleted
26380
27326
  *
26381
27327
  * @param callback The function to call when the event was fired
26382
27328
  * @returns an {@link Amity.Unsubscriber} function to stop listening
26383
27329
  *
26384
27330
  * @category Channel Events
26385
27331
  */
26386
- const onChannelMemberRemoved = (callback) => {
27332
+ const onChannelDeleted = (callback) => {
26387
27333
  const client = getActiveClient();
26388
- const filter = (payload) => {
26389
- const preparedPayload = prepareChannelPayload(payload);
26390
- const { channels, channelUsers } = preparedPayload;
26391
- ingestInCache(preparedPayload);
26392
- callback(channels[0], channelUsers[0]);
27334
+ const filter = async (payload) => {
27335
+ const data = await prepareChannelPayload(payload);
27336
+ ingestInCache(data);
27337
+ callback(data.channels[0]);
26393
27338
  };
26394
- return createEventSubscriber(client, 'onChannelMemberRemoved', 'channel.membersRemoved', filter);
27339
+ return createEventSubscriber(client, 'onChannelDeleted', 'channel.deleted', filter);
26395
27340
  };
26396
27341
 
26397
27342
  /**
26398
27343
  * ```js
26399
- * import { onChannelMemberBanned } from '@amityco/ts-sdk'
26400
- * const dispose = onChannelMemberBanned((channel, member) => {
27344
+ * import { onChannelJoined } from '@amityco/ts-sdk'
27345
+ * const dispose = onChannelJoined((channel, member) => {
26401
27346
  * // ...
26402
27347
  * })
26403
27348
  * ```
26404
27349
  *
26405
- * Fired when any {@link Amity.User} has been banned from any {@link Amity.Channel}
27350
+ * Fired when any {@link Amity.Channel} was joined
26406
27351
  *
26407
27352
  * @param callback The function to call when the event was fired
26408
27353
  * @returns an {@link Amity.Unsubscriber} function to stop listening
26409
27354
  *
26410
27355
  * @category Channel Events
26411
27356
  */
26412
- const onChannelMemberBanned = (callback) => {
27357
+ const onChannelJoined = (callback) => {
26413
27358
  const client = getActiveClient();
26414
- const filter = (payload) => {
26415
- const preparedPayload = prepareChannelPayload(payload);
27359
+ const filter = async (payload) => {
27360
+ const preparedPayload = await prepareChannelPayload(payload);
26416
27361
  const { channels, channelUsers } = preparedPayload;
26417
27362
  ingestInCache(preparedPayload);
26418
- callback(channels[0], channelUsers.find(cu => cu.membership === 'banned'));
27363
+ callback(channels[0], channelUsers[0]);
26419
27364
  };
26420
- return createEventSubscriber(client, 'onChannelMemberBanned', 'channel.banned', filter);
27365
+ return createEventSubscriber(client, 'onChannelJoined', 'channel.joined', filter);
26421
27366
  };
26422
27367
 
26423
27368
  /**
26424
27369
  * ```js
26425
- * import { onChannelMemberUnbanned } from '@amityco/ts-sdk'
26426
- * const dispose = onChannelMemberUnbanned((channel, member) => {
27370
+ * import { onChannelLeft } from '@amityco/ts-sdk'
27371
+ * const dispose = onChannelLeft((channel, member) => {
26427
27372
  * // ...
26428
27373
  * })
26429
27374
  * ```
26430
27375
  *
26431
- * Fired when any {@link Amity.User} has been unbanned from any {@link Amity.Channel}
27376
+ * Fired when any {@link Amity.Channel} was left
26432
27377
  *
26433
27378
  * @param callback The function to call when the event was fired
26434
27379
  * @returns an {@link Amity.Unsubscriber} function to stop listening
26435
27380
  *
26436
27381
  * @category Channel Events
26437
27382
  */
26438
- const onChannelMemberUnbanned = (callback) => {
27383
+ const onChannelLeft = (callback) => {
26439
27384
  const client = getActiveClient();
26440
- const filter = (payload) => {
26441
- const preparedPayload = prepareChannelPayload(payload);
27385
+ const filter = async (payload) => {
27386
+ const preparedPayload = await prepareChannelPayload(payload);
26442
27387
  const { channels, channelUsers } = preparedPayload;
26443
27388
  ingestInCache(preparedPayload);
26444
- callback(channels[0], channelUsers.find(cu => cu.membership === 'none'));
26445
- };
26446
- return createEventSubscriber(client, 'onChannelMemberUnbanned', 'channel.unbanned', filter);
26447
- };
26448
-
26449
- /**
26450
- * ```js
26451
- * import { observeChannel } from '@amityco/ts-sdk'
26452
- *
26453
- * let channel = {}
26454
- * const dispose = observeChannel(channelId, ({ data }) => channel = data)
26455
- * ```
26456
- *
26457
- * Observe all mutation on a given {@link Amity.Channel}
26458
- *
26459
- * @param channelId the ID of the channel to observe
26460
- * @param callback the function to call when new data are available
26461
- * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the channel
26462
- *
26463
- * @category Channel Observer
26464
- */
26465
- const observeChannel = (channelId, callback) => {
26466
- const { log } = getActiveClient();
26467
- const timestamp = Date.now();
26468
- log(`observeChannel(tmpid: ${timestamp}) > listen`);
26469
- // wrapper function to make sure
26470
- const router = (result, action) => {
26471
- var _a, _b, _c;
26472
- // filter function
26473
- if (((_a = result.data) === null || _a === void 0 ? void 0 : _a.channelId) !== channelId)
26474
- return;
26475
- if (callback instanceof Function)
26476
- return callback(result);
26477
- if (action !== 'onFetch')
26478
- (_b = callback.onEvent) === null || _b === void 0 ? void 0 : _b.call(callback, action, result);
26479
- (_c = callback[action]) === null || _c === void 0 ? void 0 : _c.call(callback, result);
26480
- };
26481
- const disposers = [];
26482
- disposers.push(onChannelUpdated(data => router({ data, loading: false, origin: 'event' }, 'onUpdate')), onChannelDeleted(data => router({ data, loading: false, origin: 'event' }, 'onDelete')), onChannelJoined(data => router({ data, loading: false, origin: 'event' }, 'onJoin')), onChannelLeft(data => router({ data, loading: false, origin: 'event' }, 'onLeft')), onChannelMuted(data => router({ data, loading: false, origin: 'event' }, 'onMute')), onChannelMemberAdded(data => router({ data, loading: false, origin: 'event' }, 'onMemberAdded')), onChannelMemberRemoved(data => router({ data, loading: false, origin: 'event' }, 'onMemberRemoved')));
26483
- runQuery(createQuery(getChannel, channelId), result => result.data && router(result, 'onFetch'));
26484
- return () => {
26485
- log(`observeChannel(tmpid: ${timestamp}) > dispose`);
26486
- disposers.forEach(fn => fn());
26487
- };
26488
- };
26489
-
26490
- /**
26491
- * ```js
26492
- * import { observeChannels } from '@amityco/ts-sdk'
26493
- *
26494
- * let channels = []
26495
- * const unsub = observeChannels(channel => merge(channels, channel))
26496
- * ```
26497
- *
26498
- * Observe all mutations on a list of {@link Amity.Channel} for a current user
26499
- *
26500
- * @param callback the function to call when new data are available
26501
- * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the channels
26502
- *
26503
- * @category Channel Observer
26504
- */
26505
- const observeChannels = (callback) => {
26506
- const { log } = getActiveClient();
26507
- const timestamp = Date.now();
26508
- log(`observeChannels(tmpid: ${timestamp}) > listen`);
26509
- const disposers = [];
26510
- const router = (channel, action) => {
26511
- var _a, _b;
26512
- if (callback instanceof Function)
26513
- return callback(channel);
26514
- (_a = callback.onEvent) === null || _a === void 0 ? void 0 : _a.call(callback, action, channel);
26515
- (_b = callback[action]) === null || _b === void 0 ? void 0 : _b.call(callback, channel);
26516
- };
26517
- disposers.push(onChannelCreated(data => router(data, 'onCreate')), onChannelUpdated(data => router(data, 'onUpdate')), onChannelDeleted(data => router(data, 'onDelete')), onChannelJoined(data => router(data, 'onJoin')), onChannelLeft(data => router(data, 'onLeft')), onChannelMuted(data => router(data, 'onMute')), onChannelMemberAdded(data => router(data, 'onMemberAdded')), onChannelMemberRemoved(data => router(data, 'onMemberRemoved')));
26518
- return () => {
26519
- log(`observeChannels(tmpid: ${timestamp}) > dispose`);
26520
- disposers.forEach(fn => fn());
26521
- };
26522
- };
26523
-
26524
- function hasMention(model, userId) {
26525
- var _a, _b;
26526
- const channelMention = (_a = model === null || model === void 0 ? void 0 : model.mentionees) === null || _a === void 0 ? void 0 : _a.find(x => x.type === 'channel');
26527
- if (channelMention) {
26528
- return true;
26529
- }
26530
- const userMention = (_b = model === null || model === void 0 ? void 0 : model.mentionees) === null || _b === void 0 ? void 0 : _b.find(x => x.type === 'user');
26531
- if (userMention) {
26532
- return userMention.userIds.includes(userId);
26533
- }
26534
- return false;
26535
- }
26536
- function isCollectionOutdated(collection, newItem, action) {
26537
- const key = identifyModelKey(newItem);
26538
- // @ts-ignore
26539
- const item = collection.find(x => x[key] === newItem[key]);
26540
- if (item) {
26541
- return hasUpdates(item, newItem);
26542
- }
26543
- return action === 'onCreate';
26544
- }
26545
- function merge(collection1, collection2) {
26546
- const temp = [...collection1, ...collection2];
26547
- if (temp.length === 0) {
26548
- return [];
26549
- }
26550
- const key = identifyModelKey(temp[0]);
26551
- const map = new Map();
26552
- // @ts-ignore
26553
- temp.forEach(x => map.set(x[key], x));
26554
- return Array.from(map.values());
26555
- }
26556
-
26557
- /**
26558
- * ```js
26559
- * import { onMessageCreated } from '@amityco/ts-sdk'
26560
- * const dispose = onMessageCreated(message => {
26561
- * // ...
26562
- * })
26563
- * ```
26564
- *
26565
- * Fired when an {@link Amity.Message} has been created
26566
- *
26567
- * @param callback The function to call when the event was fired
26568
- * @returns an {@link Amity.Unsubscriber} function to stop listening
26569
- *
26570
- * @category Message Events
26571
- */
26572
- const onMessageCreated = (callback) => {
26573
- const client = getActiveClient();
26574
- const filter = (rawPayload) => {
26575
- const payload = prepareMessagePayload(rawPayload);
26576
- const message = payload.messages[0];
26577
- const cached = pullFromCache(['channel', 'get', message.channelId]);
26578
- if (cached && cached.data.defaultSubChannelId === message.subChannelId) {
26579
- let update;
26580
- // @ts-ignore
26581
- if (cached.data.localReading) {
26582
- update = Object.assign(Object.assign({}, cached.data), { localReadToSegment: message.channelSegment, localLastMentionSegment: hasMention(message, client.userId)
26583
- ? message.channelSegment
26584
- : cached.data.localLastMentionSegment, messageCount: message.channelSegment, lastActivity: message.createdAt, updatedAt: message.createdAt });
26585
- }
26586
- else {
26587
- update = Object.assign(Object.assign({}, cached.data), { defaultSubChannelHasUnreadMention: hasMention(message, client.userId) || cached.data.defaultSubChannelHasUnreadMention, defaultSubChannelUnreadCount: message.channelSegment - cached.data.localReadToSegment, lastActivity: message.createdAt, messageCount: message.channelSegment, updatedAt: message.createdAt });
26588
- }
26589
- pushToCache(['channel', 'get', message.channelId], update);
26590
- client.emitter.emit('local.channel.updated', { channels: [update] });
26591
- }
26592
- ingestInCache(payload);
26593
- callback(message);
26594
- };
26595
- const disposers = [
26596
- createEventSubscriber(client, 'message/onMessageCreated', 'message.created', filter),
26597
- createEventSubscriber(client, 'local.message.created', 'local.message.created', payload => callback(payload.messages[0])),
26598
- ];
26599
- return () => {
26600
- disposers.forEach(fn => fn());
27389
+ callback(channels[0], channelUsers[0]);
26601
27390
  };
27391
+ return createEventSubscriber(client, 'onChannelLeft', 'channel.left', filter);
26602
27392
  };
26603
27393
 
26604
27394
  /**
26605
27395
  * ```js
26606
- * import { onMessageUpdated } from '@amityco/ts-sdk'
26607
- * const dispose = onMessageUpdated(message => {
27396
+ * import { onChannelMuted } from '@amityco/ts-sdk'
27397
+ * const dispose = onChannelMuted(channel => {
26608
27398
  * // ...
26609
27399
  * })
26610
27400
  * ```
26611
27401
  *
26612
- * Fired when an {@link Amity.Message} has been updated
27402
+ * Fired when any {@link Amity.Channel} have been muted
26613
27403
  *
26614
27404
  * @param callback The function to call when the event was fired
26615
27405
  * @returns an {@link Amity.Unsubscriber} function to stop listening
26616
27406
  *
26617
- * @category Message Events
27407
+ * @category Channel Events
26618
27408
  */
26619
- const onMessageUpdated = (callback) => {
27409
+ const onChannelMuted = (callback) => {
26620
27410
  const client = getActiveClient();
26621
- const filter = (rawPayload) => {
26622
- const payload = prepareMessagePayload(rawPayload);
26623
- ingestInCache(payload);
26624
- callback(payload.messages[0]);
26625
- };
26626
- const disposers = [
26627
- createEventSubscriber(client, 'message/onMessageUpdated', 'message.updated', filter),
26628
- createEventSubscriber(client, 'local.message.updated', 'local.message.updated', payload => callback(payload.messages[0])),
26629
- ];
26630
- return () => {
26631
- disposers.forEach(fn => fn());
27411
+ const filter = async (payload) => {
27412
+ const data = await prepareChannelPayload(payload);
27413
+ ingestInCache(data);
27414
+ callback(data.channels[0]);
26632
27415
  };
27416
+ return createEventSubscriber(client, 'onChannelMuted', 'channel.setMuted', filter);
26633
27417
  };
26634
27418
 
26635
27419
  /**
26636
27420
  * ```js
26637
- * import { onMessageDeleted } from '@amityco/ts-sdk'
26638
- * const dispose = onMessageDeleted(message => {
27421
+ * import { onChannelMemberAdded } from '@amityco/ts-sdk'
27422
+ * const dispose = onChannelMemberAdded((channel, member) => {
26639
27423
  * // ...
26640
27424
  * })
26641
27425
  * ```
26642
27426
  *
26643
- * Fired when an {@link Amity.Message} was deleted
27427
+ * Fired when any {@link Amity.User} has been added to any {@link Amity.Channel}
26644
27428
  *
26645
27429
  * @param callback The function to call when the event was fired
26646
27430
  * @returns an {@link Amity.Unsubscriber} function to stop listening
26647
27431
  *
26648
- * @category Message Events
27432
+ * @category Channel Events
26649
27433
  */
26650
- const onMessageDeleted = (callback) => {
27434
+ const onChannelMemberAdded = (callback) => {
26651
27435
  const client = getActiveClient();
26652
- const filter = (rawPayload) => {
26653
- const payload = prepareMessagePayload(rawPayload);
26654
- ingestInCache(payload);
26655
- callback(payload.messages[0]);
26656
- };
26657
- const disposers = [
26658
- createEventSubscriber(client, 'message/onMessageDeleted', 'message.deleted', filter),
26659
- createEventSubscriber(client, 'local.message.deleted', 'local.message.deleted', payload => callback(payload.messages[0])),
26660
- ];
26661
- return () => {
26662
- disposers.forEach(fn => fn());
27436
+ const filter = async (payload) => {
27437
+ const preparedPayload = await prepareChannelPayload(payload);
27438
+ const { channels, channelUsers } = preparedPayload;
27439
+ ingestInCache(preparedPayload);
27440
+ callback(channels[0], channelUsers.find(cu => cu.membership === 'member'));
26663
27441
  };
27442
+ return createEventSubscriber(client, 'onChannelMemberAdded', 'channel.membersAdded', filter);
26664
27443
  };
26665
27444
 
26666
27445
  /**
26667
27446
  * ```js
26668
- * import { onMessageFlagged } from '@amityco/ts-sdk'
26669
- * const dispose = onMessageFlagged(message => {
27447
+ * import { onChannelMemberRemoved } from '@amityco/ts-sdk'
27448
+ * const dispose = onChannelMemberRemoved((channel, member) => {
26670
27449
  * // ...
26671
27450
  * })
26672
27451
  * ```
26673
27452
  *
26674
- * Fired when a {@link Amity.Message} has been flagged
27453
+ * Fired when any {@link Amity.User} has been removed from any {@link Amity.Channel}
26675
27454
  *
26676
27455
  * @param callback The function to call when the event was fired
26677
27456
  * @returns an {@link Amity.Unsubscriber} function to stop listening
26678
27457
  *
26679
- * @category Message Events
27458
+ * @category Channel Events
26680
27459
  */
26681
- const onMessageFlagged = (callback) => {
27460
+ const onChannelMemberRemoved = (callback) => {
26682
27461
  const client = getActiveClient();
26683
- const filter = (rawPayload) => {
26684
- const payload = prepareMessagePayload(rawPayload);
26685
- ingestInCache(payload);
26686
- callback(payload.messages[0]);
27462
+ const filter = async (payload) => {
27463
+ const preparedPayload = await prepareChannelPayload(payload);
27464
+ const { channels, channelUsers } = preparedPayload;
27465
+ ingestInCache(preparedPayload);
27466
+ callback(channels[0], channelUsers[0]);
26687
27467
  };
26688
- return createEventSubscriber(client, 'onMessageFlagged', 'message.flagged', filter);
27468
+ return createEventSubscriber(client, 'onChannelMemberRemoved', 'channel.membersRemoved', filter);
26689
27469
  };
26690
27470
 
26691
27471
  /**
26692
27472
  * ```js
26693
- * import { onMessageUnflagged } from '@amityco/ts-sdk'
26694
- * const dispose = onMessageUnflagged(message => {
27473
+ * import { onChannelMemberBanned } from '@amityco/ts-sdk'
27474
+ * const dispose = onChannelMemberBanned((channel, member) => {
26695
27475
  * // ...
26696
27476
  * })
26697
27477
  * ```
26698
27478
  *
26699
- * Fired when a flag has been removed from a {@link Amity.Message}
27479
+ * Fired when any {@link Amity.User} has been banned from any {@link Amity.Channel}
26700
27480
  *
26701
27481
  * @param callback The function to call when the event was fired
26702
27482
  * @returns an {@link Amity.Unsubscriber} function to stop listening
26703
27483
  *
26704
- * @category Message Events
27484
+ * @category Channel Events
26705
27485
  */
26706
- const onMessageUnflagged = (callback) => {
27486
+ const onChannelMemberBanned = (callback) => {
26707
27487
  const client = getActiveClient();
26708
- const filter = (rawPayload) => {
26709
- const payload = prepareMessagePayload(rawPayload);
26710
- ingestInCache(payload);
26711
- callback(payload.messages[0]);
27488
+ const filter = async (payload) => {
27489
+ const preparedPayload = await prepareChannelPayload(payload);
27490
+ const { channels, channelUsers } = preparedPayload;
27491
+ ingestInCache(preparedPayload);
27492
+ callback(channels[0], channelUsers.find(cu => cu.membership === 'banned'));
26712
27493
  };
26713
- return createEventSubscriber(client, 'onMessageUnflagged', 'message.unflagged', filter);
27494
+ return createEventSubscriber(client, 'onChannelMemberBanned', 'channel.banned', filter);
26714
27495
  };
26715
27496
 
26716
27497
  /**
26717
27498
  * ```js
26718
- * import { onMessageFlagCleared } from '@amityco/ts-sdk'
26719
- * const dispose = onMessageFlagCleared(message => {
27499
+ * import { onChannelMemberUnbanned } from '@amityco/ts-sdk'
27500
+ * const dispose = onChannelMemberUnbanned((channel, member) => {
26720
27501
  * // ...
26721
27502
  * })
26722
27503
  * ```
26723
27504
  *
26724
- * Fired when flags have been cleared for a {@link Amity.Message}
27505
+ * Fired when any {@link Amity.User} has been unbanned from any {@link Amity.Channel}
26725
27506
  *
26726
27507
  * @param callback The function to call when the event was fired
26727
27508
  * @returns an {@link Amity.Unsubscriber} function to stop listening
26728
27509
  *
26729
- * @category Message Events
27510
+ * @category Channel Events
26730
27511
  */
26731
- const onMessageFlagCleared = (callback) => {
27512
+ const onChannelMemberUnbanned = (callback) => {
26732
27513
  const client = getActiveClient();
26733
- const filter = (rawPayload) => {
26734
- const payload = prepareMessagePayload(rawPayload);
26735
- ingestInCache(payload);
26736
- callback(payload.messages[0]);
27514
+ const filter = async (payload) => {
27515
+ const preparedPayload = await prepareChannelPayload(payload);
27516
+ const { channels, channelUsers } = preparedPayload;
27517
+ ingestInCache(preparedPayload);
27518
+ callback(channels[0], channelUsers.find(cu => cu.membership === 'none'));
26737
27519
  };
26738
- return createEventSubscriber(client, 'onMessageFlagCleared', 'message.flagCleared', filter);
27520
+ return createEventSubscriber(client, 'onChannelMemberUnbanned', 'channel.unbanned', filter);
26739
27521
  };
26740
27522
 
26741
27523
  /**
26742
27524
  * ```js
26743
- * import { onMessageReactionAdded } from '@amityco/ts-sdk';
27525
+ * import { observeChannel } from '@amityco/ts-sdk'
26744
27526
  *
26745
- * const unsubscribe = onMessageReactionAdded(message => {
26746
- * // ...
26747
- * });
27527
+ * let channel = {}
27528
+ * const dispose = observeChannel(channelId, ({ data }) => channel = data)
26748
27529
  * ```
26749
27530
  *
26750
- * Fired when a {@link Amity.Message} has been reacted
27531
+ * Observe all mutation on a given {@link Amity.Channel}
26751
27532
  *
26752
- * @param callback The function to call when the event was fired
26753
- * @returns an {@link Amity.Unsubscriber} function to stop listening
27533
+ * @param channelId the ID of the channel to observe
27534
+ * @param callback the function to call when new data are available
27535
+ * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the channel
26754
27536
  *
26755
- * @category Post Events
27537
+ * @category Channel Observer
26756
27538
  */
26757
- const onMessageReactionAdded = (callback) => {
26758
- const client = getActiveClient();
26759
- const filter = (rawPayload) => {
26760
- const payload = prepareMessagePayload(rawPayload);
26761
- ingestInCache(payload);
26762
- callback(payload.messages[0]);
27539
+ const observeChannel = (channelId, callback) => {
27540
+ const { log } = getActiveClient();
27541
+ const timestamp = Date.now();
27542
+ log(`observeChannel(tmpid: ${timestamp}) > listen`);
27543
+ // wrapper function to make sure
27544
+ const router = (result, action) => {
27545
+ var _a, _b, _c;
27546
+ // filter function
27547
+ if (((_a = result.data) === null || _a === void 0 ? void 0 : _a.channelId) !== channelId)
27548
+ return;
27549
+ if (callback instanceof Function)
27550
+ return callback(result);
27551
+ if (action !== 'onFetch')
27552
+ (_b = callback.onEvent) === null || _b === void 0 ? void 0 : _b.call(callback, action, result);
27553
+ (_c = callback[action]) === null || _c === void 0 ? void 0 : _c.call(callback, result);
27554
+ };
27555
+ const disposers = [];
27556
+ disposers.push(onChannelUpdated(data => router({ data, loading: false, origin: 'event' }, 'onUpdate')), onChannelDeleted(data => router({ data, loading: false, origin: 'event' }, 'onDelete')), onChannelJoined(data => router({ data, loading: false, origin: 'event' }, 'onJoin')), onChannelLeft(data => router({ data, loading: false, origin: 'event' }, 'onLeft')), onChannelMuted(data => router({ data, loading: false, origin: 'event' }, 'onMute')), onChannelMemberAdded(data => router({ data, loading: false, origin: 'event' }, 'onMemberAdded')), onChannelMemberRemoved(data => router({ data, loading: false, origin: 'event' }, 'onMemberRemoved')));
27557
+ runQuery(createQuery(getChannel, channelId), result => result.data && router(result, 'onFetch'));
27558
+ return () => {
27559
+ log(`observeChannel(tmpid: ${timestamp}) > dispose`);
27560
+ disposers.forEach(fn => fn());
26763
27561
  };
26764
- return createEventSubscriber(client, 'onMessageReactionAdded', 'message.reactionAdded', filter);
26765
27562
  };
26766
27563
 
26767
27564
  /**
26768
27565
  * ```js
26769
- * import { onMessageReactionRemoved } from '@amityco/ts-sdk';
27566
+ * import { observeChannels } from '@amityco/ts-sdk'
26770
27567
  *
26771
- * const unsubscribe = onMessageReactionRemoved(message => {
26772
- * // ...
26773
- * });
27568
+ * let channels = []
27569
+ * const unsub = observeChannels(channel => merge(channels, channel))
26774
27570
  * ```
26775
27571
  *
26776
- * Fired when a reaction has been removed from a {@link Amity.Message}
27572
+ * Observe all mutations on a list of {@link Amity.Channel} for a current user
26777
27573
  *
26778
- * @param callback The function to call when the event was fired
26779
- * @returns an {@link Amity.Unsubscriber} function to stop listening
27574
+ * @param callback the function to call when new data are available
27575
+ * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the channels
26780
27576
  *
26781
- * @category Post Events
27577
+ * @category Channel Observer
26782
27578
  */
26783
- const onMessageReactionRemoved = (callback) => {
26784
- const client = getActiveClient();
26785
- const filter = (rawPayload) => {
26786
- const payload = prepareMessagePayload(rawPayload);
26787
- ingestInCache(payload);
26788
- callback(payload.messages[0]);
27579
+ const observeChannels = (callback) => {
27580
+ const { log } = getActiveClient();
27581
+ const timestamp = Date.now();
27582
+ log(`observeChannels(tmpid: ${timestamp}) > listen`);
27583
+ const disposers = [];
27584
+ const router = (channel, action) => {
27585
+ var _a, _b;
27586
+ if (callback instanceof Function)
27587
+ return callback(channel);
27588
+ (_a = callback.onEvent) === null || _a === void 0 ? void 0 : _a.call(callback, action, channel);
27589
+ (_b = callback[action]) === null || _b === void 0 ? void 0 : _b.call(callback, channel);
27590
+ };
27591
+ disposers.push(onChannelCreated(data => router(data, 'onCreate')), onChannelUpdated(data => router(data, 'onUpdate')), onChannelDeleted(data => router(data, 'onDelete')), onChannelJoined(data => router(data, 'onJoin')), onChannelLeft(data => router(data, 'onLeft')), onChannelMuted(data => router(data, 'onMute')), onChannelMemberAdded(data => router(data, 'onMemberAdded')), onChannelMemberRemoved(data => router(data, 'onMemberRemoved')));
27592
+ return () => {
27593
+ log(`observeChannels(tmpid: ${timestamp}) > dispose`);
27594
+ disposers.forEach(fn => fn());
26789
27595
  };
26790
- return createEventSubscriber(client, 'onMessageReactionRemoved', 'message.reactionRemoved', filter);
26791
27596
  };
26792
27597
 
26793
27598
  /**
@@ -27064,22 +27869,6 @@ const liveChannelMembers = (params, callback, config) => {
27064
27869
  };
27065
27870
  };
27066
27871
 
27067
- function convertFromRaw(_a) {
27068
- var { channelId, channelPublicId, channelType, childCount, creatorId, creatorPublicId, lastMessageId, lastMessageTimestamp, messageFeedId, name } = _a, rest = __rest(_a, ["channelId", "channelPublicId", "channelType", "childCount", "creatorId", "creatorPublicId", "lastMessageId", "lastMessageTimestamp", "messageFeedId", "name"]);
27069
- return Object.assign(Object.assign({}, rest), { channelId: channelPublicId, creatorId: creatorPublicId, displayName: name, lastActivity: lastMessageTimestamp, latestMessageId: lastMessageId, messageCount: childCount, subChannelId: messageFeedId });
27070
- }
27071
- const prepareSubChannelPayload = (payload) => {
27072
- return Object.assign(Object.assign({}, payload), { messageFeeds: payload.messageFeeds.map(convertFromRaw) });
27073
- };
27074
- function convertQueryParams(_a) {
27075
- var { excludeDefaultSubChannel } = _a, rest = __rest(_a, ["excludeDefaultSubChannel"]);
27076
- const out = Object.assign({}, rest);
27077
- if (excludeDefaultSubChannel !== undefined) {
27078
- out.excludeDefaultMessageFeed = excludeDefaultSubChannel;
27079
- }
27080
- return out;
27081
- }
27082
-
27083
27872
  /* begin_public_function
27084
27873
  id: subchannel.query
27085
27874
  */
@@ -27107,7 +27896,7 @@ const querySubChannels = async (query) => {
27107
27896
  } }),
27108
27897
  });
27109
27898
  const _b = response.data, { paging } = _b, payload = __rest(_b, ["paging"]);
27110
- const data = prepareSubChannelPayload(payload);
27899
+ const data = await prepareSubChannelPayload(payload);
27111
27900
  const subChannels = data.messageFeeds;
27112
27901
  const cachedAt = client.cache && Date.now();
27113
27902
  if (client.cache) {
@@ -27183,7 +27972,7 @@ const getSubChannels = async (subChannelIds) => {
27183
27972
  const response = await client.http.get('/api/v5/message-feeds/list', {
27184
27973
  params: { messageFeedIds: subChannelIds.map(encodeURIComponent) },
27185
27974
  });
27186
- const data = prepareSubChannelPayload(response.data);
27975
+ const data = await prepareSubChannelPayload(response.data);
27187
27976
  const cachedAt = client.cache && Date.now();
27188
27977
  if (client.cache)
27189
27978
  ingestInCache(data, { cachedAt });
@@ -27248,7 +28037,7 @@ const getSubChannel = async (subChannelId) => {
27248
28037
  isInTombstone('subChannel', subChannelId);
27249
28038
  try {
27250
28039
  const response = await client.http.get(`/api/v5/message-feeds/${encodeURIComponent(subChannelId)}`);
27251
- const data = prepareSubChannelPayload(response.data);
28040
+ const data = await prepareSubChannelPayload(response.data);
27252
28041
  const cachedAt = client.cache && Date.now();
27253
28042
  if (client.cache)
27254
28043
  ingestInCache(data, { cachedAt });
@@ -27317,7 +28106,7 @@ const createSubChannel = async (bundle) => {
27317
28106
  channelId: bundle.channelId,
27318
28107
  name: bundle.displayName,
27319
28108
  });
27320
- const data = prepareSubChannelPayload(response.data);
28109
+ const data = await prepareSubChannelPayload(response.data);
27321
28110
  const cachedAt = client.cache && Date.now();
27322
28111
  if (client.cache)
27323
28112
  ingestInCache(data, { cachedAt });
@@ -27351,7 +28140,7 @@ const updateSubChannel = async (subChannelId, patch) => {
27351
28140
  const client = getActiveClient();
27352
28141
  client.log('channel/updateSubChannel', subChannelId, patch);
27353
28142
  const response = await client.http.put(`/api/v5/message-feeds/${encodeURIComponent(subChannelId)}`, { name: patch.displayName });
27354
- const data = prepareSubChannelPayload(response.data);
28143
+ const data = await prepareSubChannelPayload(response.data);
27355
28144
  const cachedAt = client.cache && Date.now();
27356
28145
  if (client.cache)
27357
28146
  ingestInCache(data, { cachedAt });
@@ -27399,87 +28188,6 @@ const deleteSubChannel = async (subChannelId, permanent = false) => {
27399
28188
  };
27400
28189
  /* end_public_function */
27401
28190
 
27402
- /**
27403
- * ```js
27404
- * import { onChannelSubCreated } from '@amityco/ts-sdk'
27405
- * const dispose = onSubChannelCreated(subChannel => {
27406
- * // ...
27407
- * })
27408
- * ```
27409
- *
27410
- * Fired when any {@link Amity.SubChannel} have been created
27411
- *
27412
- * @param callback The function to call when the event was fired
27413
- * @returns an {@link Amity.Unsubscriber} function to stop listening
27414
- *
27415
- * @category Channel Events
27416
- */
27417
- const onSubChannelCreated = (callback) => {
27418
- const client = getActiveClient();
27419
- const filter = (rawPayload) => {
27420
- const payload = prepareSubChannelPayload(rawPayload);
27421
- ingestInCache(payload);
27422
- callback(payload.messageFeeds[0]);
27423
- };
27424
- return createEventSubscriber(client, 'onSubChannelCreated', 'message-feed.created', filter);
27425
- };
27426
-
27427
- /**
27428
- * ```js
27429
- * import { onSubChannelUpdated } from '@amityco/ts-sdk'
27430
- * const dispose = onSubChannelUpdated(subChannel => {
27431
- * // ...
27432
- * })
27433
- * ```
27434
- *
27435
- * Fired when any {@link Amity.SubChannel} have been updated
27436
- *
27437
- * @param callback The function to call when the event was fired
27438
- * @returns an {@link Amity.Unsubscriber} function to stop listening
27439
- *
27440
- * @category Channel Events
27441
- */
27442
- const onSubChannelUpdated = (callback) => {
27443
- const client = getActiveClient();
27444
- const filter = (rawPayload) => {
27445
- const payload = prepareSubChannelPayload(rawPayload);
27446
- ingestInCache(payload);
27447
- callback(payload.messageFeeds[0]);
27448
- };
27449
- return createEventSubscriber(client, 'onSubChannelUpdated', 'message-feed.updated', filter);
27450
- };
27451
-
27452
- /**
27453
- * ```js
27454
- * import { onSubChannelDeleted } from '@amityco/ts-sdk'
27455
- * const dispose = onSubChannelDeleted(subChannel => {
27456
- * // ...
27457
- * })
27458
- * ```
27459
- *
27460
- * Fired when any {@link Amity.SubChannel} have been deleted
27461
- *
27462
- * @param callback The function to call when the event was fired
27463
- * @returns an {@link Amity.Unsubscriber} function to stop listening
27464
- *
27465
- * @category Channel Events
27466
- */
27467
- const onSubChannelDeleted = (callback) => {
27468
- const client = getActiveClient();
27469
- const filter = (rawPayload) => {
27470
- const payload = prepareSubChannelPayload(rawPayload);
27471
- ingestInCache(payload);
27472
- callback(payload.messageFeeds[0]);
27473
- };
27474
- const disposers = [
27475
- createEventSubscriber(client, 'onSubChannelDeleted', 'message-feed.deleted', filter),
27476
- createEventSubscriber(client, 'local.message-feed.deleted', 'local.message-feed.deleted', payload => callback(payload.messageFeeds[0])),
27477
- ];
27478
- return () => {
27479
- disposers.forEach(fn => fn());
27480
- };
27481
- };
27482
-
27483
28191
  /** @hidden */
27484
28192
  const onSubChannelFetched = (callback) => {
27485
28193
  return createEventSubscriber(getActiveClient(), 'onSubChannelFetched', 'local.message-feed.fetched', payload => callback(payload.messageFeeds[0]));
@@ -27512,6 +28220,27 @@ const liveSubChannel = (subChannelId, callback) => {
27512
28220
  ]);
27513
28221
  };
27514
28222
 
28223
+ function isCollectionOutdated(collection, newItem, action) {
28224
+ const key = identifyModelKey(newItem);
28225
+ // @ts-ignore
28226
+ const item = collection.find(x => x[key] === newItem[key]);
28227
+ if (item) {
28228
+ return hasUpdates(item, newItem);
28229
+ }
28230
+ return action === 'onCreate';
28231
+ }
28232
+ function merge(collection1, collection2) {
28233
+ const temp = [...collection1, ...collection2];
28234
+ if (temp.length === 0) {
28235
+ return [];
28236
+ }
28237
+ const key = identifyModelKey(temp[0]);
28238
+ const map = new Map();
28239
+ // @ts-ignore
28240
+ temp.forEach(x => map.set(x[key], x));
28241
+ return Array.from(map.values());
28242
+ }
28243
+
27515
28244
  /**
27516
28245
  * ```js
27517
28246
  * import { liveSubChannels } from '@amityco/ts-sdk';
@@ -27596,30 +28325,6 @@ const liveSubChannels = (params, callback, config) => {
27596
28325
  };
27597
28326
  };
27598
28327
 
27599
- /**
27600
- * ```js
27601
- * import { onMessageFetched } from '@amityco/ts-sdk'
27602
- * const dispose = onMessageFetched(message => {
27603
- * // ...
27604
- * })
27605
- * ```
27606
- *
27607
- * Fired when an {@link Amity.Message} has been fetched
27608
- *
27609
- * @param callback The function to call when the event was fired
27610
- * @returns an {@link Amity.Unsubscriber} function to stop listening
27611
- *
27612
- * @category Message Events
27613
- */
27614
- const onMessageFetched = (callback) => {
27615
- const client = getActiveClient();
27616
- const filter = (payload) => {
27617
- ingestInCache(payload);
27618
- callback(payload.messages[0]);
27619
- };
27620
- return createEventSubscriber(client, 'message/onMessageFetched', 'local.message.fetched', filter);
27621
- };
27622
-
27623
28328
  /**
27624
28329
  * ```js
27625
28330
  * import { liveMessage } from '@amityco/ts-sdk';
@@ -30618,4 +31323,4 @@ const createUserToken = async (apiKey, apiRegion, params) => {
30618
31323
  return { accessToken: data.accessToken };
30619
31324
  };
30620
31325
 
30621
- export { API_REGIONS, CommunityPostSettingMaps, CommunityPostSettings, ContentFeedType, DefaultCommunityPostSetting, FileType, MessageContentType, PostContentType, SubscriptionLevels, VERSION, VideoResolution, VideoSize, VideoTranscodingStatus, acceptFollower, addChannelMembers, addChannelMembersRole, addCommunityMembers, addCommunityMembersRoles, addReaction, approvePost, backupCache, banChannelMembers, closePoll, connectClient, createChannel, createClient, createComment, createCommunity, createFile, createImage, createMessage, createPoll, createPost, createQuery, createReport, createStream, createSubChannel, createUserToken, createVideo, declineFollower, declinePost, deleteChannel, deleteComment, deleteCommunity, deleteFile, deleteMessage, deletePoll, deletePost, deleteReport, deleteStream, deleteSubChannel, disableCache, disconnectClient, disposeStream, dropFromCache, enableCache, fileUrlWithSize, filterByChannelMembership, filterByFeedType, filterByPropEquality, filterByPropInclusion, follow, getActiveClient, getCategory, getChannel, getChannelTopic, getChannels, getComment, getCommentTopic, getComments, getCommunities, getCommunity, getCommunityTopic, getFeedSettings, getFile, getFollowInfo, getMessage, getMessageTopic, getMessages, getMyFollowersTopic, getMyFollowingsTopic, getNetworkTopic, getPoll, getPost, getPostTopic, getPosts, getRecommendedCommunities, getRole, getSmartFeedChannelTopic, getSmartFeedMessageTopic, getSmartFeedSubChannelTopic, getStream, getSubChannel, getSubChannelTopic, getSubChannels, getTopTrendingCommunities, getUser, getUserTopic, getUsers, isAfterBefore, isAfterBeforeRaw, isCachable, isConnected, isFetcher, isFresh, isLocal, isMutator, isOffline, isPaged, isReportedByMe, isSkip, joinChannel, joinCommunity, leaveChannel, leaveCommunity, liveCategories, liveChannel, liveChannelMembers, liveChannels, liveComment, liveComments, liveCommunities, liveCommunity, liveCommunityMembers, liveFollowInfo, liveFollowers, liveFollowings, liveMessage, liveMessages, livePost, livePosts, liveReactions, liveSubChannel, liveSubChannels, liveUser, liveUsers, mergeInCache, observeChannel, observeChannels, observeComment, observeComments, observeCommunity, observeFile, observeFollowInfo, observeFollowers, observeFollowings, observeMessage, observeMessages, observePoll, observePost, observePosts, observeUser, onChannelCreated, onChannelDeleted, onChannelJoined, onChannelLeft, onChannelMemberAdded, onChannelMemberBanned, onChannelMemberRemoved, onChannelMemberUnbanned, onChannelMuted, onChannelUpdated, onClientBanned, onClientDisconnected, onCommentCreated, onCommentDeleted, onCommentFlagged, onCommentReactionAdded, onCommentReactionRemoved, onCommentUnflagged, onCommentUpdated, onCommunityCreated, onCommunityDeleted, onCommunityJoined, onCommunityLeft, onCommunityUpdated, onCommunityUserAdded, onCommunityUserBanned, onCommunityUserChanged, onCommunityUserRemoved, onCommunityUserRoleAdded, onCommunityUserRoleRemoved, onCommunityUserUnbanned, onConnectionError, onFollowInfoUpdated, onFollowRequestAccepted, onFollowRequestCanceled, onFollowRequestDeclined, onFollowerDeleted, onFollowerRequested, onMessageCreated, onMessageDeleted, onMessageFlagCleared, onMessageFlagged, onMessageReactionAdded, onMessageReactionRemoved, onMessageUnflagged, onMessageUpdated, onPollDeleted, onPollUpdated, onPostApproved, onPostCreated, onPostDeclined, onPostDeleted, onPostFlagged, onPostReactionAdded, onPostReactionRemoved, onPostUnflagged, onPostUpdated, onReactionAdded, onReactionRemoved, onReactorAdded, onReactorRemoved, onSessionStateChange, onStreamRecorded, onStreamStarted, onStreamStopped, onSubChannelCreated, onSubChannelDeleted, onSubChannelUpdated, onUserDeleted, onUserFlagCleared, onUserFlagged, onUserFollowed, onUserUnflagged, onUserUnfollowed, onUserUpdated, pullFromCache, pushToCache, queryCache, queryCategories, queryChannelMembers, queryChannels, queryComments, queryCommunities, queryCommunityMembers, queryFollowers, queryFollowings, queryGlobalFeed, queryMessages, queryOptions, queryPosts, queryReactions, queryRoles, queryStreams, querySubChannels, queryUsers, removeChannelMembers, removeChannelMembersRole, removeCommunityMembers, removeCommunityMembersRoles, removeReaction, renewal, restoreCache, runQuery, sortByChannelSegment, sortByDisplayName, sortByFirstCreated, sortByLastActivity, sortByLastCreated, sortByName, sortBySegmentNumber, startReading, stopReading, subscribeTopic, toPage, toPageRaw, toToken, unbanChannelMembers, unfollow, updateChannel, updateComment, updateCommunity, updateMessage, updatePost, updateStream, updateSubChannel, updateUser, upsertInCache, votePoll, wipeCache };
31326
+ export { API_REGIONS, CommunityPostSettingMaps, CommunityPostSettings, ContentFeedType, DefaultCommunityPostSetting, FileType, MARKER_INCLUDED_SUB_CHANNEL_TYPE, MessageContentType, PostContentType, SubscriptionLevels, VERSION, VideoResolution, VideoSize, VideoTranscodingStatus, acceptFollower, addChannelMembers, addChannelMembersRole, addCommunityMembers, addCommunityMembersRoles, addReaction, approvePost, backupCache, banChannelMembers, closePoll, connectClient, convertFromRaw$1 as convertFromRaw, convertQueryParams, createChannel, createClient, createComment, createCommunity, createFile, createImage, createMessage, createPoll, createPost, createQuery, createReport, createStream, createSubChannel, createUserToken, createVideo, declineFollower, declinePost, deleteChannel, deleteComment, deleteCommunity, deleteFile, deleteMessage, deletePoll, deletePost, deleteReport, deleteStream, deleteSubChannel, disableCache, disconnectClient, disposeStream, dropFromCache, enableCache, fileUrlWithSize, filterByChannelMembership, filterByFeedType, filterByPropEquality, filterByPropInclusion, follow, getActiveClient, getActiveUser, getCategory, getChannel, getChannelMarkers, getChannelTopic, getChannels, getComment, getCommentTopic, getComments, getCommunities, getCommunity, getCommunityTopic, getFeedSettings, getFile, getFollowInfo, getMarkerSyncEvents, getMessage, getMessageMarkers, getMessageTopic, getMessages, getMyFollowersTopic, getMyFollowingsTopic, getNetworkTopic, getPoll, getPost, getPostTopic, getPosts, getRecommendedCommunities, getRole, getSmartFeedChannelTopic, getSmartFeedMessageTopic, getSmartFeedSubChannelTopic, getStream, getSubChannel, getSubChannelMarkers, getSubChannelTopic, getSubChannels, getTopTrendingCommunities, getTotalUnreadCount, getUnreadCount$1 as getUnreadCount, getUser, getUserMarker, getUserTopic, getUsers, isAfterBefore, isAfterBeforeRaw, isCachable, isConnected, isFetcher, isFresh, isLocal, isMutator, isOffline, isPaged, isReportedByMe, isSkip, isUnreadCountSupport$1 as isUnreadCountSupport, joinChannel, joinCommunity, leaveChannel, leaveCommunity, liveCategories, liveChannel, liveChannelMembers, liveChannels, liveComment, liveComments, liveCommunities, liveCommunity, liveCommunityMembers, liveFollowInfo, liveFollowers, liveFollowings, liveMessage, liveMessages, livePost, livePosts, liveReactions, liveSubChannel, liveSubChannels, liveUser, liveUsers, markAsDelivered, markerSync, markerSyncTrigger, mergeInCache, observeChannel, observeChannels, observeComment, observeComments, observeCommunity, observeFile, observeFollowInfo, observeFollowers, observeFollowings, observeMessage, observeMessages, observePoll, observePost, observePosts, observeUser, onChannelCreated, onChannelDeleted, onChannelJoined, onChannelLeft, onChannelMarkerFetched, onChannelMemberAdded, onChannelMemberBanned, onChannelMemberRemoved, onChannelMemberUnbanned, onChannelMuted, onChannelUpdated, onClientBanned, onClientDisconnected, onCommentCreated, onCommentDeleted, onCommentFlagged, onCommentReactionAdded, onCommentReactionRemoved, onCommentUnflagged, onCommentUpdated, onCommunityCreated, onCommunityDeleted, onCommunityJoined, onCommunityLeft, onCommunityUpdated, onCommunityUserAdded, onCommunityUserBanned, onCommunityUserChanged, onCommunityUserRemoved, onCommunityUserRoleAdded, onCommunityUserRoleRemoved, onCommunityUserUnbanned, onConnectionError, onFeedMarkerFetched, onFollowInfoUpdated, onFollowRequestAccepted, onFollowRequestCanceled, onFollowRequestDeclined, onFollowerDeleted, onFollowerRequested, onMessageCreated, onMessageDeleted, onMessageFetched, onMessageFlagCleared, onMessageFlagged, onMessageMarkerFetched, onMessageReactionAdded, onMessageReactionRemoved, onMessageUnflagged, onMessageUpdated, onPollDeleted, onPollUpdated, onPostApproved, onPostCreated, onPostDeclined, onPostDeleted, onPostFlagged, onPostReactionAdded, onPostReactionRemoved, onPostUnflagged, onPostUpdated, onReactionAdded, onReactionRemoved, onReactorAdded, onReactorRemoved, onSessionStateChange, onStreamRecorded, onStreamStarted, onStreamStopped, onSubChannelCreated, onSubChannelDeleted, onSubChannelMarkerFetched, onSubChannelMarkerUpdated, onSubChannelUpdated, onUserDeleted, onUserFlagCleared, onUserFlagged, onUserFollowed, onUserMarkerFetched, onUserUnflagged, onUserUnfollowed, onUserUpdated, prepareSubChannelPayload, pullFromCache, pushMarkerSyncEvent, pushToCache, queryCache, queryCategories, queryChannelMembers, queryChannels, queryComments, queryCommunities, queryCommunityMembers, queryFollowers, queryFollowings, queryGlobalFeed, queryMessages, queryOptions, queryPosts, queryReactions, queryRoles, queryStreams, querySubChannels, queryUsers, removeChannelMembers, removeChannelMembersRole, removeCommunityMembers, removeCommunityMembersRoles, removeReaction, renewal, restoreCache, runQuery, setActiveUser, setMarkerSyncEvents, sortByChannelSegment, sortByDisplayName, sortByFirstCreated, sortByLastActivity, sortByLastCreated, sortByName, sortBySegmentNumber, startReading, startReadingAPI, startUnreadSync, stopReading, stopReadingAPI, stopUnreadSyncing, subscribeTopic, toPage, toPageRaw, toToken, unbanChannelMembers, unfollow, updateChannel, updateComment, updateCommunity, updateMessage, updatePost, updateStream, updateSubChannel, updateSubChannelMarker, updateUser, upsertInCache, votePoll, wipeCache };