@amityco/ts-sdk 6.35.3-fa3d4ac.0 → 7.0.1-7547014.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (348) hide show
  1. package/dist/@types/core/events.d.ts +6 -6
  2. package/dist/@types/core/events.d.ts.map +1 -1
  3. package/dist/@types/core/linkPreview.d.ts +12 -0
  4. package/dist/@types/core/linkPreview.d.ts.map +1 -0
  5. package/dist/@types/domains/analytics.d.ts +0 -3
  6. package/dist/@types/domains/analytics.d.ts.map +1 -1
  7. package/dist/@types/domains/channel.d.ts +9 -33
  8. package/dist/@types/domains/channel.d.ts.map +1 -1
  9. package/dist/@types/domains/client.d.ts +0 -4
  10. package/dist/@types/domains/client.d.ts.map +1 -1
  11. package/dist/@types/domains/community.d.ts +2 -10
  12. package/dist/@types/domains/community.d.ts.map +1 -1
  13. package/dist/@types/domains/feed.d.ts +0 -11
  14. package/dist/@types/domains/feed.d.ts.map +1 -1
  15. package/dist/@types/domains/message.d.ts +0 -12
  16. package/dist/@types/domains/message.d.ts.map +1 -1
  17. package/dist/@types/domains/subChannel.d.ts +0 -4
  18. package/dist/@types/domains/subChannel.d.ts.map +1 -1
  19. package/dist/@types/domains/user.d.ts +1 -5
  20. package/dist/@types/domains/user.d.ts.map +1 -1
  21. package/dist/channelRepository/api/deleteChannel.d.ts.map +1 -1
  22. package/dist/channelRepository/api/index.d.ts +0 -1
  23. package/dist/channelRepository/api/index.d.ts.map +1 -1
  24. package/dist/channelRepository/channelMembership/observers/getMembers/ChannelMemberLiveCollectionController.d.ts.map +1 -1
  25. package/dist/channelRepository/channelMembership/observers/getMembers/getMembers.d.ts.map +1 -1
  26. package/dist/channelRepository/channelMembership/observers/searchMembers/SearchChannelMemberLiveCollectionController.d.ts.map +1 -1
  27. package/dist/channelRepository/channelMembership/observers/searchMembers/searchMembers.d.ts.map +1 -1
  28. package/dist/channelRepository/{api → internalApi}/getChannel.d.ts +2 -2
  29. package/dist/channelRepository/internalApi/getChannel.d.ts.map +1 -0
  30. package/dist/channelRepository/internalApi/getChannelByIds.d.ts +32 -0
  31. package/dist/channelRepository/internalApi/getChannelByIds.d.ts.map +1 -0
  32. package/dist/channelRepository/{api → internalApi}/markAsRead.d.ts +0 -3
  33. package/dist/channelRepository/internalApi/markAsRead.d.ts.map +1 -0
  34. package/dist/channelRepository/observers/getChannel.d.ts.map +1 -1
  35. package/dist/channelRepository/observers/getChannels/ChannelLiveCollectionController.d.ts.map +1 -1
  36. package/dist/channelRepository/observers/index.d.ts +0 -2
  37. package/dist/channelRepository/observers/index.d.ts.map +1 -1
  38. package/dist/channelRepository/utils/constructChannelDynamicValue.d.ts.map +1 -1
  39. package/dist/channelRepository/utils/constructChannelObject.d.ts +2 -0
  40. package/dist/channelRepository/utils/constructChannelObject.d.ts.map +1 -0
  41. package/dist/channelRepository/utils/getChannelIsMentioned.d.ts +1 -1
  42. package/dist/channelRepository/utils/getChannelIsMentioned.d.ts.map +1 -1
  43. package/dist/channelRepository/utils/getSubChannelsUnreadCount.d.ts +1 -1
  44. package/dist/channelRepository/utils/getSubChannelsUnreadCount.d.ts.map +1 -1
  45. package/dist/channelRepository/utils/resolveChannels.d.ts.map +1 -1
  46. package/dist/channelRepository/utils/updateChannelCache.d.ts +1 -1
  47. package/dist/channelRepository/utils/updateChannelCache.d.ts.map +1 -1
  48. package/dist/client/api/fetchLinkPreview.d.ts +14 -0
  49. package/dist/client/api/fetchLinkPreview.d.ts.map +1 -0
  50. package/dist/client/api/index.d.ts +1 -0
  51. package/dist/client/api/index.d.ts.map +1 -1
  52. package/dist/client/observers/index.d.ts +0 -1
  53. package/dist/client/observers/index.d.ts.map +1 -1
  54. package/dist/client/utils/endpoints.d.ts +1 -1
  55. package/dist/client/utils/markerSyncEngine.d.ts +0 -4
  56. package/dist/client/utils/markerSyncEngine.d.ts.map +1 -1
  57. package/dist/client/utils/subscribeGlobalTopic.d.ts.map +1 -1
  58. package/dist/commentRepository/observers/index.d.ts +0 -2
  59. package/dist/commentRepository/observers/index.d.ts.map +1 -1
  60. package/dist/communityRepository/api/index.d.ts +0 -1
  61. package/dist/communityRepository/api/index.d.ts.map +1 -1
  62. package/dist/communityRepository/api/queryCommunities.d.ts.map +1 -1
  63. package/dist/communityRepository/communityMembership/observers/getMembers/CommunityMembersLiveCollectionController.d.ts.map +1 -1
  64. package/dist/communityRepository/communityMembership/observers/getMembers/CommunityMembersQueryStreamController.d.ts.map +1 -1
  65. package/dist/communityRepository/communityMembership/observers/getMembers.d.ts.map +1 -1
  66. package/dist/communityRepository/communityMembership/observers/searchMembers/SearchCommunityMembersPaginationController.d.ts +1 -1
  67. package/dist/communityRepository/communityMembership/observers/searchMembers/SearchCommunityMembersPaginationController.d.ts.map +1 -1
  68. package/dist/communityRepository/observers/getCommunities/CommunitiesLiveCollectionController.d.ts.map +1 -1
  69. package/dist/communityRepository/observers/getCommunities/CommunitiesPaginationController.d.ts.map +1 -1
  70. package/dist/communityRepository/observers/getCommunities/CommunitiesQueryStreamController.d.ts.map +1 -1
  71. package/dist/communityRepository/observers/index.d.ts +0 -1
  72. package/dist/communityRepository/observers/index.d.ts.map +1 -1
  73. package/dist/communityRepository/observers/searchCommunities.d.ts +1 -1
  74. package/dist/communityRepository/observers/searchCommunities.d.ts.map +1 -1
  75. package/dist/communityRepository/utils/communityQueryFilter.d.ts.map +1 -1
  76. package/dist/core/events.d.ts +3 -3
  77. package/dist/core/events.d.ts.map +1 -1
  78. package/dist/core/subscription.d.ts +1 -0
  79. package/dist/core/subscription.d.ts.map +1 -1
  80. package/dist/feedRepository/api/getCustomRankingGlobalFeed.d.ts +2 -35
  81. package/dist/feedRepository/api/getCustomRankingGlobalFeed.d.ts.map +1 -1
  82. package/dist/feedRepository/api/queryGlobalFeed.d.ts +2 -24
  83. package/dist/feedRepository/api/queryGlobalFeed.d.ts.map +1 -1
  84. package/dist/fileRepository/api/index.d.ts +0 -3
  85. package/dist/fileRepository/api/index.d.ts.map +1 -1
  86. package/dist/fileRepository/index.d.ts +0 -1
  87. package/dist/fileRepository/index.d.ts.map +1 -1
  88. package/dist/index.cjs.js +1282 -2686
  89. package/dist/index.esm.js +1233 -2638
  90. package/dist/index.umd.js +4 -4
  91. package/dist/messagePreview/utils/getChannelMessagePreviewWithUser.d.ts +1 -5
  92. package/dist/messagePreview/utils/getChannelMessagePreviewWithUser.d.ts.map +1 -1
  93. package/dist/messagePreview/utils/getSubChannelMessagePreviewWithUser.d.ts +0 -1
  94. package/dist/messagePreview/utils/getSubChannelMessagePreviewWithUser.d.ts.map +1 -1
  95. package/dist/messageRepository/api/createMessage.d.ts.map +1 -1
  96. package/dist/messageRepository/api/index.d.ts +0 -1
  97. package/dist/messageRepository/api/index.d.ts.map +1 -1
  98. package/dist/messageRepository/internalApi/getMessage.d.ts.map +1 -1
  99. package/dist/messageRepository/observers/getMessages/MessageLiveCollectionController.d.ts.map +1 -1
  100. package/dist/messageRepository/observers/getMessages/MessageQueryStreamController.d.ts.map +1 -1
  101. package/dist/messageRepository/observers/getMessages/getMessages.d.ts +0 -1
  102. package/dist/messageRepository/observers/getMessages/getMessages.d.ts.map +1 -1
  103. package/dist/messageRepository/observers/index.d.ts +0 -2
  104. package/dist/messageRepository/observers/index.d.ts.map +1 -1
  105. package/dist/messageRepository/utils/prepareMessagePayload.d.ts +1 -1
  106. package/dist/messageRepository/utils/prepareMessagePayload.d.ts.map +1 -1
  107. package/dist/pollRepository/observers/index.d.ts +0 -1
  108. package/dist/pollRepository/observers/index.d.ts.map +1 -1
  109. package/dist/postRepository/api/index.d.ts +0 -1
  110. package/dist/postRepository/api/index.d.ts.map +1 -1
  111. package/dist/postRepository/observers/index.d.ts +0 -2
  112. package/dist/postRepository/observers/index.d.ts.map +1 -1
  113. package/dist/role/api/queryRoles.d.ts +0 -7
  114. package/dist/role/api/queryRoles.d.ts.map +1 -1
  115. package/dist/streamRepository/api/index.d.ts +0 -2
  116. package/dist/streamRepository/api/index.d.ts.map +1 -1
  117. package/dist/streamRepository/events/onStreamFlagged.d.ts.map +1 -1
  118. package/dist/streamRepository/internalApi/getStream.d.ts.map +1 -0
  119. package/dist/subChannelRepository/utils/markReadEngine.d.ts +0 -34
  120. package/dist/subChannelRepository/utils/markReadEngine.d.ts.map +1 -1
  121. package/dist/userRepository/internalApi/queryUsers.d.ts.map +1 -1
  122. package/dist/userRepository/observers/getUsers/UserLiveCollectionController.d.ts.map +1 -1
  123. package/dist/userRepository/observers/getUsers/UserPaginationController.d.ts.map +1 -1
  124. package/dist/userRepository/observers/index.d.ts +0 -2
  125. package/dist/userRepository/observers/index.d.ts.map +1 -1
  126. package/dist/userRepository/relationship/block/index.d.ts +0 -1
  127. package/dist/userRepository/relationship/block/index.d.ts.map +1 -1
  128. package/dist/userRepository/relationship/follow/api/index.d.ts +0 -2
  129. package/dist/userRepository/relationship/follow/api/index.d.ts.map +1 -1
  130. package/dist/userRepository/relationship/follow/observers/index.d.ts +0 -3
  131. package/dist/userRepository/relationship/follow/observers/index.d.ts.map +1 -1
  132. package/dist/utils/liveObject.d.ts +1 -1
  133. package/package.json +1 -1
  134. package/src/@types/core/events.ts +8 -9
  135. package/src/@types/core/linkPreview.ts +12 -0
  136. package/src/@types/domains/analytics.ts +0 -7
  137. package/src/@types/domains/channel.ts +15 -46
  138. package/src/@types/domains/client.ts +0 -4
  139. package/src/@types/domains/community.ts +0 -8
  140. package/src/@types/domains/feed.ts +0 -11
  141. package/src/@types/domains/message.ts +0 -12
  142. package/src/@types/domains/subChannel.ts +0 -4
  143. package/src/@types/domains/user.ts +0 -4
  144. package/src/analytic/api/queryReachUser.ts +1 -1
  145. package/src/channelRepository/api/deleteChannel.ts +3 -2
  146. package/src/channelRepository/api/getChannelByIds.ts +5 -5
  147. package/src/channelRepository/api/index.ts +0 -2
  148. package/src/channelRepository/channelMembership/observers/getMembers/ChannelMemberLiveCollectionController.ts +0 -8
  149. package/src/channelRepository/channelMembership/observers/getMembers/getMembers.ts +0 -8
  150. package/src/channelRepository/channelMembership/observers/searchMembers/SearchChannelMemberLiveCollectionController.ts +0 -8
  151. package/src/channelRepository/channelMembership/observers/searchMembers/searchMembers.ts +0 -8
  152. package/src/channelRepository/{api → internalApi}/getChannel.ts +4 -4
  153. package/src/channelRepository/internalApi/getChannelByIds.ts +105 -0
  154. package/src/channelRepository/{api → internalApi}/markAsRead.ts +0 -3
  155. package/src/channelRepository/observers/getChannel.ts +36 -15
  156. package/src/channelRepository/observers/getChannels/ChannelLiveCollectionController.ts +11 -12
  157. package/src/channelRepository/observers/index.ts +0 -2
  158. package/src/channelRepository/utils/constructChannelDynamicValue.ts +4 -9
  159. package/src/channelRepository/utils/constructChannelObject.ts +16 -0
  160. package/src/channelRepository/utils/getChannelIsMentioned.ts +4 -1
  161. package/src/channelRepository/utils/getSubChannelsUnreadCount.ts +1 -1
  162. package/src/channelRepository/utils/resolveChannels.ts +7 -2
  163. package/src/channelRepository/utils/updateChannelCache.ts +4 -1
  164. package/src/client/api/fetchLinkPreview.ts +30 -0
  165. package/src/client/api/index.ts +2 -0
  166. package/src/client/observers/getUserUnread.ts +1 -1
  167. package/src/client/observers/index.ts +0 -1
  168. package/src/client/utils/endpoints.ts +1 -1
  169. package/src/client/utils/markerSyncEngine.ts +0 -9
  170. package/src/client/utils/subscribeGlobalTopic.ts +3 -0
  171. package/src/commentRepository/observers/index.ts +0 -2
  172. package/src/communityRepository/api/index.ts +0 -3
  173. package/src/communityRepository/api/queryCommunities.ts +1 -2
  174. package/src/communityRepository/communityMembership/observers/getMembers/CommunityMembersLiveCollectionController.ts +0 -12
  175. package/src/communityRepository/communityMembership/observers/getMembers/CommunityMembersQueryStreamController.ts +0 -7
  176. package/src/communityRepository/communityMembership/observers/getMembers.ts +0 -4
  177. package/src/communityRepository/communityMembership/observers/searchMembers/SearchCommunityMembersPaginationController.ts +1 -1
  178. package/src/communityRepository/communityMembership/observers/tests/getMembers.test.ts +0 -1
  179. package/src/communityRepository/observers/getCommunities/CommunitiesLiveCollectionController.ts +12 -16
  180. package/src/communityRepository/observers/getCommunities/CommunitiesPaginationController.ts +0 -1
  181. package/src/communityRepository/observers/getCommunities/CommunitiesQueryStreamController.ts +0 -4
  182. package/src/communityRepository/observers/index.ts +0 -2
  183. package/src/communityRepository/observers/searchCommunities.ts +1 -1
  184. package/src/communityRepository/observers/tests/getCommunities.test.ts +0 -1
  185. package/src/communityRepository/utils/communityQueryFilter.ts +1 -8
  186. package/src/core/events.ts +7 -5
  187. package/src/core/subscription.ts +6 -0
  188. package/src/feedRepository/api/getCustomRankingGlobalFeed.ts +8 -55
  189. package/src/feedRepository/api/queryGlobalFeed.ts +6 -58
  190. package/src/feedRepository/api/test/getCustomRankingGlobalFeed.test.ts +1 -1
  191. package/src/feedRepository/api/test/queryGlobalFeed.test.ts +1 -1
  192. package/src/fileRepository/api/index.ts +0 -5
  193. package/src/fileRepository/index.ts +0 -1
  194. package/src/liveStreamPlayer/api/getPlayer.ts +1 -1
  195. package/src/messagePreview/utils/getChannelMessagePreviewWithUser.ts +2 -2
  196. package/src/messageRepository/api/createMessage.ts +5 -1
  197. package/src/messageRepository/api/index.ts +0 -2
  198. package/src/messageRepository/api/tests/createMessage.test.ts +6 -1
  199. package/src/messageRepository/api/tests/deleteMessage.test.ts +5 -1
  200. package/src/messageRepository/internalApi/getMessage.ts +0 -6
  201. package/src/messageRepository/observers/getMessages/MessageLiveCollectionController.ts +0 -20
  202. package/src/messageRepository/observers/getMessages/MessageQueryStreamController.ts +0 -10
  203. package/src/messageRepository/observers/getMessages/getMessages.ts +0 -54
  204. package/src/messageRepository/observers/index.ts +0 -3
  205. package/src/messageRepository/utils/prepareMessagePayload.ts +1 -7
  206. package/src/pollRepository/observers/index.ts +0 -1
  207. package/src/postRepository/api/index.ts +0 -1
  208. package/src/postRepository/observers/index.ts +0 -2
  209. package/src/role/api/queryRoles.ts +1 -13
  210. package/src/streamRepository/api/deleteStream.ts +1 -1
  211. package/src/streamRepository/api/index.ts +0 -4
  212. package/src/streamRepository/api/tests/getStream.test.ts +1 -1
  213. package/src/streamRepository/events/onStreamFlagged.ts +1 -6
  214. package/src/streamRepository/events/onStreamRecorded.ts +1 -1
  215. package/src/streamRepository/events/onStreamStarted.ts +1 -1
  216. package/src/streamRepository/events/onStreamStopped.ts +1 -1
  217. package/src/streamRepository/events/onStreamTerminated.ts +1 -1
  218. package/src/streamRepository/observers/getStreamById.ts +1 -1
  219. package/src/subChannelRepository/utils/markReadEngine.ts +0 -106
  220. package/src/userRepository/internalApi/queryUsers.ts +1 -9
  221. package/src/userRepository/observers/getUsers/UserLiveCollectionController.ts +12 -16
  222. package/src/userRepository/observers/getUsers/UserPaginationController.ts +1 -2
  223. package/src/userRepository/observers/index.ts +0 -2
  224. package/src/userRepository/observers/tests/getUsers.test.ts +1 -43
  225. package/src/userRepository/relationship/block/index.ts +0 -1
  226. package/src/userRepository/relationship/follow/api/index.ts +0 -4
  227. package/src/userRepository/relationship/follow/observers/index.ts +0 -4
  228. package/src/utils/linkedObject/channelLinkedObject.ts +1 -1
  229. package/src/utils/liveObject.ts +2 -2
  230. package/dist/channelRepository/api/getChannel.d.ts.map +0 -1
  231. package/dist/channelRepository/api/markAsRead.d.ts.map +0 -1
  232. package/dist/channelRepository/observers/observeChannel.d.ts +0 -18
  233. package/dist/channelRepository/observers/observeChannel.d.ts.map +0 -1
  234. package/dist/channelRepository/observers/observeChannels.d.ts +0 -17
  235. package/dist/channelRepository/observers/observeChannels.d.ts.map +0 -1
  236. package/dist/client/observers/getTotalUnreadCount.d.ts +0 -20
  237. package/dist/client/observers/getTotalUnreadCount.d.ts.map +0 -1
  238. package/dist/client/observers/tests/getTotalUnreadCount.test.d.ts +0 -2
  239. package/dist/client/observers/tests/getTotalUnreadCount.test.d.ts.map +0 -1
  240. package/dist/commentRepository/observers/observeComment.d.ts +0 -18
  241. package/dist/commentRepository/observers/observeComment.d.ts.map +0 -1
  242. package/dist/commentRepository/observers/observeComments.d.ts +0 -26
  243. package/dist/commentRepository/observers/observeComments.d.ts.map +0 -1
  244. package/dist/communityRepository/api/getTopTrendingCommunities.d.ts +0 -35
  245. package/dist/communityRepository/api/getTopTrendingCommunities.d.ts.map +0 -1
  246. package/dist/communityRepository/api/test/getTopTrendingCommunities.test.d.ts +0 -2
  247. package/dist/communityRepository/api/test/getTopTrendingCommunities.test.d.ts.map +0 -1
  248. package/dist/communityRepository/observers/observeCommunity.d.ts +0 -18
  249. package/dist/communityRepository/observers/observeCommunity.d.ts.map +0 -1
  250. package/dist/feedRepository/internalApi/getCustomRankingGlobalFeed.d.ts +0 -8
  251. package/dist/feedRepository/internalApi/getCustomRankingGlobalFeed.d.ts.map +0 -1
  252. package/dist/feedRepository/internalApi/index.d.ts +0 -3
  253. package/dist/feedRepository/internalApi/index.d.ts.map +0 -1
  254. package/dist/feedRepository/internalApi/queryGlobalFeed.d.ts +0 -9
  255. package/dist/feedRepository/internalApi/queryGlobalFeed.d.ts.map +0 -1
  256. package/dist/feedRepository/internalApi/test/getCustomRankingGlobalFeed.test.d.ts +0 -2
  257. package/dist/feedRepository/internalApi/test/getCustomRankingGlobalFeed.test.d.ts.map +0 -1
  258. package/dist/feedRepository/internalApi/test/queryGlobalFeed.test.d.ts +0 -2
  259. package/dist/feedRepository/internalApi/test/queryGlobalFeed.test.d.ts.map +0 -1
  260. package/dist/fileRepository/api/createFile.d.ts +0 -17
  261. package/dist/fileRepository/api/createFile.d.ts.map +0 -1
  262. package/dist/fileRepository/api/createImage.d.ts +0 -17
  263. package/dist/fileRepository/api/createImage.d.ts.map +0 -1
  264. package/dist/fileRepository/api/createVideo.d.ts +0 -18
  265. package/dist/fileRepository/api/createVideo.d.ts.map +0 -1
  266. package/dist/fileRepository/observers/index.d.ts +0 -2
  267. package/dist/fileRepository/observers/index.d.ts.map +0 -1
  268. package/dist/fileRepository/observers/observeFile.d.ts +0 -18
  269. package/dist/fileRepository/observers/observeFile.d.ts.map +0 -1
  270. package/dist/messageRepository/api/getMessage.d.ts +0 -32
  271. package/dist/messageRepository/api/getMessage.d.ts.map +0 -1
  272. package/dist/messageRepository/api/getMessages.d.ts +0 -32
  273. package/dist/messageRepository/api/getMessages.d.ts.map +0 -1
  274. package/dist/messageRepository/observers/observeMessage.d.ts +0 -21
  275. package/dist/messageRepository/observers/observeMessage.d.ts.map +0 -1
  276. package/dist/messageRepository/observers/observeMessages.d.ts +0 -23
  277. package/dist/messageRepository/observers/observeMessages.d.ts.map +0 -1
  278. package/dist/pollRepository/observers/observePoll.d.ts +0 -18
  279. package/dist/pollRepository/observers/observePoll.d.ts.map +0 -1
  280. package/dist/postRepository/api/updatePost.d.ts +0 -24
  281. package/dist/postRepository/api/updatePost.d.ts.map +0 -1
  282. package/dist/postRepository/observers/observePost.d.ts +0 -18
  283. package/dist/postRepository/observers/observePost.d.ts.map +0 -1
  284. package/dist/postRepository/observers/observePosts.d.ts +0 -34
  285. package/dist/postRepository/observers/observePosts.d.ts.map +0 -1
  286. package/dist/streamRepository/api/getStream.d.ts.map +0 -1
  287. package/dist/streamRepository/api/queryStreams.d.ts +0 -25
  288. package/dist/streamRepository/api/queryStreams.d.ts.map +0 -1
  289. package/dist/userRepository/observers/getViewedUsers.d.ts +0 -7
  290. package/dist/userRepository/observers/getViewedUsers.d.ts.map +0 -1
  291. package/dist/userRepository/observers/observeUser.d.ts +0 -17
  292. package/dist/userRepository/observers/observeUser.d.ts.map +0 -1
  293. package/dist/userRepository/observers/tests/getViewedUsers.test.d.ts +0 -2
  294. package/dist/userRepository/observers/tests/getViewedUsers.test.d.ts.map +0 -1
  295. package/dist/userRepository/relationship/block/observers/getBlockedUsers.d.ts +0 -2
  296. package/dist/userRepository/relationship/block/observers/getBlockedUsers.d.ts.map +0 -1
  297. package/dist/userRepository/relationship/block/observers/index.d.ts +0 -2
  298. package/dist/userRepository/relationship/block/observers/index.d.ts.map +0 -1
  299. package/dist/userRepository/relationship/follow/api/acceptFollower.d.ts +0 -19
  300. package/dist/userRepository/relationship/follow/api/acceptFollower.d.ts.map +0 -1
  301. package/dist/userRepository/relationship/follow/api/declineFollower.d.ts +0 -19
  302. package/dist/userRepository/relationship/follow/api/declineFollower.d.ts.map +0 -1
  303. package/dist/userRepository/relationship/follow/observers/observeFollowInfo.d.ts +0 -18
  304. package/dist/userRepository/relationship/follow/observers/observeFollowInfo.d.ts.map +0 -1
  305. package/dist/userRepository/relationship/follow/observers/observeFollowers.d.ts +0 -18
  306. package/dist/userRepository/relationship/follow/observers/observeFollowers.d.ts.map +0 -1
  307. package/dist/userRepository/relationship/follow/observers/observeFollowings.d.ts +0 -18
  308. package/dist/userRepository/relationship/follow/observers/observeFollowings.d.ts.map +0 -1
  309. package/src/channelRepository/observers/observeChannel.ts +0 -109
  310. package/src/channelRepository/observers/observeChannels.ts +0 -74
  311. package/src/client/observers/getTotalUnreadCount.ts +0 -53
  312. package/src/client/observers/tests/getTotalUnreadCount.test.ts +0 -101
  313. package/src/commentRepository/observers/observeComment.ts +0 -102
  314. package/src/commentRepository/observers/observeComments.ts +0 -77
  315. package/src/communityRepository/api/getTopTrendingCommunities.ts +0 -97
  316. package/src/communityRepository/api/test/getTopTrendingCommunities.test.ts +0 -102
  317. package/src/communityRepository/observers/observeCommunity.ts +0 -103
  318. package/src/feedRepository/internalApi/getCustomRankingGlobalFeed.ts +0 -87
  319. package/src/feedRepository/internalApi/index.ts +0 -2
  320. package/src/feedRepository/internalApi/queryGlobalFeed.ts +0 -95
  321. package/src/feedRepository/internalApi/test/getCustomRankingGlobalFeed.test.ts +0 -138
  322. package/src/feedRepository/internalApi/test/queryGlobalFeed.test.ts +0 -130
  323. package/src/fileRepository/api/createFile.ts +0 -59
  324. package/src/fileRepository/api/createImage.ts +0 -59
  325. package/src/fileRepository/api/createVideo.ts +0 -69
  326. package/src/fileRepository/observers/index.ts +0 -1
  327. package/src/fileRepository/observers/observeFile.ts +0 -49
  328. package/src/messageRepository/api/getMessage.ts +0 -102
  329. package/src/messageRepository/api/getMessages.ts +0 -83
  330. package/src/messageRepository/observers/observeMessage.ts +0 -94
  331. package/src/messageRepository/observers/observeMessages.ts +0 -89
  332. package/src/pollRepository/observers/observePoll.ts +0 -67
  333. package/src/postRepository/api/updatePost.ts +0 -63
  334. package/src/postRepository/observers/observePost.ts +0 -115
  335. package/src/postRepository/observers/observePosts.ts +0 -86
  336. package/src/streamRepository/api/queryStreams.ts +0 -63
  337. package/src/userRepository/observers/getViewedUsers.ts +0 -99
  338. package/src/userRepository/observers/observeUser.ts +0 -71
  339. package/src/userRepository/observers/tests/getViewedUsers.test.ts +0 -39
  340. package/src/userRepository/relationship/block/observers/getBlockedUsers.ts +0 -13
  341. package/src/userRepository/relationship/block/observers/index.ts +0 -1
  342. package/src/userRepository/relationship/follow/api/acceptFollower.ts +0 -40
  343. package/src/userRepository/relationship/follow/api/declineFollower.ts +0 -40
  344. package/src/userRepository/relationship/follow/observers/observeFollowInfo.ts +0 -64
  345. package/src/userRepository/relationship/follow/observers/observeFollowers.ts +0 -74
  346. package/src/userRepository/relationship/follow/observers/observeFollowings.ts +0 -74
  347. /package/dist/streamRepository/{api → internalApi}/getStream.d.ts +0 -0
  348. /package/src/streamRepository/{api → internalApi}/getStream.ts +0 -0
package/dist/index.cjs.js CHANGED
@@ -102,8 +102,8 @@ const PostContentType = Object.freeze({
102
102
 
103
103
  function getVersion() {
104
104
  try {
105
- // the string ''v6.35.2-cjs'' should be replaced by actual value by @rollup/plugin-replace
106
- return 'v6.35.2-cjs';
105
+ // the string ''v7.0.0-cjs'' should be replaced by actual value by @rollup/plugin-replace
106
+ return 'v7.0.0-cjs';
107
107
  }
108
108
  catch (error) {
109
109
  return '__dev__';
@@ -1319,9 +1319,6 @@ const WS_EVENTS = [
1319
1319
  'sessionStateChange',
1320
1320
  // for internal use by accessTokenExpiryWatcher
1321
1321
  'tokenExpired',
1322
- 'v3.video-streaming.didRecord',
1323
- 'v3.video-streaming.didStart',
1324
- 'v3.video-streaming.didStop',
1325
1322
  ];
1326
1323
  const MQTT_EVENTS = [
1327
1324
  'connect',
@@ -1331,7 +1328,12 @@ const MQTT_EVENTS = [
1331
1328
  'close',
1332
1329
  'end',
1333
1330
  'reconnect',
1334
- 'user.didGlobalBan',
1331
+ 'video-streaming.didStart',
1332
+ 'video-streaming.didRecord',
1333
+ 'video-streaming.didStop',
1334
+ 'video-streaming.didFlag',
1335
+ 'video-streaming.didTerminate',
1336
+ // 'user.didGlobalBan' remove due to message event,
1335
1337
  ];
1336
1338
  /** @hidden */
1337
1339
  const createEventEmitter = () => {
@@ -1530,7 +1532,11 @@ function subscribeTopic(topic, callback) {
1530
1532
  return () => null;
1531
1533
  modifyMqttConnection();
1532
1534
  return mqtt.subscribe(topic, callback);
1533
- }
1535
+ }
1536
+ const getLiveStreamTopic = () => {
1537
+ const user = getActiveUser();
1538
+ return `${getNetworkId(user)}/videostreaming`;
1539
+ };
1534
1540
 
1535
1541
  var _a;
1536
1542
  /* eslint-disable no-undef */
@@ -1566,7 +1572,7 @@ const API_REGIONS = {
1566
1572
  US: 'us',
1567
1573
  };
1568
1574
  const URLS = {
1569
- http: 'https://api.{region}.amity.co',
1575
+ http: 'https://apix.{region}.amity.co',
1570
1576
  mqtt: 'wss://sse.{region}.amity.co:443/mqtt',
1571
1577
  };
1572
1578
  function computeUrl(type, region) {
@@ -4384,6 +4390,7 @@ const subscribeGlobalTopic = () => {
4384
4390
  // subscribing to user topic is necessary to handle ban event
4385
4391
  subscribeTopic(getUserTopic(getActiveUser())),
4386
4392
  subscribeTopic(getMarkerUserFeedTopic()),
4393
+ subscribeTopic(getLiveStreamTopic()),
4387
4394
  ];
4388
4395
  return () => disposers.forEach(fn => fn());
4389
4396
  };
@@ -5880,9 +5887,6 @@ const reactorLinkedObject = (reactor) => {
5880
5887
  * import { ChannelRepository } from '@amityco/ts-sdk'
5881
5888
  * const success = await ChannelRepository.markAsRead('channelId')
5882
5889
  * ```
5883
- *
5884
- * @deprecated Please use the {@link Amity.Channel.markAsRead} method instead
5885
- *
5886
5890
  * Updating all {@link Amity.SubChannel} in specify {@link Amity.Channel} as read
5887
5891
  *
5888
5892
  * @param channelId the ID of to specify {@link Amity.Channel}
@@ -6495,7 +6499,7 @@ const prepareMessagePayload = async (payload, event) => {
6495
6499
  var _a, _b;
6496
6500
  const subChannelCache = (_b = (_a = pullFromCache(['subChannel', 'get', messageFeed.messageFeedId])) === null || _a === void 0 ? void 0 : _a.data) !== null && _b !== void 0 ? _b : {};
6497
6501
  // exclude getter properties from existing subChannel cache, update only other properties to existing subChannel cache
6498
- const _c = convertFromRaw$2(messageFeed), restSubChannel = __rest(_c, ["unreadCount", "hasMentioned", "isMentioned"]);
6502
+ const _c = convertFromRaw$2(messageFeed), restSubChannel = __rest(_c, ["unreadCount", "isMentioned"]);
6499
6503
  updateSubChannelCache(messageFeed.messageFeedId, subChannelCache, restSubChannel);
6500
6504
  });
6501
6505
  }
@@ -6509,15 +6513,12 @@ function convertParams(_a) {
6509
6513
  return Object.assign({ messageFeedId: subChannelId, mentionedUsers: mentionees, dataType, data }, rest);
6510
6514
  }
6511
6515
  function convertQueryParams$1(_a) {
6512
- var { sortBy, subChannelId, tags, includingTags, excludingTags, includeDeleted, aroundMessageId, limit, type } = _a, rest = __rest(_a, ["sortBy", "subChannelId", "tags", "includingTags", "excludingTags", "includeDeleted", "aroundMessageId", "limit", "type"]);
6516
+ var { sortBy, subChannelId, includingTags, excludingTags, includeDeleted, aroundMessageId, limit, type } = _a, rest = __rest(_a, ["sortBy", "subChannelId", "includingTags", "excludingTags", "includeDeleted", "aroundMessageId", "limit", "type"]);
6513
6517
  const out = Object.assign(Object.assign({}, rest), { messageFeedId: subChannelId, isDeleted: inferIsDeleted(includeDeleted), options: {
6514
6518
  sortBy,
6515
6519
  limit: limit || COLLECTION_DEFAULT_PAGINATION_LIMIT,
6516
6520
  around: aroundMessageId,
6517
6521
  } });
6518
- if (tags) {
6519
- out.includeTags = tags;
6520
- }
6521
6522
  if (includingTags) {
6522
6523
  out.includeTags = includingTags;
6523
6524
  }
@@ -7001,22 +7002,27 @@ const getSubChannelsUnreadCount = (channel, marker) => {
7001
7002
  };
7002
7003
 
7003
7004
  const constructChannelDynamicValue = (channel) => {
7004
- return shallowClone(channel, {
7005
- get unreadCount() {
7006
- return getSubChannelsUnreadCount(channel);
7007
- },
7008
- get hasMentioned() {
7009
- return getChannelIsMentioned(channel);
7010
- },
7005
+ const rest = __rest(channel, ["messageCount"]);
7006
+ return shallowClone(rest, {
7011
7007
  get isMentioned() {
7012
- return getChannelIsMentioned(channel);
7008
+ return getChannelIsMentioned(rest);
7013
7009
  },
7014
7010
  get subChannelsUnreadCount() {
7015
- return getSubChannelsUnreadCount(channel);
7011
+ return getSubChannelsUnreadCount(rest);
7016
7012
  },
7017
7013
  });
7018
7014
  };
7019
7015
 
7016
+ const constructChannelObject = (channel) => {
7017
+ /**
7018
+ * convert internal cache data to be public channel data
7019
+ * 1. [getChannelMessagePreviewWithUser] add messagePreview >> Amity.InternalChannel -> Amity.InternalChannel
7020
+ * 2. [constructChannelDynamicValue] construct getter value >> Amity.StaticInternalChannel -> Amity.Channel
7021
+ * 3. [LinkedObject.channel] add markAsRead >> Amity.InternalChannel -> Amity.Channel
7022
+ */
7023
+ return LinkedObject.channel(constructChannelDynamicValue(getChannelMessagePreviewWithUser(channel)));
7024
+ };
7025
+
7020
7026
  /**
7021
7027
  * ```js
7022
7028
  * import { getChannelByIds } from '@amityco/ts-sdk'
@@ -7031,7 +7037,7 @@ const constructChannelDynamicValue = (channel) => {
7031
7037
  * @category Channel API
7032
7038
  * @async
7033
7039
  */
7034
- const getChannelByIds = async (channelIds) => {
7040
+ const getChannelByIds$1 = async (channelIds) => {
7035
7041
  const client = getActiveClient();
7036
7042
  client.log('channel/getChannelByIds', channelIds);
7037
7043
  const encodedChannelIds = channelIds.map(channelId => encodeURIComponent(channelId));
@@ -7061,7 +7067,7 @@ const getChannelByIds = async (channelIds) => {
7061
7067
  ingestInCache(data, { cachedAt });
7062
7068
  fireEvent('local.channel.fetched', data.channels);
7063
7069
  return {
7064
- data: data.channels.map(channel => LinkedObject.channel(constructChannelDynamicValue(channel))),
7070
+ data: data.channels.map(channel => constructChannelObject(channel)),
7065
7071
  cachedAt,
7066
7072
  };
7067
7073
  };
@@ -7078,7 +7084,7 @@ const getChannelByIds = async (channelIds) => {
7078
7084
  *
7079
7085
  * @category Channel API
7080
7086
  */
7081
- getChannelByIds.locally = (channelIds) => {
7087
+ getChannelByIds$1.locally = (channelIds) => {
7082
7088
  var _a, _b;
7083
7089
  const client = getActiveClient();
7084
7090
  client.log('channel/getChannelByIds.locally', channelIds);
@@ -7092,7 +7098,7 @@ getChannelByIds.locally = (channelIds) => {
7092
7098
  const channels = cached.map(({ data }) => data);
7093
7099
  const oldest = (_b = cached.sort((a, b) => (a.cachedAt < b.cachedAt ? -1 : 1))) === null || _b === void 0 ? void 0 : _b[0];
7094
7100
  return {
7095
- data: channels.map(channel => LinkedObject.channel(channel)),
7101
+ data: channels.map(channel => constructChannelObject(channel)),
7096
7102
  cachedAt: oldest.cachedAt,
7097
7103
  };
7098
7104
  };
@@ -7150,20 +7156,6 @@ const setIntervalTask = (handler, timeout) => {
7150
7156
  return () => clearInterval(timer);
7151
7157
  };
7152
7158
 
7153
- const onOnline = (callback) => {
7154
- if (typeof window !== 'undefined' && window.addEventListener) {
7155
- window.addEventListener('online', callback);
7156
- return () => window.removeEventListener('online', callback);
7157
- }
7158
- if (typeof document !== 'undefined' && document.addEventListener) {
7159
- document.addEventListener('online', callback);
7160
- return () => document.removeEventListener('online', callback);
7161
- }
7162
- // Handle unsupported environment
7163
- console.error('Unsupported environment');
7164
- return () => console.error('Unsupported environment');
7165
- };
7166
-
7167
7159
  /**
7168
7160
  * ```js
7169
7161
  * import { SubChannel } from '@amityco/ts-sdk'
@@ -7196,73 +7188,8 @@ const readingAPI = async (messageFeedIds) => {
7196
7188
  return true;
7197
7189
  };
7198
7190
 
7199
- /**
7200
- * ```js
7201
- * import { SubChannel } from '@amityco/ts-sdk'
7202
- * const success = await SubChannel('foo')
7203
- * ```
7204
- *
7205
- * Mark all messages as read and start reading message inside channel
7206
- *
7207
- * @param messageFeedId - Sub channel ID to start reading.
7208
- * @return A success boolean if reading of the sub channel had begun.
7209
- *
7210
- * @category Channel API
7211
- * @async
7212
- * @private
7213
- */
7214
- const startReadingAPI = async (messageFeedId) => {
7215
- const client = getActiveClient();
7216
- client.log('subChannel/startReadingAPI', messageFeedId);
7217
- const { data: payload } = await client.http.post(`/api/v1/markers/message-feeds/${messageFeedId}/start-reading`);
7218
- const { userEntityMarkers: userEntityMarkersPayload, userFeedMarkers: userFeedMarkersPayload, feedMarkers, userMarkers, } = payload;
7219
- const userEntityMarkers = convertChannelMarkerResponse(userEntityMarkersPayload);
7220
- const userFeedMarkers = convertSubChannelMarkerResponse(userFeedMarkersPayload);
7221
- const cachedAt = client.cache && Date.now();
7222
- if (client.cache)
7223
- ingestInCache({ userEntityMarkers, userFeedMarkers, feedMarkers, userMarkers }, { cachedAt });
7224
- fireEvent('local.feedMarker.fetched', { feedMarkers });
7225
- fireEvent('local.channelMarker.fetched', { userEntityMarkers });
7226
- fireEvent('local.subChannelMarker.fetched', { userFeedMarkers });
7227
- fireEvent('local.userMarker.fetched', { userMarkers });
7228
- return true;
7229
- };
7230
-
7231
- /**
7232
- * ```js
7233
- * import { stopReading } from '@amityco/ts-sdk'
7234
- * const success = await stopReading('foo')
7235
- * ```
7236
- *
7237
- * Mark all messages as read and stop reading message inside channel
7238
- *
7239
- * @param messageFeedId - The sub channel ID to stop reading.
7240
- * @return A success boolean if reading of the sub channel had begun.
7241
- *
7242
- * @category Channel API
7243
- * @async
7244
- * @private
7245
- */
7246
- const stopReadingAPI = async (messageFeedId) => {
7247
- const client = getActiveClient();
7248
- client.log('channel/stopReadingAPI', messageFeedId);
7249
- const { data: payload } = await client.http.post(`/api/v1/markers/message-feeds/${messageFeedId}/stop-reading`);
7250
- const { userEntityMarkers: userEntityMarkersPayload, userFeedMarkers: userFeedMarkersPayload, feedMarkers, userMarkers, } = payload;
7251
- const userEntityMarkers = convertChannelMarkerResponse(userEntityMarkersPayload);
7252
- const userFeedMarkers = convertSubChannelMarkerResponse(userFeedMarkersPayload);
7253
- const cachedAt = client.cache && Date.now();
7254
- if (client.cache)
7255
- ingestInCache({ userEntityMarkers, userFeedMarkers, feedMarkers, userMarkers }, { cachedAt });
7256
- fireEvent('local.feedMarker.fetched', { feedMarkers });
7257
- fireEvent('local.channelMarker.fetched', { userEntityMarkers });
7258
- fireEvent('local.subChannelMarker.fetched', { userFeedMarkers });
7259
- fireEvent('local.userMarker.fetched', { userMarkers });
7260
- return true;
7261
- };
7262
-
7263
7191
  const START_READING_INTERVAL_TIME = 30000;
7264
7192
  let isSyncRunning$1 = false;
7265
- let disposers$2 = [];
7266
7193
  /**
7267
7194
  * map contains subChannelId and isReading flag to determine which subChannel is on reading state
7268
7195
  */
@@ -7306,91 +7233,6 @@ const markReadEngineOnLoginHandler = () => {
7306
7233
  stopIntervalTask();
7307
7234
  };
7308
7235
  };
7309
- const getParentChannelId$1 = async (subChannelId) => {
7310
- const cached = getSubChannel$1.locally(subChannelId);
7311
- if (cached) {
7312
- return cached.data.channelId;
7313
- }
7314
- const { data } = await getSubChannel$1(subChannelId);
7315
- return data.channelId;
7316
- };
7317
- const registerEventListeners$1 = () => {
7318
- if (disposers$2.length > 0) {
7319
- return;
7320
- }
7321
- disposers$2.push(onOnline(() => {
7322
- // Start reading the reading subChannel again when resume from offline state
7323
- startReadingFromReadingList();
7324
- }));
7325
- };
7326
- const registerTopicSubscribers$1 = async (subChannelId) => {
7327
- const channelId = await getParentChannelId$1(subChannelId);
7328
- const markedMessageTopic = getMarkedMessageTopic({ channelId, subChannelId });
7329
- disposers$2.push(subscribeTopic(markedMessageTopic));
7330
- };
7331
- const disposeAll = () => {
7332
- disposers$2.forEach(fn => fn());
7333
- disposers$2 = [];
7334
- };
7335
- /* begin_public_function
7336
- id: subchannel.start_reading
7337
- */
7338
- /**
7339
- * @deprecated Use {@link startMessageReceiptSync} instead.
7340
- * ```js
7341
- * import { startReading } from '@amityco/ts-sdk'
7342
- * const success = await startReading('foo')
7343
- * ```
7344
- *
7345
- * Set local reading state of channel to `true` and then call mark all
7346
- * messages as read API.
7347
- *
7348
- * @param subChannelId - The sub channel ID to start reading.
7349
- * @return A success boolean if reading of the sub channel had begun.
7350
- *
7351
- * @category Channel API
7352
- * @async
7353
- */
7354
- const startReading = async (subChannelId) => {
7355
- isReadingMap[subChannelId] = true;
7356
- if (disposers$2.length === 0) {
7357
- registerEventListeners$1();
7358
- registerTopicSubscribers$1(subChannelId);
7359
- }
7360
- try {
7361
- return await startReadingAPI(subChannelId);
7362
- }
7363
- catch (e) {
7364
- isReadingMap[subChannelId] = false;
7365
- return false;
7366
- }
7367
- };
7368
- /* end_public_function */
7369
- /* begin_public_function
7370
- id: subchannel.stop_reading
7371
- */
7372
- /**
7373
- * @deprecated Use {@link stopMessageReceiptSync} instead.
7374
- * ```js
7375
- * import { stopReading } from '@amityco/ts-sdk'
7376
- * const success = await stopReading('foo')
7377
- * ```
7378
- *
7379
- * Set local reading state of channel to `false` and then call mark all
7380
- * messages as unread API.
7381
- *
7382
- * @param subChannelId - The sub channel ID to stop reading.
7383
- * @return A success boolean if reading of the sub channel had begun.
7384
- *
7385
- * @category Channel API
7386
- * @async
7387
- */
7388
- const stopReading = (subChannelId) => {
7389
- isReadingMap[subChannelId] = false;
7390
- disposeAll();
7391
- return stopReadingAPI(subChannelId);
7392
- };
7393
- /* end_public_function */
7394
7236
  setIntervalTask(async () => {
7395
7237
  if (!isSyncRunning$1)
7396
7238
  return;
@@ -7545,7 +7387,7 @@ const initializeMessagePreviewSetting = async () => {
7545
7387
  * 2. channel and subChannel which isDelete = true
7546
7388
  */
7547
7389
  if (channelWithIsDeletedTrue.length !== 0)
7548
- await getChannelByIds(channelWithIsDeletedTrue);
7390
+ await getChannelByIds$1(channelWithIsDeletedTrue);
7549
7391
  if (subChannelWithIsDeletedTrue.length !== 0)
7550
7392
  await getSubChannels$1(subChannelWithIsDeletedTrue);
7551
7393
  }
@@ -7943,6 +7785,20 @@ var readReceiptSyncEngineOnLoginHandler = () => {
7943
7785
  };
7944
7786
  };
7945
7787
 
7788
+ const onOnline = (callback) => {
7789
+ if (typeof window !== 'undefined' && window.addEventListener) {
7790
+ window.addEventListener('online', callback);
7791
+ return () => window.removeEventListener('online', callback);
7792
+ }
7793
+ if (typeof document !== 'undefined' && document.addEventListener) {
7794
+ document.addEventListener('online', callback);
7795
+ return () => document.removeEventListener('online', callback);
7796
+ }
7797
+ // Handle unsupported environment
7798
+ console.error('Unsupported environment');
7799
+ return () => console.error('Unsupported environment');
7800
+ };
7801
+
7946
7802
  const onOffline = (callback) => {
7947
7803
  if (typeof window !== 'undefined' && window.addEventListener) {
7948
7804
  window.addEventListener('offline', callback);
@@ -7957,8 +7813,90 @@ const onOffline = (callback) => {
7957
7813
  return () => console.error('Unsupported environment');
7958
7814
  };
7959
7815
 
7816
+ /**
7817
+ * ```js
7818
+ * import { getChannelByIds } from '@amityco/ts-sdk'
7819
+ * const channels = await getChannelByIds(['foo', 'bar'])
7820
+ * ```
7821
+ *
7822
+ * Fetches a collection of {@link Amity.Channel} objects
7823
+ *
7824
+ * @param channelIds the IDs of the {@link Amity.Channel} to fetch
7825
+ * @returns the associated collection of {@link Amity.Channel} objects
7826
+ *
7827
+ * @category Channel API
7828
+ * @async
7829
+ */
7830
+ const getChannelByIds = async (channelIds) => {
7831
+ const client = getActiveClient();
7832
+ client.log('channel/getChannelByIds', channelIds);
7833
+ const encodedChannelIds = channelIds.map(channelId => encodeURIComponent(channelId));
7834
+ let payload;
7835
+ try {
7836
+ // API-FIX: endpoint should not be /list, parameters should be querystring.
7837
+ const response = await client.http.get(`/api/v3/channels/list`, {
7838
+ params: { channelIds: encodedChannelIds },
7839
+ });
7840
+ payload = response.data;
7841
+ }
7842
+ catch (error) {
7843
+ channelIds.forEach(channelId => {
7844
+ if (checkIfShouldGoesToTombstone(error === null || error === void 0 ? void 0 : error.code)) {
7845
+ // NOTE: use channelPublicId as tombstone cache key since we cannot get the channelPrivateId that come along with channel data from server
7846
+ pushToTombstone('channel', channelId);
7847
+ }
7848
+ });
7849
+ throw error;
7850
+ }
7851
+ const data = await prepareChannelPayload(payload);
7852
+ if (client.isUnreadCountEnabled && client.getMarkerSyncConsistentMode()) {
7853
+ await prepareUnreadCountInfo(payload);
7854
+ }
7855
+ const cachedAt = client.cache && Date.now();
7856
+ if (client.cache)
7857
+ ingestInCache(data, { cachedAt });
7858
+ fireEvent('local.channel.fetched', data.channels);
7859
+ return {
7860
+ data: data.channels,
7861
+ cachedAt,
7862
+ };
7863
+ };
7864
+ /**
7865
+ * ```js
7866
+ * import { getChannelByIds } from '@amityco/ts-sdk'
7867
+ * const channels = getChannelByIds.locally(['foo', 'bar']) ?? []
7868
+ * ```
7869
+ *
7870
+ * Fetches a collection of {@link Amity.Channel} objects from cache
7871
+ *
7872
+ * @param channelIds the IDs of the {@link Amity.Channel} to fetch
7873
+ * @returns the associated collection of {@link Amity.Channel} objects
7874
+ *
7875
+ * @category Channel API
7876
+ */
7877
+ getChannelByIds.locally = (channelIds) => {
7878
+ var _a, _b;
7879
+ const client = getActiveClient();
7880
+ client.log('channel/getChannelByIds.locally', channelIds);
7881
+ if (!client.cache)
7882
+ return;
7883
+ const cached = (_a = queryCache(['channel', 'get'])) === null || _a === void 0 ? void 0 : _a.filter(({ data }) => {
7884
+ return channelIds.includes(data.channelPublicId);
7885
+ });
7886
+ if (!cached || (cached === null || cached === void 0 ? void 0 : cached.length) < channelIds.length)
7887
+ return;
7888
+ const channels = cached.map(({ data }) => data);
7889
+ const oldest = (_b = cached.sort((a, b) => (a.cachedAt < b.cachedAt ? -1 : 1))) === null || _b === void 0 ? void 0 : _b[0];
7890
+ return {
7891
+ data: channels,
7892
+ cachedAt: oldest.cachedAt,
7893
+ };
7894
+ };
7895
+
7960
7896
  const resolveChannels = async (channelIds) => {
7961
- const { data: channels } = await getChannelByIds(channelIds);
7897
+ var _a, _b, _c;
7898
+ await getChannelByIds(channelIds);
7899
+ const channels = (_c = (_b = (_a = queryCache(['channel', 'get'])) === null || _a === void 0 ? void 0 : _a.filter(({ data }) => data.channelPublicId && channelIds.includes(data.channelPublicId))) === null || _b === void 0 ? void 0 : _b.map(({ data }) => data)) !== null && _c !== void 0 ? _c : [];
7962
7900
  fireEvent('local.channel.resolved', channels);
7963
7901
  };
7964
7902
 
@@ -9086,13 +9024,6 @@ const stopUnreadSync = () => {
9086
9024
  setMarkerSyncEvents([]);
9087
9025
  unRegisterEventListeners();
9088
9026
  };
9089
- /**
9090
- * @deprecated Please use `startUnreadSync` instead
9091
- */
9092
- const stopUnreadSyncing = () => {
9093
- console.warn('`stopUnreadSyncing` has been deprecated, please use `stopUnreadSync` instead');
9094
- return stopUnreadSync();
9095
- };
9096
9027
  setIntervalTask(async () => {
9097
9028
  if (!isSyncRunning)
9098
9029
  return;
@@ -9547,6 +9478,28 @@ function setUploadedFileAccessType(accessType) {
9547
9478
  GlobalFileAccessType$1.getInstance().setFileAccessType(accessType);
9548
9479
  }
9549
9480
 
9481
+ /**
9482
+ * ```js
9483
+ * import { fetchLinkPreview } from '@amityco/ts-sdk'
9484
+ * const { title, description, imageUrl } = fetchLinkPreview('https://www.example.com/')
9485
+ * ```
9486
+ *
9487
+ *
9488
+ * @param url the url to fetch link preview
9489
+ * @returns A {@link Amity.LinkPreview} instance
9490
+ *
9491
+ * @category Client API
9492
+ * */
9493
+ const fetchLinkPreview = async (url) => {
9494
+ const client = getActiveClient();
9495
+ let fetchUrl = url;
9496
+ if (!/^https?:\/\//i.test(url)) {
9497
+ fetchUrl = `https://${url}`;
9498
+ }
9499
+ const { data } = await client.http.get(`/api/v1/link-preview?url=${encodeURIComponent(fetchUrl)}`);
9500
+ return data;
9501
+ };
9502
+
9550
9503
  /**
9551
9504
  * ```js
9552
9505
  * import { onChannelMarkerFetched } from '@amityco/ts-sdk'
@@ -9791,115 +9744,21 @@ const removeFunctionProperties = (obj) => {
9791
9744
  };
9792
9745
 
9793
9746
  /**
9794
- * @deprecated This function is deprecated
9795
- */
9796
- const liveObject = (id, callback, key, fetcher, eventHandlers, options) => {
9797
- const { forceDispatch, callbackDataSelector, callbackFilter } = Object.assign({ forceDispatch: false, callbackDataSelector: (data) => data }, options);
9798
- const { cache } = getActiveClient();
9799
- if (!cache) {
9800
- console.log(LIVE_OBJECT_ENABLE_CACHE_MESSAGE);
9801
- }
9802
- let model;
9803
- let isUnsyncedModel = false; // for messages
9804
- const disposers = [];
9805
- const dispatcher = (data) => {
9806
- const { data: newModel } = data, rest = __rest(data, ["data"]);
9807
- if (!callbackFilter || callbackFilter(newModel, model)) {
9808
- callback(Object.assign({ data: callbackDataSelector(newModel) }, rest));
9809
- }
9810
- // resolve all getter on data model to a static value to avoid comparison problems
9811
- model = convertGetterPropsToStatic(newModel);
9812
- };
9813
- const realtimeRouter = (eventModel, forceDispatch = false) => {
9814
- if (id !== eventModel[key]) {
9815
- return;
9816
- }
9817
- if (model) {
9818
- if (!forceDispatch && isEqual(model, eventModel)) {
9819
- return;
9820
- }
9821
- }
9822
- dispatcher({ loading: false, data: eventModel, origin: 'event' });
9823
- };
9824
- const onFetch = () => {
9825
- // TODO: Ihis `@ts-ignore` is bring back to fix the build and it needs to be removed later
9826
- // @ts-ignore
9827
- const query = createQuery(fetcher, id, true);
9828
- runQuery(query, ({ error, data, loading, origin, cachedAt }) => {
9829
- if (cachedAt === UNSYNCED_OBJECT_CACHED_AT_VALUE) {
9830
- dispatcher({
9831
- // @ts-ignore
9832
- data,
9833
- origin,
9834
- loading: false,
9835
- error: new ASCApiError(UNSYNCED_OBJECT_CACHED_AT_MESSAGE, 800800 /* Amity.ClientError.DISALOOW_UNSYNCED_OBJECT */, "error" /* Amity.ErrorLevel.ERROR */),
9836
- });
9837
- isUnsyncedModel = true;
9838
- disposers.forEach(fn => fn());
9839
- }
9840
- else if (!isUnsyncedModel) {
9841
- // @ts-ignore
9842
- dispatcher({ loading, data, origin, error });
9843
- }
9844
- if (error) {
9845
- disposers.forEach(fn => fn());
9846
- }
9847
- });
9848
- };
9849
- disposers.push(...eventHandlers.map(fn => fn(eventModel => realtimeRouter(eventModel, forceDispatch))));
9850
- onFetch();
9851
- return () => {
9852
- disposers.forEach(fn => fn());
9853
- };
9854
- };
9855
-
9856
- /**
9857
- * @deprecated Please use unreadCount from `getUserUnread` instead.
9858
- *
9859
- * ```js
9860
- * import { getTotalUnreadCount } from '@amityco/ts-sdk';
9861
- *
9862
- * const unsubscribe = getTotalUnreadCount(response => {
9863
- * totalUnreadCount = response.data;
9864
- * });
9865
- * ```
9866
- *
9867
- * Observe current user's unread count from {@link Amity.UserMarker}
9868
- *
9869
- * @param callback the function to call when new data are available
9870
- * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the events
9871
- *
9872
- * @category Message Live Object
9873
- */
9874
- const getTotalUnreadCount = (callback) => {
9875
- const { _id: userId } = getActiveUser();
9876
- if (!userId)
9877
- throw new ASCError('The _id has not been defined in ActiveUser', 800000 /* Amity.ClientError.UNKNOWN_ERROR */, "error" /* Amity.ErrorLevel.ERROR */);
9878
- const callbackDataSelector = (data) => { var _a; return (_a = data === null || data === void 0 ? void 0 : data.unreadCount) !== null && _a !== void 0 ? _a : 0; };
9879
- return liveObject(userId, callback, 'userId', async () => {
9880
- const { data: userMarker, cachedAt } = await getUserMarker();
9881
- return { data: userMarker, cachedAt };
9882
- }, [onUserMarkerFetchedLegacy], {
9883
- callbackDataSelector,
9884
- });
9885
- };
9886
-
9887
- /**
9888
- *
9889
- * ```js
9890
- * import { getUserUnread } from '@amityco/ts-sdk';
9891
- *
9892
- * const unsubscribe = getUserUnread(response => {
9893
- * userUnread = response.data;
9894
- * });
9895
- * ```
9896
- *
9897
- * Observe current user's unread including unreadCount and hasMentioned from {@link Amity.UserMarker}
9898
- *
9899
- * @param callback the function to call when new data are available
9900
- * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the events
9901
- *
9902
- * @category Message Live Object
9747
+ *
9748
+ * ```js
9749
+ * import { getUserUnread } from '@amityco/ts-sdk';
9750
+ *
9751
+ * const unsubscribe = getUserUnread(response => {
9752
+ * userUnread = response.data;
9753
+ * });
9754
+ * ```
9755
+ *
9756
+ * Observe current user's unread including unreadCount and hasMentioned from {@link Amity.UserMarker}
9757
+ *
9758
+ * @param callback the function to call when new data are available
9759
+ * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the events
9760
+ *
9761
+ * @category Message Live Object
9903
9762
  */
9904
9763
  const getUserUnread = (callback) => {
9905
9764
  const { _id: userId } = getActiveUser();
@@ -9925,7 +9784,7 @@ const getUserUnread = (callback) => {
9925
9784
  model = callbackModel ? convertGetterPropsToStatic(callbackModel) : callbackModel;
9926
9785
  callback({
9927
9786
  data: callbackModel
9928
- ? Object.assign(Object.assign({}, callbackModel), { hasMentioned: callbackModel.isMentioned }) : callbackModel,
9787
+ ? Object.assign(Object.assign({}, callbackModel), { isMentioned: callbackModel.isMentioned }) : callbackModel,
9929
9788
  loading: data.loading,
9930
9789
  error: data.error,
9931
9790
  });
@@ -10008,12 +9867,12 @@ var index$l = /*#__PURE__*/Object.freeze({
10008
9867
  markerSync: markerSync,
10009
9868
  enableUnreadCount: enableUnreadCount,
10010
9869
  setUploadedFileAccessType: setUploadedFileAccessType,
9870
+ fetchLinkPreview: fetchLinkPreview,
10011
9871
  onConnectionError: onConnectionError,
10012
9872
  onClientDisconnected: onClientDisconnected,
10013
9873
  onClientBanned: onClientBanned,
10014
9874
  onSessionStateChange: onSessionStateChange,
10015
9875
  onNetworkActivities: onNetworkActivities,
10016
- getTotalUnreadCount: getTotalUnreadCount,
10017
9876
  getUserUnread: getUserUnread,
10018
9877
  getMarkerSyncEvents: getMarkerSyncEvents,
10019
9878
  setMarkerSyncEvents: setMarkerSyncEvents,
@@ -10022,7 +9881,6 @@ var index$l = /*#__PURE__*/Object.freeze({
10022
9881
  startMarkerSync: startMarkerSync,
10023
9882
  startUnreadSync: startUnreadSync,
10024
9883
  stopUnreadSync: stopUnreadSync,
10025
- stopUnreadSyncing: stopUnreadSyncing,
10026
9884
  getMarkerSyncConsistentMode: getMarkerSyncConsistentMode
10027
9885
  });
10028
9886
 
@@ -10107,311 +9965,134 @@ const unBlockUser = async (userId) => {
10107
9965
  };
10108
9966
  /* end_public_function */
10109
9967
 
10110
- class PaginationController {
10111
- constructor(queryParams) {
10112
- const { http } = getActiveClient();
10113
- this.queryParams = queryParams;
10114
- this.http = http;
10115
- }
10116
- loadFirstPage() {
10117
- return this.onFetch("first" /* Amity.LiveCollectionPageDirection.FIRST */);
10118
- }
10119
- loadNextPage() {
10120
- return this.onFetch("next" /* Amity.LiveCollectionPageDirection.NEXT */);
10121
- }
10122
- loadPreviousPage() {
10123
- return this.onFetch("prev" /* Amity.LiveCollectionPageDirection.PREV */);
10124
- }
10125
- async onFetch(direction = "first" /* Amity.LiveCollectionPageDirection.FIRST */) {
10126
- var _a, _b, _c, _d;
10127
- if (direction === 'prev' && !this.previousToken)
10128
- return;
10129
- if (direction === 'next' && !this.nextToken)
10130
- return;
10131
- let token;
10132
- if (direction === 'prev')
10133
- token = this.previousToken;
10134
- if (direction === 'next')
10135
- token = this.nextToken;
10136
- const queryResponse = await this.getRequest(this.queryParams, token);
10137
- if (direction === 'first') {
10138
- this.nextToken = (_a = queryResponse.paging) === null || _a === void 0 ? void 0 : _a.next;
10139
- this.previousToken = (_b = queryResponse.paging) === null || _b === void 0 ? void 0 : _b.previous;
10140
- }
10141
- if (direction === 'prev')
10142
- this.previousToken = (_c = queryResponse.paging) === null || _c === void 0 ? void 0 : _c.previous;
10143
- if (direction === 'next')
10144
- this.nextToken = (_d = queryResponse.paging) === null || _d === void 0 ? void 0 : _d.next;
10145
- return queryResponse;
9968
+ /* begin_public_function
9969
+ id: user.relationship.follow
9970
+ */
9971
+ /**
9972
+ * ```js
9973
+ * import { follow } from '@amityco/ts-sdk'
9974
+ * const status = await follow('foobar')
9975
+ * ```
9976
+ *
9977
+ * Follow the user
9978
+ *
9979
+ * @param userId the ID of the {@link Amity.InternalUser}
9980
+ * @returns the status {@link Amity.FollowStatus}
9981
+ *
9982
+ * @category Follow API
9983
+ * @async
9984
+ */
9985
+ const follow = async (userId) => {
9986
+ const client = getActiveClient();
9987
+ client.log('follow/follow', userId);
9988
+ const { data } = await client.http.post(`/api/v4/me/following/${userId}`);
9989
+ const cachedAt = client.cache && Date.now();
9990
+ if (client.cache) {
9991
+ ingestInCache(data, { cachedAt });
10146
9992
  }
10147
- getNextToken() {
10148
- return this.nextToken;
9993
+ const payload = prepareFollowStatusPayload(data);
9994
+ if (data.follows[0].status === 'accepted') {
9995
+ fireEvent('local.follow.created', payload);
10149
9996
  }
10150
- getPrevToken() {
10151
- return this.previousToken;
9997
+ else {
9998
+ fireEvent('local.follow.requested', payload);
10152
9999
  }
10153
- }
10000
+ return {
10001
+ data: data.follows[0],
10002
+ cachedAt,
10003
+ };
10004
+ };
10005
+ /* end_public_function */
10154
10006
 
10155
- class BlockedUserPaginationController extends PaginationController {
10156
- async getRequest(queryParams, token) {
10157
- const { limit = COLLECTION_DEFAULT_PAGINATION_LIMIT } = queryParams, params = __rest(queryParams, ["limit"]);
10158
- const options = token ? { token } : { limit };
10159
- const { data: queryResponse } = await this.http.get('/api/v4/me/user-blocks', {
10160
- params: Object.assign(Object.assign({}, params), { options, isDeleted: false }),
10161
- });
10162
- return queryResponse;
10007
+ /* begin_public_function
10008
+ id: user.relationship.unfollow
10009
+ */
10010
+ /**
10011
+ * ```js
10012
+ * import { unfollow } from '@amityco/ts-sdk'
10013
+ * await unfollow('foobar')
10014
+ * ```
10015
+ *
10016
+ * Cancel the follow request or unfollow the user
10017
+ *
10018
+ * @param userId the ID of the {@link Amity.InternalUser}
10019
+ * @returns A success boolean if the user {@link Amity.InternalUser} was unfollowed
10020
+ *
10021
+ * @category Follow API
10022
+ * @async
10023
+ */
10024
+ const unfollow = async (userId) => {
10025
+ const client = getActiveClient();
10026
+ client.log('follow/unfollow', userId);
10027
+ const { data } = await client.http.delete(`/api/v4/me/following/${userId}`);
10028
+ if (client.cache) {
10029
+ ingestInCache(data);
10163
10030
  }
10164
- }
10031
+ const payload = prepareFollowStatusPayload(data);
10032
+ fireEvent('local.follow.unfollowed', payload);
10033
+ return true;
10034
+ };
10035
+ /* end_public_function */
10165
10036
 
10166
- class QueryStreamController {
10167
- constructor(query, cacheKey) {
10168
- this.query = query;
10169
- this.cacheKey = cacheKey;
10037
+ /* begin_public_function
10038
+ id: user.relationship.accept_follow
10039
+ */
10040
+ /**
10041
+ * ```js
10042
+ * import { UserRepository } from '@amityco/ts-sdk'
10043
+ * await UserRepository.Relationship.acceptMyFollower('foobar')
10044
+ * ```
10045
+ *
10046
+ * Accept the follow request
10047
+ *
10048
+ * @param userId the ID of the {@link Amity.InternalUser} follower
10049
+ * @returns A success boolean if the follow request was accepted
10050
+ *
10051
+ * @category Follow API
10052
+ * @async
10053
+ */
10054
+ const acceptMyFollower = async (userId) => {
10055
+ const client = getActiveClient();
10056
+ client.log('follow/acceptMyFollower', userId);
10057
+ const { data } = await client.http.post(`/api/v4/me/followers/${userId}`);
10058
+ if (client.cache) {
10059
+ ingestInCache(data);
10170
10060
  }
10171
- }
10172
-
10173
- var EnumFollowActions;
10174
- (function (EnumFollowActions) {
10175
- EnumFollowActions["OnRequested"] = "onRequested";
10176
- EnumFollowActions["OnAccepted"] = "onAccepted";
10177
- EnumFollowActions["OnDeclined"] = "onDeclined";
10178
- EnumFollowActions["OnCanceled"] = "onCanceled";
10179
- EnumFollowActions["OnFollowed"] = "onFollowed";
10180
- EnumFollowActions["OnUnfollowed"] = "onUnfollowed";
10181
- EnumFollowActions["OnDeleted"] = "onDeleted";
10182
- EnumFollowActions["OnUserDeleted"] = "onUserDeleted";
10183
- })(EnumFollowActions || (EnumFollowActions = {}));
10184
-
10185
- class BlockedUserQueryStreamController extends QueryStreamController {
10186
- constructor(query, cacheKey, notifyChange, preparePayload) {
10187
- super(query, cacheKey);
10188
- this.notifyChange = notifyChange;
10189
- this.preparePayload = preparePayload;
10190
- }
10191
- async saveToMainDB(response) {
10192
- const processedPayload = await this.preparePayload(response);
10193
- const client = getActiveClient();
10194
- const cachedAt = client.cache && Date.now();
10195
- if (client.cache) {
10196
- ingestInCache(processedPayload, { cachedAt });
10197
- }
10198
- }
10199
- appendToQueryStream(response, direction, refresh = false) {
10200
- var _a, _b;
10201
- if (refresh) {
10202
- pushToCache(this.cacheKey, {
10203
- data: response.users.map(getResolver('user')),
10204
- });
10205
- }
10206
- else {
10207
- const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
10208
- const users = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
10209
- pushToCache(this.cacheKey, Object.assign(Object.assign({}, collection), { data: [...new Set([...users, ...response.users.map(getResolver('user'))])] }));
10210
- }
10211
- }
10212
- reactor(action) {
10213
- return (targetUser) => {
10214
- var _a;
10215
- if (action === EnumFollowActions.OnFollowed) {
10216
- const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
10217
- const updatedCollection = collection === null || collection === void 0 ? void 0 : collection.data.filter(id => id !== targetUser.userId);
10218
- pushToCache(this.cacheKey, Object.assign(Object.assign({}, collection), { data: updatedCollection }));
10219
- }
10220
- this.notifyChange({ origin: "event" /* Amity.LiveDataOrigin.EVENT */, loading: false });
10221
- };
10222
- }
10223
- subscribeRTE(createSubscriber) {
10224
- return createSubscriber.map(subscriber => subscriber.fn(this.reactor(subscriber.action)));
10225
- }
10226
- }
10227
-
10228
- class PaginationNoPageController {
10229
- constructor(queryParams) {
10230
- const { http } = getActiveClient();
10231
- this.queryParams = queryParams;
10232
- this.http = http;
10233
- }
10234
- async onFetch() {
10235
- const queryResponse = await this.getRequest(this.queryParams);
10236
- return queryResponse;
10237
- }
10238
- }
10239
-
10240
- class LiveCollectionController {
10241
- constructor(paginationController, queryStreamId, cacheKey, callback) {
10242
- this.paginationController = paginationController;
10243
- this.queryStreamId = queryStreamId;
10244
- this.cacheKey = cacheKey;
10245
- this.callback = callback;
10246
- }
10247
- async refresh() {
10248
- try {
10249
- let result;
10250
- if (this.paginationController instanceof PaginationNoPageController) {
10251
- result = await this.paginationController.onFetch();
10252
- }
10253
- else {
10254
- result = await this.paginationController.loadFirstPage();
10255
- }
10256
- if (!result)
10257
- return;
10258
- await this.persistModel(result);
10259
- this.persistQueryStream({
10260
- response: result,
10261
- direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */,
10262
- refresh: true,
10263
- });
10264
- this.notifyChange({ origin: "server" /* Amity.LiveDataOrigin.SERVER */, loading: false });
10265
- }
10266
- catch (e) {
10267
- this.notifyChange({ origin: "server" /* Amity.LiveDataOrigin.SERVER */, loading: false, error: e });
10268
- }
10269
- }
10270
- loadPage({ initial = false, direction = "next" /* Amity.LiveCollectionPageDirection.NEXT */, }) {
10271
- this.setup();
10272
- this.notifyChange({ origin: "local" /* Amity.LiveDataOrigin.LOCAL */, loading: true });
10273
- if (initial) {
10274
- this.refresh();
10275
- }
10276
- else if (direction === "prev" /* Amity.LiveCollectionPageDirection.PREV */) {
10277
- this.loadPrevPage();
10278
- }
10279
- else if (direction === "next" /* Amity.LiveCollectionPageDirection.NEXT */) {
10280
- this.loadNextPage();
10281
- }
10282
- }
10283
- async loadNextPage() {
10284
- try {
10285
- if (this.paginationController instanceof PaginationNoPageController)
10286
- return;
10287
- const result = await this.paginationController.loadNextPage();
10288
- if (!result)
10289
- return;
10290
- await this.persistModel(result);
10291
- this.persistQueryStream({
10292
- response: result,
10293
- direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */,
10294
- });
10295
- this.notifyChange({ origin: "server" /* Amity.LiveDataOrigin.SERVER */, loading: false });
10296
- }
10297
- catch (e) {
10298
- this.notifyChange({ origin: "server" /* Amity.LiveDataOrigin.SERVER */, loading: false, error: e });
10299
- }
10300
- }
10301
- async loadPrevPage() {
10302
- try {
10303
- if (this.paginationController instanceof PaginationNoPageController)
10304
- return;
10305
- const result = await this.paginationController.loadPreviousPage();
10306
- if (!result)
10307
- return;
10308
- await this.persistModel(result);
10309
- this.persistQueryStream({
10310
- response: result,
10311
- direction: "prev" /* Amity.LiveCollectionPageDirection.PREV */,
10312
- });
10313
- this.notifyChange({ origin: "server" /* Amity.LiveDataOrigin.SERVER */, loading: false });
10314
- }
10315
- catch (e) {
10316
- this.notifyChange({ origin: "server" /* Amity.LiveDataOrigin.SERVER */, loading: false, error: e });
10317
- }
10318
- }
10319
- shouldNotify(data) {
10320
- const newData = data.map(convertGetterPropsToStatic).map(removeFunctionProperties);
10321
- if (isEqual(this.snapshot, newData))
10322
- return false;
10323
- this.snapshot = newData;
10324
- return true;
10325
- }
10326
- getCacheKey() {
10327
- return this.cacheKey;
10328
- }
10329
- }
10330
-
10331
- function prepareBlockedUserPayload(response) {
10332
- const { users, follows } = response, rest = __rest(response, ["users", "follows"]);
10333
- return Object.assign(Object.assign({}, rest), { follows: follows.map(follow => {
10334
- const followUser = users.find(user => user.userId === follow.from);
10335
- return Object.assign(Object.assign({}, follow), { user: convertRawUserToInternalUser(followUser) });
10336
- }), users: users.map(convertRawUserToInternalUser) });
10337
- }
10338
-
10339
- /**
10340
- * ```js
10341
- * import { onUserUpdated } from '@amityco/ts-sdk'
10342
- * const dispose = onUserUpdated(user => {
10343
- * // ...
10344
- * })
10345
- * ```
10346
- *
10347
- * Fired when a {@link Amity.InternalUser} has been updated
10348
- *
10349
- * @param callback The function to call when the event was fired
10350
- * @returns an {@link Amity.Unsubscriber} function to stop listening
10351
- *
10352
- * @category User Events
10353
- */
10354
- const onUserUpdated = (callback) => createUserEventSubscriber('user.updated', callback);
10355
-
10356
- /**
10357
- * ```js
10358
- * import { onUserFlagged } from '@amityco/ts-sdk'
10359
- * const dispose = onUserFlagged(user => {
10360
- * // ...
10361
- * })
10362
- * ```
10363
- *
10364
- * Fired when a {@link Amity.InternalUser} has been flagged
10365
- *
10366
- * @param callback The function to call when the event was fired
10367
- * @returns an {@link Amity.Unsubscriber} function to stop listening
10368
- *
10369
- * @category User Events
10370
- */
10371
- const onUserFlagged = (callback) => createUserEventSubscriber('user.flagged', callback);
10372
-
10373
- /**
10374
- * ```js
10375
- * import { onUserUnflagged } from '@amityco/ts-sdk'
10376
- * const dispose = onUserUnflagged(user => {
10377
- * // ...
10378
- * })
10379
- * ```
10380
- *
10381
- * Fired when a flag has been removed from a {@link Amity.InternalUser}
10382
- *
10383
- * @param callback The function to call when the event was fired
10384
- * @returns an {@link Amity.Unsubscriber} function to stop listening
10385
- *
10386
- * @category User Events
10387
- */
10388
- const onUserUnflagged = (callback) => createUserEventSubscriber('user.unflagged', callback);
10061
+ const payload = prepareFollowStatusPayload(data);
10062
+ fireEvent('local.follow.accepted', payload);
10063
+ return true;
10064
+ };
10065
+ /* end_public_function */
10389
10066
 
10067
+ /* begin_public_function
10068
+ id: user.relationship.decline_follow
10069
+ */
10390
10070
  /**
10391
10071
  * ```js
10392
- * import { onUserFlagCleared } from '@amityco/ts-sdk'
10393
- * const dispose = onUserFlagCleared(user => {
10394
- * // ...
10395
- * })
10072
+ * import { UserRepository } from '@amityco/ts-sdk'
10073
+ * await UserRepository.Relationship.declineMyFollower('foobar')
10396
10074
  * ```
10397
10075
  *
10398
- * Fired when flags have been cleared for a {@link Amity.InternalUser}
10076
+ * Decline the follow request or delete the follower
10399
10077
  *
10400
- * @param callback The function to call when the event was fired
10401
- * @returns an {@link Amity.Unsubscriber} function to stop listening
10078
+ * @param userId the ID of the {@link Amity.InternalUser} follower
10079
+ * @returns A success boolean if the follow request was decline
10402
10080
  *
10403
- * @category User Events
10081
+ * @category Follow API
10082
+ * @async
10404
10083
  */
10405
- const onUserFlagCleared = (callback) => createUserEventSubscriber('user.flagCleared', callback);
10406
-
10407
- var EnumUserActions;
10408
- (function (EnumUserActions) {
10409
- EnumUserActions["OnUserDeleted"] = "onUserDeleted";
10410
- EnumUserActions["OnUserUpdated"] = "onUserUpdated";
10411
- EnumUserActions["OnUserFlagged"] = "onUserFlagged";
10412
- EnumUserActions["OnUserUnflagged"] = "onUserUnflagged";
10413
- EnumUserActions["OnUserFlagCleared"] = "onUserFlagCleared";
10414
- })(EnumUserActions || (EnumUserActions = {}));
10084
+ const declineMyFollower = async (userId) => {
10085
+ const client = getActiveClient();
10086
+ client.log('follow/declineMyFollower', userId);
10087
+ const { data } = await client.http.delete(`/api/v4/me/followers/${userId}`);
10088
+ if (client.cache) {
10089
+ ingestInCache(data);
10090
+ }
10091
+ const payload = prepareFollowStatusPayload(data);
10092
+ fireEvent('local.follow.requestDeclined', payload);
10093
+ return true;
10094
+ };
10095
+ /* end_public_function */
10415
10096
 
10416
10097
  const createFollowEventSubscriber = (event, callback) => {
10417
10098
  const client = getActiveClient();
@@ -10675,446 +10356,50 @@ const onLocalFollowRequestAccepted = (callback) => createLocalFollowEventSubscri
10675
10356
 
10676
10357
  const onLocalFollowRequestDeclined = (callback) => createLocalFollowEventSubscriber('local.follow.requestDeclined', callback);
10677
10358
 
10678
- const convertEventPayload = (eventHandler, sourceModelProp, destinationDomain) => (callback) => eventHandler(sourceModel => {
10679
- var _a, _b;
10680
- if (!sourceModel) {
10681
- return sourceModel;
10359
+ class PaginationController {
10360
+ constructor(queryParams) {
10361
+ const { http } = getActiveClient();
10362
+ this.queryParams = queryParams;
10363
+ this.http = http;
10682
10364
  }
10683
- const client = getActiveClient();
10684
- const { objectSyncMap } = client;
10685
- /*
10686
- * NOTE: For objects created locally (optimistic creation), the SDK stores them with their local ID as the cache key, which is used throughout the entire SDK session (in-memory) for syncing updates.
10687
- * If the payload or response only contains the remote ID of the same object, the SDK will look up the corresponding local ID to retrieve the object.
10688
- */
10689
- const resolvedId = isLocalId(sourceModel[sourceModelProp])
10690
- ? sourceModel[sourceModelProp]
10691
- : (_a = objectSyncMap.get(sourceModel[sourceModelProp])) !== null && _a !== void 0 ? _a : sourceModel[sourceModelProp];
10692
- const model = (_b = pullFromCache([
10693
- destinationDomain,
10694
- 'get',
10695
- `${resolvedId}`,
10696
- ])) === null || _b === void 0 ? void 0 : _b.data;
10697
- if (!model)
10698
- return;
10699
- return callback(model);
10700
- });
10701
-
10702
- class BlockedUserLiveCollectionController extends LiveCollectionController {
10703
- constructor(query, callback) {
10704
- const queryStreamId = hash__default["default"](query);
10705
- const cacheKey = ['blockedUsers', 'collection', queryStreamId];
10706
- const paginationController = new BlockedUserPaginationController(query);
10707
- super(paginationController, queryStreamId, cacheKey, callback);
10708
- this.query = query;
10709
- this.queryStreamController = new BlockedUserQueryStreamController(this.query, this.cacheKey, this.notifyChange.bind(this), prepareBlockedUserPayload);
10710
- this.callback = callback.bind(this);
10711
- this.loadPage({ initial: true });
10712
- }
10713
- setup() {
10714
- var _a;
10715
- const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
10716
- if (!collection) {
10717
- pushToCache(this.cacheKey, {
10718
- data: [],
10719
- params: {},
10720
- });
10721
- }
10722
- }
10723
- async persistModel(queryPayload) {
10724
- await this.queryStreamController.saveToMainDB(queryPayload);
10365
+ loadFirstPage() {
10366
+ return this.onFetch("first" /* Amity.LiveCollectionPageDirection.FIRST */);
10725
10367
  }
10726
- persistQueryStream({ response, direction, refresh, }) {
10727
- this.queryStreamController.appendToQueryStream(response, direction, refresh);
10368
+ loadNextPage() {
10369
+ return this.onFetch("next" /* Amity.LiveCollectionPageDirection.NEXT */);
10728
10370
  }
10729
- startSubscription() {
10730
- return this.queryStreamController.subscribeRTE([
10731
- {
10732
- fn: onUserDeleted$2,
10733
- action: EnumUserActions.OnUserDeleted,
10734
- },
10735
- // In the case of unblocking a user, we need to subscribe to the follow events
10736
- {
10737
- fn: convertEventPayload(onLocalUserFollowed, 'to', 'user'),
10738
- action: EnumFollowActions.OnFollowed,
10739
- },
10740
- {
10741
- fn: convertEventPayload(onUserFollowed, 'to', 'user'),
10742
- action: EnumFollowActions.OnFollowed,
10743
- },
10744
- ]);
10371
+ loadPreviousPage() {
10372
+ return this.onFetch("prev" /* Amity.LiveCollectionPageDirection.PREV */);
10745
10373
  }
10746
- notifyChange({ origin, loading, error }) {
10747
- var _a, _b;
10748
- const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
10749
- if (!collection)
10374
+ async onFetch(direction = "first" /* Amity.LiveCollectionPageDirection.FIRST */) {
10375
+ var _a, _b, _c, _d;
10376
+ if (direction === 'prev' && !this.previousToken)
10750
10377
  return;
10751
- const data = this.applyFilter((_b = collection.data
10752
- .map(id => pullFromCache(['user', 'get', id]))
10753
- .filter(isNonNullable)
10754
- .map(({ data }) => data)
10755
- .map(LinkedObject.user)) !== null && _b !== void 0 ? _b : []);
10756
- if (!this.shouldNotify(data) && origin === 'event')
10378
+ if (direction === 'next' && !this.nextToken)
10757
10379
  return;
10758
- this.callback({
10759
- onNextPage: () => this.loadPage({ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */ }),
10760
- data,
10761
- hasNextPage: !!this.paginationController.getNextToken(),
10762
- loading,
10763
- error,
10764
- });
10765
- }
10766
- // eslint-disable-next-line class-methods-use-this
10767
- applyFilter(data) {
10768
- let users = data;
10769
- users = users.filter(user => user.isDeleted == null || user.isDeleted === false);
10770
- return users;
10771
- }
10772
- }
10773
-
10774
- /* begin_public_function
10775
- id: user.get_blocked_users
10776
- */
10777
- /**
10778
- * ```js
10779
- * import { UserRepository } from '@amityco/ts-sdk'
10780
- * const unblockedUser = await UserRepository.blockUser('userId')
10781
- * ```
10782
- *
10783
- * Blocks a {@link Amity.InternalUser}
10784
- *
10785
- * @param params The params to get blocked {@link Amity.InternalUser}s
10786
- * @param callback to recieve updates on unblocked {@link Amity.InternalUser}s
10787
- * @returns {@link Amity.Unsubscriber} to unsubscribe from collection
10788
- *
10789
- * @category Post API
10790
- * @async
10791
- */
10792
- const getBlockedUsers$1 = (params, callback, config) => {
10793
- const { log, cache } = getActiveClient();
10794
- if (!cache) {
10795
- console.log(ENABLE_CACHE_MESSAGE);
10796
- }
10797
- const timestamp = Date.now();
10798
- log(`getBlockedUsers(tmpid: ${timestamp}) > listen`);
10799
- const blockedUserLiveCollection = new BlockedUserLiveCollectionController(params, callback);
10800
- const disposers = blockedUserLiveCollection.startSubscription();
10801
- const cacheKey = blockedUserLiveCollection.getCacheKey();
10802
- disposers.push(() => dropFromCache(cacheKey));
10803
- return () => {
10804
- log(`getBlockedUsers(tmpid: ${timestamp}) > dispose`);
10805
- disposers.forEach(fn => fn());
10806
- dropFromCache(cacheKey);
10807
- };
10808
- };
10809
- /* end_public_function */
10810
-
10811
- /* eslint-disable no-use-before-define */
10812
- const getBlockedUsers = (params, callback, config) => {
10813
- console.log('Deprecation Notice: UserRepository.Relationship.getBlockedUsers will be deprecated on 9th June 2023, please use UserRepository.getBlockedUsers instead.');
10814
- return getBlockedUsers$1(params, callback);
10815
- };
10816
-
10817
- /* begin_public_function
10818
- id: user.relationship.follow
10819
- */
10820
- /**
10821
- * ```js
10822
- * import { follow } from '@amityco/ts-sdk'
10823
- * const status = await follow('foobar')
10824
- * ```
10825
- *
10826
- * Follow the user
10827
- *
10828
- * @param userId the ID of the {@link Amity.InternalUser}
10829
- * @returns the status {@link Amity.FollowStatus}
10830
- *
10831
- * @category Follow API
10832
- * @async
10833
- */
10834
- const follow = async (userId) => {
10835
- const client = getActiveClient();
10836
- client.log('follow/follow', userId);
10837
- const { data } = await client.http.post(`/api/v4/me/following/${userId}`);
10838
- const cachedAt = client.cache && Date.now();
10839
- if (client.cache) {
10840
- ingestInCache(data, { cachedAt });
10841
- }
10842
- const payload = prepareFollowStatusPayload(data);
10843
- if (data.follows[0].status === 'accepted') {
10844
- fireEvent('local.follow.created', payload);
10845
- }
10846
- else {
10847
- fireEvent('local.follow.requested', payload);
10848
- }
10849
- return {
10850
- data: data.follows[0],
10851
- cachedAt,
10852
- };
10853
- };
10854
- /* end_public_function */
10855
-
10856
- /* begin_public_function
10857
- id: user.relationship.unfollow
10858
- */
10859
- /**
10860
- * ```js
10861
- * import { unfollow } from '@amityco/ts-sdk'
10862
- * await unfollow('foobar')
10863
- * ```
10864
- *
10865
- * Cancel the follow request or unfollow the user
10866
- *
10867
- * @param userId the ID of the {@link Amity.InternalUser}
10868
- * @returns A success boolean if the user {@link Amity.InternalUser} was unfollowed
10869
- *
10870
- * @category Follow API
10871
- * @async
10872
- */
10873
- const unfollow = async (userId) => {
10874
- const client = getActiveClient();
10875
- client.log('follow/unfollow', userId);
10876
- const { data } = await client.http.delete(`/api/v4/me/following/${userId}`);
10877
- if (client.cache) {
10878
- ingestInCache(data);
10879
- }
10880
- const payload = prepareFollowStatusPayload(data);
10881
- fireEvent('local.follow.unfollowed', payload);
10882
- return true;
10883
- };
10884
- /* end_public_function */
10885
-
10886
- /**
10887
- * @deprecated This API renamed to `acceptMyFollower`.
10888
- * Please use acceptMyFollower() instead.
10889
- *
10890
- * ```js
10891
- * import { acceptFollower } from '@amityco/ts-sdk'
10892
- * await acceptFollower('foobar')
10893
- * ```
10894
- *
10895
- * Accept the follow request
10896
- *
10897
- * @param userId the ID of the {@link Amity.InternalUser} follower
10898
- * @returns A success boolean if the follow request was accepted
10899
- *
10900
- * @category Follow API
10901
- * @async
10902
- */
10903
- const acceptFollower = async (userId) => {
10904
- const client = getActiveClient();
10905
- client.log('follow/acceptFollower', userId);
10906
- const { data } = await client.http.post(`/api/v4/me/followers/${userId}`);
10907
- if (client.cache) {
10908
- ingestInCache(data);
10909
- }
10910
- const payload = prepareFollowStatusPayload(data);
10911
- fireEvent('local.follow.accepted', payload);
10912
- return true;
10913
- };
10914
-
10915
- /* begin_public_function
10916
- id: user.relationship.accept_follow
10917
- */
10918
- /**
10919
- * ```js
10920
- * import { UserRepository } from '@amityco/ts-sdk'
10921
- * await UserRepository.Relationship.acceptMyFollower('foobar')
10922
- * ```
10923
- *
10924
- * Accept the follow request
10925
- *
10926
- * @param userId the ID of the {@link Amity.InternalUser} follower
10927
- * @returns A success boolean if the follow request was accepted
10928
- *
10929
- * @category Follow API
10930
- * @async
10931
- */
10932
- const acceptMyFollower = async (userId) => {
10933
- const client = getActiveClient();
10934
- client.log('follow/acceptMyFollower', userId);
10935
- const { data } = await client.http.post(`/api/v4/me/followers/${userId}`);
10936
- if (client.cache) {
10937
- ingestInCache(data);
10380
+ let token;
10381
+ if (direction === 'prev')
10382
+ token = this.previousToken;
10383
+ if (direction === 'next')
10384
+ token = this.nextToken;
10385
+ const queryResponse = await this.getRequest(this.queryParams, token);
10386
+ if (direction === 'first') {
10387
+ this.nextToken = (_a = queryResponse.paging) === null || _a === void 0 ? void 0 : _a.next;
10388
+ this.previousToken = (_b = queryResponse.paging) === null || _b === void 0 ? void 0 : _b.previous;
10389
+ }
10390
+ if (direction === 'prev')
10391
+ this.previousToken = (_c = queryResponse.paging) === null || _c === void 0 ? void 0 : _c.previous;
10392
+ if (direction === 'next')
10393
+ this.nextToken = (_d = queryResponse.paging) === null || _d === void 0 ? void 0 : _d.next;
10394
+ return queryResponse;
10938
10395
  }
10939
- const payload = prepareFollowStatusPayload(data);
10940
- fireEvent('local.follow.accepted', payload);
10941
- return true;
10942
- };
10943
- /* end_public_function */
10944
-
10945
- /**
10946
- * @deprecated This API renamed to `declineMyFollower`.
10947
- * Please use declineMyFollower() instead.
10948
- *
10949
- * ```js
10950
- * import { declineFollower } from '@amityco/ts-sdk'
10951
- * await declineFollower('foobar')
10952
- * ```
10953
- *
10954
- * Decline the follow request or delete the follower
10955
- *
10956
- * @param userId the ID of the {@link Amity.InternalUser} follower
10957
- * @returns A success boolean if the follow request was decline
10958
- *
10959
- * @category Follow API
10960
- * @async
10961
- */
10962
- const declineFollower = async (userId) => {
10963
- const client = getActiveClient();
10964
- client.log('follow/declineFollower', userId);
10965
- const { data } = await client.http.delete(`/api/v4/me/followers/${userId}`);
10966
- if (client.cache) {
10967
- ingestInCache(data);
10396
+ getNextToken() {
10397
+ return this.nextToken;
10968
10398
  }
10969
- const payload = prepareFollowStatusPayload(data);
10970
- fireEvent('local.follow.requestDeclined', payload);
10971
- return true;
10972
- };
10973
-
10974
- /* begin_public_function
10975
- id: user.relationship.decline_follow
10976
- */
10977
- /**
10978
- * ```js
10979
- * import { UserRepository } from '@amityco/ts-sdk'
10980
- * await UserRepository.Relationship.declineMyFollower('foobar')
10981
- * ```
10982
- *
10983
- * Decline the follow request or delete the follower
10984
- *
10985
- * @param userId the ID of the {@link Amity.InternalUser} follower
10986
- * @returns A success boolean if the follow request was decline
10987
- *
10988
- * @category Follow API
10989
- * @async
10990
- */
10991
- const declineMyFollower = async (userId) => {
10992
- const client = getActiveClient();
10993
- client.log('follow/declineMyFollower', userId);
10994
- const { data } = await client.http.delete(`/api/v4/me/followers/${userId}`);
10995
- if (client.cache) {
10996
- ingestInCache(data);
10399
+ getPrevToken() {
10400
+ return this.previousToken;
10997
10401
  }
10998
- const payload = prepareFollowStatusPayload(data);
10999
- fireEvent('local.follow.requestDeclined', payload);
11000
- return true;
11001
- };
11002
- /* end_public_function */
11003
-
11004
- /**
11005
- * ```js
11006
- * import { observeFollowInfo } from '@amityco/ts-sdk'
11007
- *
11008
- * let followInfo = {}
11009
- * const dispose = observeFollowInfo(userId, updated => followInfo = updated)
11010
- * ```
11011
- *
11012
- * Observe all mutation on a given {@link Amity.FollowInfo}
11013
- *
11014
- * @param userId the ID of the user to observe
11015
- * @param callback the function to call when new data are available
11016
- * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the post
11017
- *
11018
- * @category Follow Observer
11019
- */
11020
- const observeFollowInfo = (userId, callback, policy = 'cache_then_server') => {
11021
- const { log } = getActiveClient();
11022
- const timestamp = Date.now();
11023
- log(`observeFollowInfo(tmpid: ${timestamp}) > listen`);
11024
- const router = (result, action) => {
11025
- var _a, _b;
11026
- if (callback instanceof Function)
11027
- return callback(result);
11028
- if (action !== 'onFetch')
11029
- (_a = callback.onEvent) === null || _a === void 0 ? void 0 : _a.call(callback, action, result);
11030
- (_b = callback[action]) === null || _b === void 0 ? void 0 : _b.call(callback, result);
11031
- };
11032
- const realtimeRouter = (result, action) => {
11033
- var _a;
11034
- if (((_a = result.data) === null || _a === void 0 ? void 0 : _a.userId) !== userId)
11035
- return;
11036
- router(result, action);
11037
- };
11038
- const disposers = [];
11039
- disposers.push(onFollowInfoUpdated(data => realtimeRouter({ data, loading: false, origin: 'event' }, 'onUpdate')));
11040
- runQuery(createQuery(getFollowInfo$1, userId), result => (result.data || result.error) && router(result, 'onFetch'), queryOptions(policy));
11041
- return () => {
11042
- log(`observeFollowInfo(tmpid: ${timestamp}) > dispose`);
11043
- disposers.forEach(fn => fn());
11044
- };
11045
- };
11046
-
11047
- /**
11048
- * ```js
11049
- * import { observeFollowers } from '@amityco/ts-sdk'
11050
- *
11051
- * let followers = []
11052
- * const unsub = observeFollowers('userId', follower => merge(followers, follower))
11053
- * ```
11054
- *
11055
- * Observe all mutations on a list of followers {@link Amity.FollowStatus} for a given user
11056
- *
11057
- * @param userId the ID of the {@link Amity.InternalUser}
11058
- * @param callback the function to call when new data are available
11059
- * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the messages
11060
- *
11061
- * @category Follow Observer
11062
- */
11063
- const observeFollowers = (userId, callback) => {
11064
- const { log } = getActiveClient();
11065
- const timestamp = Date.now();
11066
- log(`observeFollowers(tmpid: ${timestamp}) > listen`);
11067
- const disposers = [];
11068
- const router = (status, action) => {
11069
- var _a, _b;
11070
- if (callback instanceof Function) {
11071
- return callback(status);
11072
- }
11073
- (_a = callback.onEvent) === null || _a === void 0 ? void 0 : _a.call(callback, action, status);
11074
- (_b = callback[action]) === null || _b === void 0 ? void 0 : _b.call(callback, status);
11075
- };
11076
- disposers.push(onFollowerRequested(x => router(x, 'onRequested')), onFollowRequestAccepted(x => router(x, 'onAccepted')), onFollowRequestDeclined(x => router(x, 'onDeclined')), onFollowRequestCanceled(x => router(x, 'onCanceled')), onUserFollowed(x => router(x, 'onFollowed')), onUserUnfollowed(x => router(x, 'onUnfollowed')), onFollowerDeleted(x => router(x, 'onDeleted')), onLocalFollowerRequested(x => router(x, 'onRequested')), onLocalFollowRequestAccepted(x => router(x, 'onAccepted')), onLocalFollowRequestDeclined(x => router(x, 'onDeclined')), onLocalUserFollowed(x => router(x, 'onFollowed')), onLocalUserUnfollowed(x => router(x, 'onUnfollowed')));
11077
- return () => {
11078
- log(`observeFollowers(tmpid: ${timestamp}) > dispose`);
11079
- disposers.forEach(fn => fn());
11080
- };
11081
- };
11082
-
11083
- /**
11084
- * ```js
11085
- * import { observeFollowings } from '@amityco/ts-sdk'
11086
- *
11087
- * let followings = []
11088
- * const unsub = observeFollowers('userId', follower => merge(followings, following))
11089
- * ```
11090
- *
11091
- * Observe all mutations on a list of followings {@link Amity.FollowStatus} for a given user
11092
- *
11093
- * @param userId the ID of the {@link Amity.InternalUser}
11094
- * @param callback the function to call when new data are available
11095
- * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the messages
11096
- *
11097
- * @category Follow Observer
11098
- */
11099
- const observeFollowings = (userId, callback) => {
11100
- const { log } = getActiveClient();
11101
- const timestamp = Date.now();
11102
- log(`observeFollowings(tmpid: ${timestamp}) > listen`);
11103
- const disposers = [];
11104
- const router = (status, action) => {
11105
- var _a, _b;
11106
- if (callback instanceof Function) {
11107
- return callback(status);
11108
- }
11109
- (_a = callback.onEvent) === null || _a === void 0 ? void 0 : _a.call(callback, action, status);
11110
- (_b = callback[action]) === null || _b === void 0 ? void 0 : _b.call(callback, status);
11111
- };
11112
- disposers.push(onFollowerRequested(x => router(x, 'onRequested')), onFollowRequestAccepted(x => router(x, 'onAccepted')), onFollowRequestDeclined(x => router(x, 'onDeclined')), onFollowRequestCanceled(x => router(x, 'onCanceled')), onUserFollowed(x => router(x, 'onFollowed')), onUserUnfollowed(x => router(x, 'onUnfollowed')), onFollowerDeleted(x => router(x, 'onDeleted')), onLocalFollowerRequested(x => router(x, 'onRequested')), onLocalFollowRequestAccepted(x => router(x, 'onAccepted')), onLocalFollowRequestDeclined(x => router(x, 'onDeclined')), onLocalUserFollowed(x => router(x, 'onFollowed')), onLocalUserUnfollowed(x => router(x, 'onUnfollowed')));
11113
- return () => {
11114
- log(`observeFollowings(tmpid: ${timestamp}) > dispose`);
11115
- disposers.forEach(fn => fn());
11116
- };
11117
- };
10402
+ }
11118
10403
 
11119
10404
  class FollowerPaginationController extends PaginationController {
11120
10405
  async getRequest(queryParams, token) {
@@ -11129,6 +10414,25 @@ class FollowerPaginationController extends PaginationController {
11129
10414
  }
11130
10415
  }
11131
10416
 
10417
+ class QueryStreamController {
10418
+ constructor(query, cacheKey) {
10419
+ this.query = query;
10420
+ this.cacheKey = cacheKey;
10421
+ }
10422
+ }
10423
+
10424
+ var EnumFollowActions;
10425
+ (function (EnumFollowActions) {
10426
+ EnumFollowActions["OnRequested"] = "onRequested";
10427
+ EnumFollowActions["OnAccepted"] = "onAccepted";
10428
+ EnumFollowActions["OnDeclined"] = "onDeclined";
10429
+ EnumFollowActions["OnCanceled"] = "onCanceled";
10430
+ EnumFollowActions["OnFollowed"] = "onFollowed";
10431
+ EnumFollowActions["OnUnfollowed"] = "onUnfollowed";
10432
+ EnumFollowActions["OnDeleted"] = "onDeleted";
10433
+ EnumFollowActions["OnUserDeleted"] = "onUserDeleted";
10434
+ })(EnumFollowActions || (EnumFollowActions = {}));
10435
+
11132
10436
  class FollowerQueryStreamController extends QueryStreamController {
11133
10437
  constructor(query, cacheKey, notifyChange, preparePayload) {
11134
10438
  super(query, cacheKey);
@@ -11184,6 +10488,109 @@ class FollowerQueryStreamController extends QueryStreamController {
11184
10488
  }
11185
10489
  }
11186
10490
 
10491
+ class PaginationNoPageController {
10492
+ constructor(queryParams) {
10493
+ const { http } = getActiveClient();
10494
+ this.queryParams = queryParams;
10495
+ this.http = http;
10496
+ }
10497
+ async onFetch() {
10498
+ const queryResponse = await this.getRequest(this.queryParams);
10499
+ return queryResponse;
10500
+ }
10501
+ }
10502
+
10503
+ class LiveCollectionController {
10504
+ constructor(paginationController, queryStreamId, cacheKey, callback) {
10505
+ this.paginationController = paginationController;
10506
+ this.queryStreamId = queryStreamId;
10507
+ this.cacheKey = cacheKey;
10508
+ this.callback = callback;
10509
+ }
10510
+ async refresh() {
10511
+ try {
10512
+ let result;
10513
+ if (this.paginationController instanceof PaginationNoPageController) {
10514
+ result = await this.paginationController.onFetch();
10515
+ }
10516
+ else {
10517
+ result = await this.paginationController.loadFirstPage();
10518
+ }
10519
+ if (!result)
10520
+ return;
10521
+ await this.persistModel(result);
10522
+ this.persistQueryStream({
10523
+ response: result,
10524
+ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */,
10525
+ refresh: true,
10526
+ });
10527
+ this.notifyChange({ origin: "server" /* Amity.LiveDataOrigin.SERVER */, loading: false });
10528
+ }
10529
+ catch (e) {
10530
+ this.notifyChange({ origin: "server" /* Amity.LiveDataOrigin.SERVER */, loading: false, error: e });
10531
+ }
10532
+ }
10533
+ loadPage({ initial = false, direction = "next" /* Amity.LiveCollectionPageDirection.NEXT */, }) {
10534
+ this.setup();
10535
+ this.notifyChange({ origin: "local" /* Amity.LiveDataOrigin.LOCAL */, loading: true });
10536
+ if (initial) {
10537
+ this.refresh();
10538
+ }
10539
+ else if (direction === "prev" /* Amity.LiveCollectionPageDirection.PREV */) {
10540
+ this.loadPrevPage();
10541
+ }
10542
+ else if (direction === "next" /* Amity.LiveCollectionPageDirection.NEXT */) {
10543
+ this.loadNextPage();
10544
+ }
10545
+ }
10546
+ async loadNextPage() {
10547
+ try {
10548
+ if (this.paginationController instanceof PaginationNoPageController)
10549
+ return;
10550
+ const result = await this.paginationController.loadNextPage();
10551
+ if (!result)
10552
+ return;
10553
+ await this.persistModel(result);
10554
+ this.persistQueryStream({
10555
+ response: result,
10556
+ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */,
10557
+ });
10558
+ this.notifyChange({ origin: "server" /* Amity.LiveDataOrigin.SERVER */, loading: false });
10559
+ }
10560
+ catch (e) {
10561
+ this.notifyChange({ origin: "server" /* Amity.LiveDataOrigin.SERVER */, loading: false, error: e });
10562
+ }
10563
+ }
10564
+ async loadPrevPage() {
10565
+ try {
10566
+ if (this.paginationController instanceof PaginationNoPageController)
10567
+ return;
10568
+ const result = await this.paginationController.loadPreviousPage();
10569
+ if (!result)
10570
+ return;
10571
+ await this.persistModel(result);
10572
+ this.persistQueryStream({
10573
+ response: result,
10574
+ direction: "prev" /* Amity.LiveCollectionPageDirection.PREV */,
10575
+ });
10576
+ this.notifyChange({ origin: "server" /* Amity.LiveDataOrigin.SERVER */, loading: false });
10577
+ }
10578
+ catch (e) {
10579
+ this.notifyChange({ origin: "server" /* Amity.LiveDataOrigin.SERVER */, loading: false, error: e });
10580
+ }
10581
+ }
10582
+ shouldNotify(data) {
10583
+ const newData = data.map(convertGetterPropsToStatic).map(removeFunctionProperties);
10584
+ if (isEqual(this.snapshot, newData))
10585
+ return false;
10586
+ this.snapshot = newData;
10587
+ return true;
10588
+ }
10589
+ getCacheKey() {
10590
+ return this.cacheKey;
10591
+ }
10592
+ }
10593
+
11187
10594
  const onFollowerUserDeleted = ({ userId }) => (callback) => {
11188
10595
  const client = getActiveClient();
11189
10596
  const filter = (data) => {
@@ -11528,6 +10935,69 @@ const getFollowings = (params, callback, config) => {
11528
10935
  };
11529
10936
  /* end_public_function */
11530
10937
 
10938
+ /**
10939
+ * @deprecated This function will to be deprecated soon.
10940
+ */
10941
+ const liveObject = (id, callback, key, fetcher, eventHandlers, options) => {
10942
+ const { forceDispatch, callbackDataSelector, callbackFilter } = Object.assign({ forceDispatch: false, callbackDataSelector: (data) => data }, options);
10943
+ const { cache } = getActiveClient();
10944
+ if (!cache) {
10945
+ console.log(LIVE_OBJECT_ENABLE_CACHE_MESSAGE);
10946
+ }
10947
+ let model;
10948
+ let isUnsyncedModel = false; // for messages
10949
+ const disposers = [];
10950
+ const dispatcher = (data) => {
10951
+ const { data: newModel } = data, rest = __rest(data, ["data"]);
10952
+ if (!callbackFilter || callbackFilter(newModel, model)) {
10953
+ callback(Object.assign({ data: callbackDataSelector(newModel) }, rest));
10954
+ }
10955
+ // resolve all getter on data model to a static value to avoid comparison problems
10956
+ model = convertGetterPropsToStatic(newModel);
10957
+ };
10958
+ const realtimeRouter = (eventModel, forceDispatch = false) => {
10959
+ if (id !== eventModel[key]) {
10960
+ return;
10961
+ }
10962
+ if (model) {
10963
+ if (!forceDispatch && isEqual(model, eventModel)) {
10964
+ return;
10965
+ }
10966
+ }
10967
+ dispatcher({ loading: false, data: eventModel, origin: 'event' });
10968
+ };
10969
+ const onFetch = () => {
10970
+ // TODO: Ihis `@ts-ignore` is bring back to fix the build and it needs to be removed later
10971
+ // @ts-ignore
10972
+ const query = createQuery(fetcher, id, true);
10973
+ runQuery(query, ({ error, data, loading, origin, cachedAt }) => {
10974
+ if (cachedAt === UNSYNCED_OBJECT_CACHED_AT_VALUE) {
10975
+ dispatcher({
10976
+ // @ts-ignore
10977
+ data,
10978
+ origin,
10979
+ loading: false,
10980
+ error: new ASCApiError(UNSYNCED_OBJECT_CACHED_AT_MESSAGE, 800800 /* Amity.ClientError.DISALOOW_UNSYNCED_OBJECT */, "error" /* Amity.ErrorLevel.ERROR */),
10981
+ });
10982
+ isUnsyncedModel = true;
10983
+ disposers.forEach(fn => fn());
10984
+ }
10985
+ else if (!isUnsyncedModel) {
10986
+ // @ts-ignore
10987
+ dispatcher({ loading, data, origin, error });
10988
+ }
10989
+ if (error) {
10990
+ disposers.forEach(fn => fn());
10991
+ }
10992
+ });
10993
+ };
10994
+ disposers.push(...eventHandlers.map(fn => fn(eventModel => realtimeRouter(eventModel, forceDispatch))));
10995
+ onFetch();
10996
+ return () => {
10997
+ disposers.forEach(fn => fn());
10998
+ };
10999
+ };
11000
+
11531
11001
  /* begin_public_function
11532
11002
  id: user.relationship.get_follow_info
11533
11003
  */
@@ -11593,12 +11063,9 @@ var index$k = /*#__PURE__*/Object.freeze({
11593
11063
  __proto__: null,
11594
11064
  blockUser: blockUser,
11595
11065
  unBlockUser: unBlockUser,
11596
- getBlockedUsers: getBlockedUsers,
11597
11066
  follow: follow,
11598
11067
  unfollow: unfollow,
11599
- acceptFollower: acceptFollower,
11600
11068
  acceptMyFollower: acceptMyFollower,
11601
- declineFollower: declineFollower,
11602
11069
  declineMyFollower: declineMyFollower,
11603
11070
  onUserFollowed: onUserFollowed,
11604
11071
  onUserUnfollowed: onUserUnfollowed,
@@ -11613,9 +11080,6 @@ var index$k = /*#__PURE__*/Object.freeze({
11613
11080
  onLocalFollowerRequested: onLocalFollowerRequested,
11614
11081
  onLocalFollowRequestAccepted: onLocalFollowRequestAccepted,
11615
11082
  onLocalFollowRequestDeclined: onLocalFollowRequestDeclined,
11616
- observeFollowInfo: observeFollowInfo,
11617
- observeFollowers: observeFollowers,
11618
- observeFollowings: observeFollowings,
11619
11083
  getFollowers: getFollowers,
11620
11084
  getFollowings: getFollowings,
11621
11085
  getFollowInfo: getFollowInfo,
@@ -11752,56 +11216,124 @@ const flagUser = async (userId) => {
11752
11216
  };
11753
11217
  /* end_public_function */
11754
11218
 
11755
- /* begin_public_function
11756
- id: user.unflag
11757
- */
11219
+ /* begin_public_function
11220
+ id: user.unflag
11221
+ */
11222
+ /**
11223
+ * ```js
11224
+ * import { UserRepository } from '@amityco/ts-sdk'
11225
+ * const unflagged = await UserRepository.unflagUser('post', postId)
11226
+ * ```
11227
+ *
11228
+ * @param userId The ID of the user to unflag
11229
+ * @returns the deleted report result
11230
+ *
11231
+ * @category User API
11232
+ * @async
11233
+ * */
11234
+ const unflagUser = async (userId) => {
11235
+ const client = getActiveClient();
11236
+ client.log('user/unflag', userId);
11237
+ const { data } = await client.http.delete(`/api/v4/me/flags/${encodeURIComponent(userId)}`);
11238
+ const payload = prepareUserPayload(data);
11239
+ if (client.cache) {
11240
+ ingestInCache(payload);
11241
+ }
11242
+ fireEvent('user.unflagged', data);
11243
+ return !!payload;
11244
+ };
11245
+ /* end_public_function */
11246
+
11247
+ /* begin_public_function
11248
+ id: user.check_flag_by_me
11249
+ */
11250
+ /**
11251
+ * ```js
11252
+ * import { UserRepository } from '@amityco/ts-sdk'
11253
+ * const isFlagged = await UserRepository.isUserFlaggedByMe(postId)
11254
+ * ```
11255
+ *
11256
+ * @param userId The ID of the thing to check a report to.
11257
+ * @returns `true` if the report is created by me, `false` if doesn't.
11258
+ *
11259
+ * @category Report API
11260
+ * @async
11261
+ * */
11262
+ const isUserFlaggedByMe = async (userId) => {
11263
+ const client = getActiveClient();
11264
+ client.log('user/isUserFlaggedByMe', userId);
11265
+ const { data: { isFlagByMe }, } = await client.http.get(`/api/v3/users/${userId}/isFlagByMe`);
11266
+ return isFlagByMe;
11267
+ };
11268
+ /* end_public_function */
11269
+
11270
+ /**
11271
+ * ```js
11272
+ * import { onUserUpdated } from '@amityco/ts-sdk'
11273
+ * const dispose = onUserUpdated(user => {
11274
+ * // ...
11275
+ * })
11276
+ * ```
11277
+ *
11278
+ * Fired when a {@link Amity.InternalUser} has been updated
11279
+ *
11280
+ * @param callback The function to call when the event was fired
11281
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
11282
+ *
11283
+ * @category User Events
11284
+ */
11285
+ const onUserUpdated = (callback) => createUserEventSubscriber('user.updated', callback);
11286
+
11287
+ /**
11288
+ * ```js
11289
+ * import { onUserFlagged } from '@amityco/ts-sdk'
11290
+ * const dispose = onUserFlagged(user => {
11291
+ * // ...
11292
+ * })
11293
+ * ```
11294
+ *
11295
+ * Fired when a {@link Amity.InternalUser} has been flagged
11296
+ *
11297
+ * @param callback The function to call when the event was fired
11298
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
11299
+ *
11300
+ * @category User Events
11301
+ */
11302
+ const onUserFlagged = (callback) => createUserEventSubscriber('user.flagged', callback);
11303
+
11758
11304
  /**
11759
11305
  * ```js
11760
- * import { UserRepository } from '@amityco/ts-sdk'
11761
- * const unflagged = await UserRepository.unflagUser('post', postId)
11306
+ * import { onUserUnflagged } from '@amityco/ts-sdk'
11307
+ * const dispose = onUserUnflagged(user => {
11308
+ * // ...
11309
+ * })
11762
11310
  * ```
11763
11311
  *
11764
- * @param userId The ID of the user to unflag
11765
- * @returns the deleted report result
11312
+ * Fired when a flag has been removed from a {@link Amity.InternalUser}
11766
11313
  *
11767
- * @category User API
11768
- * @async
11769
- * */
11770
- const unflagUser = async (userId) => {
11771
- const client = getActiveClient();
11772
- client.log('user/unflag', userId);
11773
- const { data } = await client.http.delete(`/api/v4/me/flags/${encodeURIComponent(userId)}`);
11774
- const payload = prepareUserPayload(data);
11775
- if (client.cache) {
11776
- ingestInCache(payload);
11777
- }
11778
- fireEvent('user.unflagged', data);
11779
- return !!payload;
11780
- };
11781
- /* end_public_function */
11314
+ * @param callback The function to call when the event was fired
11315
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
11316
+ *
11317
+ * @category User Events
11318
+ */
11319
+ const onUserUnflagged = (callback) => createUserEventSubscriber('user.unflagged', callback);
11782
11320
 
11783
- /* begin_public_function
11784
- id: user.check_flag_by_me
11785
- */
11786
11321
  /**
11787
11322
  * ```js
11788
- * import { UserRepository } from '@amityco/ts-sdk'
11789
- * const isFlagged = await UserRepository.isUserFlaggedByMe(postId)
11323
+ * import { onUserFlagCleared } from '@amityco/ts-sdk'
11324
+ * const dispose = onUserFlagCleared(user => {
11325
+ * // ...
11326
+ * })
11790
11327
  * ```
11791
11328
  *
11792
- * @param userId The ID of the thing to check a report to.
11793
- * @returns `true` if the report is created by me, `false` if doesn't.
11329
+ * Fired when flags have been cleared for a {@link Amity.InternalUser}
11794
11330
  *
11795
- * @category Report API
11796
- * @async
11797
- * */
11798
- const isUserFlaggedByMe = async (userId) => {
11799
- const client = getActiveClient();
11800
- client.log('user/isUserFlaggedByMe', userId);
11801
- const { data: { isFlagByMe }, } = await client.http.get(`/api/v3/users/${userId}/isFlagByMe`);
11802
- return isFlagByMe;
11803
- };
11804
- /* end_public_function */
11331
+ * @param callback The function to call when the event was fired
11332
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
11333
+ *
11334
+ * @category User Events
11335
+ */
11336
+ const onUserFlagCleared = (callback) => createUserEventSubscriber('user.flagCleared', callback);
11805
11337
 
11806
11338
  /**
11807
11339
  * ```js
@@ -11834,7 +11366,7 @@ const onUserFetched = (callback) => createUserEventSubscriber('user.fetched', ca
11834
11366
  * @category Private
11835
11367
  * @async
11836
11368
  */
11837
- const getUser$2 = async (userId) => {
11369
+ const getUser$1 = async (userId) => {
11838
11370
  const client = getActiveClient();
11839
11371
  client.log('user/getUser', userId);
11840
11372
  isInTombstone('user', userId);
@@ -11870,7 +11402,7 @@ const getUser$2 = async (userId) => {
11870
11402
  *
11871
11403
  * @category User API
11872
11404
  */
11873
- getUser$2.locally = (userId) => {
11405
+ getUser$1.locally = (userId) => {
11874
11406
  const client = getActiveClient();
11875
11407
  client.log('user/getUser.locally', userId);
11876
11408
  if (!client.cache)
@@ -11906,11 +11438,11 @@ getUser$2.locally = (userId) => {
11906
11438
  *
11907
11439
  * @category Message Live Object
11908
11440
  */
11909
- const getUser$1 = (userId, callback) => {
11441
+ const getUser = (userId, callback) => {
11910
11442
  const reactor = (response) => {
11911
11443
  return callback(Object.assign(Object.assign({}, response), { data: response.data ? LinkedObject.user(response.data) : response.data }));
11912
11444
  };
11913
- return liveObject(userId, reactor, 'userId', getUser$2, [
11445
+ return liveObject(userId, reactor, 'userId', getUser$1, [
11914
11446
  onUserFetched,
11915
11447
  onUserUpdated,
11916
11448
  onUserDeleted$2,
@@ -11923,10 +11455,10 @@ const getUser$1 = (userId, callback) => {
11923
11455
 
11924
11456
  class UserPaginationController extends PaginationController {
11925
11457
  async getRequest(queryParams, token) {
11926
- const { limit = COLLECTION_DEFAULT_PAGINATION_LIMIT, displayName } = queryParams, params = __rest(queryParams, ["limit", "displayName"]);
11458
+ const { limit = COLLECTION_DEFAULT_PAGINATION_LIMIT } = queryParams, params = __rest(queryParams, ["limit"]);
11927
11459
  const options = token ? { token } : { limit };
11928
11460
  const { data: queryResponse } = await this.http.get(`/api/v3/users`, {
11929
- params: Object.assign(Object.assign({}, params), { keyword: displayName, options, isDeleted: false }),
11461
+ params: Object.assign(Object.assign({}, params), { options, isDeleted: false }),
11930
11462
  });
11931
11463
  return queryResponse;
11932
11464
  }
@@ -11978,6 +11510,15 @@ class UserQueryStreamController extends QueryStreamController {
11978
11510
  }
11979
11511
  }
11980
11512
 
11513
+ var EnumUserActions;
11514
+ (function (EnumUserActions) {
11515
+ EnumUserActions["OnUserDeleted"] = "onUserDeleted";
11516
+ EnumUserActions["OnUserUpdated"] = "onUserUpdated";
11517
+ EnumUserActions["OnUserFlagged"] = "onUserFlagged";
11518
+ EnumUserActions["OnUserUnflagged"] = "onUserUnflagged";
11519
+ EnumUserActions["OnUserFlagCleared"] = "onUserFlagCleared";
11520
+ })(EnumUserActions || (EnumUserActions = {}));
11521
+
11981
11522
  class UserLiveCollectionController extends LiveCollectionController {
11982
11523
  constructor(query, callback) {
11983
11524
  const queryStreamId = hash__default["default"](query);
@@ -12036,21 +11577,17 @@ class UserLiveCollectionController extends LiveCollectionController {
12036
11577
  }
12037
11578
  applyFilter(data) {
12038
11579
  let users = data;
12039
- if (!this.query.displayName) {
12040
- const sortFn = (() => {
12041
- switch (this.query.sortBy) {
12042
- case 'firstCreated':
12043
- return sortByFirstCreated;
12044
- case 'lastCreated':
12045
- return sortByLastCreated;
12046
- case 'displayName':
12047
- return sortByDisplayName;
12048
- default:
12049
- return sortByLastCreated;
12050
- }
12051
- })();
12052
- users = users.sort(sortFn);
12053
- }
11580
+ const sortFn = (() => {
11581
+ switch (this.query.sortBy) {
11582
+ case 'firstCreated':
11583
+ return sortByFirstCreated;
11584
+ case 'lastCreated':
11585
+ return sortByLastCreated;
11586
+ default:
11587
+ return sortByLastCreated;
11588
+ }
11589
+ })();
11590
+ users = users.sort(sortFn);
12054
11591
  if (this.query.filter === 'flagged') {
12055
11592
  users = users.filter(user => !!user.hashFlag);
12056
11593
  }
@@ -12097,90 +11634,200 @@ const getUsers = (params, callback, config) => {
12097
11634
  };
12098
11635
  /* end_public_function */
12099
11636
 
12100
- /**
12101
- * ```js
12102
- * import { getUser } from '~/user/api'
12103
- * const { data: user } = await getUser('foobar')
12104
- * ```
12105
- *
12106
- * Fetches a {@link Amity.User} object
12107
- *
12108
- * @param userId the ID of the {@link Amity.User} to fetch
12109
- * @returns the associated {@link Amity.User} object
12110
- *
12111
- * @category Private
12112
- * @async
12113
- */
12114
- const getUser = async (userId) => {
12115
- const { data, cachedAt } = await getUser$2(userId);
12116
- return {
12117
- data: LinkedObject.user(data),
12118
- cachedAt,
12119
- };
12120
- };
12121
- /**
12122
- * ```js
12123
- * import { getUser } from '@amityco/ts-sdk'
12124
- * const { data: user } = getUser.locally('foobar')
12125
- * ```
12126
- *
12127
- * Fetches a {@link Amity.User} object from cache
12128
- *
12129
- * @param userId the ID of the {@link Amity.User} to fetch
12130
- * @returns the associated {@link Amity.User} object
12131
- *
12132
- * @category User API
12133
- */
12134
- getUser.locally = (userId) => {
12135
- const cached = getUser$2.locally(userId);
12136
- if (!cached)
11637
+ class BlockedUserPaginationController extends PaginationController {
11638
+ async getRequest(queryParams, token) {
11639
+ const { limit = COLLECTION_DEFAULT_PAGINATION_LIMIT } = queryParams, params = __rest(queryParams, ["limit"]);
11640
+ const options = token ? { token } : { limit };
11641
+ const { data: queryResponse } = await this.http.get('/api/v4/me/user-blocks', {
11642
+ params: Object.assign(Object.assign({}, params), { options, isDeleted: false }),
11643
+ });
11644
+ return queryResponse;
11645
+ }
11646
+ }
11647
+
11648
+ class BlockedUserQueryStreamController extends QueryStreamController {
11649
+ constructor(query, cacheKey, notifyChange, preparePayload) {
11650
+ super(query, cacheKey);
11651
+ this.notifyChange = notifyChange;
11652
+ this.preparePayload = preparePayload;
11653
+ }
11654
+ async saveToMainDB(response) {
11655
+ const processedPayload = await this.preparePayload(response);
11656
+ const client = getActiveClient();
11657
+ const cachedAt = client.cache && Date.now();
11658
+ if (client.cache) {
11659
+ ingestInCache(processedPayload, { cachedAt });
11660
+ }
11661
+ }
11662
+ appendToQueryStream(response, direction, refresh = false) {
11663
+ var _a, _b;
11664
+ if (refresh) {
11665
+ pushToCache(this.cacheKey, {
11666
+ data: response.users.map(getResolver('user')),
11667
+ });
11668
+ }
11669
+ else {
11670
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
11671
+ const users = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
11672
+ pushToCache(this.cacheKey, Object.assign(Object.assign({}, collection), { data: [...new Set([...users, ...response.users.map(getResolver('user'))])] }));
11673
+ }
11674
+ }
11675
+ reactor(action) {
11676
+ return (targetUser) => {
11677
+ var _a;
11678
+ if (action === EnumFollowActions.OnFollowed) {
11679
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
11680
+ const updatedCollection = collection === null || collection === void 0 ? void 0 : collection.data.filter(id => id !== targetUser.userId);
11681
+ pushToCache(this.cacheKey, Object.assign(Object.assign({}, collection), { data: updatedCollection }));
11682
+ }
11683
+ this.notifyChange({ origin: "event" /* Amity.LiveDataOrigin.EVENT */, loading: false });
11684
+ };
11685
+ }
11686
+ subscribeRTE(createSubscriber) {
11687
+ return createSubscriber.map(subscriber => subscriber.fn(this.reactor(subscriber.action)));
11688
+ }
11689
+ }
11690
+
11691
+ function prepareBlockedUserPayload(response) {
11692
+ const { users, follows } = response, rest = __rest(response, ["users", "follows"]);
11693
+ return Object.assign(Object.assign({}, rest), { follows: follows.map(follow => {
11694
+ const followUser = users.find(user => user.userId === follow.from);
11695
+ return Object.assign(Object.assign({}, follow), { user: convertRawUserToInternalUser(followUser) });
11696
+ }), users: users.map(convertRawUserToInternalUser) });
11697
+ }
11698
+
11699
+ const convertEventPayload = (eventHandler, sourceModelProp, destinationDomain) => (callback) => eventHandler(sourceModel => {
11700
+ var _a, _b;
11701
+ if (!sourceModel) {
11702
+ return sourceModel;
11703
+ }
11704
+ const client = getActiveClient();
11705
+ const { objectSyncMap } = client;
11706
+ /*
11707
+ * NOTE: For objects created locally (optimistic creation), the SDK stores them with their local ID as the cache key, which is used throughout the entire SDK session (in-memory) for syncing updates.
11708
+ * If the payload or response only contains the remote ID of the same object, the SDK will look up the corresponding local ID to retrieve the object.
11709
+ */
11710
+ const resolvedId = isLocalId(sourceModel[sourceModelProp])
11711
+ ? sourceModel[sourceModelProp]
11712
+ : (_a = objectSyncMap.get(sourceModel[sourceModelProp])) !== null && _a !== void 0 ? _a : sourceModel[sourceModelProp];
11713
+ const model = (_b = pullFromCache([
11714
+ destinationDomain,
11715
+ 'get',
11716
+ `${resolvedId}`,
11717
+ ])) === null || _b === void 0 ? void 0 : _b.data;
11718
+ if (!model)
12137
11719
  return;
12138
- return {
12139
- data: LinkedObject.user(cached.data),
12140
- cachedAt: cached.cachedAt,
12141
- };
12142
- };
11720
+ return callback(model);
11721
+ });
11722
+
11723
+ class BlockedUserLiveCollectionController extends LiveCollectionController {
11724
+ constructor(query, callback) {
11725
+ const queryStreamId = hash__default["default"](query);
11726
+ const cacheKey = ['blockedUsers', 'collection', queryStreamId];
11727
+ const paginationController = new BlockedUserPaginationController(query);
11728
+ super(paginationController, queryStreamId, cacheKey, callback);
11729
+ this.query = query;
11730
+ this.queryStreamController = new BlockedUserQueryStreamController(this.query, this.cacheKey, this.notifyChange.bind(this), prepareBlockedUserPayload);
11731
+ this.callback = callback.bind(this);
11732
+ this.loadPage({ initial: true });
11733
+ }
11734
+ setup() {
11735
+ var _a;
11736
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
11737
+ if (!collection) {
11738
+ pushToCache(this.cacheKey, {
11739
+ data: [],
11740
+ params: {},
11741
+ });
11742
+ }
11743
+ }
11744
+ async persistModel(queryPayload) {
11745
+ await this.queryStreamController.saveToMainDB(queryPayload);
11746
+ }
11747
+ persistQueryStream({ response, direction, refresh, }) {
11748
+ this.queryStreamController.appendToQueryStream(response, direction, refresh);
11749
+ }
11750
+ startSubscription() {
11751
+ return this.queryStreamController.subscribeRTE([
11752
+ {
11753
+ fn: onUserDeleted$2,
11754
+ action: EnumUserActions.OnUserDeleted,
11755
+ },
11756
+ // In the case of unblocking a user, we need to subscribe to the follow events
11757
+ {
11758
+ fn: convertEventPayload(onLocalUserFollowed, 'to', 'user'),
11759
+ action: EnumFollowActions.OnFollowed,
11760
+ },
11761
+ {
11762
+ fn: convertEventPayload(onUserFollowed, 'to', 'user'),
11763
+ action: EnumFollowActions.OnFollowed,
11764
+ },
11765
+ ]);
11766
+ }
11767
+ notifyChange({ origin, loading, error }) {
11768
+ var _a, _b;
11769
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
11770
+ if (!collection)
11771
+ return;
11772
+ const data = this.applyFilter((_b = collection.data
11773
+ .map(id => pullFromCache(['user', 'get', id]))
11774
+ .filter(isNonNullable)
11775
+ .map(({ data }) => data)
11776
+ .map(LinkedObject.user)) !== null && _b !== void 0 ? _b : []);
11777
+ if (!this.shouldNotify(data) && origin === 'event')
11778
+ return;
11779
+ this.callback({
11780
+ onNextPage: () => this.loadPage({ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */ }),
11781
+ data,
11782
+ hasNextPage: !!this.paginationController.getNextToken(),
11783
+ loading,
11784
+ error,
11785
+ });
11786
+ }
11787
+ // eslint-disable-next-line class-methods-use-this
11788
+ applyFilter(data) {
11789
+ let users = data;
11790
+ users = users.filter(user => user.isDeleted == null || user.isDeleted === false);
11791
+ return users;
11792
+ }
11793
+ }
12143
11794
 
11795
+ /* begin_public_function
11796
+ id: user.get_blocked_users
11797
+ */
12144
11798
  /**
12145
11799
  * ```js
12146
- * import { observeUser } from '@amityco/ts-sdk'
12147
- *
12148
- * let user = {}
12149
- * const dispose = observeUser(userId, updated => user = updated)
11800
+ * import { UserRepository } from '@amityco/ts-sdk'
11801
+ * const unblockedUser = await UserRepository.blockUser('userId')
12150
11802
  * ```
12151
11803
  *
12152
- * @param userId the ID of the user to observe
12153
- * @param callback the function to call when new data are available
12154
- * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the user
11804
+ * Blocks a {@link Amity.InternalUser}
11805
+ *
11806
+ * @param params The params to get blocked {@link Amity.InternalUser}s
11807
+ * @param callback to recieve updates on unblocked {@link Amity.InternalUser}s
11808
+ * @returns {@link Amity.Unsubscriber} to unsubscribe from collection
12155
11809
  *
12156
- * Observe all mutation on a given {@link Amity.InternalUser}
12157
- * @category User Observer
11810
+ * @category Post API
11811
+ * @async
12158
11812
  */
12159
- const observeUser = (userId, callback) => {
12160
- const { log } = getActiveClient();
11813
+ const getBlockedUsers = (params, callback, config) => {
11814
+ const { log, cache } = getActiveClient();
11815
+ if (!cache) {
11816
+ console.log(ENABLE_CACHE_MESSAGE);
11817
+ }
12161
11818
  const timestamp = Date.now();
12162
- log(`observeUser(tmpid: ${timestamp}) > listen`);
12163
- // wrapper function to make sure
12164
- const router = (result, action) => {
12165
- var _a, _b, _c;
12166
- // filter function
12167
- if (((_a = result.data) === null || _a === void 0 ? void 0 : _a.userId) !== userId)
12168
- return;
12169
- const newResult = Object.assign(Object.assign({}, result), { data: LinkedObject.user(result.data) });
12170
- if (callback instanceof Function)
12171
- return callback(newResult);
12172
- if (action !== 'onFetch')
12173
- (_b = callback.onEvent) === null || _b === void 0 ? void 0 : _b.call(callback, action, newResult);
12174
- (_c = callback[action]) === null || _c === void 0 ? void 0 : _c.call(callback, newResult);
12175
- };
12176
- const disposers = [];
12177
- disposers.push(onUserUpdated(data => router({ data, loading: false, origin: 'event' }, 'onUpdate')), onUserDeleted$2(data => router({ data, loading: false, origin: 'event' }, 'onDelete')), onUserFlagged(data => router({ data, loading: false, origin: 'event' }, 'onFlagged')), onUserUnflagged(data => router({ data, loading: false, origin: 'event' }, 'onUnflagged')), onUserFlagCleared(data => router({ data, loading: false, origin: 'event' }, 'onFlagCleared')));
12178
- runQuery(createQuery(getUser, userId), result => result.data && router(result, 'onFetch'));
11819
+ log(`getBlockedUsers(tmpid: ${timestamp}) > listen`);
11820
+ const blockedUserLiveCollection = new BlockedUserLiveCollectionController(params, callback);
11821
+ const disposers = blockedUserLiveCollection.startSubscription();
11822
+ const cacheKey = blockedUserLiveCollection.getCacheKey();
11823
+ disposers.push(() => dropFromCache(cacheKey));
12179
11824
  return () => {
12180
- log(`observeUser(tmpid: ${timestamp}) > dispose`);
11825
+ log(`getBlockedUsers(tmpid: ${timestamp}) > dispose`);
12181
11826
  disposers.forEach(fn => fn());
11827
+ dropFromCache(cacheKey);
12182
11828
  };
12183
- };
11829
+ };
11830
+ /* end_public_function */
12184
11831
 
12185
11832
  class SearchUserPaginationController extends PaginationController {
12186
11833
  async getRequest(queryParams, token) {
@@ -12365,74 +12012,6 @@ const queryReachUser = async ({ viewId, viewedType, limit, token, }) => {
12365
12012
  return response.data;
12366
12013
  };
12367
12014
 
12368
- /**
12369
- * @deprecated: Please use {@link UserRepository.getReachUsers} instead
12370
- * @param params
12371
- * @param callback
12372
- */
12373
- const getViewedUsers = (params, callback) => {
12374
- const { log, cache } = getActiveClient();
12375
- const cacheKey = ['postViewedUsers', 'collection', { postId: params.postId }];
12376
- if (!cache) {
12377
- console.log(ENABLE_CACHE_MESSAGE);
12378
- }
12379
- const timestamp = Date.now();
12380
- log(`getViewedUsers(tmpid: ${timestamp}) > listen`);
12381
- const { limit: queryLimit, postId } = params;
12382
- const responder = (snapshot) => {
12383
- var _a, _b;
12384
- let users = [];
12385
- if (snapshot === null || snapshot === void 0 ? void 0 : snapshot.data) {
12386
- users =
12387
- snapshot.data
12388
- .map((userId) => pullFromCache(['user', 'get', userId]))
12389
- .filter(Boolean)
12390
- .map(data => data === null || data === void 0 ? void 0 : data.data) || [];
12391
- }
12392
- callback({
12393
- // eslint-disable-next-line no-use-before-define
12394
- onNextPage: onFetch,
12395
- data: users,
12396
- hasNextPage: !!((_b = (_a = snapshot.params) === null || _a === void 0 ? void 0 : _a.page) === null || _b === void 0 ? void 0 : _b.next),
12397
- loading: snapshot.loading || false,
12398
- });
12399
- };
12400
- const onFetch = (initial = false) => {
12401
- var _a, _b, _c;
12402
- const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
12403
- const users = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
12404
- if (!initial && users.length > 0 && !(collection === null || collection === void 0 ? void 0 : collection.params.page))
12405
- return;
12406
- const query = createQuery(queryReachUser, {
12407
- viewId: postId,
12408
- viewedType: "post" /* Amity.AnalyticEventContentType.Post */,
12409
- limit: queryLimit || 10,
12410
- token: !initial ? (_c = collection === null || collection === void 0 ? void 0 : collection.params.page) === null || _c === void 0 ? void 0 : _c.next : undefined,
12411
- });
12412
- runQuery(query, result => {
12413
- var _a, _b, _c, _d, _e;
12414
- let userIds = (_c = (_b = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.data) !== null && _c !== void 0 ? _c : [];
12415
- if ((_d = result.data) === null || _d === void 0 ? void 0 : _d.users) {
12416
- userIds = [
12417
- ...new Set([...userIds, ...result.data.users.map(({ userId }) => userId)]),
12418
- ];
12419
- }
12420
- const saveToCache = {
12421
- loading: result.loading,
12422
- params: { page: (_e = result.data) === null || _e === void 0 ? void 0 : _e.paging },
12423
- data: userIds || [],
12424
- };
12425
- pushToCache(cacheKey, saveToCache);
12426
- responder(saveToCache);
12427
- }, queryOptions(COLLECTION_DEFAULT_CACHING_POLICY, CACHE_SHORTEN_LIFESPAN));
12428
- };
12429
- onFetch(true);
12430
- return () => {
12431
- log(`getViewedUsers(tmpid: ${timestamp}) > dispose`);
12432
- dropFromCache(cacheKey);
12433
- };
12434
- };
12435
-
12436
12015
  const getReachedUsers = (params, callback) => {
12437
12016
  // Pre-defined function to avoid undefined function call
12438
12017
  let onFetch = (initial = false) => undefined;
@@ -12520,12 +12099,10 @@ var index$j = /*#__PURE__*/Object.freeze({
12520
12099
  onUserFlagged: onUserFlagged,
12521
12100
  onUserUnflagged: onUserUnflagged,
12522
12101
  onUserFlagCleared: onUserFlagCleared,
12523
- getUser: getUser$1,
12102
+ getUser: getUser,
12524
12103
  getUsers: getUsers,
12525
- observeUser: observeUser,
12526
- getBlockedUsers: getBlockedUsers$1,
12104
+ getBlockedUsers: getBlockedUsers,
12527
12105
  searchUserByDisplayName: searchUserByDisplayName,
12528
- getViewedUsers: getViewedUsers,
12529
12106
  getReachedUsers: getReachedUsers,
12530
12107
  get AmityUserSearchMatchType () { return AmityUserSearchMatchType; }
12531
12108
  });
@@ -12772,183 +12349,8 @@ const uploadImage = async (formData, onProgress) => {
12772
12349
  data,
12773
12350
  cachedAt,
12774
12351
  };
12775
- };
12776
- /* end_public_function */
12777
-
12778
- /**
12779
- * ```js
12780
- * import { createImage } from '@amityco/ts-sdk'
12781
- * const created = await createImage(formData)
12782
- * ```
12783
- *
12784
- * Creates an {@link Amity.File<'image'>}
12785
- *
12786
- * @param formData The data necessary to create a new {@link Amity.File<'image'>}
12787
- * @param onProgress The callback to track the upload progress
12788
- * @returns The newly created {@link Amity.File<'image'>}
12789
- *
12790
- * @category File API
12791
- * @async
12792
- */
12793
- const createImage = async (formData, onProgress) => {
12794
- const client = getActiveClient();
12795
- client.log('file/createImage', formData);
12796
- const files = formData.getAll('files');
12797
- if (!files.length)
12798
- throw new Error('The formData object must have a `files` key.');
12799
- const accessType = GlobalFileAccessType$1.getInstance().getFileAccessType();
12800
- formData.append('accessType', accessType);
12801
- formData.append('preferredFilename', files[0].name);
12802
- const headers = 'getHeaders' in formData
12803
- ? formData.getHeaders()
12804
- : { 'content-type': 'multipart/form-data' };
12805
- const { data } = await client.http.post('/api/v4/images', formData, {
12806
- headers,
12807
- onUploadProgress({ loaded, total = 100 }) {
12808
- onProgress && onProgress(Math.round((loaded * 100) / total));
12809
- },
12810
- });
12811
- // API-FIX: payload should be serialized properly
12812
- // const { files } = data
12813
- const cachedAt = client.cache && Date.now();
12814
- if (client.cache)
12815
- ingestInCache({ files: data }, { cachedAt });
12816
- return {
12817
- data,
12818
- cachedAt,
12819
- };
12820
- };
12821
- /* end_public_function */
12822
-
12823
- /**
12824
- * ```js
12825
- * import { FileRepository } from '@amityco/ts-sdk'
12826
- * const created = await FileRepository.createFile(formData)
12827
- * ```
12828
- *
12829
- * Creates an {@link Amity.File}
12830
- *
12831
- * @param formData The data necessary to create a new {@link Amity.File}
12832
- * @param onProgress The callback to track the upload progress
12833
- * @returns The newly created {@link Amity.File}
12834
- *
12835
- * @category File API
12836
- * @async
12837
- */
12838
- const createFile = async (formData, onProgress) => {
12839
- const client = getActiveClient();
12840
- client.log('file/createFile', formData);
12841
- const files = formData.getAll('files');
12842
- if (!files.length)
12843
- throw new Error('The formData object must have a `files` key.');
12844
- const accessType = GlobalFileAccessType$1.getInstance().getFileAccessType();
12845
- formData.append('accessType', accessType);
12846
- formData.append('preferredFilename', files[0].name);
12847
- const headers = 'getHeaders' in formData
12848
- ? formData.getHeaders()
12849
- : { 'content-type': 'multipart/form-data' };
12850
- const { data } = await client.http.post('/api/v4/files', formData, {
12851
- headers,
12852
- onUploadProgress({ loaded, total = 100 }) {
12853
- onProgress && onProgress(Math.round((loaded * 100) / total));
12854
- },
12855
- });
12856
- // API-FIX: payload should be serialized properly
12857
- // const { files } = data
12858
- const cachedAt = client.cache && Date.now();
12859
- if (client.cache)
12860
- ingestInCache({ files: data }, { cachedAt });
12861
- return {
12862
- data,
12863
- cachedAt,
12864
- };
12865
- };
12866
-
12867
- /**
12868
- * ```js
12869
- * import { FileRepository } from '@amityco/ts-sdk'
12870
- * const created = await FileRepository.createVideo(formData)
12871
- * ```
12872
- *
12873
- * Creates an {@link Amity.File<'video'>}
12874
- *
12875
- * @param formData The data necessary to create a new {@link Amity.File<'video'>}
12876
- * @param feedType The {@link Amity.File<'video'>} feed type
12877
- * @param onProgress The callback to track the upload progress
12878
- * @returns The newly uploaded {@link Amity.File<'video'>}
12879
- *
12880
- * @category File API
12881
- * @async
12882
- */
12883
- const createVideo = async (formData, feedType, onProgress) => {
12884
- const client = getActiveClient();
12885
- client.log('file/createVideo', formData);
12886
- const files = formData.getAll('files');
12887
- if (!files.length)
12888
- throw new Error('The formData object must have a `files` key.');
12889
- const accessType = GlobalFileAccessType$1.getInstance().getFileAccessType();
12890
- formData.append('accessType', accessType);
12891
- formData.append('preferredFilename', files[0].name);
12892
- if (feedType) {
12893
- formData.append('feedType', feedType);
12894
- }
12895
- const headers = 'getHeaders' in formData
12896
- ? formData.getHeaders()
12897
- : { 'content-type': 'multipart/form-data' };
12898
- const { data } = await client.http.post('/api/v4/videos', formData, {
12899
- headers,
12900
- onUploadProgress({ loaded, total = 100 }) {
12901
- onProgress && onProgress(Math.round((loaded * 100) / total));
12902
- },
12903
- });
12904
- // API-FIX: payload should be serialized properly
12905
- // const { files } = data
12906
- const cachedAt = client.cache && Date.now();
12907
- if (client.cache)
12908
- ingestInCache({ files: data }, { cachedAt });
12909
- return {
12910
- data,
12911
- cachedAt,
12912
- };
12913
- };
12914
-
12915
- /**
12916
- * ```js
12917
- * import { observeFile } from '@amityco/ts-sdk'
12918
- *
12919
- * let file = {}
12920
- * const dispose = observeFile(fileId, updated => file = updated)
12921
- * ```
12922
- *
12923
- * Observe all mutation on a given {@link Amity.File}
12924
- *
12925
- * @param fileId the ID of the file to observe
12926
- * @param callback the function to call when new data are available
12927
- * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the file
12928
- *
12929
- * @category File Observer
12930
- */
12931
- const observeFile = (fileId, callback) => {
12932
- const { log } = getActiveClient();
12933
- const timestamp = Date.now();
12934
- log(`observeFile(tmpid: ${timestamp}) > listen`);
12935
- // wrapper function to make sure
12936
- const router = (result, action) => {
12937
- var _a, _b, _c;
12938
- // filter function
12939
- if (((_a = result.data) === null || _a === void 0 ? void 0 : _a.fileId) !== fileId)
12940
- return;
12941
- if (callback instanceof Function)
12942
- return callback(result);
12943
- if (action !== 'onFetch')
12944
- (_b = callback.onEvent) === null || _b === void 0 ? void 0 : _b.call(callback, action, result);
12945
- (_c = callback[action]) === null || _c === void 0 ? void 0 : _c.call(callback, result);
12946
- };
12947
- runQuery(createQuery(getFile, fileId), result => result.data && router(result, 'onFetch'));
12948
- return () => {
12949
- log(`observeFile(tmpid: ${timestamp}) > dispose`);
12950
- };
12951
- };
12352
+ };
12353
+ /* end_public_function */
12952
12354
 
12953
12355
  var index$i = /*#__PURE__*/Object.freeze({
12954
12356
  __proto__: null,
@@ -12957,11 +12359,7 @@ var index$i = /*#__PURE__*/Object.freeze({
12957
12359
  deleteFile: deleteFile,
12958
12360
  fileUrlWithSize: fileUrlWithSize,
12959
12361
  uploadVideo: uploadVideo,
12960
- uploadImage: uploadImage,
12961
- createImage: createImage,
12962
- createFile: createFile,
12963
- createVideo: createVideo,
12964
- observeFile: observeFile
12362
+ uploadImage: uploadImage
12965
12363
  });
12966
12364
 
12967
12365
  /**
@@ -12982,16 +12380,12 @@ var index$i = /*#__PURE__*/Object.freeze({
12982
12380
  const queryRoles = async (query) => {
12983
12381
  const client = getActiveClient();
12984
12382
  client.log('role/queryRoles', query);
12985
- const _a = query !== null && query !== void 0 ? query : {}, { page, limit = 10, queryToken, displayName, sortBy } = _a, params = __rest(_a, ["page", "limit", "queryToken", "displayName", "sortBy"]);
12383
+ const _a = query !== null && query !== void 0 ? query : {}, { limit = 10, queryToken, displayName, sortBy } = _a, params = __rest(_a, ["limit", "queryToken", "displayName", "sortBy"]);
12986
12384
  const options = (() => {
12987
12385
  if (queryToken)
12988
12386
  return { token: queryToken };
12989
12387
  if (limit)
12990
12388
  return { limit };
12991
- if (page)
12992
- return {
12993
- token: toToken(page, 'skiplimit'),
12994
- };
12995
12389
  return undefined;
12996
12390
  })();
12997
12391
  // API-FIX: parameters should be querystring.
@@ -13119,12 +12513,9 @@ const dispatchReactable = (referenceType, model) => {
13119
12513
  * @category Message API
13120
12514
  * @async
13121
12515
  */
13122
- const getMessage$2 = async (messageId, isLive = false) => {
12516
+ const getMessage$1 = async (messageId, isLive = false) => {
13123
12517
  const client = getActiveClient();
13124
12518
  client.log('message/getMessage', messageId);
13125
- if (!isLive) {
13126
- console.log('getMessage will be deprecated on 15th November 2022, please use liveMessage instead.');
13127
- }
13128
12519
  isInTombstone('message', messageId);
13129
12520
  let data;
13130
12521
  try {
@@ -13161,7 +12552,7 @@ const getMessage$2 = async (messageId, isLive = false) => {
13161
12552
  *
13162
12553
  * @category Message API
13163
12554
  */
13164
- getMessage$2.locally = (messageId) => {
12555
+ getMessage$1.locally = (messageId) => {
13165
12556
  const client = getActiveClient();
13166
12557
  client.log('message/getMessage.locally', messageId);
13167
12558
  if (!client.cache)
@@ -15090,7 +14481,7 @@ const getChannel$1 = async (channelId) => {
15090
14481
  ingestInCache(data, { cachedAt });
15091
14482
  const { channels } = data;
15092
14483
  return {
15093
- data: constructChannelDynamicValue(channels.find(channel => channel.channelId === channelId)),
14484
+ data: channels.find(channel => channel.channelId === channelId),
15094
14485
  cachedAt,
15095
14486
  };
15096
14487
  };
@@ -15120,7 +14511,7 @@ getChannel$1.locally = (channelId) => {
15120
14511
  if (!cached || (cached === null || cached === void 0 ? void 0 : cached.length) === 0)
15121
14512
  return;
15122
14513
  return {
15123
- data: constructChannelDynamicValue(cached[0].data),
14514
+ data: cached[0].data,
15124
14515
  cachedAt: cached[0].cachedAt,
15125
14516
  };
15126
14517
  };
@@ -15145,7 +14536,7 @@ const deleteChannel = async (channelId) => {
15145
14536
  await client.http.delete(`/api/v3/channels/${encodeURIComponent(channelId)}`);
15146
14537
  const deleted = await getChannel$1(channelId);
15147
14538
  // no need for event, fired by server
15148
- return deleted.data;
14539
+ return constructChannelDynamicValue(deleted.data);
15149
14540
  };
15150
14541
 
15151
14542
  /* begin_public_function
@@ -15267,81 +14658,6 @@ const unmuteChannel = async (channelId) => {
15267
14658
  };
15268
14659
  /* end_public_function */
15269
14660
 
15270
- /**
15271
- * ```js
15272
- * import { observeChannel } from '@amityco/ts-sdk'
15273
- *
15274
- * let channel = {}
15275
- * const dispose = observeChannel(channelId, ({ data }) => channel = data)
15276
- * ```
15277
- *
15278
- * Observe all mutation on a given {@link Amity.Channel}
15279
- *
15280
- * @param channelId the ID of the channel to observe
15281
- * @param callback the function to call when new data are available
15282
- * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the channel
15283
- *
15284
- * @category Channel Observer
15285
- */
15286
- const observeChannel = (channelId, callback) => {
15287
- const { log } = getActiveClient();
15288
- const timestamp = Date.now();
15289
- log(`observeChannel(tmpid: ${timestamp}) > listen`);
15290
- // wrapper function to make sure
15291
- const router = (result, action) => {
15292
- var _a, _b, _c;
15293
- // filter function
15294
- if (((_a = result.data) === null || _a === void 0 ? void 0 : _a.channelId) !== channelId)
15295
- return;
15296
- if (callback instanceof Function)
15297
- return callback(Object.assign(Object.assign({}, result), { data: LinkedObject.channel(constructChannelDynamicValue(result.data)) }));
15298
- if (action !== 'onFetch')
15299
- (_b = callback.onEvent) === null || _b === void 0 ? void 0 : _b.call(callback, action, Object.assign(Object.assign({}, result), { data: LinkedObject.channel(constructChannelDynamicValue(result.data)) }));
15300
- (_c = callback[action]) === null || _c === void 0 ? void 0 : _c.call(callback, Object.assign(Object.assign({}, result), { data: LinkedObject.channel(constructChannelDynamicValue(result.data)) }));
15301
- };
15302
- const disposers = [];
15303
- disposers.push(onChannelUpdated(data => router({ data, loading: false, origin: 'event' }, "onUpdate" /* Amity.ChannelActionType.OnUpdate */)), onChannelDeleted(data => router({ data, loading: false, origin: 'event' }, "onDelete" /* Amity.ChannelActionType.OnDelete */)), onChannelJoined(data => router({ data, loading: false, origin: 'event' }, "onJoin" /* Amity.ChannelActionType.OnJoin */)), onChannelLeft(data => router({ data, loading: false, origin: 'event' }, "onLeft" /* Amity.ChannelActionType.OnLeft */)), onChannelMuted(data => router({ data, loading: false, origin: 'event' }, "onMute" /* Amity.ChannelActionType.OnMute */)), onChannelMemberAdded(data => router({ data, loading: false, origin: 'event' }, "onMemberAdded" /* Amity.ChannelActionType.OnMemberAdded */)), onChannelMemberRemoved(data => router({ data, loading: false, origin: 'event' }, "onMemberRemoved" /* Amity.ChannelActionType.OnMemberRemoved */)), convertEventPayload(onChannelMarkerFetched, 'entityId', 'channel')(data => router({ data, loading: false, origin: 'event' }, "onUpdate" /* Amity.ChannelActionType.OnUpdate */)));
15304
- runQuery(createQuery(getChannel$1, channelId), result => result.data && router(result, "onFetch" /* Amity.ChannelActionType.OnFetch */));
15305
- return () => {
15306
- log(`observeChannel(tmpid: ${timestamp}) > dispose`);
15307
- disposers.forEach(fn => fn());
15308
- };
15309
- };
15310
-
15311
- /**
15312
- * ```js
15313
- * import { observeChannels } from '@amityco/ts-sdk'
15314
- *
15315
- * let channels = []
15316
- * const unsub = observeChannels(channel => merge(channels, channel))
15317
- * ```
15318
- *
15319
- * Observe all mutations on a list of {@link Amity.Channel} for a current user
15320
- *
15321
- * @param callback the function to call when new data are available
15322
- * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the channels
15323
- *
15324
- * @category Channel Observer
15325
- */
15326
- const observeChannels = (callback) => {
15327
- const { log } = getActiveClient();
15328
- const timestamp = Date.now();
15329
- log(`observeChannels(tmpid: ${timestamp}) > listen`);
15330
- const disposers = [];
15331
- const router = (channel, action) => {
15332
- var _a, _b;
15333
- if (callback instanceof Function)
15334
- return callback(LinkedObject.channel(constructChannelDynamicValue(channel)));
15335
- (_a = callback.onEvent) === null || _a === void 0 ? void 0 : _a.call(callback, action, LinkedObject.channel(constructChannelDynamicValue(channel)));
15336
- (_b = callback[action]) === null || _b === void 0 ? void 0 : _b.call(callback, LinkedObject.channel(constructChannelDynamicValue(channel)));
15337
- };
15338
- disposers.push(onChannelCreated(data => router(data, "onCreate" /* Amity.ChannelActionType.OnCreate */)), onChannelUpdated(data => router(data, "onUpdate" /* Amity.ChannelActionType.OnUpdate */)), onChannelDeleted(data => router(data, "onDelete" /* Amity.ChannelActionType.OnDelete */)), onChannelJoined(data => router(data, "onJoin" /* Amity.ChannelActionType.OnJoin */)), onChannelLeft(data => router(data, "onLeft" /* Amity.ChannelActionType.OnLeft */)), onChannelMuted(data => router(data, "onMute" /* Amity.ChannelActionType.OnMute */)), onChannelMemberAdded(data => router(data, "onMemberAdded" /* Amity.ChannelActionType.OnMemberAdded */)), onChannelMemberRemoved(data => router(data, "onMemberRemoved" /* Amity.ChannelActionType.OnMemberRemoved */)), convertEventPayload(onChannelMarkerFetched, 'entityId', 'channel')(data => router(data, "onUpdate" /* Amity.ChannelActionType.OnUpdate */)));
15339
- return () => {
15340
- log(`observeChannels(tmpid: ${timestamp}) > dispose`);
15341
- disposers.forEach(fn => fn());
15342
- };
15343
- };
15344
-
15345
14661
  /**
15346
14662
  * ```js
15347
14663
  * import { onMessageUpdated } from '@amityco/ts-sdk'
@@ -15620,69 +14936,6 @@ const onSubChannelFetched = (callback) => {
15620
14936
  return createEventSubscriber(getActiveClient(), 'onSubChannelFetched', 'local.message-feed.fetched', payload => callback(payload.messageFeeds[0]));
15621
14937
  };
15622
14938
 
15623
- /**
15624
- * ```js
15625
- * import { getMessages } from '@amityco/ts-sdk'
15626
- * const messages = await getMessages(['foo', 'bar'])
15627
- * ```
15628
- *
15629
- * Fetches a collection of {@link Amity.Message} objects
15630
- *
15631
- * @param messageIds the IDs of the {@link Amity.Message} to fetch
15632
- * @returns the associated collection of {@link Amity.Message} objects
15633
- *
15634
- * @category Message API
15635
- * @async
15636
- */
15637
- const getMessages$1 = async (messageIds) => {
15638
- const client = getActiveClient();
15639
- client.log('message/getMessages', messageIds);
15640
- const { data: payload } = await client.http.get(`/api/v5/messages/list`, {
15641
- params: { messageIds: messageIds.map(encodeURIComponent) },
15642
- });
15643
- const data = await prepareMessagePayload(payload);
15644
- const cachedAt = client.cache && Date.now();
15645
- if (client.cache)
15646
- ingestInCache(data, { cachedAt });
15647
- const { messages } = data;
15648
- fireEvent('local.message.fetched', { messages });
15649
- return {
15650
- data: messages.map(message => LinkedObject.message(message)),
15651
- cachedAt,
15652
- };
15653
- };
15654
- /**
15655
- * ```js
15656
- * import { getMessages } from '@amityco/ts-sdk'
15657
- * const messages = getMessages.locally(['foo', 'bar']) ?? []
15658
- * ```
15659
- *
15660
- * Fetches a collection of {@link Amity.Message} objects from cache
15661
- *
15662
- * @param messageIds the IDs of the {@link Amity.Message} to fetch
15663
- * @returns the associated collection of {@link Amity.Message} objects
15664
- *
15665
- * @category Message API
15666
- */
15667
- getMessages$1.locally = (messageIds) => {
15668
- var _a;
15669
- const client = getActiveClient();
15670
- client.log('message/getMessages.locally', messageIds);
15671
- if (!client.cache)
15672
- return;
15673
- const cached = messageIds
15674
- .map(messageId => pullFromCache(['message', 'get', messageId]))
15675
- .filter(Boolean);
15676
- const messages = cached.map(({ data }) => data);
15677
- const oldest = (_a = cached.sort((a, b) => (a.cachedAt < b.cachedAt ? -1 : 1))) === null || _a === void 0 ? void 0 : _a[0];
15678
- if ((cached === null || cached === void 0 ? void 0 : cached.length) < messageIds.length)
15679
- return;
15680
- return {
15681
- data: messages,
15682
- cachedAt: oldest.cachedAt,
15683
- };
15684
- };
15685
-
15686
14939
  const getLocalId = () => `LOCAL_${uuid()}`;
15687
14940
  // FIXME: temp solution
15688
14941
  let uniqueId;
@@ -15707,7 +14960,11 @@ const createMessageOptimistic = (bundle) => {
15707
14960
  if (subChannel) {
15708
14961
  upsertInCache(['subChannel', 'get', bundle.subChannelId], Object.assign(Object.assign({}, subChannel.data), { messageCount: subChannel.data.messageCount + 1 }));
15709
14962
  if (subChannel.data.channelId === subChannel.data.subChannelId) {
15710
- const channel = pullFromCache(['channel', 'get', subChannel.data.channelId]);
14963
+ const channel = pullFromCache([
14964
+ 'channel',
14965
+ 'get',
14966
+ subChannel.data.channelId,
14967
+ ]);
15711
14968
  if (channel === null || channel === void 0 ? void 0 : channel.data) {
15712
14969
  upsertInCache(['channel', 'get', subChannel.data.channelId], Object.assign(Object.assign({}, channel.data), { messageCount: ((_a = channel.data.messageCount) !== null && _a !== void 0 ? _a : 0) + 1 }));
15713
14970
  }
@@ -15995,7 +15252,7 @@ const softDeleteMessage = async (messageId) => {
15995
15252
  client.log('message/softDeleteMessage', messageId);
15996
15253
  // API-FIX: This endpoint has not been implemented yet.
15997
15254
  await client.http.delete(`/api/v5/messages/${encodeURIComponent(messageId)}`);
15998
- const deleted = await getMessage$2(messageId);
15255
+ const deleted = await getMessage$1(messageId);
15999
15256
  fireEvent('local.message.deleted', { messages: [deleted.data] });
16000
15257
  return LinkedObject.message(deleted.data);
16001
15258
  };
@@ -16469,12 +15726,12 @@ const onMessageFetched = (callback) => {
16469
15726
  *
16470
15727
  * @category Message Live Object
16471
15728
  */
16472
- const getMessage$1 = (messageId, callback) => {
15729
+ const getMessage = (messageId, callback) => {
16473
15730
  const responder = (snapshot) => {
16474
15731
  const { data } = snapshot;
16475
15732
  callback(Object.assign(Object.assign({}, snapshot), { data: data ? LinkedObject.message(snapshot.data) : data }));
16476
15733
  };
16477
- return liveObject(messageId, responder, 'messageId', getMessage$2, [
15734
+ return liveObject(messageId, responder, 'messageId', getMessage$1, [
16478
15735
  onMessageFetched,
16479
15736
  onMessageUpdated,
16480
15737
  onMessageDeleted,
@@ -16523,7 +15780,7 @@ class MessageQueryStreamController extends QueryStreamController {
16523
15780
  }
16524
15781
  reactor(action) {
16525
15782
  return (payload) => {
16526
- var _a, _b, _c, _d, _e;
15783
+ var _a, _b, _c;
16527
15784
  if (action === 'onCreate') {
16528
15785
  const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
16529
15786
  const { referenceId } = payload;
@@ -16533,14 +15790,9 @@ class MessageQueryStreamController extends QueryStreamController {
16533
15790
  return;
16534
15791
  if (this.query.type && this.query.type !== payload.dataType)
16535
15792
  return;
16536
- if (this.query.dataType && this.query.dataType !== payload.dataType)
16537
- return;
16538
15793
  if (this.query.excludingTags &&
16539
15794
  ((_b = this.query.excludingTags) === null || _b === void 0 ? void 0 : _b.some(value => { var _a; return (_a = payload.tags) === null || _a === void 0 ? void 0 : _a.includes(value); })))
16540
15795
  return;
16541
- if (this.query.excludeTags &&
16542
- ((_c = this.query.excludeTags) === null || _c === void 0 ? void 0 : _c.some(value => { var _a; return (_a = payload.tags) === null || _a === void 0 ? void 0 : _a.includes(value); })))
16543
- return;
16544
15796
  if (!!this.query.hasFlags !== !!payload.flagCount)
16545
15797
  return;
16546
15798
  if (this.query.parentId && this.query.parentId !== payload.parentId)
@@ -16550,9 +15802,7 @@ class MessageQueryStreamController extends QueryStreamController {
16550
15802
  payload.isDeleted)
16551
15803
  return;
16552
15804
  if (this.query.includingTags &&
16553
- !((_d = this.query.includingTags) === null || _d === void 0 ? void 0 : _d.some(value => { var _a; return (_a = payload.tags) === null || _a === void 0 ? void 0 : _a.includes(value); })))
16554
- return;
16555
- if (this.query.tags && !((_e = this.query.tags) === null || _e === void 0 ? void 0 : _e.some(value => { var _a; return (_a = payload.tags) === null || _a === void 0 ? void 0 : _a.includes(value); })))
15805
+ !((_c = this.query.includingTags) === null || _c === void 0 ? void 0 : _c.some(value => { var _a; return (_a = payload.tags) === null || _a === void 0 ? void 0 : _a.includes(value); })))
16556
15806
  return;
16557
15807
  if ((!this.query.sortBy || this.query.sortBy === 'segmentDesc') &&
16558
15808
  !this.paginationController.getPrevToken()) {
@@ -16652,26 +15902,6 @@ class MessageLiveCollectionController extends LiveCollectionController {
16652
15902
  }
16653
15903
  applyFilter(data) {
16654
15904
  let messages = data;
16655
- messages = messages.filter(m => {
16656
- if (this.query.tags) {
16657
- return this.query.tags.find(value => {
16658
- if (!m.tags)
16659
- return false;
16660
- return m.tags.includes(value);
16661
- });
16662
- }
16663
- return true;
16664
- });
16665
- messages = messages.filter(m => {
16666
- if (this.query.excludeTags) {
16667
- return (this.query.excludeTags || []).find(value => {
16668
- if (!m.tags)
16669
- return true;
16670
- return !m.tags.includes(value);
16671
- });
16672
- }
16673
- return true;
16674
- });
16675
15905
  /*
16676
15906
  * for cases when message is deleted via RTE, this flag is used to get
16677
15907
  * items from cache that are !deleted
@@ -16687,228 +15917,71 @@ class MessageLiveCollectionController extends LiveCollectionController {
16687
15917
  return message2.channelSegment - message1.channelSegment;
16688
15918
  }
16689
15919
  return 0;
16690
- });
16691
- return messages;
16692
- }
16693
- setup() {
16694
- var _a;
16695
- const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
16696
- if (!collection) {
16697
- pushToCache(this.cacheKey, {
16698
- data: [],
16699
- query: this.query,
16700
- });
16701
- }
16702
- }
16703
- async persistModel(response) {
16704
- await this.queryStreamController.saveToMainDB(response);
16705
- }
16706
- persistQueryStream({ response, direction, refresh, }) {
16707
- this.queryStreamController.appendToQueryStream(response, direction, refresh);
16708
- }
16709
- }
16710
-
16711
- /* eslint-disable no-use-before-define */
16712
- /* begin_public_function
16713
- id: message.query
16714
- */
16715
- /**
16716
- * ```js
16717
- * import { getMessages } from '@amityco/ts-sdk';
16718
- *
16719
- * let messages = [];
16720
- *
16721
- * const unsubscribe = getMessages({
16722
- * subChannelId: Amity.SubChannel['subChannelId'];
16723
- * }, response => merge(messages, response.data));
16724
- * ```
16725
- *
16726
- * Observe all mutations on a list of {@link Amity.Message} for a given target object
16727
- *
16728
- * @param params for querying messages from a sub channel
16729
- * @param callback the function to call when new data are available
16730
- * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the messages
16731
- *
16732
- * @category Messages Live Collection
16733
- */
16734
- const getMessages = (params, callback, config) => {
16735
- const { log, cache } = getActiveClient();
16736
- if (!cache) {
16737
- console.log(ENABLE_CACHE_MESSAGE);
16738
- }
16739
- const timestamp = Date.now();
16740
- log(`getMessages(tmpid: ${timestamp}) > listen`);
16741
- const messagesLiveCollection = new MessageLiveCollectionController(params, callback);
16742
- const disposers = messagesLiveCollection.startSubscription();
16743
- const cacheKey = messagesLiveCollection.getCacheKey();
16744
- disposers.push(() => {
16745
- dropFromCache(cacheKey);
16746
- });
16747
- return () => {
16748
- log(`getMessages(tmpid: ${timestamp}) > dispose`);
16749
- disposers.forEach(fn => fn());
16750
- };
16751
- };
16752
- /* end_public_function */
16753
-
16754
- /**
16755
- * ```js
16756
- * import { getMessage } from '@amityco/ts-sdk'
16757
- * const message = await getMessage('foobar')
16758
- * ```
16759
- *
16760
- * Fetches a {@link Amity.Message} object
16761
- *
16762
- * @param messageId the ID of the {@link Amity.Message} to fetch
16763
- * @returns the associated {@link Amity.Message} object
16764
- *
16765
- * @category Message API
16766
- * @async
16767
- */
16768
- const getMessage = async (messageId, isLive = false) => {
16769
- const client = getActiveClient();
16770
- client.log('message/getMessage', messageId);
16771
- if (!isLive) {
16772
- console.log('getMessage will be deprecated on 15th November 2022, please use liveMessage instead.');
16773
- }
16774
- isInTombstone('message', messageId);
16775
- let data;
16776
- try {
16777
- // API-FIX: endpoint should not be /list, parameters should be querystring.
16778
- const { data: payload } = await client.http.get(`/api/v5/messages/${encodeURIComponent(messageId)}`);
16779
- data = await prepareMessagePayload(payload);
16780
- }
16781
- catch (error) {
16782
- if (checkIfShouldGoesToTombstone(error === null || error === void 0 ? void 0 : error.code)) {
16783
- pushToTombstone('message', messageId);
16784
- }
16785
- throw error;
16786
- }
16787
- const cachedAt = client.cache && Date.now();
16788
- if (client.cache)
16789
- ingestInCache(data, { cachedAt });
16790
- const { messages } = data;
16791
- fireEvent('local.message.fetched', { messages });
16792
- return {
16793
- data: LinkedObject.message(messages.find(message => message.messageId === messageId)),
16794
- cachedAt,
16795
- };
16796
- };
16797
- /**
16798
- * ```js
16799
- * import { getMessage } from '@amityco/ts-sdk'
16800
- * const message = getMessage.locally('foobar')
16801
- * ```
16802
- *
16803
- * Fetches a {@link Amity.Message} object
16804
- *
16805
- * @param messageId the ID of the {@link Amity.Message} to fetch
16806
- * @returns the associated {@link Amity.Message} object
16807
- *
16808
- * @category Message API
16809
- */
16810
- getMessage.locally = (messageId) => {
16811
- const client = getActiveClient();
16812
- client.log('message/getMessage.locally', messageId);
16813
- if (!client.cache)
16814
- return;
16815
- const cached = pullFromCache(['message', 'get', messageId]);
16816
- if (!cached)
16817
- return;
16818
- return {
16819
- data: cached.data,
16820
- cachedAt: cached.cachedAt,
16821
- };
16822
- };
16823
-
16824
- /**
16825
- * ```js
16826
- * import { observeMessage } from '@amityco/ts-sdk'
16827
- *
16828
- * let message = {}
16829
- *
16830
- * const unsub = observeMessage(messageId, updated => message = updated)
16831
- * ```
16832
- *
16833
- * Observe all mutations on a {@link Amity.Message} given a single messageId
16834
- *
16835
- * @param client the client to observe the message with
16836
- * @param messageId the ID of the message to observe
16837
- * @param callback the function to call when new data are available
16838
- * @param policy a query policy option for this observer
16839
- * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the message
16840
- *
16841
- * @category Message Observer
16842
- */
16843
- const observeMessage = (messageId, callback, policy = 'cache_then_server') => {
16844
- const { log } = getActiveClient();
16845
- const timestamp = Date.now();
16846
- log(`observeMessage(tmpid: ${timestamp}) > listen`);
16847
- console.log('observeMessage will be deprecated on 15th November 2022, please use liveMessage instead.');
16848
- // wrapper function to make sure
16849
- const router = (result, action) => {
16850
- var _a, _b, _c;
16851
- // filter function
16852
- if (((_a = result.data) === null || _a === void 0 ? void 0 : _a.messageId) !== messageId)
16853
- return;
16854
- if (callback instanceof Function)
16855
- return callback(result);
16856
- if (action !== 'onFetch')
16857
- (_b = callback.onEvent) === null || _b === void 0 ? void 0 : _b.call(callback, action, result);
16858
- (_c = callback[action]) === null || _c === void 0 ? void 0 : _c.call(callback, result);
16859
- };
16860
- const disposers = [];
16861
- disposers.push(onMessageUpdated(data => router({ data: LinkedObject.message(data), loading: false, origin: 'event' }, 'onUpdate')), onMessageDeleted(data => router({ data: LinkedObject.message(data), loading: false, origin: 'event' }, 'onDelete')), convertEventPayload(onMessageMarkerFetched, 'contentId', 'message')(data => router({ data: LinkedObject.message(data), loading: false, origin: 'event' }, 'onUpdate')), convertEventPayload(onMessageMarked, 'contentId', 'message')(data => router({ data: LinkedObject.message(data), loading: false, origin: 'event' }, 'onUpdate')));
16862
- if (policy !== 'no_fetch') {
16863
- runQuery(createQuery(getMessage, messageId), result => result.data && router(result, 'onFetch'), queryOptions(policy));
15920
+ });
15921
+ return messages;
16864
15922
  }
16865
- return () => {
16866
- log(`observeMessages(tmpid: ${timestamp}) > dispose`);
16867
- disposers.forEach(fn => fn());
16868
- };
16869
- };
15923
+ setup() {
15924
+ var _a;
15925
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
15926
+ if (!collection) {
15927
+ pushToCache(this.cacheKey, {
15928
+ data: [],
15929
+ query: this.query,
15930
+ });
15931
+ }
15932
+ }
15933
+ async persistModel(response) {
15934
+ await this.queryStreamController.saveToMainDB(response);
15935
+ }
15936
+ persistQueryStream({ response, direction, refresh, }) {
15937
+ this.queryStreamController.appendToQueryStream(response, direction, refresh);
15938
+ }
15939
+ }
16870
15940
 
15941
+ /* begin_public_function
15942
+ id: message.query
15943
+ */
16871
15944
  /**
16872
15945
  * ```js
16873
- * import { observeMessages } from '@amityco/ts-sdk'
15946
+ * import { getMessages } from '@amityco/ts-sdk';
16874
15947
  *
16875
- * let messages = []
15948
+ * let messages = [];
16876
15949
  *
16877
- * const unsubscribe = observeMessages(channelId, message => merge(messages, message))
15950
+ * const unsubscribe = getMessages({
15951
+ * subChannelId: Amity.SubChannel['subChannelId'];
15952
+ * }, response => merge(messages, response.data));
16878
15953
  * ```
16879
15954
  *
16880
- * Observe all mutations on a list of {@link Amity.Message} for a given {@link Amity.SubChannel} object
15955
+ * Observe all mutations on a list of {@link Amity.Message} for a given target object
16881
15956
  *
16882
- * @param subChannelId the ID of the channel where to observe the messages
15957
+ * @param params for querying messages from a sub channel
16883
15958
  * @param callback the function to call when new data are available
16884
15959
  * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the messages
16885
15960
  *
16886
- * @category Message Observer
15961
+ * @category Messages Live Collection
16887
15962
  */
16888
- const observeMessages = (subChannelId, callback) => {
16889
- const { log } = getActiveClient();
15963
+ const getMessages = (params, callback, config) => {
15964
+ const { log, cache } = getActiveClient();
15965
+ if (!cache) {
15966
+ console.log(ENABLE_CACHE_MESSAGE);
15967
+ }
16890
15968
  const timestamp = Date.now();
16891
- log(`observeMessages(tmpid: ${timestamp}) > listen`);
16892
- const disposers = [];
16893
- const router = (message, action) => {
16894
- var _a, _b, _c;
16895
- if (((_a = message.data) === null || _a === void 0 ? void 0 : _a.subChannelId) !== subChannelId)
16896
- return;
16897
- if (callback instanceof Function)
16898
- return callback(message);
16899
- (_b = callback.onEvent) === null || _b === void 0 ? void 0 : _b.call(callback, action, message);
16900
- (_c = callback[action]) === null || _c === void 0 ? void 0 : _c.call(callback, message);
16901
- };
16902
- disposers.push(onMessageCreatedMqtt(data => router({ data: LinkedObject.message(data), loading: false, origin: 'event' }, 'onCreate')), onMessageCreatedLocal(data => router({ data: LinkedObject.message(data), loading: false, origin: 'event' }, 'onCreate')), onMessageUpdated(data => router({ data: LinkedObject.message(data), loading: false, origin: 'event' }, 'onUpdate')), onMessageDeleted(data => router({ data: LinkedObject.message(data), loading: false, origin: 'event' }, 'onDelete')), convertEventPayload(onMessageMarkerFetched, 'contentId', 'message')(data => router({ data: LinkedObject.message(data), loading: false, origin: 'event' }, 'onCreate')), convertEventPayload(onMessageMarked, 'contentId', 'message')(data => router({ data: LinkedObject.message(data), loading: false, origin: 'event' }, 'onCreate')));
15969
+ log(`getMessages(tmpid: ${timestamp}) > listen`);
15970
+ const messagesLiveCollection = new MessageLiveCollectionController(params, callback);
15971
+ const disposers = messagesLiveCollection.startSubscription();
15972
+ const cacheKey = messagesLiveCollection.getCacheKey();
15973
+ disposers.push(() => {
15974
+ dropFromCache(cacheKey);
15975
+ });
16903
15976
  return () => {
16904
- log(`observeMessages(tmpid: ${timestamp}) > dispose`);
15977
+ log(`getMessages(tmpid: ${timestamp}) > dispose`);
16905
15978
  disposers.forEach(fn => fn());
16906
15979
  };
16907
- };
15980
+ };
15981
+ /* end_public_function */
16908
15982
 
16909
15983
  var index$g = /*#__PURE__*/Object.freeze({
16910
15984
  __proto__: null,
16911
- getMessageByIds: getMessages$1,
16912
15985
  createMessage: createMessage,
16913
15986
  updateMessage: updateMessage,
16914
15987
  editMessage: editMessage,
@@ -16930,10 +16003,8 @@ var index$g = /*#__PURE__*/Object.freeze({
16930
16003
  onMessageReactionAdded: onMessageReactionAdded,
16931
16004
  onMessageReactionRemoved: onMessageReactionRemoved,
16932
16005
  onMessageFetched: onMessageFetched,
16933
- getMessage: getMessage$1,
16006
+ getMessage: getMessage,
16934
16007
  getMessages: getMessages,
16935
- observeMessage: observeMessage,
16936
- observeMessages: observeMessages,
16937
16008
  convertFromRaw: convertFromRaw$1,
16938
16009
  prepareMessagePayload: prepareMessagePayload,
16939
16010
  convertParams: convertParams,
@@ -17450,8 +16521,6 @@ var index$f = /*#__PURE__*/Object.freeze({
17450
16521
  getSubChannel: getSubChannel,
17451
16522
  getSubChannels: getSubChannels,
17452
16523
  markReadEngineOnLoginHandler: markReadEngineOnLoginHandler,
17453
- startReading: startReading,
17454
- stopReading: stopReading,
17455
16524
  startMessageReceiptSync: startMessageReceiptSync,
17456
16525
  stopMessageReceiptSync: stopMessageReceiptSync
17457
16526
  });
@@ -17502,7 +16571,7 @@ const getChannel = (channelId, callback) => {
17502
16571
  const reactor = async (response) => {
17503
16572
  if (!response.data)
17504
16573
  return callback(response);
17505
- const data = Object.assign(Object.assign({}, response), { data: LinkedObject.channel(constructChannelDynamicValue(getChannelMessagePreviewWithUser(response.data))) });
16574
+ const data = Object.assign(Object.assign({}, response), { data: constructChannelObject(response.data) });
17506
16575
  const newSnapshot = __rest(data, ["origin"]);
17507
16576
  /**
17508
16577
  * check equality of previous data and current data to avoid redundancy
@@ -17536,7 +16605,11 @@ const getChannel = (channelId, callback) => {
17536
16605
  if (message.channelId !== channelId)
17537
16606
  return;
17538
16607
  // channelId from message is channelInternalId
17539
- const channel = (_a = pullFromCache(['channel', 'get', channelId])) === null || _a === void 0 ? void 0 : _a.data;
16608
+ const channel = (_a = pullFromCache([
16609
+ 'channel',
16610
+ 'get',
16611
+ channelId,
16612
+ ])) === null || _a === void 0 ? void 0 : _a.data;
17540
16613
  if (!channel)
17541
16614
  return;
17542
16615
  updateChannelCache(channel, {
@@ -17559,7 +16632,11 @@ const getChannel = (channelId, callback) => {
17559
16632
  if (message.channelId !== channelId)
17560
16633
  return;
17561
16634
  // channelId from message is channelInternalId
17562
- const channel = (_a = pullFromCache(['channel', 'get', channelId])) === null || _a === void 0 ? void 0 : _a.data;
16635
+ const channel = (_a = pullFromCache([
16636
+ 'channel',
16637
+ 'get',
16638
+ channelId,
16639
+ ])) === null || _a === void 0 ? void 0 : _a.data;
17563
16640
  if (!channel)
17564
16641
  return;
17565
16642
  updateChannelCache(channel, {
@@ -17572,7 +16649,11 @@ const getChannel = (channelId, callback) => {
17572
16649
  convertEventPayload((callback) => {
17573
16650
  const updateMessagePreview = async (message) => {
17574
16651
  var _a;
17575
- const channel = (_a = pullFromCache(['channel', 'get', channelId])) === null || _a === void 0 ? void 0 : _a.data;
16652
+ const channel = (_a = pullFromCache([
16653
+ 'channel',
16654
+ 'get',
16655
+ channelId,
16656
+ ])) === null || _a === void 0 ? void 0 : _a.data;
17576
16657
  if (!channel || channel.messagePreviewId !== message.messageId)
17577
16658
  return;
17578
16659
  const messagePreviewSetting = await client.getMessagePreviewSetting(false);
@@ -17586,7 +16667,11 @@ const getChannel = (channelId, callback) => {
17586
16667
  convertEventPayload((callback) => {
17587
16668
  const updateMessagePreview = async (message) => {
17588
16669
  var _a;
17589
- const channel = (_a = pullFromCache(['channel', 'get', channelId])) === null || _a === void 0 ? void 0 : _a.data;
16670
+ const channel = (_a = pullFromCache([
16671
+ 'channel',
16672
+ 'get',
16673
+ channelId,
16674
+ ])) === null || _a === void 0 ? void 0 : _a.data;
17590
16675
  if (!channel || channel.messagePreviewId !== message.messageId)
17591
16676
  return;
17592
16677
  const messagePreviewSetting = await client.getMessagePreviewSetting(false);
@@ -17619,7 +16704,11 @@ const getChannel = (channelId, callback) => {
17619
16704
  if (messagePreviewSetting === "no-message-preview" /* Amity.MessagePreviewSetting.NO_MESSAGE_PREVIEW */)
17620
16705
  return;
17621
16706
  await getChannel$1(channelId);
17622
- const channel = (_b = pullFromCache(['channel', 'get', channelId])) === null || _b === void 0 ? void 0 : _b.data;
16707
+ const channel = (_b = pullFromCache([
16708
+ 'channel',
16709
+ 'get',
16710
+ channelId,
16711
+ ])) === null || _b === void 0 ? void 0 : _b.data;
17623
16712
  if (!channel)
17624
16713
  return;
17625
16714
  callback(subChannel);
@@ -17641,7 +16730,11 @@ const getChannel = (channelId, callback) => {
17641
16730
  if (!messagePreviewCache ||
17642
16731
  messagePreviewCache.subChannelId !== subChannel.subChannelId)
17643
16732
  return;
17644
- const channel = (_b = pullFromCache(['channel', 'get', channelId])) === null || _b === void 0 ? void 0 : _b.data;
16733
+ const channel = (_b = pullFromCache([
16734
+ 'channel',
16735
+ 'get',
16736
+ channelId,
16737
+ ])) === null || _b === void 0 ? void 0 : _b.data;
17645
16738
  if (!channel)
17646
16739
  return;
17647
16740
  callback(subChannel);
@@ -17837,9 +16930,7 @@ class ChannelLiveCollectionController extends LiveCollectionController {
17837
16930
  .map(channelId => pullFromCache(['channel', 'get', channelId]))
17838
16931
  .filter(Boolean)
17839
16932
  .map(({ data }) => data)
17840
- .map(getChannelMessagePreviewWithUser)
17841
- .map(constructChannelDynamicValue)
17842
- .map(LinkedObject.channel)) !== null && _b !== void 0 ? _b : [];
16933
+ .map(constructChannelObject)) !== null && _b !== void 0 ? _b : [];
17843
16934
  if (this.paginationController instanceof ChannelPaginationController) {
17844
16935
  data = this.applyFilter(data);
17845
16936
  }
@@ -18486,11 +17577,6 @@ class ChannelMemberLiveCollectionController extends LiveCollectionController {
18486
17577
  return false;
18487
17578
  });
18488
17579
  }
18489
- if (this.query.search) {
18490
- // eslint-disable-next-line no-console
18491
- console.warn('`search` param will be deprecated in the next major release. If you want to search channel members by displayName, Please use `searchMembers()` instead.');
18492
- channelMembers = filterBySearchTerm(channelMembers, this.query.search);
18493
- }
18494
17580
  if (this.query.includeDeleted === false) {
18495
17581
  channelMembers = channelMembers.filter(member => { var _a; return ((_a = member.user) === null || _a === void 0 ? void 0 : _a.isDeleted) !== true; });
18496
17582
  }
@@ -18524,11 +17610,6 @@ const applyFilter$1 = (data, params) => {
18524
17610
  return params.memberships.includes(member.membership);
18525
17611
  });
18526
17612
  }
18527
- if (params.search) {
18528
- // eslint-disable-next-line no-console
18529
- console.warn('`search` param will be deprecated in the next major release. If you want to search channel members by displayName, Please use `searchMembers()` instead.');
18530
- channelMembers = filterBySearchTerm(channelMembers, params.search);
18531
- }
18532
17613
  // sort, 'lastCreated' is the default sort order
18533
17614
  const sortBy = params.sortBy ? params.sortBy : 'lastCreated';
18534
17615
  channelMembers = channelMembers.sort(sortBy === 'lastCreated' ? sortByLastCreated : sortByFirstCreated);
@@ -18820,7 +17901,7 @@ var index$c = /*#__PURE__*/Object.freeze({
18820
17901
  __proto__: null,
18821
17902
  Membership: index$e,
18822
17903
  Moderation: index$d,
18823
- getChannelByIds: getChannelByIds,
17904
+ getChannelByIds: getChannelByIds$1,
18824
17905
  createChannel: createChannel,
18825
17906
  updateChannel: updateChannel,
18826
17907
  deleteChannel: deleteChannel,
@@ -18828,7 +17909,6 @@ var index$c = /*#__PURE__*/Object.freeze({
18828
17909
  leaveChannel: leaveChannel,
18829
17910
  muteChannel: muteChannel,
18830
17911
  unmuteChannel: unmuteChannel,
18831
- markAsRead: markAsRead,
18832
17912
  onChannelCreated: onChannelCreated,
18833
17913
  onChannelUpdated: onChannelUpdated,
18834
17914
  onChannelDeleted: onChannelDeleted,
@@ -18841,8 +17921,6 @@ var index$c = /*#__PURE__*/Object.freeze({
18841
17921
  onChannelMemberUnbanned: onChannelMemberUnbanned,
18842
17922
  onChannelMemberRoleAdded: onChannelMemberRoleAdded,
18843
17923
  onChannelMemberRoleRemoved: onChannelMemberRoleRemoved,
18844
- observeChannel: observeChannel,
18845
- observeChannels: observeChannels,
18846
17924
  getChannel: getChannel,
18847
17925
  getChannels: getChannels,
18848
17926
  MARKER_INCLUDED_CHANNEL_TYPE: MARKER_INCLUDED_CHANNEL_TYPE,
@@ -19147,154 +18225,300 @@ const leaveCommunity = async (communityId) => {
19147
18225
  const data = prepareCommunityPayload(payload);
19148
18226
  const cachedAt = client.cache && Date.now();
19149
18227
  if (client.cache)
19150
- ingestInCache(data, { cachedAt });
18228
+ ingestInCache(data, { cachedAt });
18229
+ const { communityUsers } = data;
18230
+ return !!communityUsers.find(communityUser => communityUser.communityId === communityId && communityUser.communityMembership !== 'member');
18231
+ };
18232
+ /* end_public_function */
18233
+
18234
+ const createCommunityEventSubscriber = (event, callback) => {
18235
+ const client = getActiveClient();
18236
+ const filter = (payload) => {
18237
+ const unpackedPayload = prepareCommunityPayload(payload);
18238
+ if (!client.cache) {
18239
+ // TODO: here we are missing specific properties here!
18240
+ callback(unpackedPayload.communities[0]);
18241
+ }
18242
+ else {
18243
+ ingestInCache(unpackedPayload);
18244
+ const community = pullFromCache([
18245
+ 'community',
18246
+ 'get',
18247
+ unpackedPayload.communities[0].communityId,
18248
+ ]);
18249
+ callback(community.data);
18250
+ }
18251
+ };
18252
+ return createEventSubscriber(client, event, event, filter);
18253
+ };
18254
+
18255
+ /**
18256
+ * ```js
18257
+ * import { onCommunityCreated } from '@amityco/ts-sdk'
18258
+ * const dispose = onCommunityCreated(community => {
18259
+ * // ...
18260
+ * })
18261
+ * ```
18262
+ *
18263
+ * Fired when a {@link Amity.Community} have been created
18264
+ *
18265
+ * @param callback The function to call when the event was fired
18266
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
18267
+ *
18268
+ * @category Community Events
18269
+ */
18270
+ const onCommunityCreated = (callback) => createCommunityEventSubscriber('community.created', callback);
18271
+
18272
+ /**
18273
+ * ```js
18274
+ * import { onCommunityUpdated } from '@amityco/ts-sdk'
18275
+ * const dispose = onCommunityUpdated(community => {
18276
+ * // ...
18277
+ * })
18278
+ * ```
18279
+ *
18280
+ * Fired when a {@link Amity.Community} has been updated
18281
+ *
18282
+ * @param callback The function to call when the event was fired
18283
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
18284
+ *
18285
+ * @category Community Events
18286
+ */
18287
+ const onCommunityUpdated = (callback) => createCommunityEventSubscriber('community.updated', callback);
18288
+
18289
+ /**
18290
+ * ```js
18291
+ * import { onCommunityDeleted } from '@amityco/ts-sdk'
18292
+ * const dispose = onCommunityDeleted(community => {
18293
+ * // ...
18294
+ * })
18295
+ * ```
18296
+ *
18297
+ * Fired when a {@link Amity.Community} has been deleted
18298
+ *
18299
+ * @param callback The function to call when the event was fired
18300
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
18301
+ *
18302
+ * @category Community Events
18303
+ */
18304
+ const onCommunityDeleted = (callback) => createCommunityEventSubscriber('community.deleted', callback);
18305
+
18306
+ /**
18307
+ * TODO: handle cache receive cache option, and cache policy
18308
+ * TODO: check if querybyIds is supported
18309
+ */
18310
+ class CommunitiesPaginationController$1 extends PaginationController {
18311
+ async getRequest(queryParams, token) {
18312
+ const { limit = COLLECTION_DEFAULT_PAGINATION_LIMIT } = queryParams, params = __rest(queryParams, ["limit"]);
18313
+ const options = token ? { token } : { limit };
18314
+ const { data: queryResponse } = await this.http.get(`/api/v3/communities`, {
18315
+ params: Object.assign(Object.assign({}, params), { isDeleted: inferIsDeleted(params.includeDeleted), keyword: params.displayName, filter: params.membership, options }),
18316
+ });
18317
+ return queryResponse;
18318
+ }
18319
+ }
18320
+
18321
+ class CommunitiesQueryStreamController$1 extends QueryStreamController {
18322
+ constructor(query, cacheKey, notifyChange, preparePayload) {
18323
+ super(query, cacheKey);
18324
+ this.notifyChange = notifyChange;
18325
+ this.preparePayload = preparePayload;
18326
+ }
18327
+ async saveToMainDB(response) {
18328
+ const processedPayload = await this.preparePayload(response);
18329
+ const client = getActiveClient();
18330
+ const cachedAt = client.cache && Date.now();
18331
+ if (client.cache) {
18332
+ ingestInCache(processedPayload, { cachedAt });
18333
+ }
18334
+ }
18335
+ appendToQueryStream(response, direction, refresh = false) {
18336
+ var _a, _b;
18337
+ if (refresh) {
18338
+ pushToCache(this.cacheKey, {
18339
+ data: response.communities.map(getResolver('community')),
18340
+ });
18341
+ }
18342
+ else {
18343
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
18344
+ const communities = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
18345
+ pushToCache(this.cacheKey, Object.assign(Object.assign({}, collection), { data: [...new Set([...communities, ...response.communities.map(getResolver('community'))])] }));
18346
+ }
18347
+ }
18348
+ reactor(action) {
18349
+ return (community) => {
18350
+ var _a;
18351
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
18352
+ if (!collection)
18353
+ return;
18354
+ pushToCache(this.cacheKey, collection);
18355
+ this.notifyChange({ origin: "event" /* Amity.LiveDataOrigin.EVENT */, loading: false });
18356
+ };
18357
+ }
18358
+ subscribeRTE(createSubscriber) {
18359
+ return createSubscriber.map(subscriber => subscriber.fn(this.reactor(subscriber.action)));
18360
+ }
18361
+ }
18362
+
18363
+ var EnumCommunityActions$4;
18364
+ (function (EnumCommunityActions) {
18365
+ EnumCommunityActions["OnCommunityCreated"] = "onCommunityCreated";
18366
+ EnumCommunityActions["OnCommunityDeleted"] = "onCommunityDeleted";
18367
+ EnumCommunityActions["OnCommunityUpdated"] = "onCommunityUpdated";
18368
+ })(EnumCommunityActions$4 || (EnumCommunityActions$4 = {}));
18369
+
18370
+ var EnumCommunityMemberActions$1;
18371
+ (function (EnumCommunityMemberActions) {
18372
+ EnumCommunityMemberActions["OnCommunityJoined"] = "onCommunityJoined";
18373
+ EnumCommunityMemberActions["OnCommunityLeft"] = "onCommunityLeft";
18374
+ EnumCommunityMemberActions["OnCommunityUserBanned"] = "onCommunityUserBanned";
18375
+ EnumCommunityMemberActions["OnCommunityUserChanged"] = "onCommunityUserChanged";
18376
+ EnumCommunityMemberActions["OnCommunityUserRoleAdded"] = "onCommunityUserRoleAdded";
18377
+ EnumCommunityMemberActions["OnCommunityUserRoleRemoved"] = "onCommunityUserRoleRemoved";
18378
+ EnumCommunityMemberActions["OnCommunityUserUnbanned"] = "onCommunityUserUnbanned";
18379
+ EnumCommunityMemberActions["OnMemberCountChanged"] = "OnMemberCountChanged";
18380
+ EnumCommunityMemberActions["OnCommunityUserAdded"] = "OnCommunityUserAdded";
18381
+ EnumCommunityMemberActions["onCommunityUserRemoved"] = "onCommunityUserRemoved";
18382
+ EnumCommunityMemberActions["OnUserDeleted"] = "OnUserDeleted";
18383
+ })(EnumCommunityMemberActions$1 || (EnumCommunityMemberActions$1 = {}));
18384
+
18385
+ /* begin_public_function
18386
+ id: community.membership.add_members
18387
+ */
18388
+ /**
18389
+ * ```js
18390
+ * import { CommunityRepository } from '@amityco/ts-sdk'
18391
+ * const updated = await CommunityRepository.moderation.addMembers(communityId, ['foo', 'bar'])
18392
+ * ```
18393
+ *
18394
+ * Adds a list of {@link Amity.InternalUser} to a {@link Amity.Community} to add users to
18395
+ *
18396
+ * @param communityId The ID of the {@link Amity.Community} to perform
18397
+ * @param userIds The list of IDs {@link Amity.InternalUser} to add
18398
+ * @returns A success boolean if the {@link Amity.InternalUser} were added to the {@link Amity.Community}
18399
+ *
18400
+ * @category Community API
18401
+ * @async
18402
+ */
18403
+ const addMembers = async (communityId, userIds) => {
18404
+ const client = getActiveClient();
18405
+ client.log('community/moderation/addMembers', communityId, userIds);
18406
+ const { data: payload } = await client.http.post(`/api/v3/communities/${communityId}/users`, { communityId, userIds });
18407
+ fireEvent('local.community.userAdded', payload);
18408
+ const data = prepareMembershipPayload(payload, 'communityUsers');
18409
+ if (client.cache)
18410
+ ingestInCache(data);
19151
18411
  const { communityUsers } = data;
19152
- return !!communityUsers.find(communityUser => communityUser.communityId === communityId && communityUser.communityMembership !== 'member');
18412
+ return !!communityUsers.find(communityUser => communityUser.communityId === communityId && communityUser.communityMembership === 'member');
19153
18413
  };
19154
18414
  /* end_public_function */
19155
18415
 
19156
18416
  /* begin_public_function
19157
- id: community.query.trending_communities
18417
+ id: community.membership.remove_member
19158
18418
  */
19159
18419
  /**
19160
- * @deprecated This API renamed to `getTrendingCommunities()`.
19161
- * Please use getTrendingCommunities() instead.
19162
- *
19163
18420
  * ```js
19164
18421
  * import { CommunityRepository } from '@amityco/ts-sdk'
19165
- * const trendingCommunities = await CommunityRepository.getTrendingCommunities()
18422
+ * const updated = await CommunityRepository.moderation.removeMembers(communityId, ['foo', 'bar'])
19166
18423
  * ```
19167
18424
  *
19168
- * Gets a list of top trending {@link Amity.Community} objects
18425
+ * Removes a list of {@link Amity.InternalUser} from a {@link Amity.Community}
19169
18426
  *
19170
- * @param query The query parameters
19171
- * @returns A list of {@link Amity.Community} objects
18427
+ * @param communityId The ID of the {@link Amity.Community} to edit
18428
+ * @param userIds The list of IDs {@link Amity.InternalUser} to remove
18429
+ * @returns A success boolean if the list of {@link Amity.InternalUser} were removed from the {@link Amity.Community}
19172
18430
  *
19173
18431
  * @category Community API
19174
18432
  * @async
19175
18433
  */
19176
- const getTopTrendingCommunities = async (query) => {
18434
+ const removeMembers = async (communityId, userIds) => {
19177
18435
  const client = getActiveClient();
19178
- client.log('channel/getTopTrendingCommunities', query);
19179
- const { limit = 5 } = query !== null && query !== void 0 ? query : {};
19180
- // API-FIX: backend doesnt answer Amity.Response
19181
- // const { data } = await client.http.get<Amity.Response<CommunityPayload>>(
19182
- const { data: payload } = await client.http.get(`/api/v3/communities/top-trending`, { params: { options: { limit } } });
19183
- const data = prepareCommunityPayload(payload);
19184
- const { communities } = data;
19185
- const cachedAt = client.cache && Date.now();
19186
- if (client.cache) {
19187
- ingestInCache(data, { cachedAt });
19188
- const cacheKey = ['community', 'top-trending', { params: { options: { limit } } }];
19189
- pushToCache(cacheKey, { communities: communities.map(getResolver('community')) });
19190
- }
19191
- return { data: communities, cachedAt };
18436
+ client.log('community/moderation/removeMembers', communityId, userIds);
18437
+ const { data: payload } = await client.http.delete(`/api/v3/communities/${communityId}/users`, { data: { communityId, userIds } });
18438
+ fireEvent('local.community.userRemoved', payload);
18439
+ const data = prepareMembershipPayload(payload, 'communityUsers');
18440
+ if (client.cache)
18441
+ ingestInCache(data);
18442
+ const { communityUsers } = data;
18443
+ return !!communityUsers.find(communityUser => communityUser.communityId === communityId && communityUser.communityMembership !== 'member');
19192
18444
  };
19193
- /* end_public_function */
18445
+ /* end_public_function */
18446
+
19194
18447
  /**
19195
- * ```js
19196
- * import { getTopTrendingCommunities } from '@amityco/ts-sdk'
19197
- * const communities = getTopTrendingCommunities.locally()
19198
- * ```
19199
- *
19200
- * Gets a list of top trending {@link Amity.Community} objects from cache
19201
- *
19202
- * @param query The query parameters
19203
- * @returns communities
19204
- *
19205
- * @category Community API
18448
+ * TODO: handle cache receive cache option, and cache policy
18449
+ * TODO: check if querybyIds is supported
19206
18450
  */
19207
- getTopTrendingCommunities.locally = (query) => {
19208
- var _a, _b;
19209
- const client = getActiveClient();
19210
- client.log('community/getTopTrendingCommunities.locally', query);
19211
- if (!client.cache)
19212
- return;
19213
- const { limit = 5 } = query !== null && query !== void 0 ? query : {};
19214
- const queryKey = ['community', 'top-trending', { params: { options: { limit } } }];
19215
- const { data, cachedAt } = (_a = pullFromCache(queryKey)) !== null && _a !== void 0 ? _a : {};
19216
- if (!(data === null || data === void 0 ? void 0 : data.communities.length))
19217
- return;
19218
- const communities = data.communities
19219
- .map(communityId => pullFromCache(['community', 'get', communityId]))
19220
- .filter(Boolean)
19221
- .map(({ data }) => data);
19222
- return communities.length === ((_b = data === null || data === void 0 ? void 0 : data.communities) === null || _b === void 0 ? void 0 : _b.length)
19223
- ? { data: communities, cachedAt }
19224
- : undefined;
19225
- };
18451
+ class CommunityMembersPaginationController extends PaginationController {
18452
+ async getRequest(queryParams, token) {
18453
+ const { limit = COLLECTION_DEFAULT_PAGINATION_LIMIT, includeDeleted } = queryParams, params = __rest(queryParams, ["limit", "includeDeleted"]);
18454
+ const options = token ? { token } : { limit };
18455
+ const isDeleted = includeDeleted === false ? false : undefined;
18456
+ const { data: queryResponse } = await this.http.get(`/api/v3/communities/${params.communityId}/users`, {
18457
+ params: Object.assign(Object.assign({}, params), { options,
18458
+ isDeleted }),
18459
+ });
18460
+ return queryResponse;
18461
+ }
18462
+ }
19226
18463
 
19227
- const createCommunityEventSubscriber = (event, callback) => {
19228
- const client = getActiveClient();
19229
- const filter = (payload) => {
19230
- const unpackedPayload = prepareCommunityPayload(payload);
19231
- if (!client.cache) {
19232
- // TODO: here we are missing specific properties here!
19233
- callback(unpackedPayload.communities[0]);
18464
+ class CommunityMembersQueryStreamController extends QueryStreamController {
18465
+ constructor(query, cacheKey, notifyChange, preparePayload) {
18466
+ super(query, cacheKey);
18467
+ this.notifyChange = notifyChange;
18468
+ this.preparePayload = preparePayload;
18469
+ }
18470
+ async saveToMainDB(response) {
18471
+ const processedPayload = await this.preparePayload(response);
18472
+ const client = getActiveClient();
18473
+ const cachedAt = client.cache && Date.now();
18474
+ if (client.cache) {
18475
+ ingestInCache(processedPayload, { cachedAt });
18476
+ }
18477
+ }
18478
+ appendToQueryStream(response, direction, refresh = false) {
18479
+ var _a, _b;
18480
+ if (refresh) {
18481
+ pushToCache(this.cacheKey, {
18482
+ data: response.communityUsers.map(({ communityId, userId }) => getResolver('communityUsers')({ communityId, userId })),
18483
+ });
19234
18484
  }
19235
18485
  else {
19236
- ingestInCache(unpackedPayload);
19237
- const community = pullFromCache([
19238
- 'community',
19239
- 'get',
19240
- unpackedPayload.communities[0].communityId,
19241
- ]);
19242
- callback(community.data);
18486
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
18487
+ const communityUsers = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
18488
+ pushToCache(this.cacheKey, Object.assign(Object.assign({}, collection), { data: [
18489
+ ...new Set([
18490
+ ...communityUsers,
18491
+ ...response.communityUsers.map(({ communityId, userId }) => getResolver('communityUsers')({ communityId, userId })),
18492
+ ]),
18493
+ ] }));
19243
18494
  }
19244
- };
19245
- return createEventSubscriber(client, event, event, filter);
19246
- };
19247
-
19248
- /**
19249
- * ```js
19250
- * import { onCommunityCreated } from '@amityco/ts-sdk'
19251
- * const dispose = onCommunityCreated(community => {
19252
- * // ...
19253
- * })
19254
- * ```
19255
- *
19256
- * Fired when a {@link Amity.Community} have been created
19257
- *
19258
- * @param callback The function to call when the event was fired
19259
- * @returns an {@link Amity.Unsubscriber} function to stop listening
19260
- *
19261
- * @category Community Events
19262
- */
19263
- const onCommunityCreated = (callback) => createCommunityEventSubscriber('community.created', callback);
19264
-
19265
- /**
19266
- * ```js
19267
- * import { onCommunityUpdated } from '@amityco/ts-sdk'
19268
- * const dispose = onCommunityUpdated(community => {
19269
- * // ...
19270
- * })
19271
- * ```
19272
- *
19273
- * Fired when a {@link Amity.Community} has been updated
19274
- *
19275
- * @param callback The function to call when the event was fired
19276
- * @returns an {@link Amity.Unsubscriber} function to stop listening
19277
- *
19278
- * @category Community Events
19279
- */
19280
- const onCommunityUpdated = (callback) => createCommunityEventSubscriber('community.updated', callback);
19281
-
19282
- /**
19283
- * ```js
19284
- * import { onCommunityDeleted } from '@amityco/ts-sdk'
19285
- * const dispose = onCommunityDeleted(community => {
19286
- * // ...
19287
- * })
19288
- * ```
19289
- *
19290
- * Fired when a {@link Amity.Community} has been deleted
19291
- *
19292
- * @param callback The function to call when the event was fired
19293
- * @returns an {@link Amity.Unsubscriber} function to stop listening
19294
- *
19295
- * @category Community Events
19296
- */
19297
- const onCommunityDeleted = (callback) => createCommunityEventSubscriber('community.deleted', callback);
18495
+ }
18496
+ reactor(action) {
18497
+ return (community, communityMembers) => {
18498
+ var _a;
18499
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
18500
+ if (!collection)
18501
+ return;
18502
+ communityMembers.forEach(communityMember => {
18503
+ const communityMemberCacheId = getResolver('communityUsers')({
18504
+ communityId: this.query.communityId,
18505
+ userId: communityMember.userId,
18506
+ });
18507
+ if (communityMember.communityMembership === 'none') {
18508
+ collection.data = collection.data.filter(m => m !== communityMemberCacheId);
18509
+ }
18510
+ else if (!collection.data.includes(communityMemberCacheId)) {
18511
+ collection.data = [communityMemberCacheId, ...collection.data];
18512
+ }
18513
+ });
18514
+ pushToCache(this.cacheKey, collection);
18515
+ this.notifyChange({ origin: "event" /* Amity.LiveDataOrigin.EVENT */, loading: false });
18516
+ };
18517
+ }
18518
+ subscribeRTE(createSubscriber) {
18519
+ return createSubscriber.map(subscriber => subscriber.fn(this.reactor(subscriber.action)));
18520
+ }
18521
+ }
19298
18522
 
19299
18523
  function hasPermission(member, payload, permission) {
19300
18524
  if (member.permissions.some(x => x === permission)) {
@@ -19501,357 +18725,92 @@ const onCommunityUserRoleAdded = (callback) => createCommunityMemberEventSubscri
19501
18725
 
19502
18726
  /**
19503
18727
  * ```js
19504
- * import { onCommunityUserRoleRemoved } from '@amityco/ts-sdk'
19505
- * const dispose = onCommunityUserRoleRemoved((community, member) => {
19506
- * // ...
19507
- * })
19508
- * ```
19509
- *
19510
- * Fired when a role has been removed from {@link Amity.CommunityUser}
19511
- *
19512
- * @param callback The function to call when the event was fired
19513
- * @returns an {@link Amity.Unsubscriber} function to stop listening
19514
- *
19515
- * @category Community Events
19516
- */
19517
- const onCommunityUserRoleRemoved = (callback) => createCommunityMemberEventSubscriber('community.roleRemoved', callback);
19518
-
19519
- /**
19520
- * ```js
19521
- * import { onLocalCommunityUserAdded } from '@amityco/ts-sdk'
19522
- * const dispose = onLocalCommunityUserAdded((community, member) => {
19523
- * // ...
19524
- * })
19525
- * ```
19526
- *
19527
- * Fired when a user has been added to a {@link Amity.Community}
19528
- *
19529
- * @param callback The function to call when the event was fired
19530
- * @returns an {@link Amity.Unsubscriber} function to stop listening
19531
- *
19532
- * @category Community Events
19533
- */
19534
- const onLocalCommunityUserAdded = (callback) => createLocalCommunityMemberEventSubscriber('local.community.userAdded', callback);
19535
-
19536
- /**
19537
- * ```js
19538
- * import { onLocalCommunityUserRemoved } from '@amityco/ts-sdk'
19539
- * const dispose = onLocalCommunityUserRemoved((community, member) => {
19540
- * // ...
19541
- * })
19542
- * ```
19543
- *
19544
- * Fired when a user has been removed from a {@link Amity.Community}
19545
- *
19546
- * @param callback The function to call when the event was fired
19547
- * @returns an {@link Amity.Unsubscriber} function to stop listening
19548
- *
19549
- * @category Community Events
19550
- */
19551
- const onLocalCommunityUserRemoved = (callback) => createLocalCommunityMemberEventSubscriber('local.community.userRemoved', callback);
19552
-
19553
- /**
19554
- * ```js
19555
- * import { onCommunityJoined } from '@amityco/ts-sdk'
19556
- * const dispose = onCommunityJoined((community, member) => {
19557
- * // ...
19558
- * })
19559
- * ```
19560
- *
19561
- * Fired when a {@link Amity.Community} has been joined
19562
- *
19563
- * @param callback The function to call when the event was fired
19564
- * @returns an {@link Amity.Unsubscriber} function to stop listening
19565
- *
19566
- * @category Community Events
19567
- */
19568
- const onCommunityJoined = (callback) => createCommunityMemberEventSubscriber('community.joined', callback);
19569
-
19570
- /**
19571
- * ```js
19572
- * import { onCommunityLeft } from '@amityco/ts-sdk'
19573
- * const dispose = onCommunityLeft((community, member) => {
18728
+ * import { onCommunityUserRoleRemoved } from '@amityco/ts-sdk'
18729
+ * const dispose = onCommunityUserRoleRemoved((community, member) => {
19574
18730
  * // ...
19575
18731
  * })
19576
18732
  * ```
19577
18733
  *
19578
- * Fired when a {@link Amity.Community} has been left
18734
+ * Fired when a role has been removed from {@link Amity.CommunityUser}
19579
18735
  *
19580
18736
  * @param callback The function to call when the event was fired
19581
18737
  * @returns an {@link Amity.Unsubscriber} function to stop listening
19582
18738
  *
19583
18739
  * @category Community Events
19584
18740
  */
19585
- const onCommunityLeft = (callback) => createCommunityMemberEventSubscriber('community.left', callback);
19586
-
19587
- const onLocalCommunityJoined = (callback) => createLocalCommunityMemberEventSubscriber('local.community.joined', callback);
19588
-
19589
- const onLocalCommunityLeft = (callback) => createLocalCommunityMemberEventSubscriber('local.community.left', callback);
18741
+ const onCommunityUserRoleRemoved = (callback) => createCommunityMemberEventSubscriber('community.roleRemoved', callback);
19590
18742
 
19591
18743
  /**
19592
18744
  * ```js
19593
- * import { observeCommunity } from '@amityco/ts-sdk'
19594
- *
19595
- * let community = {}
19596
- * const dispose = observeCommunity(communityId, updated => community = updated)
18745
+ * import { onLocalCommunityUserAdded } from '@amityco/ts-sdk'
18746
+ * const dispose = onLocalCommunityUserAdded((community, member) => {
18747
+ * // ...
18748
+ * })
19597
18749
  * ```
19598
18750
  *
19599
- * Observe all mutation on a given {@link Amity.Community}
18751
+ * Fired when a user has been added to a {@link Amity.Community}
19600
18752
  *
19601
- * @param communityId the ID of the community to observe
19602
- * @param callback the function to call when new data are available
19603
- * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the community
18753
+ * @param callback The function to call when the event was fired
18754
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
19604
18755
  *
19605
- * @category Community Observer
19606
- */
19607
- const observeCommunity = (communityId, callback) => {
19608
- const { log } = getActiveClient();
19609
- const timestamp = Date.now();
19610
- log(`observeCommunity(tmpid: ${timestamp}) > listen`);
19611
- // wrapper function to make sure
19612
- const router = (result, action) => {
19613
- var _a, _b;
19614
- if (callback instanceof Function)
19615
- return callback(result);
19616
- if (action !== 'onFetch')
19617
- (_a = callback.onEvent) === null || _a === void 0 ? void 0 : _a.call(callback, action, result);
19618
- (_b = callback[action]) === null || _b === void 0 ? void 0 : _b.call(callback, result);
19619
- };
19620
- const realtimeRouter = (result, action) => {
19621
- var _a;
19622
- if (((_a = result.data) === null || _a === void 0 ? void 0 : _a.communityId) !== communityId)
19623
- return;
19624
- router(result, action);
19625
- };
19626
- const disposers = [];
19627
- disposers.push(onCommunityUpdated(data => realtimeRouter({ data, loading: false, origin: 'event' }, 'onUpdate')), onCommunityDeleted(data => realtimeRouter({ data, loading: false, origin: 'event' }, 'onDelete')), onCommunityJoined(data => realtimeRouter({ data, loading: false, origin: 'event' }, 'onJoin')), onCommunityLeft(data => realtimeRouter({ data, loading: false, origin: 'event' }, 'onLeft')), onCommunityUserAdded(data => realtimeRouter({ data, loading: false, origin: 'event' }, 'onUserAdded')), onCommunityUserRemoved(data => realtimeRouter({ data, loading: false, origin: 'event' }, 'onUserRemoved')), onCommunityUserBanned(data => realtimeRouter({ data, loading: false, origin: 'event' }, 'onUserBanned')), onCommunityUserUnbanned(data => realtimeRouter({ data, loading: false, origin: 'event' }, 'onUserUnbanned')));
19628
- runQuery(createQuery(getCommunity$1, communityId), result => (result.data || result.error) && router(result, 'onFetch'));
19629
- return () => {
19630
- log(`observeCommunity(tmpid: ${timestamp}) > dispose`);
19631
- disposers.forEach(fn => fn());
19632
- };
19633
- };
19634
-
19635
- /**
19636
- * TODO: handle cache receive cache option, and cache policy
19637
- * TODO: check if querybyIds is supported
18756
+ * @category Community Events
19638
18757
  */
19639
- class CommunitiesPaginationController$1 extends PaginationController {
19640
- async getRequest(queryParams, token) {
19641
- const { limit = COLLECTION_DEFAULT_PAGINATION_LIMIT } = queryParams, params = __rest(queryParams, ["limit"]);
19642
- const options = token ? { token } : { limit };
19643
- const { data: queryResponse } = await this.http.get(`/api/v3/communities`, {
19644
- params: Object.assign(Object.assign({}, params), { isDeleted: inferIsDeleted(params.includeDeleted), keyword: params.displayName, filter: params.membership, options }),
19645
- });
19646
- return queryResponse;
19647
- }
19648
- }
19649
-
19650
- class CommunitiesQueryStreamController$1 extends QueryStreamController {
19651
- constructor(query, cacheKey, notifyChange, preparePayload) {
19652
- super(query, cacheKey);
19653
- this.notifyChange = notifyChange;
19654
- this.preparePayload = preparePayload;
19655
- }
19656
- async saveToMainDB(response) {
19657
- const processedPayload = await this.preparePayload(response);
19658
- const client = getActiveClient();
19659
- const cachedAt = client.cache && Date.now();
19660
- if (client.cache) {
19661
- ingestInCache(processedPayload, { cachedAt });
19662
- }
19663
- }
19664
- appendToQueryStream(response, direction, refresh = false) {
19665
- var _a, _b;
19666
- if (refresh) {
19667
- pushToCache(this.cacheKey, {
19668
- data: response.communities.map(getResolver('community')),
19669
- });
19670
- }
19671
- else {
19672
- const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
19673
- const communities = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
19674
- pushToCache(this.cacheKey, Object.assign(Object.assign({}, collection), { data: [...new Set([...communities, ...response.communities.map(getResolver('community'))])] }));
19675
- }
19676
- }
19677
- reactor(action) {
19678
- return (community) => {
19679
- var _a;
19680
- const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
19681
- if (!collection)
19682
- return;
19683
- pushToCache(this.cacheKey, collection);
19684
- this.notifyChange({ origin: "event" /* Amity.LiveDataOrigin.EVENT */, loading: false });
19685
- };
19686
- }
19687
- subscribeRTE(createSubscriber) {
19688
- return createSubscriber.map(subscriber => subscriber.fn(this.reactor(subscriber.action)));
19689
- }
19690
- }
19691
-
19692
- var EnumCommunityActions$4;
19693
- (function (EnumCommunityActions) {
19694
- EnumCommunityActions["OnCommunityCreated"] = "onCommunityCreated";
19695
- EnumCommunityActions["OnCommunityDeleted"] = "onCommunityDeleted";
19696
- EnumCommunityActions["OnCommunityUpdated"] = "onCommunityUpdated";
19697
- })(EnumCommunityActions$4 || (EnumCommunityActions$4 = {}));
19698
-
19699
- var EnumCommunityMemberActions$1;
19700
- (function (EnumCommunityMemberActions) {
19701
- EnumCommunityMemberActions["OnCommunityJoined"] = "onCommunityJoined";
19702
- EnumCommunityMemberActions["OnCommunityLeft"] = "onCommunityLeft";
19703
- EnumCommunityMemberActions["OnCommunityUserBanned"] = "onCommunityUserBanned";
19704
- EnumCommunityMemberActions["OnCommunityUserChanged"] = "onCommunityUserChanged";
19705
- EnumCommunityMemberActions["OnCommunityUserRoleAdded"] = "onCommunityUserRoleAdded";
19706
- EnumCommunityMemberActions["OnCommunityUserRoleRemoved"] = "onCommunityUserRoleRemoved";
19707
- EnumCommunityMemberActions["OnCommunityUserUnbanned"] = "onCommunityUserUnbanned";
19708
- EnumCommunityMemberActions["OnMemberCountChanged"] = "OnMemberCountChanged";
19709
- EnumCommunityMemberActions["OnCommunityUserAdded"] = "OnCommunityUserAdded";
19710
- EnumCommunityMemberActions["onCommunityUserRemoved"] = "onCommunityUserRemoved";
19711
- EnumCommunityMemberActions["OnUserDeleted"] = "OnUserDeleted";
19712
- })(EnumCommunityMemberActions$1 || (EnumCommunityMemberActions$1 = {}));
18758
+ const onLocalCommunityUserAdded = (callback) => createLocalCommunityMemberEventSubscriber('local.community.userAdded', callback);
19713
18759
 
19714
- /* begin_public_function
19715
- id: community.membership.add_members
19716
- */
19717
18760
  /**
19718
18761
  * ```js
19719
- * import { CommunityRepository } from '@amityco/ts-sdk'
19720
- * const updated = await CommunityRepository.moderation.addMembers(communityId, ['foo', 'bar'])
18762
+ * import { onLocalCommunityUserRemoved } from '@amityco/ts-sdk'
18763
+ * const dispose = onLocalCommunityUserRemoved((community, member) => {
18764
+ * // ...
18765
+ * })
19721
18766
  * ```
19722
18767
  *
19723
- * Adds a list of {@link Amity.InternalUser} to a {@link Amity.Community} to add users to
18768
+ * Fired when a user has been removed from a {@link Amity.Community}
19724
18769
  *
19725
- * @param communityId The ID of the {@link Amity.Community} to perform
19726
- * @param userIds The list of IDs {@link Amity.InternalUser} to add
19727
- * @returns A success boolean if the {@link Amity.InternalUser} were added to the {@link Amity.Community}
18770
+ * @param callback The function to call when the event was fired
18771
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
19728
18772
  *
19729
- * @category Community API
19730
- * @async
18773
+ * @category Community Events
19731
18774
  */
19732
- const addMembers = async (communityId, userIds) => {
19733
- const client = getActiveClient();
19734
- client.log('community/moderation/addMembers', communityId, userIds);
19735
- const { data: payload } = await client.http.post(`/api/v3/communities/${communityId}/users`, { communityId, userIds });
19736
- fireEvent('local.community.userAdded', payload);
19737
- const data = prepareMembershipPayload(payload, 'communityUsers');
19738
- if (client.cache)
19739
- ingestInCache(data);
19740
- const { communityUsers } = data;
19741
- return !!communityUsers.find(communityUser => communityUser.communityId === communityId && communityUser.communityMembership === 'member');
19742
- };
19743
- /* end_public_function */
18775
+ const onLocalCommunityUserRemoved = (callback) => createLocalCommunityMemberEventSubscriber('local.community.userRemoved', callback);
19744
18776
 
19745
- /* begin_public_function
19746
- id: community.membership.remove_member
19747
- */
19748
18777
  /**
19749
18778
  * ```js
19750
- * import { CommunityRepository } from '@amityco/ts-sdk'
19751
- * const updated = await CommunityRepository.moderation.removeMembers(communityId, ['foo', 'bar'])
18779
+ * import { onCommunityJoined } from '@amityco/ts-sdk'
18780
+ * const dispose = onCommunityJoined((community, member) => {
18781
+ * // ...
18782
+ * })
19752
18783
  * ```
19753
- *
19754
- * Removes a list of {@link Amity.InternalUser} from a {@link Amity.Community}
19755
- *
19756
- * @param communityId The ID of the {@link Amity.Community} to edit
19757
- * @param userIds The list of IDs {@link Amity.InternalUser} to remove
19758
- * @returns A success boolean if the list of {@link Amity.InternalUser} were removed from the {@link Amity.Community}
19759
- *
19760
- * @category Community API
19761
- * @async
19762
- */
19763
- const removeMembers = async (communityId, userIds) => {
19764
- const client = getActiveClient();
19765
- client.log('community/moderation/removeMembers', communityId, userIds);
19766
- const { data: payload } = await client.http.delete(`/api/v3/communities/${communityId}/users`, { data: { communityId, userIds } });
19767
- fireEvent('local.community.userRemoved', payload);
19768
- const data = prepareMembershipPayload(payload, 'communityUsers');
19769
- if (client.cache)
19770
- ingestInCache(data);
19771
- const { communityUsers } = data;
19772
- return !!communityUsers.find(communityUser => communityUser.communityId === communityId && communityUser.communityMembership !== 'member');
19773
- };
19774
- /* end_public_function */
19775
-
19776
- /**
19777
- * TODO: handle cache receive cache option, and cache policy
19778
- * TODO: check if querybyIds is supported
19779
- */
19780
- class CommunityMembersPaginationController extends PaginationController {
19781
- async getRequest(queryParams, token) {
19782
- const { limit = COLLECTION_DEFAULT_PAGINATION_LIMIT, includeDeleted } = queryParams, params = __rest(queryParams, ["limit", "includeDeleted"]);
19783
- const options = token ? { token } : { limit };
19784
- const isDeleted = includeDeleted === false ? false : undefined;
19785
- const { data: queryResponse } = await this.http.get(`/api/v3/communities/${params.communityId}/users`, {
19786
- params: Object.assign(Object.assign({}, params), { options,
19787
- isDeleted }),
19788
- });
19789
- return queryResponse;
19790
- }
19791
- }
19792
-
19793
- class CommunityMembersQueryStreamController extends QueryStreamController {
19794
- constructor(query, cacheKey, notifyChange, preparePayload) {
19795
- super(query, cacheKey);
19796
- this.notifyChange = notifyChange;
19797
- this.preparePayload = preparePayload;
19798
- }
19799
- async saveToMainDB(response) {
19800
- const processedPayload = await this.preparePayload(response);
19801
- const client = getActiveClient();
19802
- const cachedAt = client.cache && Date.now();
19803
- if (client.cache) {
19804
- ingestInCache(processedPayload, { cachedAt });
19805
- }
19806
- }
19807
- appendToQueryStream(response, direction, refresh = false) {
19808
- var _a, _b;
19809
- if (refresh) {
19810
- pushToCache(this.cacheKey, {
19811
- data: response.communityUsers.map(({ communityId, userId }) => getResolver('communityUsers')({ communityId, userId })),
19812
- });
19813
- }
19814
- else {
19815
- const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
19816
- const communityUsers = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
19817
- pushToCache(this.cacheKey, Object.assign(Object.assign({}, collection), { data: [
19818
- ...new Set([
19819
- ...communityUsers,
19820
- ...response.communityUsers.map(({ communityId, userId }) => getResolver('communityUsers')({ communityId, userId })),
19821
- ]),
19822
- ] }));
19823
- }
19824
- }
19825
- reactor(action) {
19826
- return (community, communityMembers) => {
19827
- var _a;
19828
- const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
19829
- if (!collection)
19830
- return;
19831
- if (action === EnumCommunityMemberActions$1.OnCommunityUserRoleAdded &&
19832
- this.query.sortBy === 'displayName') {
19833
- return;
19834
- }
19835
- communityMembers.forEach(communityMember => {
19836
- const communityMemberCacheId = getResolver('communityUsers')({
19837
- communityId: this.query.communityId,
19838
- userId: communityMember.userId,
19839
- });
19840
- if (communityMember.communityMembership === 'none') {
19841
- collection.data = collection.data.filter(m => m !== communityMemberCacheId);
19842
- }
19843
- else if (!collection.data.includes(communityMemberCacheId)) {
19844
- collection.data = [communityMemberCacheId, ...collection.data];
19845
- }
19846
- });
19847
- pushToCache(this.cacheKey, collection);
19848
- this.notifyChange({ origin: "event" /* Amity.LiveDataOrigin.EVENT */, loading: false });
19849
- };
19850
- }
19851
- subscribeRTE(createSubscriber) {
19852
- return createSubscriber.map(subscriber => subscriber.fn(this.reactor(subscriber.action)));
19853
- }
19854
- }
18784
+ *
18785
+ * Fired when a {@link Amity.Community} has been joined
18786
+ *
18787
+ * @param callback The function to call when the event was fired
18788
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
18789
+ *
18790
+ * @category Community Events
18791
+ */
18792
+ const onCommunityJoined = (callback) => createCommunityMemberEventSubscriber('community.joined', callback);
18793
+
18794
+ /**
18795
+ * ```js
18796
+ * import { onCommunityLeft } from '@amityco/ts-sdk'
18797
+ * const dispose = onCommunityLeft((community, member) => {
18798
+ * // ...
18799
+ * })
18800
+ * ```
18801
+ *
18802
+ * Fired when a {@link Amity.Community} has been left
18803
+ *
18804
+ * @param callback The function to call when the event was fired
18805
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
18806
+ *
18807
+ * @category Community Events
18808
+ */
18809
+ const onCommunityLeft = (callback) => createCommunityMemberEventSubscriber('community.left', callback);
18810
+
18811
+ const onLocalCommunityJoined = (callback) => createLocalCommunityMemberEventSubscriber('local.community.joined', callback);
18812
+
18813
+ const onLocalCommunityLeft = (callback) => createLocalCommunityMemberEventSubscriber('local.community.left', callback);
19855
18814
 
19856
18815
  /**
19857
18816
  * ```js
@@ -20030,9 +18989,6 @@ class CommunityMembersLiveCollectionController extends LiveCollectionController
20030
18989
  return memberships.includes(communityMembership);
20031
18990
  });
20032
18991
  }
20033
- if (this.query.search) {
20034
- communityMembers = filterBySearchTerm(communityMembers, this.query.search);
20035
- }
20036
18992
  if (this.query.includeDeleted === false) {
20037
18993
  communityMembers = communityMembers.filter(({ user }) => (user === null || user === void 0 ? void 0 : user.isDeleted) !== true);
20038
18994
  }
@@ -20040,15 +18996,6 @@ class CommunityMembersLiveCollectionController extends LiveCollectionController
20040
18996
  case 'firstCreated':
20041
18997
  communityMembers = communityMembers.sort(sortByFirstCreated);
20042
18998
  break;
20043
- case 'displayName':
20044
- communityMembers = communityMembers.sort((a, b) => {
20045
- var _a, _b, _c, _d;
20046
- if (((_a = a === null || a === void 0 ? void 0 : a.user) === null || _a === void 0 ? void 0 : _a.displayName) && ((_b = b === null || b === void 0 ? void 0 : b.user) === null || _b === void 0 ? void 0 : _b.displayName)) {
20047
- return (_c = a === null || a === void 0 ? void 0 : a.user) === null || _c === void 0 ? void 0 : _c.displayName.localeCompare((_d = b === null || b === void 0 ? void 0 : b.user) === null || _d === void 0 ? void 0 : _d.displayName);
20048
- }
20049
- return 0;
20050
- });
20051
- break;
20052
18999
  case 'lastCreated':
20053
19000
  default:
20054
19001
  communityMembers = communityMembers.sort(sortByLastCreated);
@@ -20070,9 +19017,6 @@ const applyFilter = (data, params) => {
20070
19017
  return membership.includes(communityMembership);
20071
19018
  });
20072
19019
  }
20073
- if (params.search) {
20074
- communityMembers = filterBySearchTerm(communityMembers, params.search);
20075
- }
20076
19020
  const sortBy = params.sortBy ? params.sortBy : 'lastCreated';
20077
19021
  communityMembers = communityMembers.sort(sortBy === 'lastCreated' ? sortByLastCreated : sortByFirstCreated);
20078
19022
  return communityMembers;
@@ -20481,19 +19425,12 @@ class CommunitiesPaginationController extends PaginationController {
20481
19425
  const { limit = COLLECTION_DEFAULT_PAGINATION_LIMIT } = queryParams, params = __rest(queryParams, ["limit"]);
20482
19426
  const options = token ? { token } : { limit };
20483
19427
  const { data: queryResponse } = await this.http.get(`/api/v3/communities`, {
20484
- params: Object.assign(Object.assign({}, params), { isDeleted: inferIsDeleted(params.includeDeleted), keyword: params.displayName, filter: params.membership, options }),
19428
+ params: Object.assign(Object.assign({}, params), { isDeleted: inferIsDeleted(params.includeDeleted), filter: params.membership, options }),
20485
19429
  });
20486
19430
  return queryResponse;
20487
19431
  }
20488
19432
  }
20489
19433
 
20490
- var EnumCommunityActions$3;
20491
- (function (EnumCommunityActions) {
20492
- EnumCommunityActions["OnCommunityCreated"] = "onCommunityCreated";
20493
- EnumCommunityActions["OnCommunityDeleted"] = "onCommunityDeleted";
20494
- EnumCommunityActions["OnCommunityUpdated"] = "onCommunityUpdated";
20495
- })(EnumCommunityActions$3 || (EnumCommunityActions$3 = {}));
20496
-
20497
19434
  class CommunitiesQueryStreamController extends QueryStreamController {
20498
19435
  constructor(query, cacheKey, notifyChange, preparePayload) {
20499
19436
  super(query, cacheKey);
@@ -20528,9 +19465,6 @@ class CommunitiesQueryStreamController extends QueryStreamController {
20528
19465
  const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
20529
19466
  if (!collection)
20530
19467
  return;
20531
- if (this.query.displayName && action === EnumCommunityActions$3.OnCommunityCreated) {
20532
- return;
20533
- }
20534
19468
  /*
20535
19469
  * Simply update a collection and let responder decide what to do with data
20536
19470
  */
@@ -20544,6 +19478,13 @@ class CommunitiesQueryStreamController extends QueryStreamController {
20544
19478
  }
20545
19479
  }
20546
19480
 
19481
+ var EnumCommunityActions$3;
19482
+ (function (EnumCommunityActions) {
19483
+ EnumCommunityActions["OnCommunityCreated"] = "onCommunityCreated";
19484
+ EnumCommunityActions["OnCommunityDeleted"] = "onCommunityDeleted";
19485
+ EnumCommunityActions["OnCommunityUpdated"] = "onCommunityUpdated";
19486
+ })(EnumCommunityActions$3 || (EnumCommunityActions$3 = {}));
19487
+
20547
19488
  class CommunityLiveCollectionController extends LiveCollectionController {
20548
19489
  constructor(query, callback) {
20549
19490
  const queryStreamId = hash__default["default"](query);
@@ -20617,21 +19558,17 @@ class CommunityLiveCollectionController extends LiveCollectionController {
20617
19558
  if (this.query.membership && userId) {
20618
19559
  communities = filterByCommunityMembership(communities, this.query.membership, userId);
20619
19560
  }
20620
- if (!this.query.displayName) {
20621
- const sortFn = (() => {
20622
- switch (this.query.sortBy) {
20623
- case 'firstCreated':
20624
- return sortByFirstCreated;
20625
- case 'lastCreated':
20626
- return sortByLastCreated;
20627
- case 'displayName':
20628
- return sortByDisplayName;
20629
- default:
20630
- return sortByLastCreated;
20631
- }
20632
- })();
20633
- communities = communities.sort(sortFn);
20634
- }
19561
+ const sortFn = (() => {
19562
+ switch (this.query.sortBy) {
19563
+ case 'firstCreated':
19564
+ return sortByFirstCreated;
19565
+ case 'lastCreated':
19566
+ return sortByLastCreated;
19567
+ default:
19568
+ return sortByLastCreated;
19569
+ }
19570
+ })();
19571
+ communities = communities.sort(sortFn);
20635
19572
  return communities;
20636
19573
  }
20637
19574
  }
@@ -21385,11 +20322,9 @@ var index$9 = /*#__PURE__*/Object.freeze({
21385
20322
  deleteCommunity: deleteCommunity,
21386
20323
  joinCommunity: joinCommunity,
21387
20324
  leaveCommunity: leaveCommunity,
21388
- getTopTrendingCommunities: getTopTrendingCommunities,
21389
20325
  onCommunityCreated: onCommunityCreated,
21390
20326
  onCommunityUpdated: onCommunityUpdated,
21391
20327
  onCommunityDeleted: onCommunityDeleted,
21392
- observeCommunity: observeCommunity,
21393
20328
  searchCommunities: searchCommunities,
21394
20329
  getCommunities: getCommunities,
21395
20330
  getCommunity: getCommunity,
@@ -21639,21 +20574,10 @@ var index$8 = /*#__PURE__*/Object.freeze({
21639
20574
  const queryGlobalFeed = async (query) => {
21640
20575
  const client = getActiveClient();
21641
20576
  client.log('feed/queryGlobalFeed', query);
21642
- const _a = query !== null && query !== void 0 ? query : {}, { useCustomRanking, page, queryToken } = _a, params = __rest(_a, ["useCustomRanking", "page", "queryToken"]);
21643
- /*
21644
- * TODO: Remove useCustomRanking key from query
21645
- */
21646
- if (useCustomRanking)
21647
- console.warn('The param "useCustomRanking" has been deprecated. To get custom ranking feed use FeedRepository.getCustomRankingGlobalFeed instead');
21648
- if (page)
21649
- console.warn('The param "page" has been deprecated. Please use "queryToken" instead.');
20577
+ const _a = query !== null && query !== void 0 ? query : {}, { queryToken } = _a, params = __rest(_a, ["queryToken"]);
21650
20578
  const options = (() => {
21651
20579
  if (queryToken)
21652
20580
  return { token: queryToken };
21653
- if (page)
21654
- return {
21655
- token: toToken(page, 'skiplimit'),
21656
- };
21657
20581
  return undefined;
21658
20582
  })();
21659
20583
  const { data: queryPayload } = await client.http.get(`/api/v4/me/global-feeds`, {
@@ -21666,20 +20590,12 @@ const queryGlobalFeed = async (query) => {
21666
20590
  const cachedAt = client.cache && Date.now();
21667
20591
  if (client.cache) {
21668
20592
  ingestInCache(Object.assign(Object.assign({}, data), { communitis: processedCommunity }));
21669
- const cacheKey = [
21670
- 'globalFeed',
21671
- 'query',
21672
- Object.assign(Object.assign({}, params), { options: Object.assign({}, page) }),
21673
- ];
20593
+ const cacheKey = ['globalFeed', 'query', Object.assign(Object.assign({}, params), { options })];
21674
20594
  pushToCache(cacheKey, { posts: posts.map(getResolver('post')), paging });
21675
20595
  }
21676
- const nextPage = toPage(paging.next);
21677
- const prevPage = toPage(paging.previous);
21678
20596
  return {
21679
20597
  data: posts.map(LinkedObject.post),
21680
20598
  cachedAt,
21681
- prevPage,
21682
- nextPage,
21683
20599
  paging,
21684
20600
  };
21685
20601
  };
@@ -21704,12 +20620,8 @@ queryGlobalFeed.locally = (query) => {
21704
20620
  client.log('post/queryGlobalFeed.locally', query);
21705
20621
  if (!client.cache)
21706
20622
  return;
21707
- const _c = query !== null && query !== void 0 ? query : {}, { page } = _c, params = __rest(_c, ["page"]);
21708
- const queryKey = [
21709
- 'globalFeed',
21710
- 'query',
21711
- Object.assign(Object.assign({}, params), { options: Object.assign({}, page) }),
21712
- ];
20623
+ const params = __rest(query !== null && query !== void 0 ? query : {}, []);
20624
+ const queryKey = ['globalFeed', 'query', Object.assign({}, params)];
21713
20625
  const { data, cachedAt } = (_a = pullFromCache(queryKey)) !== null && _a !== void 0 ? _a : {};
21714
20626
  if (!(data === null || data === void 0 ? void 0 : data.posts.length))
21715
20627
  return;
@@ -21719,14 +20631,10 @@ queryGlobalFeed.locally = (query) => {
21719
20631
  .map(({ data }) => data)
21720
20632
  .map(LinkedObject.post);
21721
20633
  const { paging } = data;
21722
- const prevPage = toPage(data === null || data === void 0 ? void 0 : data.paging.previous);
21723
- const nextPage = toPage(data === null || data === void 0 ? void 0 : data.paging.next);
21724
20634
  return posts.length === ((_b = data === null || data === void 0 ? void 0 : data.posts) === null || _b === void 0 ? void 0 : _b.length)
21725
20635
  ? {
21726
20636
  data: posts,
21727
20637
  cachedAt,
21728
- prevPage,
21729
- nextPage,
21730
20638
  paging,
21731
20639
  }
21732
20640
  : undefined;
@@ -21752,14 +20660,10 @@ queryGlobalFeed.locally = (query) => {
21752
20660
  const getCustomRankingGlobalFeed = async (query) => {
21753
20661
  const client = getActiveClient();
21754
20662
  client.log('feed/getCustomRankingGlobalFeed', query);
21755
- const _a = query !== null && query !== void 0 ? query : {}, { page, queryToken, limit } = _a, params = __rest(_a, ["page", "queryToken", "limit"]);
20663
+ const _a = query !== null && query !== void 0 ? query : {}, { queryToken, limit } = _a, params = __rest(_a, ["queryToken", "limit"]);
21756
20664
  const options = (() => {
21757
20665
  if (queryToken)
21758
20666
  return { token: queryToken };
21759
- if (page)
21760
- return {
21761
- token: toToken(page, 'skiplimit'),
21762
- };
21763
20667
  return undefined;
21764
20668
  })();
21765
20669
  const { data: queryPayload } = await client.http.get(`/api/v5/me/global-feeds`, {
@@ -21771,16 +20675,10 @@ const getCustomRankingGlobalFeed = async (query) => {
21771
20675
  const cachedAt = client.cache && Date.now();
21772
20676
  if (client.cache) {
21773
20677
  ingestInCache(data);
21774
- const cacheKey = [
21775
- 'customGlobalFeed',
21776
- 'query',
21777
- Object.assign(Object.assign({}, params), { options: Object.assign({}, page) }),
21778
- ];
20678
+ const cacheKey = ['customGlobalFeed', 'query', Object.assign(Object.assign({}, params), { options })];
21779
20679
  pushToCache(cacheKey, { posts: posts.map(getResolver('post')), paging });
21780
20680
  }
21781
- const nextPage = toPage(paging.next);
21782
- const prevPage = toPage(paging.previous);
21783
- return { data: posts.map(LinkedObject.post), cachedAt, prevPage, nextPage, paging };
20681
+ return { data: posts.map(LinkedObject.post), cachedAt, paging };
21784
20682
  };
21785
20683
  /* end_public_function */
21786
20684
  /**
@@ -21803,12 +20701,8 @@ getCustomRankingGlobalFeed.locally = (query) => {
21803
20701
  client.log('post/getCustomRankingGlobalFeed.locally', query);
21804
20702
  if (!client.cache)
21805
20703
  return;
21806
- const _c = query !== null && query !== void 0 ? query : {}, { page } = _c, params = __rest(_c, ["page"]);
21807
- const queryKey = [
21808
- 'customGlobalFeed',
21809
- 'query',
21810
- Object.assign(Object.assign({}, params), { options: Object.assign({}, page) }),
21811
- ];
20704
+ const params = __rest(query !== null && query !== void 0 ? query : {}, []);
20705
+ const queryKey = ['customGlobalFeed', 'query', Object.assign({}, params)];
21812
20706
  const { data, cachedAt } = (_a = pullFromCache(queryKey)) !== null && _a !== void 0 ? _a : {};
21813
20707
  if (!(data === null || data === void 0 ? void 0 : data.posts.length))
21814
20708
  return;
@@ -21816,11 +20710,9 @@ getCustomRankingGlobalFeed.locally = (query) => {
21816
20710
  .map(postId => pullFromCache(['post', 'get', postId]))
21817
20711
  .filter(Boolean)
21818
20712
  .map(({ data }) => data);
21819
- const prevPage = toPage(data === null || data === void 0 ? void 0 : data.paging.previous);
21820
- const nextPage = toPage(data === null || data === void 0 ? void 0 : data.paging.next);
21821
20713
  const { paging } = data;
21822
20714
  return posts.length === ((_b = data === null || data === void 0 ? void 0 : data.posts) === null || _b === void 0 ? void 0 : _b.length)
21823
- ? { data: posts.map(LinkedObject.post), cachedAt, prevPage, nextPage, paging }
20715
+ ? { data: posts.map(LinkedObject.post), cachedAt, paging }
21824
20716
  : undefined;
21825
20717
  };
21826
20718
 
@@ -21951,44 +20843,6 @@ const createPost = async (bundle) => {
21951
20843
  };
21952
20844
  /* end_public_function */
21953
20845
 
21954
- /* begin_public_function
21955
- id: post.edit
21956
- */
21957
- /**
21958
- * ```js
21959
- * import { updatePost } from '@amityco/ts-sdk'
21960
- * const updated = await updatePost(postId, {
21961
- * data: { text: 'hello world' }
21962
- * })
21963
- * ```
21964
- *
21965
- * Updates an {@link Amity.Post}
21966
- *
21967
- * @param postId The ID of the {@link Amity.Post} to edit
21968
- * @param patch The patch data to apply
21969
- * @returns the updated {@link Amity.Post} object
21970
- *
21971
- * @category Post API
21972
- * @async
21973
- */
21974
- const updatePost = async (postId, patch) => {
21975
- const client = getActiveClient();
21976
- client.log('user/updatePost', patch);
21977
- console.warn('Deprecation: updatePost has been renamed to editPost. Update post API will be deprecated soon.');
21978
- const { data: payload } = await client.http.put(`/api/v4/posts/${encodeURIComponent(postId)}`, patch);
21979
- const data = prepareMembershipPayload(payload, 'communityUsers');
21980
- const cachedAt = client.cache && Date.now();
21981
- if (client.cache)
21982
- ingestInCache(data, { cachedAt });
21983
- fireEvent('local.post.updated', payload);
21984
- const { posts } = data;
21985
- return {
21986
- data: LinkedObject.post(posts.find(post => post.postId === postId)),
21987
- cachedAt,
21988
- };
21989
- };
21990
- /* end_public_function */
21991
-
21992
20846
  /* begin_public_function
21993
20847
  id: post.edit, post.edit.custom_post
21994
20848
  */
@@ -22306,91 +21160,6 @@ const isPostFlaggedByMe = async (postId) => {
22306
21160
  };
22307
21161
  /* end_public_function */
22308
21162
 
22309
- /**
22310
- * ```js
22311
- * import { PostRepository } from '@amityco/ts-sdk'
22312
- *
22313
- * let posts = []
22314
- * const unsub = PostRepository.observePosts({
22315
- * targetType: Amity.PostTargetType,
22316
- * targetId: Amity.InternalPost['targetId'],
22317
- * }, post => merge(posts, post))
22318
- * ```
22319
- *
22320
- * Observe all mutations on a list of {@link Amity.Post} for a given target object
22321
- *
22322
- * @param params
22323
- * @param callback the function to call when new data are available
22324
- * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the messages
22325
- *
22326
- * @category Post Observer
22327
- */
22328
- const observePosts = (params, callback) => {
22329
- const { log } = getActiveClient();
22330
- const timestamp = Date.now();
22331
- log(`observePosts(tmpid: ${timestamp}) > listen`);
22332
- const disposers = [];
22333
- const router = (post, action) => {
22334
- var _a, _b;
22335
- if (params.targetId !== post.targetId || params.targetType !== post.targetType)
22336
- return;
22337
- if (callback instanceof Function)
22338
- return callback(LinkedObject.post(post));
22339
- (_a = callback.onEvent) === null || _a === void 0 ? void 0 : _a.call(callback, action, LinkedObject.post(post));
22340
- (_b = callback[action]) === null || _b === void 0 ? void 0 : _b.call(callback, LinkedObject.post(post));
22341
- };
22342
- disposers.push(onPostCreated(post => router(post, 'onCreate')), onPostUpdated(post => router(post, 'onUpdate')), onPostDeleted(post => router(post, 'onDelete')), onPostApproved(post => router(post, 'onApproved')), onPostDeclined(post => router(post, 'onDeclined')), onPostFlagged(post => router(post, 'onFlagged')), onPostUnflagged(post => router(post, 'onUnflagged')), onPostReactionAdded(post => router(post, 'onReactionAdded')), onPostReactionRemoved(post => router(post, 'onReactionRemoved')));
22343
- return () => {
22344
- log(`observePosts(tmpid: ${timestamp}) > dispose`);
22345
- disposers.forEach(fn => fn());
22346
- };
22347
- };
22348
-
22349
- /**
22350
- * ```js
22351
- * import { observePost } from '@amityco/ts-sdk'
22352
- *
22353
- * let post = {}
22354
- * const dispose = observePost(postId, updated => post = updated)
22355
- * ```
22356
- *
22357
- * Observe all mutations on a given {@link Amity.Post}
22358
- *
22359
- * @param postId the ID of the post to observe
22360
- * @param callback the function to call when new data are available
22361
- * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the post
22362
- *
22363
- * @category Post Observer
22364
- */
22365
- const observePost = (postId, callback, policy = 'cache_then_server') => {
22366
- const { log } = getActiveClient();
22367
- const timestamp = Date.now();
22368
- log(`observePost(tmpid: ${timestamp}) > listen`);
22369
- // wrapper function to make sure
22370
- const router = (result, action) => {
22371
- var _a, _b;
22372
- if (callback instanceof Function)
22373
- return callback(result);
22374
- if (action !== 'onFetch')
22375
- (_a = callback.onEvent) === null || _a === void 0 ? void 0 : _a.call(callback, action, result);
22376
- (_b = callback[action]) === null || _b === void 0 ? void 0 : _b.call(callback, result);
22377
- };
22378
- const realtimeRouter = (result, action) => {
22379
- var _a;
22380
- if (((_a = result.data) === null || _a === void 0 ? void 0 : _a.postId) !== postId)
22381
- return;
22382
- router(Object.assign(Object.assign({}, result), { data: result.data && LinkedObject.post(result.data) }), action);
22383
- };
22384
- const disposers = [];
22385
- disposers.push(onPostUpdated(data => realtimeRouter({ data, loading: false, origin: 'event' }, 'onUpdate')), onPostDeleted(data => realtimeRouter({ data, loading: false, origin: 'event' }, 'onDelete')), onPostApproved(data => realtimeRouter({ data, loading: false, origin: 'event' }, 'onApproved')), onPostDeclined(data => realtimeRouter({ data, loading: false, origin: 'event' }, 'onDeclined')), onPostFlagged(data => realtimeRouter({ data, loading: false, origin: 'event' }, 'onFlagged')), onPostUnflagged(data => realtimeRouter({ data, loading: false, origin: 'event' }, 'onUnflagged')), onPostReactionAdded(data => realtimeRouter({ data, loading: false, origin: 'event' }, 'onReactionAdded')), onPostReactionRemoved(data => realtimeRouter({ data, loading: false, origin: 'event' }, 'onReactionRemoved')));
22386
- runQuery(createQuery(getPost$2, postId), result => (result.data || result.error) &&
22387
- router(Object.assign(Object.assign({}, result), { data: result.data && LinkedObject.post(result.data) }), 'onFetch'), queryOptions(policy));
22388
- return () => {
22389
- log(`observePosts(tmpid: ${timestamp}) > dispose`);
22390
- disposers.forEach(fn => fn());
22391
- };
22392
- };
22393
-
22394
21163
  /* begin_public_function
22395
21164
  id: comment.get_by_ids
22396
21165
  */
@@ -22866,43 +21635,6 @@ const isCommentFlaggedByMe = async (commentId) => {
22866
21635
  };
22867
21636
  /* end_public_function */
22868
21637
 
22869
- /**
22870
- * ```js
22871
- * import { observeComments } from '@amityco/ts-sdk'
22872
- *
22873
- * let comments = []
22874
- * const unsub = observeComments(postId, comment => merge(comments, comment))
22875
- * ```
22876
- *
22877
- * Observe all mutations on a list of {@link Amity.InternalComment} for a given {@link Amity.Post} object
22878
- *
22879
- * @param postId the ID of the post where to observe the comments
22880
- * @param callback the function to call when new data are available
22881
- * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the comments
22882
- *
22883
- * @category InternalComment Observer
22884
- */
22885
- const observeComments = (postId, callback) => {
22886
- const { log } = getActiveClient();
22887
- const timestamp = Date.now();
22888
- log(`observeComments(tmpid: ${timestamp}) > listen`);
22889
- const disposers = [];
22890
- const router = (comment, action) => {
22891
- var _a, _b;
22892
- if (comment.referenceId !== postId)
22893
- return;
22894
- if (callback instanceof Function)
22895
- return callback(comment);
22896
- (_a = callback.onEvent) === null || _a === void 0 ? void 0 : _a.call(callback, action, comment);
22897
- (_b = callback[action]) === null || _b === void 0 ? void 0 : _b.call(callback, comment);
22898
- };
22899
- disposers.push(onCommentCreated(comment => router(comment, 'onCreate')), onCommentUpdated(comment => router(comment, 'onUpdate')), onCommentDeleted(comment => router(comment, 'onDelete')), onCommentFlagged(comment => router(comment, 'onFlagged')), onCommentUnflagged(comment => router(comment, 'onUnflagged')), onCommentReactionAdded(comment => router(comment, 'onReactionAdded')), onCommentReactionRemoved(comment => router(comment, 'onReactionRemoved')));
22900
- return () => {
22901
- log(`observeComments(tmpid: ${timestamp}) > dispose`);
22902
- disposers.forEach(fn => fn());
22903
- };
22904
- };
22905
-
22906
21638
  const getComment$1 = async (commentId) => {
22907
21639
  const client = getActiveClient();
22908
21640
  client.log('comment/getComment', commentId);
@@ -22942,50 +21674,6 @@ getComment$1.locally = (commentId) => {
22942
21674
  };
22943
21675
  };
22944
21676
 
22945
- /**
22946
- * ```js
22947
- * import { observeComment } from '@amityco/ts-sdk'
22948
- *
22949
- * let comment = {}
22950
- * const dispose = observeComment(commentId, ({ data }) => comment = data)
22951
- * ```
22952
- *
22953
- * Observe all mutation on a given {@link Amity.InternalComment}
22954
- *
22955
- * @param commentId the ID of the comment to observe
22956
- * @param callback the function to call when new data are available
22957
- * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the comment
22958
- *
22959
- * @category InternalComment Observer
22960
- */
22961
- const observeComment = (commentId, callback, policy = 'cache_then_server') => {
22962
- const { log } = getActiveClient();
22963
- const timestamp = Date.now();
22964
- log(`observeComment(tmpid: ${timestamp}) > listen`);
22965
- // wrapper function to make sure
22966
- const router = (result, action) => {
22967
- var _a, _b;
22968
- if (callback instanceof Function)
22969
- return callback(result);
22970
- if (action !== 'onFetch')
22971
- (_a = callback.onEvent) === null || _a === void 0 ? void 0 : _a.call(callback, action, result);
22972
- (_b = callback[action]) === null || _b === void 0 ? void 0 : _b.call(callback, result);
22973
- };
22974
- const realtimeRouter = (result, action) => {
22975
- var _a;
22976
- if (((_a = result.data) === null || _a === void 0 ? void 0 : _a.commentId) !== commentId)
22977
- return;
22978
- router(result, action);
22979
- };
22980
- const disposers = [];
22981
- disposers.push(onCommentUpdated(data => realtimeRouter({ data, loading: false, origin: 'event' }, 'onUpdate')), onCommentDeleted(data => realtimeRouter({ data, loading: false, origin: 'event' }, 'onDelete')), onCommentFlagged(data => realtimeRouter({ data, loading: false, origin: 'event' }, 'onFlagged')), onCommentUnflagged(data => realtimeRouter({ data, loading: false, origin: 'event' }, 'onUnflagged')), onCommentReactionAdded(data => realtimeRouter({ data, loading: false, origin: 'event' }, 'onReactionAdded')), onCommentReactionRemoved(data => realtimeRouter({ data, loading: false, origin: 'event' }, 'onReactionRemoved')));
22982
- runQuery(createQuery(getComment$1, commentId), result => (result.data || result.error) && router(result, 'onFetch'), queryOptions(policy));
22983
- return () => {
22984
- log(`observeComment(tmpid: ${timestamp}) > dispose`);
22985
- disposers.forEach(fn => fn());
22986
- };
22987
- };
22988
-
22989
21677
  /**
22990
21678
  * ```js
22991
21679
  * import { onCommentDeleteLocal } from '@amityco/ts-sdk'
@@ -23361,8 +22049,6 @@ var index$6 = /*#__PURE__*/Object.freeze({
23361
22049
  onCommentUnflagged: onCommentUnflagged,
23362
22050
  onCommentReactionAdded: onCommentReactionAdded,
23363
22051
  onCommentReactionRemoved: onCommentReactionRemoved,
23364
- observeComments: observeComments,
23365
- observeComment: observeComment,
23366
22052
  getComment: getComment,
23367
22053
  getComments: getComments
23368
22054
  });
@@ -24356,7 +23042,6 @@ var index$5 = /*#__PURE__*/Object.freeze({
24356
23042
  __proto__: null,
24357
23043
  getPostByIds: getPostByIds,
24358
23044
  createPost: createPost,
24359
- updatePost: updatePost,
24360
23045
  editPost: editPost,
24361
23046
  deletePost: deletePost,
24362
23047
  softDeletePost: softDeletePost,
@@ -24375,8 +23060,6 @@ var index$5 = /*#__PURE__*/Object.freeze({
24375
23060
  onPostUnflagged: onPostUnflagged,
24376
23061
  onPostReactionAdded: onPostReactionAdded,
24377
23062
  onPostReactionRemoved: onPostReactionRemoved,
24378
- observePosts: observePosts,
24379
- observePost: observePost,
24380
23063
  getPost: getPost$1,
24381
23064
  getPosts: getPosts,
24382
23065
  getPinnedPosts: getPinnedPosts,
@@ -24569,47 +23252,6 @@ const disposeStream = async (streamId) => {
24569
23252
  };
24570
23253
  /* end_public_function */
24571
23254
 
24572
- /* begin_public_function
24573
- id: stream.query
24574
- */
24575
- /**
24576
- * @deprecated This API renamed to `getStreams`.
24577
- * Please use getStreams() instead.
24578
- * ```js
24579
- * import { getStreams } from '@amityco/ts-sdk'
24580
- * const streams = await getStreams()
24581
- * ```
24582
- *
24583
- * Queries a paginable list of {@link Amity.InternalStream} objects
24584
- *
24585
- * @param query The query parameters
24586
- * @returns A page of {@link Amity.InternalStream} objects
24587
- *
24588
- * @category Stream API
24589
- * @async
24590
- */
24591
- const queryStreams = async (query) => {
24592
- const client = getActiveClient();
24593
- client.log('stream/queryStreams', query);
24594
- const _a = query !== null && query !== void 0 ? query : {}, { page } = _a, params = __rest(_a, ["page"]);
24595
- const { data } = await client.http.get(`/api/v3/video-streaming`, {
24596
- params: Object.assign(Object.assign({}, params), { options: {
24597
- token: toToken(page, 'skiplimit'),
24598
- } }),
24599
- });
24600
- // API-FIX: backend to response Amity.Response: const { paging, videoStreamings } = unwrapPayload(data)
24601
- // API-FIX: seems returned data has a results identifier on top of data, like no other apis, and this is beautiful
24602
- const { paging, results: payload } = data;
24603
- const { videoStreamings } = payload;
24604
- const cachedAt = client.cache && Date.now();
24605
- if (client.cache)
24606
- ingestInCache(payload, { cachedAt });
24607
- const nextPage = toPage(paging.next);
24608
- const prevPage = toPage(paging.previous);
24609
- return { data: videoStreamings, cachedAt, prevPage, nextPage };
24610
- };
24611
- /* end_public_function */
24612
-
24613
23255
  /**
24614
23256
  * ```js
24615
23257
  * import { onStreamStarted } from '@amityco/ts-sdk'
@@ -24631,7 +23273,7 @@ const onStreamStarted = (callback) => {
24631
23273
  ingestInCache(payload);
24632
23274
  callback(payload.videoStreamings[0]);
24633
23275
  };
24634
- return createEventSubscriber(client, 'stream/onStreamStarted', 'v3.video-streaming.didStart', filter);
23276
+ return createEventSubscriber(client, 'stream/onStreamStarted', 'video-streaming.didStart', filter);
24635
23277
  };
24636
23278
 
24637
23279
  /**
@@ -24655,7 +23297,7 @@ const onStreamStopped = (callback) => {
24655
23297
  ingestInCache(payload);
24656
23298
  callback(payload.videoStreamings[0]);
24657
23299
  };
24658
- return createEventSubscriber(client, 'stream/onStreamStropped', 'v3.video-streaming.didStop', filter);
23300
+ return createEventSubscriber(client, 'stream/onStreamStropped', 'video-streaming.didStop', filter);
24659
23301
  };
24660
23302
 
24661
23303
  /**
@@ -24679,7 +23321,7 @@ const onStreamRecorded = (callback) => {
24679
23321
  ingestInCache(payload);
24680
23322
  callback(payload.videoStreamings[0]);
24681
23323
  };
24682
- return createEventSubscriber(client, 'stream/onStreamRecorded', 'v3.video-streaming.didRecord', filter);
23324
+ return createEventSubscriber(client, 'stream/onStreamRecorded', 'video-streaming.didRecord', filter);
24683
23325
  };
24684
23326
 
24685
23327
  /**
@@ -24703,7 +23345,7 @@ const onStreamFlagged = (callback) => {
24703
23345
  ingestInCache(payload);
24704
23346
  callback(payload.videoStreamings[0]);
24705
23347
  };
24706
- return createEventSubscriber(client, 'stream/onStreamFlagged', 'v3.video-streaming.didFlag', filter);
23348
+ return createEventSubscriber(client, 'stream/onStreamFlagged', 'video-streaming.didFlag', filter);
24707
23349
  };
24708
23350
 
24709
23351
  /**
@@ -24727,7 +23369,7 @@ const onStreamTerminated = (callback) => {
24727
23369
  ingestInCache(payload);
24728
23370
  callback(payload.videoStreamings[0]);
24729
23371
  };
24730
- return createEventSubscriber(client, 'stream/onStreamTerminated', 'v3.video-streaming.didTerminate', filter);
23372
+ return createEventSubscriber(client, 'stream/onStreamTerminated', 'video-streaming.didTerminate', filter);
24731
23373
  };
24732
23374
 
24733
23375
  /* eslint-disable no-use-before-define */
@@ -24936,8 +23578,6 @@ var index$4 = /*#__PURE__*/Object.freeze({
24936
23578
  updateStream: updateStream,
24937
23579
  deleteStream: deleteStream,
24938
23580
  disposeStream: disposeStream,
24939
- queryStreams: queryStreams,
24940
- getStream: getStream,
24941
23581
  onStreamStarted: onStreamStarted,
24942
23582
  onStreamStopped: onStreamStopped,
24943
23583
  onStreamRecorded: onStreamRecorded,
@@ -25192,50 +23832,6 @@ const onPollDeleted = (callback) => {
25192
23832
  return createEventSubscriber(client, 'poll/onPollDeleted', 'poll.deleted', filter);
25193
23833
  };
25194
23834
 
25195
- /**
25196
- * ```js
25197
- * import { observePoll } from '@amityco/ts-sdk'
25198
- *
25199
- * let poll = {}
25200
- * const dispose = observePoll(pollId, updated => poll = updated)
25201
- * ```
25202
- *
25203
- * Observe all mutation on a given {@link Amity.Poll}
25204
- *
25205
- * @param pollId the ID of the poll to observe
25206
- * @param callback the function to call when new data are available
25207
- * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the poll
25208
- *
25209
- * @category Poll Observer
25210
- */
25211
- const observePoll = (pollId, callback, policy = 'cache_then_server') => {
25212
- const { log } = getActiveClient();
25213
- const timestamp = Date.now();
25214
- log(`observePoll(tmpid: ${timestamp}) > listen`);
25215
- // wrapper function to make sure
25216
- const router = (result, action) => {
25217
- var _a, _b;
25218
- if (callback instanceof Function)
25219
- return callback(result);
25220
- if (action !== 'onFetch')
25221
- (_a = callback.onEvent) === null || _a === void 0 ? void 0 : _a.call(callback, action, result);
25222
- (_b = callback[action]) === null || _b === void 0 ? void 0 : _b.call(callback, result);
25223
- };
25224
- const realtimeRouter = (result, action) => {
25225
- var _a;
25226
- if (((_a = result.data) === null || _a === void 0 ? void 0 : _a.pollId) !== pollId)
25227
- return;
25228
- router(result, action);
25229
- };
25230
- const disposers = [];
25231
- disposers.push(onPollUpdated(data => realtimeRouter({ data, loading: false, origin: 'event' }, 'onUpdate')), onPollDeleted(data => realtimeRouter({ data, loading: false, origin: 'event' }, 'onDelete')));
25232
- runQuery(createQuery(getPoll$1, pollId), result => (result.data || result.error) && router(result, 'onFetch'), queryOptions(policy));
25233
- return () => {
25234
- log(`observePoll(tmpid: ${timestamp}) > dispose`);
25235
- disposers.forEach(fn => fn());
25236
- };
25237
- };
25238
-
25239
23835
  /* begin_public_function
25240
23836
  id: poll.get
25241
23837
  */
@@ -25271,7 +23867,6 @@ var index$3 = /*#__PURE__*/Object.freeze({
25271
23867
  votePoll: votePoll,
25272
23868
  onPollUpdated: onPollUpdated,
25273
23869
  onPollDeleted: onPollDeleted,
25274
- observePoll: observePoll,
25275
23870
  getPoll: getPoll
25276
23871
  });
25277
23872
 
@@ -25729,7 +24324,7 @@ const createOptimisticTarget = async ({ targetId, targetType, }) => {
25729
24324
  optimisticTarget = Object.assign(Object.assign({}, optimisticTarget), { targetPublicId: community.data.communityId, targetUpdatedAt: (_a = community.data.updatedAt) !== null && _a !== void 0 ? _a : new Date().toISOString() });
25730
24325
  }
25731
24326
  if (targetType === 'user') {
25732
- const user = await getUser$2(targetId);
24327
+ const user = await getUser$1(targetId);
25733
24328
  optimisticTarget = Object.assign(Object.assign({}, optimisticTarget), { targetPublicId: user.data.userPublicId, targetUpdatedAt: (_b = user.data.updatedAt) !== null && _b !== void 0 ? _b : new Date().toISOString() });
25734
24329
  }
25735
24330
  pushToCache(["storyTarget" /* STORY_KEY_CACHE.STORY_TARGET */, 'get', targetId], optimisticTarget);
@@ -26922,6 +25517,7 @@ exports.getChannelTopic = getChannelTopic;
26922
25517
  exports.getCommentTopic = getCommentTopic;
26923
25518
  exports.getCommunityStoriesTopic = getCommunityStoriesTopic;
26924
25519
  exports.getCommunityTopic = getCommunityTopic;
25520
+ exports.getLiveStreamTopic = getLiveStreamTopic;
26925
25521
  exports.getMarkedMessageTopic = getMarkedMessageTopic;
26926
25522
  exports.getMarkerUserFeedTopic = getMarkerUserFeedTopic;
26927
25523
  exports.getMessageTopic = getMessageTopic;