@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.esm.js CHANGED
@@ -87,8 +87,8 @@ const PostContentType = Object.freeze({
87
87
 
88
88
  function getVersion() {
89
89
  try {
90
- // the string ''v6.35.2-esm'' should be replaced by actual value by @rollup/plugin-replace
91
- return 'v6.35.2-esm';
90
+ // the string ''v7.0.0-esm'' should be replaced by actual value by @rollup/plugin-replace
91
+ return 'v7.0.0-esm';
92
92
  }
93
93
  catch (error) {
94
94
  return '__dev__';
@@ -1304,9 +1304,6 @@ const WS_EVENTS = [
1304
1304
  'sessionStateChange',
1305
1305
  // for internal use by accessTokenExpiryWatcher
1306
1306
  'tokenExpired',
1307
- 'v3.video-streaming.didRecord',
1308
- 'v3.video-streaming.didStart',
1309
- 'v3.video-streaming.didStop',
1310
1307
  ];
1311
1308
  const MQTT_EVENTS = [
1312
1309
  'connect',
@@ -1316,7 +1313,12 @@ const MQTT_EVENTS = [
1316
1313
  'close',
1317
1314
  'end',
1318
1315
  'reconnect',
1319
- 'user.didGlobalBan',
1316
+ 'video-streaming.didStart',
1317
+ 'video-streaming.didRecord',
1318
+ 'video-streaming.didStop',
1319
+ 'video-streaming.didFlag',
1320
+ 'video-streaming.didTerminate',
1321
+ // 'user.didGlobalBan' remove due to message event,
1320
1322
  ];
1321
1323
  /** @hidden */
1322
1324
  const createEventEmitter = () => {
@@ -1515,7 +1517,11 @@ function subscribeTopic(topic, callback) {
1515
1517
  return () => null;
1516
1518
  modifyMqttConnection();
1517
1519
  return mqtt.subscribe(topic, callback);
1518
- }
1520
+ }
1521
+ const getLiveStreamTopic = () => {
1522
+ const user = getActiveUser();
1523
+ return `${getNetworkId(user)}/videostreaming`;
1524
+ };
1519
1525
 
1520
1526
  var _a;
1521
1527
  /* eslint-disable no-undef */
@@ -1551,7 +1557,7 @@ const API_REGIONS = {
1551
1557
  US: 'us',
1552
1558
  };
1553
1559
  const URLS = {
1554
- http: 'https://api.{region}.amity.co',
1560
+ http: 'https://apix.{region}.amity.co',
1555
1561
  mqtt: 'wss://sse.{region}.amity.co:443/mqtt',
1556
1562
  };
1557
1563
  function computeUrl(type, region) {
@@ -20460,6 +20466,7 @@ const subscribeGlobalTopic = () => {
20460
20466
  // subscribing to user topic is necessary to handle ban event
20461
20467
  subscribeTopic(getUserTopic(getActiveUser())),
20462
20468
  subscribeTopic(getMarkerUserFeedTopic()),
20469
+ subscribeTopic(getLiveStreamTopic()),
20463
20470
  ];
20464
20471
  return () => disposers.forEach(fn => fn());
20465
20472
  };
@@ -21972,9 +21979,6 @@ const reactorLinkedObject = (reactor) => {
21972
21979
  * import { ChannelRepository } from '@amityco/ts-sdk'
21973
21980
  * const success = await ChannelRepository.markAsRead('channelId')
21974
21981
  * ```
21975
- *
21976
- * @deprecated Please use the {@link Amity.Channel.markAsRead} method instead
21977
- *
21978
21982
  * Updating all {@link Amity.SubChannel} in specify {@link Amity.Channel} as read
21979
21983
  *
21980
21984
  * @param channelId the ID of to specify {@link Amity.Channel}
@@ -22587,7 +22591,7 @@ const prepareMessagePayload = async (payload, event) => {
22587
22591
  var _a, _b;
22588
22592
  const subChannelCache = (_b = (_a = pullFromCache(['subChannel', 'get', messageFeed.messageFeedId])) === null || _a === void 0 ? void 0 : _a.data) !== null && _b !== void 0 ? _b : {};
22589
22593
  // exclude getter properties from existing subChannel cache, update only other properties to existing subChannel cache
22590
- const _c = convertFromRaw$2(messageFeed), restSubChannel = __rest(_c, ["unreadCount", "hasMentioned", "isMentioned"]);
22594
+ const _c = convertFromRaw$2(messageFeed), restSubChannel = __rest(_c, ["unreadCount", "isMentioned"]);
22591
22595
  updateSubChannelCache(messageFeed.messageFeedId, subChannelCache, restSubChannel);
22592
22596
  });
22593
22597
  }
@@ -22601,15 +22605,12 @@ function convertParams(_a) {
22601
22605
  return Object.assign({ messageFeedId: subChannelId, mentionedUsers: mentionees, dataType, data }, rest);
22602
22606
  }
22603
22607
  function convertQueryParams$1(_a) {
22604
- var { sortBy, subChannelId, tags, includingTags, excludingTags, includeDeleted, aroundMessageId, limit, type } = _a, rest = __rest(_a, ["sortBy", "subChannelId", "tags", "includingTags", "excludingTags", "includeDeleted", "aroundMessageId", "limit", "type"]);
22608
+ var { sortBy, subChannelId, includingTags, excludingTags, includeDeleted, aroundMessageId, limit, type } = _a, rest = __rest(_a, ["sortBy", "subChannelId", "includingTags", "excludingTags", "includeDeleted", "aroundMessageId", "limit", "type"]);
22605
22609
  const out = Object.assign(Object.assign({}, rest), { messageFeedId: subChannelId, isDeleted: inferIsDeleted(includeDeleted), options: {
22606
22610
  sortBy,
22607
22611
  limit: limit || COLLECTION_DEFAULT_PAGINATION_LIMIT,
22608
22612
  around: aroundMessageId,
22609
22613
  } });
22610
- if (tags) {
22611
- out.includeTags = tags;
22612
- }
22613
22614
  if (includingTags) {
22614
22615
  out.includeTags = includingTags;
22615
22616
  }
@@ -23093,22 +23094,27 @@ const getSubChannelsUnreadCount = (channel, marker) => {
23093
23094
  };
23094
23095
 
23095
23096
  const constructChannelDynamicValue = (channel) => {
23096
- return shallowClone(channel, {
23097
- get unreadCount() {
23098
- return getSubChannelsUnreadCount(channel);
23099
- },
23100
- get hasMentioned() {
23101
- return getChannelIsMentioned(channel);
23102
- },
23097
+ const rest = __rest(channel, ["messageCount"]);
23098
+ return shallowClone(rest, {
23103
23099
  get isMentioned() {
23104
- return getChannelIsMentioned(channel);
23100
+ return getChannelIsMentioned(rest);
23105
23101
  },
23106
23102
  get subChannelsUnreadCount() {
23107
- return getSubChannelsUnreadCount(channel);
23103
+ return getSubChannelsUnreadCount(rest);
23108
23104
  },
23109
23105
  });
23110
23106
  };
23111
23107
 
23108
+ const constructChannelObject = (channel) => {
23109
+ /**
23110
+ * convert internal cache data to be public channel data
23111
+ * 1. [getChannelMessagePreviewWithUser] add messagePreview >> Amity.InternalChannel -> Amity.InternalChannel
23112
+ * 2. [constructChannelDynamicValue] construct getter value >> Amity.StaticInternalChannel -> Amity.Channel
23113
+ * 3. [LinkedObject.channel] add markAsRead >> Amity.InternalChannel -> Amity.Channel
23114
+ */
23115
+ return LinkedObject.channel(constructChannelDynamicValue(getChannelMessagePreviewWithUser(channel)));
23116
+ };
23117
+
23112
23118
  /**
23113
23119
  * ```js
23114
23120
  * import { getChannelByIds } from '@amityco/ts-sdk'
@@ -23123,7 +23129,7 @@ const constructChannelDynamicValue = (channel) => {
23123
23129
  * @category Channel API
23124
23130
  * @async
23125
23131
  */
23126
- const getChannelByIds = async (channelIds) => {
23132
+ const getChannelByIds$1 = async (channelIds) => {
23127
23133
  const client = getActiveClient();
23128
23134
  client.log('channel/getChannelByIds', channelIds);
23129
23135
  const encodedChannelIds = channelIds.map(channelId => encodeURIComponent(channelId));
@@ -23153,7 +23159,7 @@ const getChannelByIds = async (channelIds) => {
23153
23159
  ingestInCache(data, { cachedAt });
23154
23160
  fireEvent('local.channel.fetched', data.channels);
23155
23161
  return {
23156
- data: data.channels.map(channel => LinkedObject.channel(constructChannelDynamicValue(channel))),
23162
+ data: data.channels.map(channel => constructChannelObject(channel)),
23157
23163
  cachedAt,
23158
23164
  };
23159
23165
  };
@@ -23170,7 +23176,7 @@ const getChannelByIds = async (channelIds) => {
23170
23176
  *
23171
23177
  * @category Channel API
23172
23178
  */
23173
- getChannelByIds.locally = (channelIds) => {
23179
+ getChannelByIds$1.locally = (channelIds) => {
23174
23180
  var _a, _b;
23175
23181
  const client = getActiveClient();
23176
23182
  client.log('channel/getChannelByIds.locally', channelIds);
@@ -23184,7 +23190,7 @@ getChannelByIds.locally = (channelIds) => {
23184
23190
  const channels = cached.map(({ data }) => data);
23185
23191
  const oldest = (_b = cached.sort((a, b) => (a.cachedAt < b.cachedAt ? -1 : 1))) === null || _b === void 0 ? void 0 : _b[0];
23186
23192
  return {
23187
- data: channels.map(channel => LinkedObject.channel(channel)),
23193
+ data: channels.map(channel => constructChannelObject(channel)),
23188
23194
  cachedAt: oldest.cachedAt,
23189
23195
  };
23190
23196
  };
@@ -23242,20 +23248,6 @@ const setIntervalTask = (handler, timeout) => {
23242
23248
  return () => clearInterval(timer);
23243
23249
  };
23244
23250
 
23245
- const onOnline = (callback) => {
23246
- if (typeof window !== 'undefined' && window.addEventListener) {
23247
- window.addEventListener('online', callback);
23248
- return () => window.removeEventListener('online', callback);
23249
- }
23250
- if (typeof document !== 'undefined' && document.addEventListener) {
23251
- document.addEventListener('online', callback);
23252
- return () => document.removeEventListener('online', callback);
23253
- }
23254
- // Handle unsupported environment
23255
- console.error('Unsupported environment');
23256
- return () => console.error('Unsupported environment');
23257
- };
23258
-
23259
23251
  /**
23260
23252
  * ```js
23261
23253
  * import { SubChannel } from '@amityco/ts-sdk'
@@ -23288,73 +23280,8 @@ const readingAPI = async (messageFeedIds) => {
23288
23280
  return true;
23289
23281
  };
23290
23282
 
23291
- /**
23292
- * ```js
23293
- * import { SubChannel } from '@amityco/ts-sdk'
23294
- * const success = await SubChannel('foo')
23295
- * ```
23296
- *
23297
- * Mark all messages as read and start reading message inside channel
23298
- *
23299
- * @param messageFeedId - Sub channel ID to start reading.
23300
- * @return A success boolean if reading of the sub channel had begun.
23301
- *
23302
- * @category Channel API
23303
- * @async
23304
- * @private
23305
- */
23306
- const startReadingAPI = async (messageFeedId) => {
23307
- const client = getActiveClient();
23308
- client.log('subChannel/startReadingAPI', messageFeedId);
23309
- const { data: payload } = await client.http.post(`/api/v1/markers/message-feeds/${messageFeedId}/start-reading`);
23310
- const { userEntityMarkers: userEntityMarkersPayload, userFeedMarkers: userFeedMarkersPayload, feedMarkers, userMarkers, } = payload;
23311
- const userEntityMarkers = convertChannelMarkerResponse(userEntityMarkersPayload);
23312
- const userFeedMarkers = convertSubChannelMarkerResponse(userFeedMarkersPayload);
23313
- const cachedAt = client.cache && Date.now();
23314
- if (client.cache)
23315
- ingestInCache({ userEntityMarkers, userFeedMarkers, feedMarkers, userMarkers }, { cachedAt });
23316
- fireEvent('local.feedMarker.fetched', { feedMarkers });
23317
- fireEvent('local.channelMarker.fetched', { userEntityMarkers });
23318
- fireEvent('local.subChannelMarker.fetched', { userFeedMarkers });
23319
- fireEvent('local.userMarker.fetched', { userMarkers });
23320
- return true;
23321
- };
23322
-
23323
- /**
23324
- * ```js
23325
- * import { stopReading } from '@amityco/ts-sdk'
23326
- * const success = await stopReading('foo')
23327
- * ```
23328
- *
23329
- * Mark all messages as read and stop reading message inside channel
23330
- *
23331
- * @param messageFeedId - The sub channel ID to stop reading.
23332
- * @return A success boolean if reading of the sub channel had begun.
23333
- *
23334
- * @category Channel API
23335
- * @async
23336
- * @private
23337
- */
23338
- const stopReadingAPI = async (messageFeedId) => {
23339
- const client = getActiveClient();
23340
- client.log('channel/stopReadingAPI', messageFeedId);
23341
- const { data: payload } = await client.http.post(`/api/v1/markers/message-feeds/${messageFeedId}/stop-reading`);
23342
- const { userEntityMarkers: userEntityMarkersPayload, userFeedMarkers: userFeedMarkersPayload, feedMarkers, userMarkers, } = payload;
23343
- const userEntityMarkers = convertChannelMarkerResponse(userEntityMarkersPayload);
23344
- const userFeedMarkers = convertSubChannelMarkerResponse(userFeedMarkersPayload);
23345
- const cachedAt = client.cache && Date.now();
23346
- if (client.cache)
23347
- ingestInCache({ userEntityMarkers, userFeedMarkers, feedMarkers, userMarkers }, { cachedAt });
23348
- fireEvent('local.feedMarker.fetched', { feedMarkers });
23349
- fireEvent('local.channelMarker.fetched', { userEntityMarkers });
23350
- fireEvent('local.subChannelMarker.fetched', { userFeedMarkers });
23351
- fireEvent('local.userMarker.fetched', { userMarkers });
23352
- return true;
23353
- };
23354
-
23355
23283
  const START_READING_INTERVAL_TIME = 30000;
23356
23284
  let isSyncRunning$1 = false;
23357
- let disposers$2 = [];
23358
23285
  /**
23359
23286
  * map contains subChannelId and isReading flag to determine which subChannel is on reading state
23360
23287
  */
@@ -23398,91 +23325,6 @@ const markReadEngineOnLoginHandler = () => {
23398
23325
  stopIntervalTask();
23399
23326
  };
23400
23327
  };
23401
- const getParentChannelId$1 = async (subChannelId) => {
23402
- const cached = getSubChannel$1.locally(subChannelId);
23403
- if (cached) {
23404
- return cached.data.channelId;
23405
- }
23406
- const { data } = await getSubChannel$1(subChannelId);
23407
- return data.channelId;
23408
- };
23409
- const registerEventListeners$1 = () => {
23410
- if (disposers$2.length > 0) {
23411
- return;
23412
- }
23413
- disposers$2.push(onOnline(() => {
23414
- // Start reading the reading subChannel again when resume from offline state
23415
- startReadingFromReadingList();
23416
- }));
23417
- };
23418
- const registerTopicSubscribers$1 = async (subChannelId) => {
23419
- const channelId = await getParentChannelId$1(subChannelId);
23420
- const markedMessageTopic = getMarkedMessageTopic({ channelId, subChannelId });
23421
- disposers$2.push(subscribeTopic(markedMessageTopic));
23422
- };
23423
- const disposeAll = () => {
23424
- disposers$2.forEach(fn => fn());
23425
- disposers$2 = [];
23426
- };
23427
- /* begin_public_function
23428
- id: subchannel.start_reading
23429
- */
23430
- /**
23431
- * @deprecated Use {@link startMessageReceiptSync} instead.
23432
- * ```js
23433
- * import { startReading } from '@amityco/ts-sdk'
23434
- * const success = await startReading('foo')
23435
- * ```
23436
- *
23437
- * Set local reading state of channel to `true` and then call mark all
23438
- * messages as read API.
23439
- *
23440
- * @param subChannelId - The sub channel ID to start reading.
23441
- * @return A success boolean if reading of the sub channel had begun.
23442
- *
23443
- * @category Channel API
23444
- * @async
23445
- */
23446
- const startReading = async (subChannelId) => {
23447
- isReadingMap[subChannelId] = true;
23448
- if (disposers$2.length === 0) {
23449
- registerEventListeners$1();
23450
- registerTopicSubscribers$1(subChannelId);
23451
- }
23452
- try {
23453
- return await startReadingAPI(subChannelId);
23454
- }
23455
- catch (e) {
23456
- isReadingMap[subChannelId] = false;
23457
- return false;
23458
- }
23459
- };
23460
- /* end_public_function */
23461
- /* begin_public_function
23462
- id: subchannel.stop_reading
23463
- */
23464
- /**
23465
- * @deprecated Use {@link stopMessageReceiptSync} instead.
23466
- * ```js
23467
- * import { stopReading } from '@amityco/ts-sdk'
23468
- * const success = await stopReading('foo')
23469
- * ```
23470
- *
23471
- * Set local reading state of channel to `false` and then call mark all
23472
- * messages as unread API.
23473
- *
23474
- * @param subChannelId - The sub channel ID to stop reading.
23475
- * @return A success boolean if reading of the sub channel had begun.
23476
- *
23477
- * @category Channel API
23478
- * @async
23479
- */
23480
- const stopReading = (subChannelId) => {
23481
- isReadingMap[subChannelId] = false;
23482
- disposeAll();
23483
- return stopReadingAPI(subChannelId);
23484
- };
23485
- /* end_public_function */
23486
23328
  setIntervalTask(async () => {
23487
23329
  if (!isSyncRunning$1)
23488
23330
  return;
@@ -23637,7 +23479,7 @@ const initializeMessagePreviewSetting = async () => {
23637
23479
  * 2. channel and subChannel which isDelete = true
23638
23480
  */
23639
23481
  if (channelWithIsDeletedTrue.length !== 0)
23640
- await getChannelByIds(channelWithIsDeletedTrue);
23482
+ await getChannelByIds$1(channelWithIsDeletedTrue);
23641
23483
  if (subChannelWithIsDeletedTrue.length !== 0)
23642
23484
  await getSubChannels$1(subChannelWithIsDeletedTrue);
23643
23485
  }
@@ -24035,6 +23877,20 @@ var readReceiptSyncEngineOnLoginHandler = () => {
24035
23877
  };
24036
23878
  };
24037
23879
 
23880
+ const onOnline = (callback) => {
23881
+ if (typeof window !== 'undefined' && window.addEventListener) {
23882
+ window.addEventListener('online', callback);
23883
+ return () => window.removeEventListener('online', callback);
23884
+ }
23885
+ if (typeof document !== 'undefined' && document.addEventListener) {
23886
+ document.addEventListener('online', callback);
23887
+ return () => document.removeEventListener('online', callback);
23888
+ }
23889
+ // Handle unsupported environment
23890
+ console.error('Unsupported environment');
23891
+ return () => console.error('Unsupported environment');
23892
+ };
23893
+
24038
23894
  const onOffline = (callback) => {
24039
23895
  if (typeof window !== 'undefined' && window.addEventListener) {
24040
23896
  window.addEventListener('offline', callback);
@@ -24049,8 +23905,90 @@ const onOffline = (callback) => {
24049
23905
  return () => console.error('Unsupported environment');
24050
23906
  };
24051
23907
 
23908
+ /**
23909
+ * ```js
23910
+ * import { getChannelByIds } from '@amityco/ts-sdk'
23911
+ * const channels = await getChannelByIds(['foo', 'bar'])
23912
+ * ```
23913
+ *
23914
+ * Fetches a collection of {@link Amity.Channel} objects
23915
+ *
23916
+ * @param channelIds the IDs of the {@link Amity.Channel} to fetch
23917
+ * @returns the associated collection of {@link Amity.Channel} objects
23918
+ *
23919
+ * @category Channel API
23920
+ * @async
23921
+ */
23922
+ const getChannelByIds = async (channelIds) => {
23923
+ const client = getActiveClient();
23924
+ client.log('channel/getChannelByIds', channelIds);
23925
+ const encodedChannelIds = channelIds.map(channelId => encodeURIComponent(channelId));
23926
+ let payload;
23927
+ try {
23928
+ // API-FIX: endpoint should not be /list, parameters should be querystring.
23929
+ const response = await client.http.get(`/api/v3/channels/list`, {
23930
+ params: { channelIds: encodedChannelIds },
23931
+ });
23932
+ payload = response.data;
23933
+ }
23934
+ catch (error) {
23935
+ channelIds.forEach(channelId => {
23936
+ if (checkIfShouldGoesToTombstone(error === null || error === void 0 ? void 0 : error.code)) {
23937
+ // NOTE: use channelPublicId as tombstone cache key since we cannot get the channelPrivateId that come along with channel data from server
23938
+ pushToTombstone('channel', channelId);
23939
+ }
23940
+ });
23941
+ throw error;
23942
+ }
23943
+ const data = await prepareChannelPayload(payload);
23944
+ if (client.isUnreadCountEnabled && client.getMarkerSyncConsistentMode()) {
23945
+ await prepareUnreadCountInfo(payload);
23946
+ }
23947
+ const cachedAt = client.cache && Date.now();
23948
+ if (client.cache)
23949
+ ingestInCache(data, { cachedAt });
23950
+ fireEvent('local.channel.fetched', data.channels);
23951
+ return {
23952
+ data: data.channels,
23953
+ cachedAt,
23954
+ };
23955
+ };
23956
+ /**
23957
+ * ```js
23958
+ * import { getChannelByIds } from '@amityco/ts-sdk'
23959
+ * const channels = getChannelByIds.locally(['foo', 'bar']) ?? []
23960
+ * ```
23961
+ *
23962
+ * Fetches a collection of {@link Amity.Channel} objects from cache
23963
+ *
23964
+ * @param channelIds the IDs of the {@link Amity.Channel} to fetch
23965
+ * @returns the associated collection of {@link Amity.Channel} objects
23966
+ *
23967
+ * @category Channel API
23968
+ */
23969
+ getChannelByIds.locally = (channelIds) => {
23970
+ var _a, _b;
23971
+ const client = getActiveClient();
23972
+ client.log('channel/getChannelByIds.locally', channelIds);
23973
+ if (!client.cache)
23974
+ return;
23975
+ const cached = (_a = queryCache(['channel', 'get'])) === null || _a === void 0 ? void 0 : _a.filter(({ data }) => {
23976
+ return channelIds.includes(data.channelPublicId);
23977
+ });
23978
+ if (!cached || (cached === null || cached === void 0 ? void 0 : cached.length) < channelIds.length)
23979
+ return;
23980
+ const channels = cached.map(({ data }) => data);
23981
+ const oldest = (_b = cached.sort((a, b) => (a.cachedAt < b.cachedAt ? -1 : 1))) === null || _b === void 0 ? void 0 : _b[0];
23982
+ return {
23983
+ data: channels,
23984
+ cachedAt: oldest.cachedAt,
23985
+ };
23986
+ };
23987
+
24052
23988
  const resolveChannels = async (channelIds) => {
24053
- const { data: channels } = await getChannelByIds(channelIds);
23989
+ var _a, _b, _c;
23990
+ await getChannelByIds(channelIds);
23991
+ 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 : [];
24054
23992
  fireEvent('local.channel.resolved', channels);
24055
23993
  };
24056
23994
 
@@ -25178,13 +25116,6 @@ const stopUnreadSync = () => {
25178
25116
  setMarkerSyncEvents([]);
25179
25117
  unRegisterEventListeners();
25180
25118
  };
25181
- /**
25182
- * @deprecated Please use `startUnreadSync` instead
25183
- */
25184
- const stopUnreadSyncing = () => {
25185
- console.warn('`stopUnreadSyncing` has been deprecated, please use `stopUnreadSync` instead');
25186
- return stopUnreadSync();
25187
- };
25188
25119
  setIntervalTask(async () => {
25189
25120
  if (!isSyncRunning)
25190
25121
  return;
@@ -25639,6 +25570,28 @@ function setUploadedFileAccessType(accessType) {
25639
25570
  GlobalFileAccessType$1.getInstance().setFileAccessType(accessType);
25640
25571
  }
25641
25572
 
25573
+ /**
25574
+ * ```js
25575
+ * import { fetchLinkPreview } from '@amityco/ts-sdk'
25576
+ * const { title, description, imageUrl } = fetchLinkPreview('https://www.example.com/')
25577
+ * ```
25578
+ *
25579
+ *
25580
+ * @param url the url to fetch link preview
25581
+ * @returns A {@link Amity.LinkPreview} instance
25582
+ *
25583
+ * @category Client API
25584
+ * */
25585
+ const fetchLinkPreview = async (url) => {
25586
+ const client = getActiveClient();
25587
+ let fetchUrl = url;
25588
+ if (!/^https?:\/\//i.test(url)) {
25589
+ fetchUrl = `https://${url}`;
25590
+ }
25591
+ const { data } = await client.http.get(`/api/v1/link-preview?url=${encodeURIComponent(fetchUrl)}`);
25592
+ return data;
25593
+ };
25594
+
25642
25595
  /**
25643
25596
  * ```js
25644
25597
  * import { onChannelMarkerFetched } from '@amityco/ts-sdk'
@@ -25882,100 +25835,6 @@ const removeFunctionProperties = (obj) => {
25882
25835
  return Object.fromEntries(entries);
25883
25836
  };
25884
25837
 
25885
- /**
25886
- * @deprecated This function is deprecated
25887
- */
25888
- const liveObject = (id, callback, key, fetcher, eventHandlers, options) => {
25889
- const { forceDispatch, callbackDataSelector, callbackFilter } = Object.assign({ forceDispatch: false, callbackDataSelector: (data) => data }, options);
25890
- const { cache } = getActiveClient();
25891
- if (!cache) {
25892
- console.log(LIVE_OBJECT_ENABLE_CACHE_MESSAGE);
25893
- }
25894
- let model;
25895
- let isUnsyncedModel = false; // for messages
25896
- const disposers = [];
25897
- const dispatcher = (data) => {
25898
- const { data: newModel } = data, rest = __rest(data, ["data"]);
25899
- if (!callbackFilter || callbackFilter(newModel, model)) {
25900
- callback(Object.assign({ data: callbackDataSelector(newModel) }, rest));
25901
- }
25902
- // resolve all getter on data model to a static value to avoid comparison problems
25903
- model = convertGetterPropsToStatic(newModel);
25904
- };
25905
- const realtimeRouter = (eventModel, forceDispatch = false) => {
25906
- if (id !== eventModel[key]) {
25907
- return;
25908
- }
25909
- if (model) {
25910
- if (!forceDispatch && isEqual(model, eventModel)) {
25911
- return;
25912
- }
25913
- }
25914
- dispatcher({ loading: false, data: eventModel, origin: 'event' });
25915
- };
25916
- const onFetch = () => {
25917
- // TODO: Ihis `@ts-ignore` is bring back to fix the build and it needs to be removed later
25918
- // @ts-ignore
25919
- const query = createQuery(fetcher, id, true);
25920
- runQuery(query, ({ error, data, loading, origin, cachedAt }) => {
25921
- if (cachedAt === UNSYNCED_OBJECT_CACHED_AT_VALUE) {
25922
- dispatcher({
25923
- // @ts-ignore
25924
- data,
25925
- origin,
25926
- loading: false,
25927
- error: new ASCApiError(UNSYNCED_OBJECT_CACHED_AT_MESSAGE, 800800 /* Amity.ClientError.DISALOOW_UNSYNCED_OBJECT */, "error" /* Amity.ErrorLevel.ERROR */),
25928
- });
25929
- isUnsyncedModel = true;
25930
- disposers.forEach(fn => fn());
25931
- }
25932
- else if (!isUnsyncedModel) {
25933
- // @ts-ignore
25934
- dispatcher({ loading, data, origin, error });
25935
- }
25936
- if (error) {
25937
- disposers.forEach(fn => fn());
25938
- }
25939
- });
25940
- };
25941
- disposers.push(...eventHandlers.map(fn => fn(eventModel => realtimeRouter(eventModel, forceDispatch))));
25942
- onFetch();
25943
- return () => {
25944
- disposers.forEach(fn => fn());
25945
- };
25946
- };
25947
-
25948
- /**
25949
- * @deprecated Please use unreadCount from `getUserUnread` instead.
25950
- *
25951
- * ```js
25952
- * import { getTotalUnreadCount } from '@amityco/ts-sdk';
25953
- *
25954
- * const unsubscribe = getTotalUnreadCount(response => {
25955
- * totalUnreadCount = response.data;
25956
- * });
25957
- * ```
25958
- *
25959
- * Observe current user's unread count from {@link Amity.UserMarker}
25960
- *
25961
- * @param callback the function to call when new data are available
25962
- * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the events
25963
- *
25964
- * @category Message Live Object
25965
- */
25966
- const getTotalUnreadCount = (callback) => {
25967
- const { _id: userId } = getActiveUser();
25968
- if (!userId)
25969
- throw new ASCError('The _id has not been defined in ActiveUser', 800000 /* Amity.ClientError.UNKNOWN_ERROR */, "error" /* Amity.ErrorLevel.ERROR */);
25970
- const callbackDataSelector = (data) => { var _a; return (_a = data === null || data === void 0 ? void 0 : data.unreadCount) !== null && _a !== void 0 ? _a : 0; };
25971
- return liveObject(userId, callback, 'userId', async () => {
25972
- const { data: userMarker, cachedAt } = await getUserMarker();
25973
- return { data: userMarker, cachedAt };
25974
- }, [onUserMarkerFetchedLegacy], {
25975
- callbackDataSelector,
25976
- });
25977
- };
25978
-
25979
25838
  /**
25980
25839
  *
25981
25840
  * ```js
@@ -26017,7 +25876,7 @@ const getUserUnread = (callback) => {
26017
25876
  model = callbackModel ? convertGetterPropsToStatic(callbackModel) : callbackModel;
26018
25877
  callback({
26019
25878
  data: callbackModel
26020
- ? Object.assign(Object.assign({}, callbackModel), { hasMentioned: callbackModel.isMentioned }) : callbackModel,
25879
+ ? Object.assign(Object.assign({}, callbackModel), { isMentioned: callbackModel.isMentioned }) : callbackModel,
26021
25880
  loading: data.loading,
26022
25881
  error: data.error,
26023
25882
  });
@@ -26100,12 +25959,12 @@ var index$l = /*#__PURE__*/Object.freeze({
26100
25959
  markerSync: markerSync,
26101
25960
  enableUnreadCount: enableUnreadCount,
26102
25961
  setUploadedFileAccessType: setUploadedFileAccessType,
25962
+ fetchLinkPreview: fetchLinkPreview,
26103
25963
  onConnectionError: onConnectionError,
26104
25964
  onClientDisconnected: onClientDisconnected,
26105
25965
  onClientBanned: onClientBanned,
26106
25966
  onSessionStateChange: onSessionStateChange,
26107
25967
  onNetworkActivities: onNetworkActivities,
26108
- getTotalUnreadCount: getTotalUnreadCount,
26109
25968
  getUserUnread: getUserUnread,
26110
25969
  getMarkerSyncEvents: getMarkerSyncEvents,
26111
25970
  setMarkerSyncEvents: setMarkerSyncEvents,
@@ -26114,7 +25973,6 @@ var index$l = /*#__PURE__*/Object.freeze({
26114
25973
  startMarkerSync: startMarkerSync,
26115
25974
  startUnreadSync: startUnreadSync,
26116
25975
  stopUnreadSync: stopUnreadSync,
26117
- stopUnreadSyncing: stopUnreadSyncing,
26118
25976
  getMarkerSyncConsistentMode: getMarkerSyncConsistentMode
26119
25977
  });
26120
25978
 
@@ -26199,311 +26057,134 @@ const unBlockUser = async (userId) => {
26199
26057
  };
26200
26058
  /* end_public_function */
26201
26059
 
26202
- class PaginationController {
26203
- constructor(queryParams) {
26204
- const { http } = getActiveClient();
26205
- this.queryParams = queryParams;
26206
- this.http = http;
26207
- }
26208
- loadFirstPage() {
26209
- return this.onFetch("first" /* Amity.LiveCollectionPageDirection.FIRST */);
26210
- }
26211
- loadNextPage() {
26212
- return this.onFetch("next" /* Amity.LiveCollectionPageDirection.NEXT */);
26213
- }
26214
- loadPreviousPage() {
26215
- return this.onFetch("prev" /* Amity.LiveCollectionPageDirection.PREV */);
26216
- }
26217
- async onFetch(direction = "first" /* Amity.LiveCollectionPageDirection.FIRST */) {
26218
- var _a, _b, _c, _d;
26219
- if (direction === 'prev' && !this.previousToken)
26220
- return;
26221
- if (direction === 'next' && !this.nextToken)
26222
- return;
26223
- let token;
26224
- if (direction === 'prev')
26225
- token = this.previousToken;
26226
- if (direction === 'next')
26227
- token = this.nextToken;
26228
- const queryResponse = await this.getRequest(this.queryParams, token);
26229
- if (direction === 'first') {
26230
- this.nextToken = (_a = queryResponse.paging) === null || _a === void 0 ? void 0 : _a.next;
26231
- this.previousToken = (_b = queryResponse.paging) === null || _b === void 0 ? void 0 : _b.previous;
26232
- }
26233
- if (direction === 'prev')
26234
- this.previousToken = (_c = queryResponse.paging) === null || _c === void 0 ? void 0 : _c.previous;
26235
- if (direction === 'next')
26236
- this.nextToken = (_d = queryResponse.paging) === null || _d === void 0 ? void 0 : _d.next;
26237
- return queryResponse;
26238
- }
26239
- getNextToken() {
26240
- return this.nextToken;
26241
- }
26242
- getPrevToken() {
26243
- return this.previousToken;
26244
- }
26245
- }
26246
-
26247
- class BlockedUserPaginationController extends PaginationController {
26248
- async getRequest(queryParams, token) {
26249
- const { limit = COLLECTION_DEFAULT_PAGINATION_LIMIT } = queryParams, params = __rest(queryParams, ["limit"]);
26250
- const options = token ? { token } : { limit };
26251
- const { data: queryResponse } = await this.http.get('/api/v4/me/user-blocks', {
26252
- params: Object.assign(Object.assign({}, params), { options, isDeleted: false }),
26253
- });
26254
- return queryResponse;
26255
- }
26256
- }
26257
-
26258
- class QueryStreamController {
26259
- constructor(query, cacheKey) {
26260
- this.query = query;
26261
- this.cacheKey = cacheKey;
26262
- }
26263
- }
26264
-
26265
- var EnumFollowActions;
26266
- (function (EnumFollowActions) {
26267
- EnumFollowActions["OnRequested"] = "onRequested";
26268
- EnumFollowActions["OnAccepted"] = "onAccepted";
26269
- EnumFollowActions["OnDeclined"] = "onDeclined";
26270
- EnumFollowActions["OnCanceled"] = "onCanceled";
26271
- EnumFollowActions["OnFollowed"] = "onFollowed";
26272
- EnumFollowActions["OnUnfollowed"] = "onUnfollowed";
26273
- EnumFollowActions["OnDeleted"] = "onDeleted";
26274
- EnumFollowActions["OnUserDeleted"] = "onUserDeleted";
26275
- })(EnumFollowActions || (EnumFollowActions = {}));
26276
-
26277
- class BlockedUserQueryStreamController extends QueryStreamController {
26278
- constructor(query, cacheKey, notifyChange, preparePayload) {
26279
- super(query, cacheKey);
26280
- this.notifyChange = notifyChange;
26281
- this.preparePayload = preparePayload;
26282
- }
26283
- async saveToMainDB(response) {
26284
- const processedPayload = await this.preparePayload(response);
26285
- const client = getActiveClient();
26286
- const cachedAt = client.cache && Date.now();
26287
- if (client.cache) {
26288
- ingestInCache(processedPayload, { cachedAt });
26289
- }
26290
- }
26291
- appendToQueryStream(response, direction, refresh = false) {
26292
- var _a, _b;
26293
- if (refresh) {
26294
- pushToCache(this.cacheKey, {
26295
- data: response.users.map(getResolver('user')),
26296
- });
26297
- }
26298
- else {
26299
- const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
26300
- const users = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
26301
- pushToCache(this.cacheKey, Object.assign(Object.assign({}, collection), { data: [...new Set([...users, ...response.users.map(getResolver('user'))])] }));
26302
- }
26303
- }
26304
- reactor(action) {
26305
- return (targetUser) => {
26306
- var _a;
26307
- if (action === EnumFollowActions.OnFollowed) {
26308
- const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
26309
- const updatedCollection = collection === null || collection === void 0 ? void 0 : collection.data.filter(id => id !== targetUser.userId);
26310
- pushToCache(this.cacheKey, Object.assign(Object.assign({}, collection), { data: updatedCollection }));
26311
- }
26312
- this.notifyChange({ origin: "event" /* Amity.LiveDataOrigin.EVENT */, loading: false });
26313
- };
26314
- }
26315
- subscribeRTE(createSubscriber) {
26316
- return createSubscriber.map(subscriber => subscriber.fn(this.reactor(subscriber.action)));
26317
- }
26318
- }
26319
-
26320
- class PaginationNoPageController {
26321
- constructor(queryParams) {
26322
- const { http } = getActiveClient();
26323
- this.queryParams = queryParams;
26324
- this.http = http;
26325
- }
26326
- async onFetch() {
26327
- const queryResponse = await this.getRequest(this.queryParams);
26328
- return queryResponse;
26329
- }
26330
- }
26331
-
26332
- class LiveCollectionController {
26333
- constructor(paginationController, queryStreamId, cacheKey, callback) {
26334
- this.paginationController = paginationController;
26335
- this.queryStreamId = queryStreamId;
26336
- this.cacheKey = cacheKey;
26337
- this.callback = callback;
26338
- }
26339
- async refresh() {
26340
- try {
26341
- let result;
26342
- if (this.paginationController instanceof PaginationNoPageController) {
26343
- result = await this.paginationController.onFetch();
26344
- }
26345
- else {
26346
- result = await this.paginationController.loadFirstPage();
26347
- }
26348
- if (!result)
26349
- return;
26350
- await this.persistModel(result);
26351
- this.persistQueryStream({
26352
- response: result,
26353
- direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */,
26354
- refresh: true,
26355
- });
26356
- this.notifyChange({ origin: "server" /* Amity.LiveDataOrigin.SERVER */, loading: false });
26357
- }
26358
- catch (e) {
26359
- this.notifyChange({ origin: "server" /* Amity.LiveDataOrigin.SERVER */, loading: false, error: e });
26360
- }
26361
- }
26362
- loadPage({ initial = false, direction = "next" /* Amity.LiveCollectionPageDirection.NEXT */, }) {
26363
- this.setup();
26364
- this.notifyChange({ origin: "local" /* Amity.LiveDataOrigin.LOCAL */, loading: true });
26365
- if (initial) {
26366
- this.refresh();
26367
- }
26368
- else if (direction === "prev" /* Amity.LiveCollectionPageDirection.PREV */) {
26369
- this.loadPrevPage();
26370
- }
26371
- else if (direction === "next" /* Amity.LiveCollectionPageDirection.NEXT */) {
26372
- this.loadNextPage();
26373
- }
26374
- }
26375
- async loadNextPage() {
26376
- try {
26377
- if (this.paginationController instanceof PaginationNoPageController)
26378
- return;
26379
- const result = await this.paginationController.loadNextPage();
26380
- if (!result)
26381
- return;
26382
- await this.persistModel(result);
26383
- this.persistQueryStream({
26384
- response: result,
26385
- direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */,
26386
- });
26387
- this.notifyChange({ origin: "server" /* Amity.LiveDataOrigin.SERVER */, loading: false });
26388
- }
26389
- catch (e) {
26390
- this.notifyChange({ origin: "server" /* Amity.LiveDataOrigin.SERVER */, loading: false, error: e });
26391
- }
26392
- }
26393
- async loadPrevPage() {
26394
- try {
26395
- if (this.paginationController instanceof PaginationNoPageController)
26396
- return;
26397
- const result = await this.paginationController.loadPreviousPage();
26398
- if (!result)
26399
- return;
26400
- await this.persistModel(result);
26401
- this.persistQueryStream({
26402
- response: result,
26403
- direction: "prev" /* Amity.LiveCollectionPageDirection.PREV */,
26404
- });
26405
- this.notifyChange({ origin: "server" /* Amity.LiveDataOrigin.SERVER */, loading: false });
26406
- }
26407
- catch (e) {
26408
- this.notifyChange({ origin: "server" /* Amity.LiveDataOrigin.SERVER */, loading: false, error: e });
26409
- }
26410
- }
26411
- shouldNotify(data) {
26412
- const newData = data.map(convertGetterPropsToStatic).map(removeFunctionProperties);
26413
- if (isEqual(this.snapshot, newData))
26414
- return false;
26415
- this.snapshot = newData;
26416
- return true;
26417
- }
26418
- getCacheKey() {
26419
- return this.cacheKey;
26420
- }
26421
- }
26422
-
26423
- function prepareBlockedUserPayload(response) {
26424
- const { users, follows } = response, rest = __rest(response, ["users", "follows"]);
26425
- return Object.assign(Object.assign({}, rest), { follows: follows.map(follow => {
26426
- const followUser = users.find(user => user.userId === follow.from);
26427
- return Object.assign(Object.assign({}, follow), { user: convertRawUserToInternalUser(followUser) });
26428
- }), users: users.map(convertRawUserToInternalUser) });
26429
- }
26430
-
26060
+ /* begin_public_function
26061
+ id: user.relationship.follow
26062
+ */
26431
26063
  /**
26432
26064
  * ```js
26433
- * import { onUserUpdated } from '@amityco/ts-sdk'
26434
- * const dispose = onUserUpdated(user => {
26435
- * // ...
26436
- * })
26065
+ * import { follow } from '@amityco/ts-sdk'
26066
+ * const status = await follow('foobar')
26437
26067
  * ```
26438
26068
  *
26439
- * Fired when a {@link Amity.InternalUser} has been updated
26069
+ * Follow the user
26440
26070
  *
26441
- * @param callback The function to call when the event was fired
26442
- * @returns an {@link Amity.Unsubscriber} function to stop listening
26071
+ * @param userId the ID of the {@link Amity.InternalUser}
26072
+ * @returns the status {@link Amity.FollowStatus}
26443
26073
  *
26444
- * @category User Events
26074
+ * @category Follow API
26075
+ * @async
26445
26076
  */
26446
- const onUserUpdated = (callback) => createUserEventSubscriber('user.updated', callback);
26077
+ const follow = async (userId) => {
26078
+ const client = getActiveClient();
26079
+ client.log('follow/follow', userId);
26080
+ const { data } = await client.http.post(`/api/v4/me/following/${userId}`);
26081
+ const cachedAt = client.cache && Date.now();
26082
+ if (client.cache) {
26083
+ ingestInCache(data, { cachedAt });
26084
+ }
26085
+ const payload = prepareFollowStatusPayload(data);
26086
+ if (data.follows[0].status === 'accepted') {
26087
+ fireEvent('local.follow.created', payload);
26088
+ }
26089
+ else {
26090
+ fireEvent('local.follow.requested', payload);
26091
+ }
26092
+ return {
26093
+ data: data.follows[0],
26094
+ cachedAt,
26095
+ };
26096
+ };
26097
+ /* end_public_function */
26447
26098
 
26099
+ /* begin_public_function
26100
+ id: user.relationship.unfollow
26101
+ */
26448
26102
  /**
26449
26103
  * ```js
26450
- * import { onUserFlagged } from '@amityco/ts-sdk'
26451
- * const dispose = onUserFlagged(user => {
26452
- * // ...
26453
- * })
26104
+ * import { unfollow } from '@amityco/ts-sdk'
26105
+ * await unfollow('foobar')
26454
26106
  * ```
26455
26107
  *
26456
- * Fired when a {@link Amity.InternalUser} has been flagged
26108
+ * Cancel the follow request or unfollow the user
26457
26109
  *
26458
- * @param callback The function to call when the event was fired
26459
- * @returns an {@link Amity.Unsubscriber} function to stop listening
26110
+ * @param userId the ID of the {@link Amity.InternalUser}
26111
+ * @returns A success boolean if the user {@link Amity.InternalUser} was unfollowed
26460
26112
  *
26461
- * @category User Events
26113
+ * @category Follow API
26114
+ * @async
26462
26115
  */
26463
- const onUserFlagged = (callback) => createUserEventSubscriber('user.flagged', callback);
26116
+ const unfollow = async (userId) => {
26117
+ const client = getActiveClient();
26118
+ client.log('follow/unfollow', userId);
26119
+ const { data } = await client.http.delete(`/api/v4/me/following/${userId}`);
26120
+ if (client.cache) {
26121
+ ingestInCache(data);
26122
+ }
26123
+ const payload = prepareFollowStatusPayload(data);
26124
+ fireEvent('local.follow.unfollowed', payload);
26125
+ return true;
26126
+ };
26127
+ /* end_public_function */
26464
26128
 
26129
+ /* begin_public_function
26130
+ id: user.relationship.accept_follow
26131
+ */
26465
26132
  /**
26466
26133
  * ```js
26467
- * import { onUserUnflagged } from '@amityco/ts-sdk'
26468
- * const dispose = onUserUnflagged(user => {
26469
- * // ...
26470
- * })
26134
+ * import { UserRepository } from '@amityco/ts-sdk'
26135
+ * await UserRepository.Relationship.acceptMyFollower('foobar')
26471
26136
  * ```
26472
26137
  *
26473
- * Fired when a flag has been removed from a {@link Amity.InternalUser}
26138
+ * Accept the follow request
26474
26139
  *
26475
- * @param callback The function to call when the event was fired
26476
- * @returns an {@link Amity.Unsubscriber} function to stop listening
26140
+ * @param userId the ID of the {@link Amity.InternalUser} follower
26141
+ * @returns A success boolean if the follow request was accepted
26477
26142
  *
26478
- * @category User Events
26143
+ * @category Follow API
26144
+ * @async
26479
26145
  */
26480
- const onUserUnflagged = (callback) => createUserEventSubscriber('user.unflagged', callback);
26146
+ const acceptMyFollower = async (userId) => {
26147
+ const client = getActiveClient();
26148
+ client.log('follow/acceptMyFollower', userId);
26149
+ const { data } = await client.http.post(`/api/v4/me/followers/${userId}`);
26150
+ if (client.cache) {
26151
+ ingestInCache(data);
26152
+ }
26153
+ const payload = prepareFollowStatusPayload(data);
26154
+ fireEvent('local.follow.accepted', payload);
26155
+ return true;
26156
+ };
26157
+ /* end_public_function */
26481
26158
 
26159
+ /* begin_public_function
26160
+ id: user.relationship.decline_follow
26161
+ */
26482
26162
  /**
26483
26163
  * ```js
26484
- * import { onUserFlagCleared } from '@amityco/ts-sdk'
26485
- * const dispose = onUserFlagCleared(user => {
26486
- * // ...
26487
- * })
26164
+ * import { UserRepository } from '@amityco/ts-sdk'
26165
+ * await UserRepository.Relationship.declineMyFollower('foobar')
26488
26166
  * ```
26489
26167
  *
26490
- * Fired when flags have been cleared for a {@link Amity.InternalUser}
26168
+ * Decline the follow request or delete the follower
26491
26169
  *
26492
- * @param callback The function to call when the event was fired
26493
- * @returns an {@link Amity.Unsubscriber} function to stop listening
26170
+ * @param userId the ID of the {@link Amity.InternalUser} follower
26171
+ * @returns A success boolean if the follow request was decline
26494
26172
  *
26495
- * @category User Events
26173
+ * @category Follow API
26174
+ * @async
26496
26175
  */
26497
- const onUserFlagCleared = (callback) => createUserEventSubscriber('user.flagCleared', callback);
26498
-
26499
- var EnumUserActions;
26500
- (function (EnumUserActions) {
26501
- EnumUserActions["OnUserDeleted"] = "onUserDeleted";
26502
- EnumUserActions["OnUserUpdated"] = "onUserUpdated";
26503
- EnumUserActions["OnUserFlagged"] = "onUserFlagged";
26504
- EnumUserActions["OnUserUnflagged"] = "onUserUnflagged";
26505
- EnumUserActions["OnUserFlagCleared"] = "onUserFlagCleared";
26506
- })(EnumUserActions || (EnumUserActions = {}));
26176
+ const declineMyFollower = async (userId) => {
26177
+ const client = getActiveClient();
26178
+ client.log('follow/declineMyFollower', userId);
26179
+ const { data } = await client.http.delete(`/api/v4/me/followers/${userId}`);
26180
+ if (client.cache) {
26181
+ ingestInCache(data);
26182
+ }
26183
+ const payload = prepareFollowStatusPayload(data);
26184
+ fireEvent('local.follow.requestDeclined', payload);
26185
+ return true;
26186
+ };
26187
+ /* end_public_function */
26507
26188
 
26508
26189
  const createFollowEventSubscriber = (event, callback) => {
26509
26190
  const client = getActiveClient();
@@ -26767,446 +26448,50 @@ const onLocalFollowRequestAccepted = (callback) => createLocalFollowEventSubscri
26767
26448
 
26768
26449
  const onLocalFollowRequestDeclined = (callback) => createLocalFollowEventSubscriber('local.follow.requestDeclined', callback);
26769
26450
 
26770
- const convertEventPayload = (eventHandler, sourceModelProp, destinationDomain) => (callback) => eventHandler(sourceModel => {
26771
- var _a, _b;
26772
- if (!sourceModel) {
26773
- return sourceModel;
26774
- }
26775
- const client = getActiveClient();
26776
- const { objectSyncMap } = client;
26777
- /*
26778
- * 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.
26779
- * 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.
26780
- */
26781
- const resolvedId = isLocalId(sourceModel[sourceModelProp])
26782
- ? sourceModel[sourceModelProp]
26783
- : (_a = objectSyncMap.get(sourceModel[sourceModelProp])) !== null && _a !== void 0 ? _a : sourceModel[sourceModelProp];
26784
- const model = (_b = pullFromCache([
26785
- destinationDomain,
26786
- 'get',
26787
- `${resolvedId}`,
26788
- ])) === null || _b === void 0 ? void 0 : _b.data;
26789
- if (!model)
26790
- return;
26791
- return callback(model);
26792
- });
26793
-
26794
- class BlockedUserLiveCollectionController extends LiveCollectionController {
26795
- constructor(query, callback) {
26796
- const queryStreamId = hash(query);
26797
- const cacheKey = ['blockedUsers', 'collection', queryStreamId];
26798
- const paginationController = new BlockedUserPaginationController(query);
26799
- super(paginationController, queryStreamId, cacheKey, callback);
26800
- this.query = query;
26801
- this.queryStreamController = new BlockedUserQueryStreamController(this.query, this.cacheKey, this.notifyChange.bind(this), prepareBlockedUserPayload);
26802
- this.callback = callback.bind(this);
26803
- this.loadPage({ initial: true });
26804
- }
26805
- setup() {
26806
- var _a;
26807
- const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
26808
- if (!collection) {
26809
- pushToCache(this.cacheKey, {
26810
- data: [],
26811
- params: {},
26812
- });
26813
- }
26451
+ class PaginationController {
26452
+ constructor(queryParams) {
26453
+ const { http } = getActiveClient();
26454
+ this.queryParams = queryParams;
26455
+ this.http = http;
26814
26456
  }
26815
- async persistModel(queryPayload) {
26816
- await this.queryStreamController.saveToMainDB(queryPayload);
26457
+ loadFirstPage() {
26458
+ return this.onFetch("first" /* Amity.LiveCollectionPageDirection.FIRST */);
26817
26459
  }
26818
- persistQueryStream({ response, direction, refresh, }) {
26819
- this.queryStreamController.appendToQueryStream(response, direction, refresh);
26460
+ loadNextPage() {
26461
+ return this.onFetch("next" /* Amity.LiveCollectionPageDirection.NEXT */);
26820
26462
  }
26821
- startSubscription() {
26822
- return this.queryStreamController.subscribeRTE([
26823
- {
26824
- fn: onUserDeleted$2,
26825
- action: EnumUserActions.OnUserDeleted,
26826
- },
26827
- // In the case of unblocking a user, we need to subscribe to the follow events
26828
- {
26829
- fn: convertEventPayload(onLocalUserFollowed, 'to', 'user'),
26830
- action: EnumFollowActions.OnFollowed,
26831
- },
26832
- {
26833
- fn: convertEventPayload(onUserFollowed, 'to', 'user'),
26834
- action: EnumFollowActions.OnFollowed,
26835
- },
26836
- ]);
26463
+ loadPreviousPage() {
26464
+ return this.onFetch("prev" /* Amity.LiveCollectionPageDirection.PREV */);
26837
26465
  }
26838
- notifyChange({ origin, loading, error }) {
26839
- var _a, _b;
26840
- const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
26841
- if (!collection)
26466
+ async onFetch(direction = "first" /* Amity.LiveCollectionPageDirection.FIRST */) {
26467
+ var _a, _b, _c, _d;
26468
+ if (direction === 'prev' && !this.previousToken)
26842
26469
  return;
26843
- const data = this.applyFilter((_b = collection.data
26844
- .map(id => pullFromCache(['user', 'get', id]))
26845
- .filter(isNonNullable)
26846
- .map(({ data }) => data)
26847
- .map(LinkedObject.user)) !== null && _b !== void 0 ? _b : []);
26848
- if (!this.shouldNotify(data) && origin === 'event')
26470
+ if (direction === 'next' && !this.nextToken)
26849
26471
  return;
26850
- this.callback({
26851
- onNextPage: () => this.loadPage({ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */ }),
26852
- data,
26853
- hasNextPage: !!this.paginationController.getNextToken(),
26854
- loading,
26855
- error,
26856
- });
26857
- }
26858
- // eslint-disable-next-line class-methods-use-this
26859
- applyFilter(data) {
26860
- let users = data;
26861
- users = users.filter(user => user.isDeleted == null || user.isDeleted === false);
26862
- return users;
26863
- }
26864
- }
26865
-
26866
- /* begin_public_function
26867
- id: user.get_blocked_users
26868
- */
26869
- /**
26870
- * ```js
26871
- * import { UserRepository } from '@amityco/ts-sdk'
26872
- * const unblockedUser = await UserRepository.blockUser('userId')
26873
- * ```
26874
- *
26875
- * Blocks a {@link Amity.InternalUser}
26876
- *
26877
- * @param params The params to get blocked {@link Amity.InternalUser}s
26878
- * @param callback to recieve updates on unblocked {@link Amity.InternalUser}s
26879
- * @returns {@link Amity.Unsubscriber} to unsubscribe from collection
26880
- *
26881
- * @category Post API
26882
- * @async
26883
- */
26884
- const getBlockedUsers$1 = (params, callback, config) => {
26885
- const { log, cache } = getActiveClient();
26886
- if (!cache) {
26887
- console.log(ENABLE_CACHE_MESSAGE);
26888
- }
26889
- const timestamp = Date.now();
26890
- log(`getBlockedUsers(tmpid: ${timestamp}) > listen`);
26891
- const blockedUserLiveCollection = new BlockedUserLiveCollectionController(params, callback);
26892
- const disposers = blockedUserLiveCollection.startSubscription();
26893
- const cacheKey = blockedUserLiveCollection.getCacheKey();
26894
- disposers.push(() => dropFromCache(cacheKey));
26895
- return () => {
26896
- log(`getBlockedUsers(tmpid: ${timestamp}) > dispose`);
26897
- disposers.forEach(fn => fn());
26898
- dropFromCache(cacheKey);
26899
- };
26900
- };
26901
- /* end_public_function */
26902
-
26903
- /* eslint-disable no-use-before-define */
26904
- const getBlockedUsers = (params, callback, config) => {
26905
- console.log('Deprecation Notice: UserRepository.Relationship.getBlockedUsers will be deprecated on 9th June 2023, please use UserRepository.getBlockedUsers instead.');
26906
- return getBlockedUsers$1(params, callback);
26907
- };
26908
-
26909
- /* begin_public_function
26910
- id: user.relationship.follow
26911
- */
26912
- /**
26913
- * ```js
26914
- * import { follow } from '@amityco/ts-sdk'
26915
- * const status = await follow('foobar')
26916
- * ```
26917
- *
26918
- * Follow the user
26919
- *
26920
- * @param userId the ID of the {@link Amity.InternalUser}
26921
- * @returns the status {@link Amity.FollowStatus}
26922
- *
26923
- * @category Follow API
26924
- * @async
26925
- */
26926
- const follow = async (userId) => {
26927
- const client = getActiveClient();
26928
- client.log('follow/follow', userId);
26929
- const { data } = await client.http.post(`/api/v4/me/following/${userId}`);
26930
- const cachedAt = client.cache && Date.now();
26931
- if (client.cache) {
26932
- ingestInCache(data, { cachedAt });
26933
- }
26934
- const payload = prepareFollowStatusPayload(data);
26935
- if (data.follows[0].status === 'accepted') {
26936
- fireEvent('local.follow.created', payload);
26937
- }
26938
- else {
26939
- fireEvent('local.follow.requested', payload);
26940
- }
26941
- return {
26942
- data: data.follows[0],
26943
- cachedAt,
26944
- };
26945
- };
26946
- /* end_public_function */
26947
-
26948
- /* begin_public_function
26949
- id: user.relationship.unfollow
26950
- */
26951
- /**
26952
- * ```js
26953
- * import { unfollow } from '@amityco/ts-sdk'
26954
- * await unfollow('foobar')
26955
- * ```
26956
- *
26957
- * Cancel the follow request or unfollow the user
26958
- *
26959
- * @param userId the ID of the {@link Amity.InternalUser}
26960
- * @returns A success boolean if the user {@link Amity.InternalUser} was unfollowed
26961
- *
26962
- * @category Follow API
26963
- * @async
26964
- */
26965
- const unfollow = async (userId) => {
26966
- const client = getActiveClient();
26967
- client.log('follow/unfollow', userId);
26968
- const { data } = await client.http.delete(`/api/v4/me/following/${userId}`);
26969
- if (client.cache) {
26970
- ingestInCache(data);
26971
- }
26972
- const payload = prepareFollowStatusPayload(data);
26973
- fireEvent('local.follow.unfollowed', payload);
26974
- return true;
26975
- };
26976
- /* end_public_function */
26977
-
26978
- /**
26979
- * @deprecated This API renamed to `acceptMyFollower`.
26980
- * Please use acceptMyFollower() instead.
26981
- *
26982
- * ```js
26983
- * import { acceptFollower } from '@amityco/ts-sdk'
26984
- * await acceptFollower('foobar')
26985
- * ```
26986
- *
26987
- * Accept the follow request
26988
- *
26989
- * @param userId the ID of the {@link Amity.InternalUser} follower
26990
- * @returns A success boolean if the follow request was accepted
26991
- *
26992
- * @category Follow API
26993
- * @async
26994
- */
26995
- const acceptFollower = async (userId) => {
26996
- const client = getActiveClient();
26997
- client.log('follow/acceptFollower', userId);
26998
- const { data } = await client.http.post(`/api/v4/me/followers/${userId}`);
26999
- if (client.cache) {
27000
- ingestInCache(data);
27001
- }
27002
- const payload = prepareFollowStatusPayload(data);
27003
- fireEvent('local.follow.accepted', payload);
27004
- return true;
27005
- };
27006
-
27007
- /* begin_public_function
27008
- id: user.relationship.accept_follow
27009
- */
27010
- /**
27011
- * ```js
27012
- * import { UserRepository } from '@amityco/ts-sdk'
27013
- * await UserRepository.Relationship.acceptMyFollower('foobar')
27014
- * ```
27015
- *
27016
- * Accept the follow request
27017
- *
27018
- * @param userId the ID of the {@link Amity.InternalUser} follower
27019
- * @returns A success boolean if the follow request was accepted
27020
- *
27021
- * @category Follow API
27022
- * @async
27023
- */
27024
- const acceptMyFollower = async (userId) => {
27025
- const client = getActiveClient();
27026
- client.log('follow/acceptMyFollower', userId);
27027
- const { data } = await client.http.post(`/api/v4/me/followers/${userId}`);
27028
- if (client.cache) {
27029
- ingestInCache(data);
26472
+ let token;
26473
+ if (direction === 'prev')
26474
+ token = this.previousToken;
26475
+ if (direction === 'next')
26476
+ token = this.nextToken;
26477
+ const queryResponse = await this.getRequest(this.queryParams, token);
26478
+ if (direction === 'first') {
26479
+ this.nextToken = (_a = queryResponse.paging) === null || _a === void 0 ? void 0 : _a.next;
26480
+ this.previousToken = (_b = queryResponse.paging) === null || _b === void 0 ? void 0 : _b.previous;
26481
+ }
26482
+ if (direction === 'prev')
26483
+ this.previousToken = (_c = queryResponse.paging) === null || _c === void 0 ? void 0 : _c.previous;
26484
+ if (direction === 'next')
26485
+ this.nextToken = (_d = queryResponse.paging) === null || _d === void 0 ? void 0 : _d.next;
26486
+ return queryResponse;
27030
26487
  }
27031
- const payload = prepareFollowStatusPayload(data);
27032
- fireEvent('local.follow.accepted', payload);
27033
- return true;
27034
- };
27035
- /* end_public_function */
27036
-
27037
- /**
27038
- * @deprecated This API renamed to `declineMyFollower`.
27039
- * Please use declineMyFollower() instead.
27040
- *
27041
- * ```js
27042
- * import { declineFollower } from '@amityco/ts-sdk'
27043
- * await declineFollower('foobar')
27044
- * ```
27045
- *
27046
- * Decline the follow request or delete the follower
27047
- *
27048
- * @param userId the ID of the {@link Amity.InternalUser} follower
27049
- * @returns A success boolean if the follow request was decline
27050
- *
27051
- * @category Follow API
27052
- * @async
27053
- */
27054
- const declineFollower = async (userId) => {
27055
- const client = getActiveClient();
27056
- client.log('follow/declineFollower', userId);
27057
- const { data } = await client.http.delete(`/api/v4/me/followers/${userId}`);
27058
- if (client.cache) {
27059
- ingestInCache(data);
26488
+ getNextToken() {
26489
+ return this.nextToken;
27060
26490
  }
27061
- const payload = prepareFollowStatusPayload(data);
27062
- fireEvent('local.follow.requestDeclined', payload);
27063
- return true;
27064
- };
27065
-
27066
- /* begin_public_function
27067
- id: user.relationship.decline_follow
27068
- */
27069
- /**
27070
- * ```js
27071
- * import { UserRepository } from '@amityco/ts-sdk'
27072
- * await UserRepository.Relationship.declineMyFollower('foobar')
27073
- * ```
27074
- *
27075
- * Decline the follow request or delete the follower
27076
- *
27077
- * @param userId the ID of the {@link Amity.InternalUser} follower
27078
- * @returns A success boolean if the follow request was decline
27079
- *
27080
- * @category Follow API
27081
- * @async
27082
- */
27083
- const declineMyFollower = async (userId) => {
27084
- const client = getActiveClient();
27085
- client.log('follow/declineMyFollower', userId);
27086
- const { data } = await client.http.delete(`/api/v4/me/followers/${userId}`);
27087
- if (client.cache) {
27088
- ingestInCache(data);
26491
+ getPrevToken() {
26492
+ return this.previousToken;
27089
26493
  }
27090
- const payload = prepareFollowStatusPayload(data);
27091
- fireEvent('local.follow.requestDeclined', payload);
27092
- return true;
27093
- };
27094
- /* end_public_function */
27095
-
27096
- /**
27097
- * ```js
27098
- * import { observeFollowInfo } from '@amityco/ts-sdk'
27099
- *
27100
- * let followInfo = {}
27101
- * const dispose = observeFollowInfo(userId, updated => followInfo = updated)
27102
- * ```
27103
- *
27104
- * Observe all mutation on a given {@link Amity.FollowInfo}
27105
- *
27106
- * @param userId the ID of the user to observe
27107
- * @param callback the function to call when new data are available
27108
- * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the post
27109
- *
27110
- * @category Follow Observer
27111
- */
27112
- const observeFollowInfo = (userId, callback, policy = 'cache_then_server') => {
27113
- const { log } = getActiveClient();
27114
- const timestamp = Date.now();
27115
- log(`observeFollowInfo(tmpid: ${timestamp}) > listen`);
27116
- const router = (result, action) => {
27117
- var _a, _b;
27118
- if (callback instanceof Function)
27119
- return callback(result);
27120
- if (action !== 'onFetch')
27121
- (_a = callback.onEvent) === null || _a === void 0 ? void 0 : _a.call(callback, action, result);
27122
- (_b = callback[action]) === null || _b === void 0 ? void 0 : _b.call(callback, result);
27123
- };
27124
- const realtimeRouter = (result, action) => {
27125
- var _a;
27126
- if (((_a = result.data) === null || _a === void 0 ? void 0 : _a.userId) !== userId)
27127
- return;
27128
- router(result, action);
27129
- };
27130
- const disposers = [];
27131
- disposers.push(onFollowInfoUpdated(data => realtimeRouter({ data, loading: false, origin: 'event' }, 'onUpdate')));
27132
- runQuery(createQuery(getFollowInfo$1, userId), result => (result.data || result.error) && router(result, 'onFetch'), queryOptions(policy));
27133
- return () => {
27134
- log(`observeFollowInfo(tmpid: ${timestamp}) > dispose`);
27135
- disposers.forEach(fn => fn());
27136
- };
27137
- };
27138
-
27139
- /**
27140
- * ```js
27141
- * import { observeFollowers } from '@amityco/ts-sdk'
27142
- *
27143
- * let followers = []
27144
- * const unsub = observeFollowers('userId', follower => merge(followers, follower))
27145
- * ```
27146
- *
27147
- * Observe all mutations on a list of followers {@link Amity.FollowStatus} for a given user
27148
- *
27149
- * @param userId the ID of the {@link Amity.InternalUser}
27150
- * @param callback the function to call when new data are available
27151
- * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the messages
27152
- *
27153
- * @category Follow Observer
27154
- */
27155
- const observeFollowers = (userId, callback) => {
27156
- const { log } = getActiveClient();
27157
- const timestamp = Date.now();
27158
- log(`observeFollowers(tmpid: ${timestamp}) > listen`);
27159
- const disposers = [];
27160
- const router = (status, action) => {
27161
- var _a, _b;
27162
- if (callback instanceof Function) {
27163
- return callback(status);
27164
- }
27165
- (_a = callback.onEvent) === null || _a === void 0 ? void 0 : _a.call(callback, action, status);
27166
- (_b = callback[action]) === null || _b === void 0 ? void 0 : _b.call(callback, status);
27167
- };
27168
- 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')));
27169
- return () => {
27170
- log(`observeFollowers(tmpid: ${timestamp}) > dispose`);
27171
- disposers.forEach(fn => fn());
27172
- };
27173
- };
27174
-
27175
- /**
27176
- * ```js
27177
- * import { observeFollowings } from '@amityco/ts-sdk'
27178
- *
27179
- * let followings = []
27180
- * const unsub = observeFollowers('userId', follower => merge(followings, following))
27181
- * ```
27182
- *
27183
- * Observe all mutations on a list of followings {@link Amity.FollowStatus} for a given user
27184
- *
27185
- * @param userId the ID of the {@link Amity.InternalUser}
27186
- * @param callback the function to call when new data are available
27187
- * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the messages
27188
- *
27189
- * @category Follow Observer
27190
- */
27191
- const observeFollowings = (userId, callback) => {
27192
- const { log } = getActiveClient();
27193
- const timestamp = Date.now();
27194
- log(`observeFollowings(tmpid: ${timestamp}) > listen`);
27195
- const disposers = [];
27196
- const router = (status, action) => {
27197
- var _a, _b;
27198
- if (callback instanceof Function) {
27199
- return callback(status);
27200
- }
27201
- (_a = callback.onEvent) === null || _a === void 0 ? void 0 : _a.call(callback, action, status);
27202
- (_b = callback[action]) === null || _b === void 0 ? void 0 : _b.call(callback, status);
27203
- };
27204
- 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')));
27205
- return () => {
27206
- log(`observeFollowings(tmpid: ${timestamp}) > dispose`);
27207
- disposers.forEach(fn => fn());
27208
- };
27209
- };
26494
+ }
27210
26495
 
27211
26496
  class FollowerPaginationController extends PaginationController {
27212
26497
  async getRequest(queryParams, token) {
@@ -27221,6 +26506,25 @@ class FollowerPaginationController extends PaginationController {
27221
26506
  }
27222
26507
  }
27223
26508
 
26509
+ class QueryStreamController {
26510
+ constructor(query, cacheKey) {
26511
+ this.query = query;
26512
+ this.cacheKey = cacheKey;
26513
+ }
26514
+ }
26515
+
26516
+ var EnumFollowActions;
26517
+ (function (EnumFollowActions) {
26518
+ EnumFollowActions["OnRequested"] = "onRequested";
26519
+ EnumFollowActions["OnAccepted"] = "onAccepted";
26520
+ EnumFollowActions["OnDeclined"] = "onDeclined";
26521
+ EnumFollowActions["OnCanceled"] = "onCanceled";
26522
+ EnumFollowActions["OnFollowed"] = "onFollowed";
26523
+ EnumFollowActions["OnUnfollowed"] = "onUnfollowed";
26524
+ EnumFollowActions["OnDeleted"] = "onDeleted";
26525
+ EnumFollowActions["OnUserDeleted"] = "onUserDeleted";
26526
+ })(EnumFollowActions || (EnumFollowActions = {}));
26527
+
27224
26528
  class FollowerQueryStreamController extends QueryStreamController {
27225
26529
  constructor(query, cacheKey, notifyChange, preparePayload) {
27226
26530
  super(query, cacheKey);
@@ -27276,6 +26580,109 @@ class FollowerQueryStreamController extends QueryStreamController {
27276
26580
  }
27277
26581
  }
27278
26582
 
26583
+ class PaginationNoPageController {
26584
+ constructor(queryParams) {
26585
+ const { http } = getActiveClient();
26586
+ this.queryParams = queryParams;
26587
+ this.http = http;
26588
+ }
26589
+ async onFetch() {
26590
+ const queryResponse = await this.getRequest(this.queryParams);
26591
+ return queryResponse;
26592
+ }
26593
+ }
26594
+
26595
+ class LiveCollectionController {
26596
+ constructor(paginationController, queryStreamId, cacheKey, callback) {
26597
+ this.paginationController = paginationController;
26598
+ this.queryStreamId = queryStreamId;
26599
+ this.cacheKey = cacheKey;
26600
+ this.callback = callback;
26601
+ }
26602
+ async refresh() {
26603
+ try {
26604
+ let result;
26605
+ if (this.paginationController instanceof PaginationNoPageController) {
26606
+ result = await this.paginationController.onFetch();
26607
+ }
26608
+ else {
26609
+ result = await this.paginationController.loadFirstPage();
26610
+ }
26611
+ if (!result)
26612
+ return;
26613
+ await this.persistModel(result);
26614
+ this.persistQueryStream({
26615
+ response: result,
26616
+ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */,
26617
+ refresh: true,
26618
+ });
26619
+ this.notifyChange({ origin: "server" /* Amity.LiveDataOrigin.SERVER */, loading: false });
26620
+ }
26621
+ catch (e) {
26622
+ this.notifyChange({ origin: "server" /* Amity.LiveDataOrigin.SERVER */, loading: false, error: e });
26623
+ }
26624
+ }
26625
+ loadPage({ initial = false, direction = "next" /* Amity.LiveCollectionPageDirection.NEXT */, }) {
26626
+ this.setup();
26627
+ this.notifyChange({ origin: "local" /* Amity.LiveDataOrigin.LOCAL */, loading: true });
26628
+ if (initial) {
26629
+ this.refresh();
26630
+ }
26631
+ else if (direction === "prev" /* Amity.LiveCollectionPageDirection.PREV */) {
26632
+ this.loadPrevPage();
26633
+ }
26634
+ else if (direction === "next" /* Amity.LiveCollectionPageDirection.NEXT */) {
26635
+ this.loadNextPage();
26636
+ }
26637
+ }
26638
+ async loadNextPage() {
26639
+ try {
26640
+ if (this.paginationController instanceof PaginationNoPageController)
26641
+ return;
26642
+ const result = await this.paginationController.loadNextPage();
26643
+ if (!result)
26644
+ return;
26645
+ await this.persistModel(result);
26646
+ this.persistQueryStream({
26647
+ response: result,
26648
+ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */,
26649
+ });
26650
+ this.notifyChange({ origin: "server" /* Amity.LiveDataOrigin.SERVER */, loading: false });
26651
+ }
26652
+ catch (e) {
26653
+ this.notifyChange({ origin: "server" /* Amity.LiveDataOrigin.SERVER */, loading: false, error: e });
26654
+ }
26655
+ }
26656
+ async loadPrevPage() {
26657
+ try {
26658
+ if (this.paginationController instanceof PaginationNoPageController)
26659
+ return;
26660
+ const result = await this.paginationController.loadPreviousPage();
26661
+ if (!result)
26662
+ return;
26663
+ await this.persistModel(result);
26664
+ this.persistQueryStream({
26665
+ response: result,
26666
+ direction: "prev" /* Amity.LiveCollectionPageDirection.PREV */,
26667
+ });
26668
+ this.notifyChange({ origin: "server" /* Amity.LiveDataOrigin.SERVER */, loading: false });
26669
+ }
26670
+ catch (e) {
26671
+ this.notifyChange({ origin: "server" /* Amity.LiveDataOrigin.SERVER */, loading: false, error: e });
26672
+ }
26673
+ }
26674
+ shouldNotify(data) {
26675
+ const newData = data.map(convertGetterPropsToStatic).map(removeFunctionProperties);
26676
+ if (isEqual(this.snapshot, newData))
26677
+ return false;
26678
+ this.snapshot = newData;
26679
+ return true;
26680
+ }
26681
+ getCacheKey() {
26682
+ return this.cacheKey;
26683
+ }
26684
+ }
26685
+
27279
26686
  const onFollowerUserDeleted = ({ userId }) => (callback) => {
27280
26687
  const client = getActiveClient();
27281
26688
  const filter = (data) => {
@@ -27620,6 +27027,69 @@ const getFollowings = (params, callback, config) => {
27620
27027
  };
27621
27028
  /* end_public_function */
27622
27029
 
27030
+ /**
27031
+ * @deprecated This function will to be deprecated soon.
27032
+ */
27033
+ const liveObject = (id, callback, key, fetcher, eventHandlers, options) => {
27034
+ const { forceDispatch, callbackDataSelector, callbackFilter } = Object.assign({ forceDispatch: false, callbackDataSelector: (data) => data }, options);
27035
+ const { cache } = getActiveClient();
27036
+ if (!cache) {
27037
+ console.log(LIVE_OBJECT_ENABLE_CACHE_MESSAGE);
27038
+ }
27039
+ let model;
27040
+ let isUnsyncedModel = false; // for messages
27041
+ const disposers = [];
27042
+ const dispatcher = (data) => {
27043
+ const { data: newModel } = data, rest = __rest(data, ["data"]);
27044
+ if (!callbackFilter || callbackFilter(newModel, model)) {
27045
+ callback(Object.assign({ data: callbackDataSelector(newModel) }, rest));
27046
+ }
27047
+ // resolve all getter on data model to a static value to avoid comparison problems
27048
+ model = convertGetterPropsToStatic(newModel);
27049
+ };
27050
+ const realtimeRouter = (eventModel, forceDispatch = false) => {
27051
+ if (id !== eventModel[key]) {
27052
+ return;
27053
+ }
27054
+ if (model) {
27055
+ if (!forceDispatch && isEqual(model, eventModel)) {
27056
+ return;
27057
+ }
27058
+ }
27059
+ dispatcher({ loading: false, data: eventModel, origin: 'event' });
27060
+ };
27061
+ const onFetch = () => {
27062
+ // TODO: Ihis `@ts-ignore` is bring back to fix the build and it needs to be removed later
27063
+ // @ts-ignore
27064
+ const query = createQuery(fetcher, id, true);
27065
+ runQuery(query, ({ error, data, loading, origin, cachedAt }) => {
27066
+ if (cachedAt === UNSYNCED_OBJECT_CACHED_AT_VALUE) {
27067
+ dispatcher({
27068
+ // @ts-ignore
27069
+ data,
27070
+ origin,
27071
+ loading: false,
27072
+ error: new ASCApiError(UNSYNCED_OBJECT_CACHED_AT_MESSAGE, 800800 /* Amity.ClientError.DISALOOW_UNSYNCED_OBJECT */, "error" /* Amity.ErrorLevel.ERROR */),
27073
+ });
27074
+ isUnsyncedModel = true;
27075
+ disposers.forEach(fn => fn());
27076
+ }
27077
+ else if (!isUnsyncedModel) {
27078
+ // @ts-ignore
27079
+ dispatcher({ loading, data, origin, error });
27080
+ }
27081
+ if (error) {
27082
+ disposers.forEach(fn => fn());
27083
+ }
27084
+ });
27085
+ };
27086
+ disposers.push(...eventHandlers.map(fn => fn(eventModel => realtimeRouter(eventModel, forceDispatch))));
27087
+ onFetch();
27088
+ return () => {
27089
+ disposers.forEach(fn => fn());
27090
+ };
27091
+ };
27092
+
27623
27093
  /* begin_public_function
27624
27094
  id: user.relationship.get_follow_info
27625
27095
  */
@@ -27685,12 +27155,9 @@ var index$k = /*#__PURE__*/Object.freeze({
27685
27155
  __proto__: null,
27686
27156
  blockUser: blockUser,
27687
27157
  unBlockUser: unBlockUser,
27688
- getBlockedUsers: getBlockedUsers,
27689
27158
  follow: follow,
27690
27159
  unfollow: unfollow,
27691
- acceptFollower: acceptFollower,
27692
27160
  acceptMyFollower: acceptMyFollower,
27693
- declineFollower: declineFollower,
27694
27161
  declineMyFollower: declineMyFollower,
27695
27162
  onUserFollowed: onUserFollowed,
27696
27163
  onUserUnfollowed: onUserUnfollowed,
@@ -27705,9 +27172,6 @@ var index$k = /*#__PURE__*/Object.freeze({
27705
27172
  onLocalFollowerRequested: onLocalFollowerRequested,
27706
27173
  onLocalFollowRequestAccepted: onLocalFollowRequestAccepted,
27707
27174
  onLocalFollowRequestDeclined: onLocalFollowRequestDeclined,
27708
- observeFollowInfo: observeFollowInfo,
27709
- observeFollowers: observeFollowers,
27710
- observeFollowings: observeFollowings,
27711
27175
  getFollowers: getFollowers,
27712
27176
  getFollowings: getFollowings,
27713
27177
  getFollowInfo: getFollowInfo,
@@ -27895,6 +27359,74 @@ const isUserFlaggedByMe = async (userId) => {
27895
27359
  };
27896
27360
  /* end_public_function */
27897
27361
 
27362
+ /**
27363
+ * ```js
27364
+ * import { onUserUpdated } from '@amityco/ts-sdk'
27365
+ * const dispose = onUserUpdated(user => {
27366
+ * // ...
27367
+ * })
27368
+ * ```
27369
+ *
27370
+ * Fired when a {@link Amity.InternalUser} has been updated
27371
+ *
27372
+ * @param callback The function to call when the event was fired
27373
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
27374
+ *
27375
+ * @category User Events
27376
+ */
27377
+ const onUserUpdated = (callback) => createUserEventSubscriber('user.updated', callback);
27378
+
27379
+ /**
27380
+ * ```js
27381
+ * import { onUserFlagged } from '@amityco/ts-sdk'
27382
+ * const dispose = onUserFlagged(user => {
27383
+ * // ...
27384
+ * })
27385
+ * ```
27386
+ *
27387
+ * Fired when a {@link Amity.InternalUser} has been flagged
27388
+ *
27389
+ * @param callback The function to call when the event was fired
27390
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
27391
+ *
27392
+ * @category User Events
27393
+ */
27394
+ const onUserFlagged = (callback) => createUserEventSubscriber('user.flagged', callback);
27395
+
27396
+ /**
27397
+ * ```js
27398
+ * import { onUserUnflagged } from '@amityco/ts-sdk'
27399
+ * const dispose = onUserUnflagged(user => {
27400
+ * // ...
27401
+ * })
27402
+ * ```
27403
+ *
27404
+ * Fired when a flag has been removed from a {@link Amity.InternalUser}
27405
+ *
27406
+ * @param callback The function to call when the event was fired
27407
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
27408
+ *
27409
+ * @category User Events
27410
+ */
27411
+ const onUserUnflagged = (callback) => createUserEventSubscriber('user.unflagged', callback);
27412
+
27413
+ /**
27414
+ * ```js
27415
+ * import { onUserFlagCleared } from '@amityco/ts-sdk'
27416
+ * const dispose = onUserFlagCleared(user => {
27417
+ * // ...
27418
+ * })
27419
+ * ```
27420
+ *
27421
+ * Fired when flags have been cleared for a {@link Amity.InternalUser}
27422
+ *
27423
+ * @param callback The function to call when the event was fired
27424
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
27425
+ *
27426
+ * @category User Events
27427
+ */
27428
+ const onUserFlagCleared = (callback) => createUserEventSubscriber('user.flagCleared', callback);
27429
+
27898
27430
  /**
27899
27431
  * ```js
27900
27432
  * import { onUserFetched } from '@amityco/ts-sdk'
@@ -27926,7 +27458,7 @@ const onUserFetched = (callback) => createUserEventSubscriber('user.fetched', ca
27926
27458
  * @category Private
27927
27459
  * @async
27928
27460
  */
27929
- const getUser$2 = async (userId) => {
27461
+ const getUser$1 = async (userId) => {
27930
27462
  const client = getActiveClient();
27931
27463
  client.log('user/getUser', userId);
27932
27464
  isInTombstone('user', userId);
@@ -27962,7 +27494,7 @@ const getUser$2 = async (userId) => {
27962
27494
  *
27963
27495
  * @category User API
27964
27496
  */
27965
- getUser$2.locally = (userId) => {
27497
+ getUser$1.locally = (userId) => {
27966
27498
  const client = getActiveClient();
27967
27499
  client.log('user/getUser.locally', userId);
27968
27500
  if (!client.cache)
@@ -27998,11 +27530,11 @@ getUser$2.locally = (userId) => {
27998
27530
  *
27999
27531
  * @category Message Live Object
28000
27532
  */
28001
- const getUser$1 = (userId, callback) => {
27533
+ const getUser = (userId, callback) => {
28002
27534
  const reactor = (response) => {
28003
27535
  return callback(Object.assign(Object.assign({}, response), { data: response.data ? LinkedObject.user(response.data) : response.data }));
28004
27536
  };
28005
- return liveObject(userId, reactor, 'userId', getUser$2, [
27537
+ return liveObject(userId, reactor, 'userId', getUser$1, [
28006
27538
  onUserFetched,
28007
27539
  onUserUpdated,
28008
27540
  onUserDeleted$2,
@@ -28015,10 +27547,10 @@ const getUser$1 = (userId, callback) => {
28015
27547
 
28016
27548
  class UserPaginationController extends PaginationController {
28017
27549
  async getRequest(queryParams, token) {
28018
- const { limit = COLLECTION_DEFAULT_PAGINATION_LIMIT, displayName } = queryParams, params = __rest(queryParams, ["limit", "displayName"]);
27550
+ const { limit = COLLECTION_DEFAULT_PAGINATION_LIMIT } = queryParams, params = __rest(queryParams, ["limit"]);
28019
27551
  const options = token ? { token } : { limit };
28020
27552
  const { data: queryResponse } = await this.http.get(`/api/v3/users`, {
28021
- params: Object.assign(Object.assign({}, params), { keyword: displayName, options, isDeleted: false }),
27553
+ params: Object.assign(Object.assign({}, params), { options, isDeleted: false }),
28022
27554
  });
28023
27555
  return queryResponse;
28024
27556
  }
@@ -28070,6 +27602,15 @@ class UserQueryStreamController extends QueryStreamController {
28070
27602
  }
28071
27603
  }
28072
27604
 
27605
+ var EnumUserActions;
27606
+ (function (EnumUserActions) {
27607
+ EnumUserActions["OnUserDeleted"] = "onUserDeleted";
27608
+ EnumUserActions["OnUserUpdated"] = "onUserUpdated";
27609
+ EnumUserActions["OnUserFlagged"] = "onUserFlagged";
27610
+ EnumUserActions["OnUserUnflagged"] = "onUserUnflagged";
27611
+ EnumUserActions["OnUserFlagCleared"] = "onUserFlagCleared";
27612
+ })(EnumUserActions || (EnumUserActions = {}));
27613
+
28073
27614
  class UserLiveCollectionController extends LiveCollectionController {
28074
27615
  constructor(query, callback) {
28075
27616
  const queryStreamId = hash(query);
@@ -28128,21 +27669,17 @@ class UserLiveCollectionController extends LiveCollectionController {
28128
27669
  }
28129
27670
  applyFilter(data) {
28130
27671
  let users = data;
28131
- if (!this.query.displayName) {
28132
- const sortFn = (() => {
28133
- switch (this.query.sortBy) {
28134
- case 'firstCreated':
28135
- return sortByFirstCreated;
28136
- case 'lastCreated':
28137
- return sortByLastCreated;
28138
- case 'displayName':
28139
- return sortByDisplayName;
28140
- default:
28141
- return sortByLastCreated;
28142
- }
28143
- })();
28144
- users = users.sort(sortFn);
28145
- }
27672
+ const sortFn = (() => {
27673
+ switch (this.query.sortBy) {
27674
+ case 'firstCreated':
27675
+ return sortByFirstCreated;
27676
+ case 'lastCreated':
27677
+ return sortByLastCreated;
27678
+ default:
27679
+ return sortByLastCreated;
27680
+ }
27681
+ })();
27682
+ users = users.sort(sortFn);
28146
27683
  if (this.query.filter === 'flagged') {
28147
27684
  users = users.filter(user => !!user.hashFlag);
28148
27685
  }
@@ -28189,90 +27726,200 @@ const getUsers = (params, callback, config) => {
28189
27726
  };
28190
27727
  /* end_public_function */
28191
27728
 
28192
- /**
28193
- * ```js
28194
- * import { getUser } from '~/user/api'
28195
- * const { data: user } = await getUser('foobar')
28196
- * ```
28197
- *
28198
- * Fetches a {@link Amity.User} object
28199
- *
28200
- * @param userId the ID of the {@link Amity.User} to fetch
28201
- * @returns the associated {@link Amity.User} object
28202
- *
28203
- * @category Private
28204
- * @async
28205
- */
28206
- const getUser = async (userId) => {
28207
- const { data, cachedAt } = await getUser$2(userId);
28208
- return {
28209
- data: LinkedObject.user(data),
28210
- cachedAt,
28211
- };
28212
- };
28213
- /**
28214
- * ```js
28215
- * import { getUser } from '@amityco/ts-sdk'
28216
- * const { data: user } = getUser.locally('foobar')
28217
- * ```
28218
- *
28219
- * Fetches a {@link Amity.User} object from cache
28220
- *
28221
- * @param userId the ID of the {@link Amity.User} to fetch
28222
- * @returns the associated {@link Amity.User} object
28223
- *
28224
- * @category User API
28225
- */
28226
- getUser.locally = (userId) => {
28227
- const cached = getUser$2.locally(userId);
28228
- if (!cached)
27729
+ class BlockedUserPaginationController extends PaginationController {
27730
+ async getRequest(queryParams, token) {
27731
+ const { limit = COLLECTION_DEFAULT_PAGINATION_LIMIT } = queryParams, params = __rest(queryParams, ["limit"]);
27732
+ const options = token ? { token } : { limit };
27733
+ const { data: queryResponse } = await this.http.get('/api/v4/me/user-blocks', {
27734
+ params: Object.assign(Object.assign({}, params), { options, isDeleted: false }),
27735
+ });
27736
+ return queryResponse;
27737
+ }
27738
+ }
27739
+
27740
+ class BlockedUserQueryStreamController extends QueryStreamController {
27741
+ constructor(query, cacheKey, notifyChange, preparePayload) {
27742
+ super(query, cacheKey);
27743
+ this.notifyChange = notifyChange;
27744
+ this.preparePayload = preparePayload;
27745
+ }
27746
+ async saveToMainDB(response) {
27747
+ const processedPayload = await this.preparePayload(response);
27748
+ const client = getActiveClient();
27749
+ const cachedAt = client.cache && Date.now();
27750
+ if (client.cache) {
27751
+ ingestInCache(processedPayload, { cachedAt });
27752
+ }
27753
+ }
27754
+ appendToQueryStream(response, direction, refresh = false) {
27755
+ var _a, _b;
27756
+ if (refresh) {
27757
+ pushToCache(this.cacheKey, {
27758
+ data: response.users.map(getResolver('user')),
27759
+ });
27760
+ }
27761
+ else {
27762
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
27763
+ const users = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
27764
+ pushToCache(this.cacheKey, Object.assign(Object.assign({}, collection), { data: [...new Set([...users, ...response.users.map(getResolver('user'))])] }));
27765
+ }
27766
+ }
27767
+ reactor(action) {
27768
+ return (targetUser) => {
27769
+ var _a;
27770
+ if (action === EnumFollowActions.OnFollowed) {
27771
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
27772
+ const updatedCollection = collection === null || collection === void 0 ? void 0 : collection.data.filter(id => id !== targetUser.userId);
27773
+ pushToCache(this.cacheKey, Object.assign(Object.assign({}, collection), { data: updatedCollection }));
27774
+ }
27775
+ this.notifyChange({ origin: "event" /* Amity.LiveDataOrigin.EVENT */, loading: false });
27776
+ };
27777
+ }
27778
+ subscribeRTE(createSubscriber) {
27779
+ return createSubscriber.map(subscriber => subscriber.fn(this.reactor(subscriber.action)));
27780
+ }
27781
+ }
27782
+
27783
+ function prepareBlockedUserPayload(response) {
27784
+ const { users, follows } = response, rest = __rest(response, ["users", "follows"]);
27785
+ return Object.assign(Object.assign({}, rest), { follows: follows.map(follow => {
27786
+ const followUser = users.find(user => user.userId === follow.from);
27787
+ return Object.assign(Object.assign({}, follow), { user: convertRawUserToInternalUser(followUser) });
27788
+ }), users: users.map(convertRawUserToInternalUser) });
27789
+ }
27790
+
27791
+ const convertEventPayload = (eventHandler, sourceModelProp, destinationDomain) => (callback) => eventHandler(sourceModel => {
27792
+ var _a, _b;
27793
+ if (!sourceModel) {
27794
+ return sourceModel;
27795
+ }
27796
+ const client = getActiveClient();
27797
+ const { objectSyncMap } = client;
27798
+ /*
27799
+ * 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.
27800
+ * 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.
27801
+ */
27802
+ const resolvedId = isLocalId(sourceModel[sourceModelProp])
27803
+ ? sourceModel[sourceModelProp]
27804
+ : (_a = objectSyncMap.get(sourceModel[sourceModelProp])) !== null && _a !== void 0 ? _a : sourceModel[sourceModelProp];
27805
+ const model = (_b = pullFromCache([
27806
+ destinationDomain,
27807
+ 'get',
27808
+ `${resolvedId}`,
27809
+ ])) === null || _b === void 0 ? void 0 : _b.data;
27810
+ if (!model)
28229
27811
  return;
28230
- return {
28231
- data: LinkedObject.user(cached.data),
28232
- cachedAt: cached.cachedAt,
28233
- };
28234
- };
27812
+ return callback(model);
27813
+ });
28235
27814
 
27815
+ class BlockedUserLiveCollectionController extends LiveCollectionController {
27816
+ constructor(query, callback) {
27817
+ const queryStreamId = hash(query);
27818
+ const cacheKey = ['blockedUsers', 'collection', queryStreamId];
27819
+ const paginationController = new BlockedUserPaginationController(query);
27820
+ super(paginationController, queryStreamId, cacheKey, callback);
27821
+ this.query = query;
27822
+ this.queryStreamController = new BlockedUserQueryStreamController(this.query, this.cacheKey, this.notifyChange.bind(this), prepareBlockedUserPayload);
27823
+ this.callback = callback.bind(this);
27824
+ this.loadPage({ initial: true });
27825
+ }
27826
+ setup() {
27827
+ var _a;
27828
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
27829
+ if (!collection) {
27830
+ pushToCache(this.cacheKey, {
27831
+ data: [],
27832
+ params: {},
27833
+ });
27834
+ }
27835
+ }
27836
+ async persistModel(queryPayload) {
27837
+ await this.queryStreamController.saveToMainDB(queryPayload);
27838
+ }
27839
+ persistQueryStream({ response, direction, refresh, }) {
27840
+ this.queryStreamController.appendToQueryStream(response, direction, refresh);
27841
+ }
27842
+ startSubscription() {
27843
+ return this.queryStreamController.subscribeRTE([
27844
+ {
27845
+ fn: onUserDeleted$2,
27846
+ action: EnumUserActions.OnUserDeleted,
27847
+ },
27848
+ // In the case of unblocking a user, we need to subscribe to the follow events
27849
+ {
27850
+ fn: convertEventPayload(onLocalUserFollowed, 'to', 'user'),
27851
+ action: EnumFollowActions.OnFollowed,
27852
+ },
27853
+ {
27854
+ fn: convertEventPayload(onUserFollowed, 'to', 'user'),
27855
+ action: EnumFollowActions.OnFollowed,
27856
+ },
27857
+ ]);
27858
+ }
27859
+ notifyChange({ origin, loading, error }) {
27860
+ var _a, _b;
27861
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
27862
+ if (!collection)
27863
+ return;
27864
+ const data = this.applyFilter((_b = collection.data
27865
+ .map(id => pullFromCache(['user', 'get', id]))
27866
+ .filter(isNonNullable)
27867
+ .map(({ data }) => data)
27868
+ .map(LinkedObject.user)) !== null && _b !== void 0 ? _b : []);
27869
+ if (!this.shouldNotify(data) && origin === 'event')
27870
+ return;
27871
+ this.callback({
27872
+ onNextPage: () => this.loadPage({ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */ }),
27873
+ data,
27874
+ hasNextPage: !!this.paginationController.getNextToken(),
27875
+ loading,
27876
+ error,
27877
+ });
27878
+ }
27879
+ // eslint-disable-next-line class-methods-use-this
27880
+ applyFilter(data) {
27881
+ let users = data;
27882
+ users = users.filter(user => user.isDeleted == null || user.isDeleted === false);
27883
+ return users;
27884
+ }
27885
+ }
27886
+
27887
+ /* begin_public_function
27888
+ id: user.get_blocked_users
27889
+ */
28236
27890
  /**
28237
27891
  * ```js
28238
- * import { observeUser } from '@amityco/ts-sdk'
28239
- *
28240
- * let user = {}
28241
- * const dispose = observeUser(userId, updated => user = updated)
27892
+ * import { UserRepository } from '@amityco/ts-sdk'
27893
+ * const unblockedUser = await UserRepository.blockUser('userId')
28242
27894
  * ```
28243
27895
  *
28244
- * @param userId the ID of the user to observe
28245
- * @param callback the function to call when new data are available
28246
- * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the user
27896
+ * Blocks a {@link Amity.InternalUser}
27897
+ *
27898
+ * @param params The params to get blocked {@link Amity.InternalUser}s
27899
+ * @param callback to recieve updates on unblocked {@link Amity.InternalUser}s
27900
+ * @returns {@link Amity.Unsubscriber} to unsubscribe from collection
28247
27901
  *
28248
- * Observe all mutation on a given {@link Amity.InternalUser}
28249
- * @category User Observer
27902
+ * @category Post API
27903
+ * @async
28250
27904
  */
28251
- const observeUser = (userId, callback) => {
28252
- const { log } = getActiveClient();
27905
+ const getBlockedUsers = (params, callback, config) => {
27906
+ const { log, cache } = getActiveClient();
27907
+ if (!cache) {
27908
+ console.log(ENABLE_CACHE_MESSAGE);
27909
+ }
28253
27910
  const timestamp = Date.now();
28254
- log(`observeUser(tmpid: ${timestamp}) > listen`);
28255
- // wrapper function to make sure
28256
- const router = (result, action) => {
28257
- var _a, _b, _c;
28258
- // filter function
28259
- if (((_a = result.data) === null || _a === void 0 ? void 0 : _a.userId) !== userId)
28260
- return;
28261
- const newResult = Object.assign(Object.assign({}, result), { data: LinkedObject.user(result.data) });
28262
- if (callback instanceof Function)
28263
- return callback(newResult);
28264
- if (action !== 'onFetch')
28265
- (_b = callback.onEvent) === null || _b === void 0 ? void 0 : _b.call(callback, action, newResult);
28266
- (_c = callback[action]) === null || _c === void 0 ? void 0 : _c.call(callback, newResult);
28267
- };
28268
- const disposers = [];
28269
- 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')));
28270
- runQuery(createQuery(getUser, userId), result => result.data && router(result, 'onFetch'));
27911
+ log(`getBlockedUsers(tmpid: ${timestamp}) > listen`);
27912
+ const blockedUserLiveCollection = new BlockedUserLiveCollectionController(params, callback);
27913
+ const disposers = blockedUserLiveCollection.startSubscription();
27914
+ const cacheKey = blockedUserLiveCollection.getCacheKey();
27915
+ disposers.push(() => dropFromCache(cacheKey));
28271
27916
  return () => {
28272
- log(`observeUser(tmpid: ${timestamp}) > dispose`);
27917
+ log(`getBlockedUsers(tmpid: ${timestamp}) > dispose`);
28273
27918
  disposers.forEach(fn => fn());
27919
+ dropFromCache(cacheKey);
28274
27920
  };
28275
- };
27921
+ };
27922
+ /* end_public_function */
28276
27923
 
28277
27924
  class SearchUserPaginationController extends PaginationController {
28278
27925
  async getRequest(queryParams, token) {
@@ -28457,74 +28104,6 @@ const queryReachUser = async ({ viewId, viewedType, limit, token, }) => {
28457
28104
  return response.data;
28458
28105
  };
28459
28106
 
28460
- /**
28461
- * @deprecated: Please use {@link UserRepository.getReachUsers} instead
28462
- * @param params
28463
- * @param callback
28464
- */
28465
- const getViewedUsers = (params, callback) => {
28466
- const { log, cache } = getActiveClient();
28467
- const cacheKey = ['postViewedUsers', 'collection', { postId: params.postId }];
28468
- if (!cache) {
28469
- console.log(ENABLE_CACHE_MESSAGE);
28470
- }
28471
- const timestamp = Date.now();
28472
- log(`getViewedUsers(tmpid: ${timestamp}) > listen`);
28473
- const { limit: queryLimit, postId } = params;
28474
- const responder = (snapshot) => {
28475
- var _a, _b;
28476
- let users = [];
28477
- if (snapshot === null || snapshot === void 0 ? void 0 : snapshot.data) {
28478
- users =
28479
- snapshot.data
28480
- .map((userId) => pullFromCache(['user', 'get', userId]))
28481
- .filter(Boolean)
28482
- .map(data => data === null || data === void 0 ? void 0 : data.data) || [];
28483
- }
28484
- callback({
28485
- // eslint-disable-next-line no-use-before-define
28486
- onNextPage: onFetch,
28487
- data: users,
28488
- hasNextPage: !!((_b = (_a = snapshot.params) === null || _a === void 0 ? void 0 : _a.page) === null || _b === void 0 ? void 0 : _b.next),
28489
- loading: snapshot.loading || false,
28490
- });
28491
- };
28492
- const onFetch = (initial = false) => {
28493
- var _a, _b, _c;
28494
- const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
28495
- const users = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
28496
- if (!initial && users.length > 0 && !(collection === null || collection === void 0 ? void 0 : collection.params.page))
28497
- return;
28498
- const query = createQuery(queryReachUser, {
28499
- viewId: postId,
28500
- viewedType: "post" /* Amity.AnalyticEventContentType.Post */,
28501
- limit: queryLimit || 10,
28502
- token: !initial ? (_c = collection === null || collection === void 0 ? void 0 : collection.params.page) === null || _c === void 0 ? void 0 : _c.next : undefined,
28503
- });
28504
- runQuery(query, result => {
28505
- var _a, _b, _c, _d, _e;
28506
- 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 : [];
28507
- if ((_d = result.data) === null || _d === void 0 ? void 0 : _d.users) {
28508
- userIds = [
28509
- ...new Set([...userIds, ...result.data.users.map(({ userId }) => userId)]),
28510
- ];
28511
- }
28512
- const saveToCache = {
28513
- loading: result.loading,
28514
- params: { page: (_e = result.data) === null || _e === void 0 ? void 0 : _e.paging },
28515
- data: userIds || [],
28516
- };
28517
- pushToCache(cacheKey, saveToCache);
28518
- responder(saveToCache);
28519
- }, queryOptions(COLLECTION_DEFAULT_CACHING_POLICY, CACHE_SHORTEN_LIFESPAN));
28520
- };
28521
- onFetch(true);
28522
- return () => {
28523
- log(`getViewedUsers(tmpid: ${timestamp}) > dispose`);
28524
- dropFromCache(cacheKey);
28525
- };
28526
- };
28527
-
28528
28107
  const getReachedUsers = (params, callback) => {
28529
28108
  // Pre-defined function to avoid undefined function call
28530
28109
  let onFetch = (initial = false) => undefined;
@@ -28612,12 +28191,10 @@ var index$j = /*#__PURE__*/Object.freeze({
28612
28191
  onUserFlagged: onUserFlagged,
28613
28192
  onUserUnflagged: onUserUnflagged,
28614
28193
  onUserFlagCleared: onUserFlagCleared,
28615
- getUser: getUser$1,
28194
+ getUser: getUser,
28616
28195
  getUsers: getUsers,
28617
- observeUser: observeUser,
28618
- getBlockedUsers: getBlockedUsers$1,
28196
+ getBlockedUsers: getBlockedUsers,
28619
28197
  searchUserByDisplayName: searchUserByDisplayName,
28620
- getViewedUsers: getViewedUsers,
28621
28198
  getReachedUsers: getReachedUsers,
28622
28199
  get AmityUserSearchMatchType () { return AmityUserSearchMatchType; }
28623
28200
  });
@@ -28867,181 +28444,6 @@ const uploadImage = async (formData, onProgress) => {
28867
28444
  };
28868
28445
  /* end_public_function */
28869
28446
 
28870
- /**
28871
- * ```js
28872
- * import { createImage } from '@amityco/ts-sdk'
28873
- * const created = await createImage(formData)
28874
- * ```
28875
- *
28876
- * Creates an {@link Amity.File<'image'>}
28877
- *
28878
- * @param formData The data necessary to create a new {@link Amity.File<'image'>}
28879
- * @param onProgress The callback to track the upload progress
28880
- * @returns The newly created {@link Amity.File<'image'>}
28881
- *
28882
- * @category File API
28883
- * @async
28884
- */
28885
- const createImage = async (formData, onProgress) => {
28886
- const client = getActiveClient();
28887
- client.log('file/createImage', formData);
28888
- const files = formData.getAll('files');
28889
- if (!files.length)
28890
- throw new Error('The formData object must have a `files` key.');
28891
- const accessType = GlobalFileAccessType$1.getInstance().getFileAccessType();
28892
- formData.append('accessType', accessType);
28893
- formData.append('preferredFilename', files[0].name);
28894
- const headers = 'getHeaders' in formData
28895
- ? formData.getHeaders()
28896
- : { 'content-type': 'multipart/form-data' };
28897
- const { data } = await client.http.post('/api/v4/images', formData, {
28898
- headers,
28899
- onUploadProgress({ loaded, total = 100 }) {
28900
- onProgress && onProgress(Math.round((loaded * 100) / total));
28901
- },
28902
- });
28903
- // API-FIX: payload should be serialized properly
28904
- // const { files } = data
28905
- const cachedAt = client.cache && Date.now();
28906
- if (client.cache)
28907
- ingestInCache({ files: data }, { cachedAt });
28908
- return {
28909
- data,
28910
- cachedAt,
28911
- };
28912
- };
28913
- /* end_public_function */
28914
-
28915
- /**
28916
- * ```js
28917
- * import { FileRepository } from '@amityco/ts-sdk'
28918
- * const created = await FileRepository.createFile(formData)
28919
- * ```
28920
- *
28921
- * Creates an {@link Amity.File}
28922
- *
28923
- * @param formData The data necessary to create a new {@link Amity.File}
28924
- * @param onProgress The callback to track the upload progress
28925
- * @returns The newly created {@link Amity.File}
28926
- *
28927
- * @category File API
28928
- * @async
28929
- */
28930
- const createFile = async (formData, onProgress) => {
28931
- const client = getActiveClient();
28932
- client.log('file/createFile', formData);
28933
- const files = formData.getAll('files');
28934
- if (!files.length)
28935
- throw new Error('The formData object must have a `files` key.');
28936
- const accessType = GlobalFileAccessType$1.getInstance().getFileAccessType();
28937
- formData.append('accessType', accessType);
28938
- formData.append('preferredFilename', files[0].name);
28939
- const headers = 'getHeaders' in formData
28940
- ? formData.getHeaders()
28941
- : { 'content-type': 'multipart/form-data' };
28942
- const { data } = await client.http.post('/api/v4/files', formData, {
28943
- headers,
28944
- onUploadProgress({ loaded, total = 100 }) {
28945
- onProgress && onProgress(Math.round((loaded * 100) / total));
28946
- },
28947
- });
28948
- // API-FIX: payload should be serialized properly
28949
- // const { files } = data
28950
- const cachedAt = client.cache && Date.now();
28951
- if (client.cache)
28952
- ingestInCache({ files: data }, { cachedAt });
28953
- return {
28954
- data,
28955
- cachedAt,
28956
- };
28957
- };
28958
-
28959
- /**
28960
- * ```js
28961
- * import { FileRepository } from '@amityco/ts-sdk'
28962
- * const created = await FileRepository.createVideo(formData)
28963
- * ```
28964
- *
28965
- * Creates an {@link Amity.File<'video'>}
28966
- *
28967
- * @param formData The data necessary to create a new {@link Amity.File<'video'>}
28968
- * @param feedType The {@link Amity.File<'video'>} feed type
28969
- * @param onProgress The callback to track the upload progress
28970
- * @returns The newly uploaded {@link Amity.File<'video'>}
28971
- *
28972
- * @category File API
28973
- * @async
28974
- */
28975
- const createVideo = async (formData, feedType, onProgress) => {
28976
- const client = getActiveClient();
28977
- client.log('file/createVideo', formData);
28978
- const files = formData.getAll('files');
28979
- if (!files.length)
28980
- throw new Error('The formData object must have a `files` key.');
28981
- const accessType = GlobalFileAccessType$1.getInstance().getFileAccessType();
28982
- formData.append('accessType', accessType);
28983
- formData.append('preferredFilename', files[0].name);
28984
- if (feedType) {
28985
- formData.append('feedType', feedType);
28986
- }
28987
- const headers = 'getHeaders' in formData
28988
- ? formData.getHeaders()
28989
- : { 'content-type': 'multipart/form-data' };
28990
- const { data } = await client.http.post('/api/v4/videos', formData, {
28991
- headers,
28992
- onUploadProgress({ loaded, total = 100 }) {
28993
- onProgress && onProgress(Math.round((loaded * 100) / total));
28994
- },
28995
- });
28996
- // API-FIX: payload should be serialized properly
28997
- // const { files } = data
28998
- const cachedAt = client.cache && Date.now();
28999
- if (client.cache)
29000
- ingestInCache({ files: data }, { cachedAt });
29001
- return {
29002
- data,
29003
- cachedAt,
29004
- };
29005
- };
29006
-
29007
- /**
29008
- * ```js
29009
- * import { observeFile } from '@amityco/ts-sdk'
29010
- *
29011
- * let file = {}
29012
- * const dispose = observeFile(fileId, updated => file = updated)
29013
- * ```
29014
- *
29015
- * Observe all mutation on a given {@link Amity.File}
29016
- *
29017
- * @param fileId the ID of the file to observe
29018
- * @param callback the function to call when new data are available
29019
- * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the file
29020
- *
29021
- * @category File Observer
29022
- */
29023
- const observeFile = (fileId, callback) => {
29024
- const { log } = getActiveClient();
29025
- const timestamp = Date.now();
29026
- log(`observeFile(tmpid: ${timestamp}) > listen`);
29027
- // wrapper function to make sure
29028
- const router = (result, action) => {
29029
- var _a, _b, _c;
29030
- // filter function
29031
- if (((_a = result.data) === null || _a === void 0 ? void 0 : _a.fileId) !== fileId)
29032
- return;
29033
- if (callback instanceof Function)
29034
- return callback(result);
29035
- if (action !== 'onFetch')
29036
- (_b = callback.onEvent) === null || _b === void 0 ? void 0 : _b.call(callback, action, result);
29037
- (_c = callback[action]) === null || _c === void 0 ? void 0 : _c.call(callback, result);
29038
- };
29039
- runQuery(createQuery(getFile, fileId), result => result.data && router(result, 'onFetch'));
29040
- return () => {
29041
- log(`observeFile(tmpid: ${timestamp}) > dispose`);
29042
- };
29043
- };
29044
-
29045
28447
  var index$i = /*#__PURE__*/Object.freeze({
29046
28448
  __proto__: null,
29047
28449
  getFile: getFile,
@@ -29049,11 +28451,7 @@ var index$i = /*#__PURE__*/Object.freeze({
29049
28451
  deleteFile: deleteFile,
29050
28452
  fileUrlWithSize: fileUrlWithSize,
29051
28453
  uploadVideo: uploadVideo,
29052
- uploadImage: uploadImage,
29053
- createImage: createImage,
29054
- createFile: createFile,
29055
- createVideo: createVideo,
29056
- observeFile: observeFile
28454
+ uploadImage: uploadImage
29057
28455
  });
29058
28456
 
29059
28457
  /**
@@ -29074,16 +28472,12 @@ var index$i = /*#__PURE__*/Object.freeze({
29074
28472
  const queryRoles = async (query) => {
29075
28473
  const client = getActiveClient();
29076
28474
  client.log('role/queryRoles', query);
29077
- const _a = query !== null && query !== void 0 ? query : {}, { page, limit = 10, queryToken, displayName, sortBy } = _a, params = __rest(_a, ["page", "limit", "queryToken", "displayName", "sortBy"]);
28475
+ const _a = query !== null && query !== void 0 ? query : {}, { limit = 10, queryToken, displayName, sortBy } = _a, params = __rest(_a, ["limit", "queryToken", "displayName", "sortBy"]);
29078
28476
  const options = (() => {
29079
28477
  if (queryToken)
29080
28478
  return { token: queryToken };
29081
28479
  if (limit)
29082
28480
  return { limit };
29083
- if (page)
29084
- return {
29085
- token: toToken(page, 'skiplimit'),
29086
- };
29087
28481
  return undefined;
29088
28482
  })();
29089
28483
  // API-FIX: parameters should be querystring.
@@ -29211,12 +28605,9 @@ const dispatchReactable = (referenceType, model) => {
29211
28605
  * @category Message API
29212
28606
  * @async
29213
28607
  */
29214
- const getMessage$2 = async (messageId, isLive = false) => {
28608
+ const getMessage$1 = async (messageId, isLive = false) => {
29215
28609
  const client = getActiveClient();
29216
28610
  client.log('message/getMessage', messageId);
29217
- if (!isLive) {
29218
- console.log('getMessage will be deprecated on 15th November 2022, please use liveMessage instead.');
29219
- }
29220
28611
  isInTombstone('message', messageId);
29221
28612
  let data;
29222
28613
  try {
@@ -29253,7 +28644,7 @@ const getMessage$2 = async (messageId, isLive = false) => {
29253
28644
  *
29254
28645
  * @category Message API
29255
28646
  */
29256
- getMessage$2.locally = (messageId) => {
28647
+ getMessage$1.locally = (messageId) => {
29257
28648
  const client = getActiveClient();
29258
28649
  client.log('message/getMessage.locally', messageId);
29259
28650
  if (!client.cache)
@@ -31182,7 +30573,7 @@ const getChannel$1 = async (channelId) => {
31182
30573
  ingestInCache(data, { cachedAt });
31183
30574
  const { channels } = data;
31184
30575
  return {
31185
- data: constructChannelDynamicValue(channels.find(channel => channel.channelId === channelId)),
30576
+ data: channels.find(channel => channel.channelId === channelId),
31186
30577
  cachedAt,
31187
30578
  };
31188
30579
  };
@@ -31212,7 +30603,7 @@ getChannel$1.locally = (channelId) => {
31212
30603
  if (!cached || (cached === null || cached === void 0 ? void 0 : cached.length) === 0)
31213
30604
  return;
31214
30605
  return {
31215
- data: constructChannelDynamicValue(cached[0].data),
30606
+ data: cached[0].data,
31216
30607
  cachedAt: cached[0].cachedAt,
31217
30608
  };
31218
30609
  };
@@ -31237,7 +30628,7 @@ const deleteChannel = async (channelId) => {
31237
30628
  await client.http.delete(`/api/v3/channels/${encodeURIComponent(channelId)}`);
31238
30629
  const deleted = await getChannel$1(channelId);
31239
30630
  // no need for event, fired by server
31240
- return deleted.data;
30631
+ return constructChannelDynamicValue(deleted.data);
31241
30632
  };
31242
30633
 
31243
30634
  /* begin_public_function
@@ -31359,81 +30750,6 @@ const unmuteChannel = async (channelId) => {
31359
30750
  };
31360
30751
  /* end_public_function */
31361
30752
 
31362
- /**
31363
- * ```js
31364
- * import { observeChannel } from '@amityco/ts-sdk'
31365
- *
31366
- * let channel = {}
31367
- * const dispose = observeChannel(channelId, ({ data }) => channel = data)
31368
- * ```
31369
- *
31370
- * Observe all mutation on a given {@link Amity.Channel}
31371
- *
31372
- * @param channelId the ID of the channel to observe
31373
- * @param callback the function to call when new data are available
31374
- * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the channel
31375
- *
31376
- * @category Channel Observer
31377
- */
31378
- const observeChannel = (channelId, callback) => {
31379
- const { log } = getActiveClient();
31380
- const timestamp = Date.now();
31381
- log(`observeChannel(tmpid: ${timestamp}) > listen`);
31382
- // wrapper function to make sure
31383
- const router = (result, action) => {
31384
- var _a, _b, _c;
31385
- // filter function
31386
- if (((_a = result.data) === null || _a === void 0 ? void 0 : _a.channelId) !== channelId)
31387
- return;
31388
- if (callback instanceof Function)
31389
- return callback(Object.assign(Object.assign({}, result), { data: LinkedObject.channel(constructChannelDynamicValue(result.data)) }));
31390
- if (action !== 'onFetch')
31391
- (_b = callback.onEvent) === null || _b === void 0 ? void 0 : _b.call(callback, action, Object.assign(Object.assign({}, result), { data: LinkedObject.channel(constructChannelDynamicValue(result.data)) }));
31392
- (_c = callback[action]) === null || _c === void 0 ? void 0 : _c.call(callback, Object.assign(Object.assign({}, result), { data: LinkedObject.channel(constructChannelDynamicValue(result.data)) }));
31393
- };
31394
- const disposers = [];
31395
- 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 */)));
31396
- runQuery(createQuery(getChannel$1, channelId), result => result.data && router(result, "onFetch" /* Amity.ChannelActionType.OnFetch */));
31397
- return () => {
31398
- log(`observeChannel(tmpid: ${timestamp}) > dispose`);
31399
- disposers.forEach(fn => fn());
31400
- };
31401
- };
31402
-
31403
- /**
31404
- * ```js
31405
- * import { observeChannels } from '@amityco/ts-sdk'
31406
- *
31407
- * let channels = []
31408
- * const unsub = observeChannels(channel => merge(channels, channel))
31409
- * ```
31410
- *
31411
- * Observe all mutations on a list of {@link Amity.Channel} for a current user
31412
- *
31413
- * @param callback the function to call when new data are available
31414
- * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the channels
31415
- *
31416
- * @category Channel Observer
31417
- */
31418
- const observeChannels = (callback) => {
31419
- const { log } = getActiveClient();
31420
- const timestamp = Date.now();
31421
- log(`observeChannels(tmpid: ${timestamp}) > listen`);
31422
- const disposers = [];
31423
- const router = (channel, action) => {
31424
- var _a, _b;
31425
- if (callback instanceof Function)
31426
- return callback(LinkedObject.channel(constructChannelDynamicValue(channel)));
31427
- (_a = callback.onEvent) === null || _a === void 0 ? void 0 : _a.call(callback, action, LinkedObject.channel(constructChannelDynamicValue(channel)));
31428
- (_b = callback[action]) === null || _b === void 0 ? void 0 : _b.call(callback, LinkedObject.channel(constructChannelDynamicValue(channel)));
31429
- };
31430
- 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 */)));
31431
- return () => {
31432
- log(`observeChannels(tmpid: ${timestamp}) > dispose`);
31433
- disposers.forEach(fn => fn());
31434
- };
31435
- };
31436
-
31437
30753
  /**
31438
30754
  * ```js
31439
30755
  * import { onMessageUpdated } from '@amityco/ts-sdk'
@@ -31712,69 +31028,6 @@ const onSubChannelFetched = (callback) => {
31712
31028
  return createEventSubscriber(getActiveClient(), 'onSubChannelFetched', 'local.message-feed.fetched', payload => callback(payload.messageFeeds[0]));
31713
31029
  };
31714
31030
 
31715
- /**
31716
- * ```js
31717
- * import { getMessages } from '@amityco/ts-sdk'
31718
- * const messages = await getMessages(['foo', 'bar'])
31719
- * ```
31720
- *
31721
- * Fetches a collection of {@link Amity.Message} objects
31722
- *
31723
- * @param messageIds the IDs of the {@link Amity.Message} to fetch
31724
- * @returns the associated collection of {@link Amity.Message} objects
31725
- *
31726
- * @category Message API
31727
- * @async
31728
- */
31729
- const getMessages$1 = async (messageIds) => {
31730
- const client = getActiveClient();
31731
- client.log('message/getMessages', messageIds);
31732
- const { data: payload } = await client.http.get(`/api/v5/messages/list`, {
31733
- params: { messageIds: messageIds.map(encodeURIComponent) },
31734
- });
31735
- const data = await prepareMessagePayload(payload);
31736
- const cachedAt = client.cache && Date.now();
31737
- if (client.cache)
31738
- ingestInCache(data, { cachedAt });
31739
- const { messages } = data;
31740
- fireEvent('local.message.fetched', { messages });
31741
- return {
31742
- data: messages.map(message => LinkedObject.message(message)),
31743
- cachedAt,
31744
- };
31745
- };
31746
- /**
31747
- * ```js
31748
- * import { getMessages } from '@amityco/ts-sdk'
31749
- * const messages = getMessages.locally(['foo', 'bar']) ?? []
31750
- * ```
31751
- *
31752
- * Fetches a collection of {@link Amity.Message} objects from cache
31753
- *
31754
- * @param messageIds the IDs of the {@link Amity.Message} to fetch
31755
- * @returns the associated collection of {@link Amity.Message} objects
31756
- *
31757
- * @category Message API
31758
- */
31759
- getMessages$1.locally = (messageIds) => {
31760
- var _a;
31761
- const client = getActiveClient();
31762
- client.log('message/getMessages.locally', messageIds);
31763
- if (!client.cache)
31764
- return;
31765
- const cached = messageIds
31766
- .map(messageId => pullFromCache(['message', 'get', messageId]))
31767
- .filter(Boolean);
31768
- const messages = cached.map(({ data }) => data);
31769
- const oldest = (_a = cached.sort((a, b) => (a.cachedAt < b.cachedAt ? -1 : 1))) === null || _a === void 0 ? void 0 : _a[0];
31770
- if ((cached === null || cached === void 0 ? void 0 : cached.length) < messageIds.length)
31771
- return;
31772
- return {
31773
- data: messages,
31774
- cachedAt: oldest.cachedAt,
31775
- };
31776
- };
31777
-
31778
31031
  const getLocalId = () => `LOCAL_${uuid()}`;
31779
31032
  // FIXME: temp solution
31780
31033
  let uniqueId;
@@ -31799,7 +31052,11 @@ const createMessageOptimistic = (bundle) => {
31799
31052
  if (subChannel) {
31800
31053
  upsertInCache(['subChannel', 'get', bundle.subChannelId], Object.assign(Object.assign({}, subChannel.data), { messageCount: subChannel.data.messageCount + 1 }));
31801
31054
  if (subChannel.data.channelId === subChannel.data.subChannelId) {
31802
- const channel = pullFromCache(['channel', 'get', subChannel.data.channelId]);
31055
+ const channel = pullFromCache([
31056
+ 'channel',
31057
+ 'get',
31058
+ subChannel.data.channelId,
31059
+ ]);
31803
31060
  if (channel === null || channel === void 0 ? void 0 : channel.data) {
31804
31061
  upsertInCache(['channel', 'get', subChannel.data.channelId], Object.assign(Object.assign({}, channel.data), { messageCount: ((_a = channel.data.messageCount) !== null && _a !== void 0 ? _a : 0) + 1 }));
31805
31062
  }
@@ -32087,7 +31344,7 @@ const softDeleteMessage = async (messageId) => {
32087
31344
  client.log('message/softDeleteMessage', messageId);
32088
31345
  // API-FIX: This endpoint has not been implemented yet.
32089
31346
  await client.http.delete(`/api/v5/messages/${encodeURIComponent(messageId)}`);
32090
- const deleted = await getMessage$2(messageId);
31347
+ const deleted = await getMessage$1(messageId);
32091
31348
  fireEvent('local.message.deleted', { messages: [deleted.data] });
32092
31349
  return LinkedObject.message(deleted.data);
32093
31350
  };
@@ -32561,12 +31818,12 @@ const onMessageFetched = (callback) => {
32561
31818
  *
32562
31819
  * @category Message Live Object
32563
31820
  */
32564
- const getMessage$1 = (messageId, callback) => {
31821
+ const getMessage = (messageId, callback) => {
32565
31822
  const responder = (snapshot) => {
32566
31823
  const { data } = snapshot;
32567
31824
  callback(Object.assign(Object.assign({}, snapshot), { data: data ? LinkedObject.message(snapshot.data) : data }));
32568
31825
  };
32569
- return liveObject(messageId, responder, 'messageId', getMessage$2, [
31826
+ return liveObject(messageId, responder, 'messageId', getMessage$1, [
32570
31827
  onMessageFetched,
32571
31828
  onMessageUpdated,
32572
31829
  onMessageDeleted,
@@ -32615,7 +31872,7 @@ class MessageQueryStreamController extends QueryStreamController {
32615
31872
  }
32616
31873
  reactor(action) {
32617
31874
  return (payload) => {
32618
- var _a, _b, _c, _d, _e;
31875
+ var _a, _b, _c;
32619
31876
  if (action === 'onCreate') {
32620
31877
  const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
32621
31878
  const { referenceId } = payload;
@@ -32625,14 +31882,9 @@ class MessageQueryStreamController extends QueryStreamController {
32625
31882
  return;
32626
31883
  if (this.query.type && this.query.type !== payload.dataType)
32627
31884
  return;
32628
- if (this.query.dataType && this.query.dataType !== payload.dataType)
32629
- return;
32630
31885
  if (this.query.excludingTags &&
32631
31886
  ((_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); })))
32632
31887
  return;
32633
- if (this.query.excludeTags &&
32634
- ((_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); })))
32635
- return;
32636
31888
  if (!!this.query.hasFlags !== !!payload.flagCount)
32637
31889
  return;
32638
31890
  if (this.query.parentId && this.query.parentId !== payload.parentId)
@@ -32642,9 +31894,7 @@ class MessageQueryStreamController extends QueryStreamController {
32642
31894
  payload.isDeleted)
32643
31895
  return;
32644
31896
  if (this.query.includingTags &&
32645
- !((_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); })))
32646
- return;
32647
- 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); })))
31897
+ !((_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); })))
32648
31898
  return;
32649
31899
  if ((!this.query.sortBy || this.query.sortBy === 'segmentDesc') &&
32650
31900
  !this.paginationController.getPrevToken()) {
@@ -32744,26 +31994,6 @@ class MessageLiveCollectionController extends LiveCollectionController {
32744
31994
  }
32745
31995
  applyFilter(data) {
32746
31996
  let messages = data;
32747
- messages = messages.filter(m => {
32748
- if (this.query.tags) {
32749
- return this.query.tags.find(value => {
32750
- if (!m.tags)
32751
- return false;
32752
- return m.tags.includes(value);
32753
- });
32754
- }
32755
- return true;
32756
- });
32757
- messages = messages.filter(m => {
32758
- if (this.query.excludeTags) {
32759
- return (this.query.excludeTags || []).find(value => {
32760
- if (!m.tags)
32761
- return true;
32762
- return !m.tags.includes(value);
32763
- });
32764
- }
32765
- return true;
32766
- });
32767
31997
  /*
32768
31998
  * for cases when message is deleted via RTE, this flag is used to get
32769
31999
  * items from cache that are !deleted
@@ -32800,7 +32030,6 @@ class MessageLiveCollectionController extends LiveCollectionController {
32800
32030
  }
32801
32031
  }
32802
32032
 
32803
- /* eslint-disable no-use-before-define */
32804
32033
  /* begin_public_function
32805
32034
  id: message.query
32806
32035
  */
@@ -32843,164 +32072,8 @@ const getMessages = (params, callback, config) => {
32843
32072
  };
32844
32073
  /* end_public_function */
32845
32074
 
32846
- /**
32847
- * ```js
32848
- * import { getMessage } from '@amityco/ts-sdk'
32849
- * const message = await getMessage('foobar')
32850
- * ```
32851
- *
32852
- * Fetches a {@link Amity.Message} object
32853
- *
32854
- * @param messageId the ID of the {@link Amity.Message} to fetch
32855
- * @returns the associated {@link Amity.Message} object
32856
- *
32857
- * @category Message API
32858
- * @async
32859
- */
32860
- const getMessage = async (messageId, isLive = false) => {
32861
- const client = getActiveClient();
32862
- client.log('message/getMessage', messageId);
32863
- if (!isLive) {
32864
- console.log('getMessage will be deprecated on 15th November 2022, please use liveMessage instead.');
32865
- }
32866
- isInTombstone('message', messageId);
32867
- let data;
32868
- try {
32869
- // API-FIX: endpoint should not be /list, parameters should be querystring.
32870
- const { data: payload } = await client.http.get(`/api/v5/messages/${encodeURIComponent(messageId)}`);
32871
- data = await prepareMessagePayload(payload);
32872
- }
32873
- catch (error) {
32874
- if (checkIfShouldGoesToTombstone(error === null || error === void 0 ? void 0 : error.code)) {
32875
- pushToTombstone('message', messageId);
32876
- }
32877
- throw error;
32878
- }
32879
- const cachedAt = client.cache && Date.now();
32880
- if (client.cache)
32881
- ingestInCache(data, { cachedAt });
32882
- const { messages } = data;
32883
- fireEvent('local.message.fetched', { messages });
32884
- return {
32885
- data: LinkedObject.message(messages.find(message => message.messageId === messageId)),
32886
- cachedAt,
32887
- };
32888
- };
32889
- /**
32890
- * ```js
32891
- * import { getMessage } from '@amityco/ts-sdk'
32892
- * const message = getMessage.locally('foobar')
32893
- * ```
32894
- *
32895
- * Fetches a {@link Amity.Message} object
32896
- *
32897
- * @param messageId the ID of the {@link Amity.Message} to fetch
32898
- * @returns the associated {@link Amity.Message} object
32899
- *
32900
- * @category Message API
32901
- */
32902
- getMessage.locally = (messageId) => {
32903
- const client = getActiveClient();
32904
- client.log('message/getMessage.locally', messageId);
32905
- if (!client.cache)
32906
- return;
32907
- const cached = pullFromCache(['message', 'get', messageId]);
32908
- if (!cached)
32909
- return;
32910
- return {
32911
- data: cached.data,
32912
- cachedAt: cached.cachedAt,
32913
- };
32914
- };
32915
-
32916
- /**
32917
- * ```js
32918
- * import { observeMessage } from '@amityco/ts-sdk'
32919
- *
32920
- * let message = {}
32921
- *
32922
- * const unsub = observeMessage(messageId, updated => message = updated)
32923
- * ```
32924
- *
32925
- * Observe all mutations on a {@link Amity.Message} given a single messageId
32926
- *
32927
- * @param client the client to observe the message with
32928
- * @param messageId the ID of the message to observe
32929
- * @param callback the function to call when new data are available
32930
- * @param policy a query policy option for this observer
32931
- * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the message
32932
- *
32933
- * @category Message Observer
32934
- */
32935
- const observeMessage = (messageId, callback, policy = 'cache_then_server') => {
32936
- const { log } = getActiveClient();
32937
- const timestamp = Date.now();
32938
- log(`observeMessage(tmpid: ${timestamp}) > listen`);
32939
- console.log('observeMessage will be deprecated on 15th November 2022, please use liveMessage instead.');
32940
- // wrapper function to make sure
32941
- const router = (result, action) => {
32942
- var _a, _b, _c;
32943
- // filter function
32944
- if (((_a = result.data) === null || _a === void 0 ? void 0 : _a.messageId) !== messageId)
32945
- return;
32946
- if (callback instanceof Function)
32947
- return callback(result);
32948
- if (action !== 'onFetch')
32949
- (_b = callback.onEvent) === null || _b === void 0 ? void 0 : _b.call(callback, action, result);
32950
- (_c = callback[action]) === null || _c === void 0 ? void 0 : _c.call(callback, result);
32951
- };
32952
- const disposers = [];
32953
- 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')));
32954
- if (policy !== 'no_fetch') {
32955
- runQuery(createQuery(getMessage, messageId), result => result.data && router(result, 'onFetch'), queryOptions(policy));
32956
- }
32957
- return () => {
32958
- log(`observeMessages(tmpid: ${timestamp}) > dispose`);
32959
- disposers.forEach(fn => fn());
32960
- };
32961
- };
32962
-
32963
- /**
32964
- * ```js
32965
- * import { observeMessages } from '@amityco/ts-sdk'
32966
- *
32967
- * let messages = []
32968
- *
32969
- * const unsubscribe = observeMessages(channelId, message => merge(messages, message))
32970
- * ```
32971
- *
32972
- * Observe all mutations on a list of {@link Amity.Message} for a given {@link Amity.SubChannel} object
32973
- *
32974
- * @param subChannelId the ID of the channel where to observe the messages
32975
- * @param callback the function to call when new data are available
32976
- * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the messages
32977
- *
32978
- * @category Message Observer
32979
- */
32980
- const observeMessages = (subChannelId, callback) => {
32981
- const { log } = getActiveClient();
32982
- const timestamp = Date.now();
32983
- log(`observeMessages(tmpid: ${timestamp}) > listen`);
32984
- const disposers = [];
32985
- const router = (message, action) => {
32986
- var _a, _b, _c;
32987
- if (((_a = message.data) === null || _a === void 0 ? void 0 : _a.subChannelId) !== subChannelId)
32988
- return;
32989
- if (callback instanceof Function)
32990
- return callback(message);
32991
- (_b = callback.onEvent) === null || _b === void 0 ? void 0 : _b.call(callback, action, message);
32992
- (_c = callback[action]) === null || _c === void 0 ? void 0 : _c.call(callback, message);
32993
- };
32994
- 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')));
32995
- return () => {
32996
- log(`observeMessages(tmpid: ${timestamp}) > dispose`);
32997
- disposers.forEach(fn => fn());
32998
- };
32999
- };
33000
-
33001
32075
  var index$g = /*#__PURE__*/Object.freeze({
33002
32076
  __proto__: null,
33003
- getMessageByIds: getMessages$1,
33004
32077
  createMessage: createMessage,
33005
32078
  updateMessage: updateMessage,
33006
32079
  editMessage: editMessage,
@@ -33022,10 +32095,8 @@ var index$g = /*#__PURE__*/Object.freeze({
33022
32095
  onMessageReactionAdded: onMessageReactionAdded,
33023
32096
  onMessageReactionRemoved: onMessageReactionRemoved,
33024
32097
  onMessageFetched: onMessageFetched,
33025
- getMessage: getMessage$1,
32098
+ getMessage: getMessage,
33026
32099
  getMessages: getMessages,
33027
- observeMessage: observeMessage,
33028
- observeMessages: observeMessages,
33029
32100
  convertFromRaw: convertFromRaw$1,
33030
32101
  prepareMessagePayload: prepareMessagePayload,
33031
32102
  convertParams: convertParams,
@@ -33542,8 +32613,6 @@ var index$f = /*#__PURE__*/Object.freeze({
33542
32613
  getSubChannel: getSubChannel,
33543
32614
  getSubChannels: getSubChannels,
33544
32615
  markReadEngineOnLoginHandler: markReadEngineOnLoginHandler,
33545
- startReading: startReading,
33546
- stopReading: stopReading,
33547
32616
  startMessageReceiptSync: startMessageReceiptSync,
33548
32617
  stopMessageReceiptSync: stopMessageReceiptSync
33549
32618
  });
@@ -33594,7 +32663,7 @@ const getChannel = (channelId, callback) => {
33594
32663
  const reactor = async (response) => {
33595
32664
  if (!response.data)
33596
32665
  return callback(response);
33597
- const data = Object.assign(Object.assign({}, response), { data: LinkedObject.channel(constructChannelDynamicValue(getChannelMessagePreviewWithUser(response.data))) });
32666
+ const data = Object.assign(Object.assign({}, response), { data: constructChannelObject(response.data) });
33598
32667
  const newSnapshot = __rest(data, ["origin"]);
33599
32668
  /**
33600
32669
  * check equality of previous data and current data to avoid redundancy
@@ -33628,7 +32697,11 @@ const getChannel = (channelId, callback) => {
33628
32697
  if (message.channelId !== channelId)
33629
32698
  return;
33630
32699
  // channelId from message is channelInternalId
33631
- const channel = (_a = pullFromCache(['channel', 'get', channelId])) === null || _a === void 0 ? void 0 : _a.data;
32700
+ const channel = (_a = pullFromCache([
32701
+ 'channel',
32702
+ 'get',
32703
+ channelId,
32704
+ ])) === null || _a === void 0 ? void 0 : _a.data;
33632
32705
  if (!channel)
33633
32706
  return;
33634
32707
  updateChannelCache(channel, {
@@ -33651,7 +32724,11 @@ const getChannel = (channelId, callback) => {
33651
32724
  if (message.channelId !== channelId)
33652
32725
  return;
33653
32726
  // channelId from message is channelInternalId
33654
- const channel = (_a = pullFromCache(['channel', 'get', channelId])) === null || _a === void 0 ? void 0 : _a.data;
32727
+ const channel = (_a = pullFromCache([
32728
+ 'channel',
32729
+ 'get',
32730
+ channelId,
32731
+ ])) === null || _a === void 0 ? void 0 : _a.data;
33655
32732
  if (!channel)
33656
32733
  return;
33657
32734
  updateChannelCache(channel, {
@@ -33664,7 +32741,11 @@ const getChannel = (channelId, callback) => {
33664
32741
  convertEventPayload((callback) => {
33665
32742
  const updateMessagePreview = async (message) => {
33666
32743
  var _a;
33667
- const channel = (_a = pullFromCache(['channel', 'get', channelId])) === null || _a === void 0 ? void 0 : _a.data;
32744
+ const channel = (_a = pullFromCache([
32745
+ 'channel',
32746
+ 'get',
32747
+ channelId,
32748
+ ])) === null || _a === void 0 ? void 0 : _a.data;
33668
32749
  if (!channel || channel.messagePreviewId !== message.messageId)
33669
32750
  return;
33670
32751
  const messagePreviewSetting = await client.getMessagePreviewSetting(false);
@@ -33678,7 +32759,11 @@ const getChannel = (channelId, callback) => {
33678
32759
  convertEventPayload((callback) => {
33679
32760
  const updateMessagePreview = async (message) => {
33680
32761
  var _a;
33681
- const channel = (_a = pullFromCache(['channel', 'get', channelId])) === null || _a === void 0 ? void 0 : _a.data;
32762
+ const channel = (_a = pullFromCache([
32763
+ 'channel',
32764
+ 'get',
32765
+ channelId,
32766
+ ])) === null || _a === void 0 ? void 0 : _a.data;
33682
32767
  if (!channel || channel.messagePreviewId !== message.messageId)
33683
32768
  return;
33684
32769
  const messagePreviewSetting = await client.getMessagePreviewSetting(false);
@@ -33711,7 +32796,11 @@ const getChannel = (channelId, callback) => {
33711
32796
  if (messagePreviewSetting === "no-message-preview" /* Amity.MessagePreviewSetting.NO_MESSAGE_PREVIEW */)
33712
32797
  return;
33713
32798
  await getChannel$1(channelId);
33714
- const channel = (_b = pullFromCache(['channel', 'get', channelId])) === null || _b === void 0 ? void 0 : _b.data;
32799
+ const channel = (_b = pullFromCache([
32800
+ 'channel',
32801
+ 'get',
32802
+ channelId,
32803
+ ])) === null || _b === void 0 ? void 0 : _b.data;
33715
32804
  if (!channel)
33716
32805
  return;
33717
32806
  callback(subChannel);
@@ -33733,7 +32822,11 @@ const getChannel = (channelId, callback) => {
33733
32822
  if (!messagePreviewCache ||
33734
32823
  messagePreviewCache.subChannelId !== subChannel.subChannelId)
33735
32824
  return;
33736
- const channel = (_b = pullFromCache(['channel', 'get', channelId])) === null || _b === void 0 ? void 0 : _b.data;
32825
+ const channel = (_b = pullFromCache([
32826
+ 'channel',
32827
+ 'get',
32828
+ channelId,
32829
+ ])) === null || _b === void 0 ? void 0 : _b.data;
33737
32830
  if (!channel)
33738
32831
  return;
33739
32832
  callback(subChannel);
@@ -33929,9 +33022,7 @@ class ChannelLiveCollectionController extends LiveCollectionController {
33929
33022
  .map(channelId => pullFromCache(['channel', 'get', channelId]))
33930
33023
  .filter(Boolean)
33931
33024
  .map(({ data }) => data)
33932
- .map(getChannelMessagePreviewWithUser)
33933
- .map(constructChannelDynamicValue)
33934
- .map(LinkedObject.channel)) !== null && _b !== void 0 ? _b : [];
33025
+ .map(constructChannelObject)) !== null && _b !== void 0 ? _b : [];
33935
33026
  if (this.paginationController instanceof ChannelPaginationController) {
33936
33027
  data = this.applyFilter(data);
33937
33028
  }
@@ -34578,11 +33669,6 @@ class ChannelMemberLiveCollectionController extends LiveCollectionController {
34578
33669
  return false;
34579
33670
  });
34580
33671
  }
34581
- if (this.query.search) {
34582
- // eslint-disable-next-line no-console
34583
- 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.');
34584
- channelMembers = filterBySearchTerm(channelMembers, this.query.search);
34585
- }
34586
33672
  if (this.query.includeDeleted === false) {
34587
33673
  channelMembers = channelMembers.filter(member => { var _a; return ((_a = member.user) === null || _a === void 0 ? void 0 : _a.isDeleted) !== true; });
34588
33674
  }
@@ -34616,11 +33702,6 @@ const applyFilter$1 = (data, params) => {
34616
33702
  return params.memberships.includes(member.membership);
34617
33703
  });
34618
33704
  }
34619
- if (params.search) {
34620
- // eslint-disable-next-line no-console
34621
- 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.');
34622
- channelMembers = filterBySearchTerm(channelMembers, params.search);
34623
- }
34624
33705
  // sort, 'lastCreated' is the default sort order
34625
33706
  const sortBy = params.sortBy ? params.sortBy : 'lastCreated';
34626
33707
  channelMembers = channelMembers.sort(sortBy === 'lastCreated' ? sortByLastCreated : sortByFirstCreated);
@@ -34912,7 +33993,7 @@ var index$c = /*#__PURE__*/Object.freeze({
34912
33993
  __proto__: null,
34913
33994
  Membership: index$e,
34914
33995
  Moderation: index$d,
34915
- getChannelByIds: getChannelByIds,
33996
+ getChannelByIds: getChannelByIds$1,
34916
33997
  createChannel: createChannel,
34917
33998
  updateChannel: updateChannel,
34918
33999
  deleteChannel: deleteChannel,
@@ -34920,7 +34001,6 @@ var index$c = /*#__PURE__*/Object.freeze({
34920
34001
  leaveChannel: leaveChannel,
34921
34002
  muteChannel: muteChannel,
34922
34003
  unmuteChannel: unmuteChannel,
34923
- markAsRead: markAsRead,
34924
34004
  onChannelCreated: onChannelCreated,
34925
34005
  onChannelUpdated: onChannelUpdated,
34926
34006
  onChannelDeleted: onChannelDeleted,
@@ -34933,8 +34013,6 @@ var index$c = /*#__PURE__*/Object.freeze({
34933
34013
  onChannelMemberUnbanned: onChannelMemberUnbanned,
34934
34014
  onChannelMemberRoleAdded: onChannelMemberRoleAdded,
34935
34015
  onChannelMemberRoleRemoved: onChannelMemberRoleRemoved,
34936
- observeChannel: observeChannel,
34937
- observeChannels: observeChannels,
34938
34016
  getChannel: getChannel,
34939
34017
  getChannels: getChannels,
34940
34018
  MARKER_INCLUDED_CHANNEL_TYPE: MARKER_INCLUDED_CHANNEL_TYPE,
@@ -35245,77 +34323,6 @@ const leaveCommunity = async (communityId) => {
35245
34323
  };
35246
34324
  /* end_public_function */
35247
34325
 
35248
- /* begin_public_function
35249
- id: community.query.trending_communities
35250
- */
35251
- /**
35252
- * @deprecated This API renamed to `getTrendingCommunities()`.
35253
- * Please use getTrendingCommunities() instead.
35254
- *
35255
- * ```js
35256
- * import { CommunityRepository } from '@amityco/ts-sdk'
35257
- * const trendingCommunities = await CommunityRepository.getTrendingCommunities()
35258
- * ```
35259
- *
35260
- * Gets a list of top trending {@link Amity.Community} objects
35261
- *
35262
- * @param query The query parameters
35263
- * @returns A list of {@link Amity.Community} objects
35264
- *
35265
- * @category Community API
35266
- * @async
35267
- */
35268
- const getTopTrendingCommunities = async (query) => {
35269
- const client = getActiveClient();
35270
- client.log('channel/getTopTrendingCommunities', query);
35271
- const { limit = 5 } = query !== null && query !== void 0 ? query : {};
35272
- // API-FIX: backend doesnt answer Amity.Response
35273
- // const { data } = await client.http.get<Amity.Response<CommunityPayload>>(
35274
- const { data: payload } = await client.http.get(`/api/v3/communities/top-trending`, { params: { options: { limit } } });
35275
- const data = prepareCommunityPayload(payload);
35276
- const { communities } = data;
35277
- const cachedAt = client.cache && Date.now();
35278
- if (client.cache) {
35279
- ingestInCache(data, { cachedAt });
35280
- const cacheKey = ['community', 'top-trending', { params: { options: { limit } } }];
35281
- pushToCache(cacheKey, { communities: communities.map(getResolver('community')) });
35282
- }
35283
- return { data: communities, cachedAt };
35284
- };
35285
- /* end_public_function */
35286
- /**
35287
- * ```js
35288
- * import { getTopTrendingCommunities } from '@amityco/ts-sdk'
35289
- * const communities = getTopTrendingCommunities.locally()
35290
- * ```
35291
- *
35292
- * Gets a list of top trending {@link Amity.Community} objects from cache
35293
- *
35294
- * @param query The query parameters
35295
- * @returns communities
35296
- *
35297
- * @category Community API
35298
- */
35299
- getTopTrendingCommunities.locally = (query) => {
35300
- var _a, _b;
35301
- const client = getActiveClient();
35302
- client.log('community/getTopTrendingCommunities.locally', query);
35303
- if (!client.cache)
35304
- return;
35305
- const { limit = 5 } = query !== null && query !== void 0 ? query : {};
35306
- const queryKey = ['community', 'top-trending', { params: { options: { limit } } }];
35307
- const { data, cachedAt } = (_a = pullFromCache(queryKey)) !== null && _a !== void 0 ? _a : {};
35308
- if (!(data === null || data === void 0 ? void 0 : data.communities.length))
35309
- return;
35310
- const communities = data.communities
35311
- .map(communityId => pullFromCache(['community', 'get', communityId]))
35312
- .filter(Boolean)
35313
- .map(({ data }) => data);
35314
- return communities.length === ((_b = data === null || data === void 0 ? void 0 : data.communities) === null || _b === void 0 ? void 0 : _b.length)
35315
- ? { data: communities, cachedAt }
35316
- : undefined;
35317
- };
35318
-
35319
34326
  const createCommunityEventSubscriber = (event, callback) => {
35320
34327
  const client = getActiveClient();
35321
34328
  const filter = (payload) => {
@@ -35386,7 +34393,224 @@ const onCommunityUpdated = (callback) => createCommunityEventSubscriber('communi
35386
34393
  *
35387
34394
  * @category Community Events
35388
34395
  */
35389
- const onCommunityDeleted = (callback) => createCommunityEventSubscriber('community.deleted', callback);
34396
+ const onCommunityDeleted = (callback) => createCommunityEventSubscriber('community.deleted', callback);
34397
+
34398
+ /**
34399
+ * TODO: handle cache receive cache option, and cache policy
34400
+ * TODO: check if querybyIds is supported
34401
+ */
34402
+ class CommunitiesPaginationController$1 extends PaginationController {
34403
+ async getRequest(queryParams, token) {
34404
+ const { limit = COLLECTION_DEFAULT_PAGINATION_LIMIT } = queryParams, params = __rest(queryParams, ["limit"]);
34405
+ const options = token ? { token } : { limit };
34406
+ const { data: queryResponse } = await this.http.get(`/api/v3/communities`, {
34407
+ params: Object.assign(Object.assign({}, params), { isDeleted: inferIsDeleted(params.includeDeleted), keyword: params.displayName, filter: params.membership, options }),
34408
+ });
34409
+ return queryResponse;
34410
+ }
34411
+ }
34412
+
34413
+ class CommunitiesQueryStreamController$1 extends QueryStreamController {
34414
+ constructor(query, cacheKey, notifyChange, preparePayload) {
34415
+ super(query, cacheKey);
34416
+ this.notifyChange = notifyChange;
34417
+ this.preparePayload = preparePayload;
34418
+ }
34419
+ async saveToMainDB(response) {
34420
+ const processedPayload = await this.preparePayload(response);
34421
+ const client = getActiveClient();
34422
+ const cachedAt = client.cache && Date.now();
34423
+ if (client.cache) {
34424
+ ingestInCache(processedPayload, { cachedAt });
34425
+ }
34426
+ }
34427
+ appendToQueryStream(response, direction, refresh = false) {
34428
+ var _a, _b;
34429
+ if (refresh) {
34430
+ pushToCache(this.cacheKey, {
34431
+ data: response.communities.map(getResolver('community')),
34432
+ });
34433
+ }
34434
+ else {
34435
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
34436
+ const communities = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
34437
+ pushToCache(this.cacheKey, Object.assign(Object.assign({}, collection), { data: [...new Set([...communities, ...response.communities.map(getResolver('community'))])] }));
34438
+ }
34439
+ }
34440
+ reactor(action) {
34441
+ return (community) => {
34442
+ var _a;
34443
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
34444
+ if (!collection)
34445
+ return;
34446
+ pushToCache(this.cacheKey, collection);
34447
+ this.notifyChange({ origin: "event" /* Amity.LiveDataOrigin.EVENT */, loading: false });
34448
+ };
34449
+ }
34450
+ subscribeRTE(createSubscriber) {
34451
+ return createSubscriber.map(subscriber => subscriber.fn(this.reactor(subscriber.action)));
34452
+ }
34453
+ }
34454
+
34455
+ var EnumCommunityActions$4;
34456
+ (function (EnumCommunityActions) {
34457
+ EnumCommunityActions["OnCommunityCreated"] = "onCommunityCreated";
34458
+ EnumCommunityActions["OnCommunityDeleted"] = "onCommunityDeleted";
34459
+ EnumCommunityActions["OnCommunityUpdated"] = "onCommunityUpdated";
34460
+ })(EnumCommunityActions$4 || (EnumCommunityActions$4 = {}));
34461
+
34462
+ var EnumCommunityMemberActions$1;
34463
+ (function (EnumCommunityMemberActions) {
34464
+ EnumCommunityMemberActions["OnCommunityJoined"] = "onCommunityJoined";
34465
+ EnumCommunityMemberActions["OnCommunityLeft"] = "onCommunityLeft";
34466
+ EnumCommunityMemberActions["OnCommunityUserBanned"] = "onCommunityUserBanned";
34467
+ EnumCommunityMemberActions["OnCommunityUserChanged"] = "onCommunityUserChanged";
34468
+ EnumCommunityMemberActions["OnCommunityUserRoleAdded"] = "onCommunityUserRoleAdded";
34469
+ EnumCommunityMemberActions["OnCommunityUserRoleRemoved"] = "onCommunityUserRoleRemoved";
34470
+ EnumCommunityMemberActions["OnCommunityUserUnbanned"] = "onCommunityUserUnbanned";
34471
+ EnumCommunityMemberActions["OnMemberCountChanged"] = "OnMemberCountChanged";
34472
+ EnumCommunityMemberActions["OnCommunityUserAdded"] = "OnCommunityUserAdded";
34473
+ EnumCommunityMemberActions["onCommunityUserRemoved"] = "onCommunityUserRemoved";
34474
+ EnumCommunityMemberActions["OnUserDeleted"] = "OnUserDeleted";
34475
+ })(EnumCommunityMemberActions$1 || (EnumCommunityMemberActions$1 = {}));
34476
+
34477
+ /* begin_public_function
34478
+ id: community.membership.add_members
34479
+ */
34480
+ /**
34481
+ * ```js
34482
+ * import { CommunityRepository } from '@amityco/ts-sdk'
34483
+ * const updated = await CommunityRepository.moderation.addMembers(communityId, ['foo', 'bar'])
34484
+ * ```
34485
+ *
34486
+ * Adds a list of {@link Amity.InternalUser} to a {@link Amity.Community} to add users to
34487
+ *
34488
+ * @param communityId The ID of the {@link Amity.Community} to perform
34489
+ * @param userIds The list of IDs {@link Amity.InternalUser} to add
34490
+ * @returns A success boolean if the {@link Amity.InternalUser} were added to the {@link Amity.Community}
34491
+ *
34492
+ * @category Community API
34493
+ * @async
34494
+ */
34495
+ const addMembers = async (communityId, userIds) => {
34496
+ const client = getActiveClient();
34497
+ client.log('community/moderation/addMembers', communityId, userIds);
34498
+ const { data: payload } = await client.http.post(`/api/v3/communities/${communityId}/users`, { communityId, userIds });
34499
+ fireEvent('local.community.userAdded', payload);
34500
+ const data = prepareMembershipPayload(payload, 'communityUsers');
34501
+ if (client.cache)
34502
+ ingestInCache(data);
34503
+ const { communityUsers } = data;
34504
+ return !!communityUsers.find(communityUser => communityUser.communityId === communityId && communityUser.communityMembership === 'member');
34505
+ };
34506
+ /* end_public_function */
34507
+
34508
+ /* begin_public_function
34509
+ id: community.membership.remove_member
34510
+ */
34511
+ /**
34512
+ * ```js
34513
+ * import { CommunityRepository } from '@amityco/ts-sdk'
34514
+ * const updated = await CommunityRepository.moderation.removeMembers(communityId, ['foo', 'bar'])
34515
+ * ```
34516
+ *
34517
+ * Removes a list of {@link Amity.InternalUser} from a {@link Amity.Community}
34518
+ *
34519
+ * @param communityId The ID of the {@link Amity.Community} to edit
34520
+ * @param userIds The list of IDs {@link Amity.InternalUser} to remove
34521
+ * @returns A success boolean if the list of {@link Amity.InternalUser} were removed from the {@link Amity.Community}
34522
+ *
34523
+ * @category Community API
34524
+ * @async
34525
+ */
34526
+ const removeMembers = async (communityId, userIds) => {
34527
+ const client = getActiveClient();
34528
+ client.log('community/moderation/removeMembers', communityId, userIds);
34529
+ const { data: payload } = await client.http.delete(`/api/v3/communities/${communityId}/users`, { data: { communityId, userIds } });
34530
+ fireEvent('local.community.userRemoved', payload);
34531
+ const data = prepareMembershipPayload(payload, 'communityUsers');
34532
+ if (client.cache)
34533
+ ingestInCache(data);
34534
+ const { communityUsers } = data;
34535
+ return !!communityUsers.find(communityUser => communityUser.communityId === communityId && communityUser.communityMembership !== 'member');
34536
+ };
34537
+ /* end_public_function */
34538
+
34539
+ /**
34540
+ * TODO: handle cache receive cache option, and cache policy
34541
+ * TODO: check if querybyIds is supported
34542
+ */
34543
+ class CommunityMembersPaginationController extends PaginationController {
34544
+ async getRequest(queryParams, token) {
34545
+ const { limit = COLLECTION_DEFAULT_PAGINATION_LIMIT, includeDeleted } = queryParams, params = __rest(queryParams, ["limit", "includeDeleted"]);
34546
+ const options = token ? { token } : { limit };
34547
+ const isDeleted = includeDeleted === false ? false : undefined;
34548
+ const { data: queryResponse } = await this.http.get(`/api/v3/communities/${params.communityId}/users`, {
34549
+ params: Object.assign(Object.assign({}, params), { options,
34550
+ isDeleted }),
34551
+ });
34552
+ return queryResponse;
34553
+ }
34554
+ }
34555
+
34556
+ class CommunityMembersQueryStreamController extends QueryStreamController {
34557
+ constructor(query, cacheKey, notifyChange, preparePayload) {
34558
+ super(query, cacheKey);
34559
+ this.notifyChange = notifyChange;
34560
+ this.preparePayload = preparePayload;
34561
+ }
34562
+ async saveToMainDB(response) {
34563
+ const processedPayload = await this.preparePayload(response);
34564
+ const client = getActiveClient();
34565
+ const cachedAt = client.cache && Date.now();
34566
+ if (client.cache) {
34567
+ ingestInCache(processedPayload, { cachedAt });
34568
+ }
34569
+ }
34570
+ appendToQueryStream(response, direction, refresh = false) {
34571
+ var _a, _b;
34572
+ if (refresh) {
34573
+ pushToCache(this.cacheKey, {
34574
+ data: response.communityUsers.map(({ communityId, userId }) => getResolver('communityUsers')({ communityId, userId })),
34575
+ });
34576
+ }
34577
+ else {
34578
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
34579
+ const communityUsers = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
34580
+ pushToCache(this.cacheKey, Object.assign(Object.assign({}, collection), { data: [
34581
+ ...new Set([
34582
+ ...communityUsers,
34583
+ ...response.communityUsers.map(({ communityId, userId }) => getResolver('communityUsers')({ communityId, userId })),
34584
+ ]),
34585
+ ] }));
34586
+ }
34587
+ }
34588
+ reactor(action) {
34589
+ return (community, communityMembers) => {
34590
+ var _a;
34591
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
34592
+ if (!collection)
34593
+ return;
34594
+ communityMembers.forEach(communityMember => {
34595
+ const communityMemberCacheId = getResolver('communityUsers')({
34596
+ communityId: this.query.communityId,
34597
+ userId: communityMember.userId,
34598
+ });
34599
+ if (communityMember.communityMembership === 'none') {
34600
+ collection.data = collection.data.filter(m => m !== communityMemberCacheId);
34601
+ }
34602
+ else if (!collection.data.includes(communityMemberCacheId)) {
34603
+ collection.data = [communityMemberCacheId, ...collection.data];
34604
+ }
34605
+ });
34606
+ pushToCache(this.cacheKey, collection);
34607
+ this.notifyChange({ origin: "event" /* Amity.LiveDataOrigin.EVENT */, loading: false });
34608
+ };
34609
+ }
34610
+ subscribeRTE(createSubscriber) {
34611
+ return createSubscriber.map(subscriber => subscriber.fn(this.reactor(subscriber.action)));
34612
+ }
34613
+ }
35390
34614
 
35391
34615
  function hasPermission(member, payload, permission) {
35392
34616
  if (member.permissions.some(x => x === permission)) {
@@ -35680,271 +34904,6 @@ const onLocalCommunityJoined = (callback) => createLocalCommunityMemberEventSubs
35680
34904
 
35681
34905
  const onLocalCommunityLeft = (callback) => createLocalCommunityMemberEventSubscriber('local.community.left', callback);
35682
34906
 
35683
- /**
35684
- * ```js
35685
- * import { observeCommunity } from '@amityco/ts-sdk'
35686
- *
35687
- * let community = {}
35688
- * const dispose = observeCommunity(communityId, updated => community = updated)
35689
- * ```
35690
- *
35691
- * Observe all mutation on a given {@link Amity.Community}
35692
- *
35693
- * @param communityId the ID of the community to observe
35694
- * @param callback the function to call when new data are available
35695
- * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the community
35696
- *
35697
- * @category Community Observer
35698
- */
35699
- const observeCommunity = (communityId, callback) => {
35700
- const { log } = getActiveClient();
35701
- const timestamp = Date.now();
35702
- log(`observeCommunity(tmpid: ${timestamp}) > listen`);
35703
- // wrapper function to make sure
35704
- const router = (result, action) => {
35705
- var _a, _b;
35706
- if (callback instanceof Function)
35707
- return callback(result);
35708
- if (action !== 'onFetch')
35709
- (_a = callback.onEvent) === null || _a === void 0 ? void 0 : _a.call(callback, action, result);
35710
- (_b = callback[action]) === null || _b === void 0 ? void 0 : _b.call(callback, result);
35711
- };
35712
- const realtimeRouter = (result, action) => {
35713
- var _a;
35714
- if (((_a = result.data) === null || _a === void 0 ? void 0 : _a.communityId) !== communityId)
35715
- return;
35716
- router(result, action);
35717
- };
35718
- const disposers = [];
35719
- 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')));
35720
- runQuery(createQuery(getCommunity$1, communityId), result => (result.data || result.error) && router(result, 'onFetch'));
35721
- return () => {
35722
- log(`observeCommunity(tmpid: ${timestamp}) > dispose`);
35723
- disposers.forEach(fn => fn());
35724
- };
35725
- };
35726
-
35727
- /**
35728
- * TODO: handle cache receive cache option, and cache policy
35729
- * TODO: check if querybyIds is supported
35730
- */
35731
- class CommunitiesPaginationController$1 extends PaginationController {
35732
- async getRequest(queryParams, token) {
35733
- const { limit = COLLECTION_DEFAULT_PAGINATION_LIMIT } = queryParams, params = __rest(queryParams, ["limit"]);
35734
- const options = token ? { token } : { limit };
35735
- const { data: queryResponse } = await this.http.get(`/api/v3/communities`, {
35736
- params: Object.assign(Object.assign({}, params), { isDeleted: inferIsDeleted(params.includeDeleted), keyword: params.displayName, filter: params.membership, options }),
35737
- });
35738
- return queryResponse;
35739
- }
35740
- }
35741
-
35742
- class CommunitiesQueryStreamController$1 extends QueryStreamController {
35743
- constructor(query, cacheKey, notifyChange, preparePayload) {
35744
- super(query, cacheKey);
35745
- this.notifyChange = notifyChange;
35746
- this.preparePayload = preparePayload;
35747
- }
35748
- async saveToMainDB(response) {
35749
- const processedPayload = await this.preparePayload(response);
35750
- const client = getActiveClient();
35751
- const cachedAt = client.cache && Date.now();
35752
- if (client.cache) {
35753
- ingestInCache(processedPayload, { cachedAt });
35754
- }
35755
- }
35756
- appendToQueryStream(response, direction, refresh = false) {
35757
- var _a, _b;
35758
- if (refresh) {
35759
- pushToCache(this.cacheKey, {
35760
- data: response.communities.map(getResolver('community')),
35761
- });
35762
- }
35763
- else {
35764
- const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
35765
- const communities = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
35766
- pushToCache(this.cacheKey, Object.assign(Object.assign({}, collection), { data: [...new Set([...communities, ...response.communities.map(getResolver('community'))])] }));
35767
- }
35768
- }
35769
- reactor(action) {
35770
- return (community) => {
35771
- var _a;
35772
- const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
35773
- if (!collection)
35774
- return;
35775
- pushToCache(this.cacheKey, collection);
35776
- this.notifyChange({ origin: "event" /* Amity.LiveDataOrigin.EVENT */, loading: false });
35777
- };
35778
- }
35779
- subscribeRTE(createSubscriber) {
35780
- return createSubscriber.map(subscriber => subscriber.fn(this.reactor(subscriber.action)));
35781
- }
35782
- }
35783
-
35784
- var EnumCommunityActions$4;
35785
- (function (EnumCommunityActions) {
35786
- EnumCommunityActions["OnCommunityCreated"] = "onCommunityCreated";
35787
- EnumCommunityActions["OnCommunityDeleted"] = "onCommunityDeleted";
35788
- EnumCommunityActions["OnCommunityUpdated"] = "onCommunityUpdated";
35789
- })(EnumCommunityActions$4 || (EnumCommunityActions$4 = {}));
35790
-
35791
- var EnumCommunityMemberActions$1;
35792
- (function (EnumCommunityMemberActions) {
35793
- EnumCommunityMemberActions["OnCommunityJoined"] = "onCommunityJoined";
35794
- EnumCommunityMemberActions["OnCommunityLeft"] = "onCommunityLeft";
35795
- EnumCommunityMemberActions["OnCommunityUserBanned"] = "onCommunityUserBanned";
35796
- EnumCommunityMemberActions["OnCommunityUserChanged"] = "onCommunityUserChanged";
35797
- EnumCommunityMemberActions["OnCommunityUserRoleAdded"] = "onCommunityUserRoleAdded";
35798
- EnumCommunityMemberActions["OnCommunityUserRoleRemoved"] = "onCommunityUserRoleRemoved";
35799
- EnumCommunityMemberActions["OnCommunityUserUnbanned"] = "onCommunityUserUnbanned";
35800
- EnumCommunityMemberActions["OnMemberCountChanged"] = "OnMemberCountChanged";
35801
- EnumCommunityMemberActions["OnCommunityUserAdded"] = "OnCommunityUserAdded";
35802
- EnumCommunityMemberActions["onCommunityUserRemoved"] = "onCommunityUserRemoved";
35803
- EnumCommunityMemberActions["OnUserDeleted"] = "OnUserDeleted";
35804
- })(EnumCommunityMemberActions$1 || (EnumCommunityMemberActions$1 = {}));
35805
-
35806
- /* begin_public_function
35807
- id: community.membership.add_members
35808
- */
35809
- /**
35810
- * ```js
35811
- * import { CommunityRepository } from '@amityco/ts-sdk'
35812
- * const updated = await CommunityRepository.moderation.addMembers(communityId, ['foo', 'bar'])
35813
- * ```
35814
- *
35815
- * Adds a list of {@link Amity.InternalUser} to a {@link Amity.Community} to add users to
35816
- *
35817
- * @param communityId The ID of the {@link Amity.Community} to perform
35818
- * @param userIds The list of IDs {@link Amity.InternalUser} to add
35819
- * @returns A success boolean if the {@link Amity.InternalUser} were added to the {@link Amity.Community}
35820
- *
35821
- * @category Community API
35822
- * @async
35823
- */
35824
- const addMembers = async (communityId, userIds) => {
35825
- const client = getActiveClient();
35826
- client.log('community/moderation/addMembers', communityId, userIds);
35827
- const { data: payload } = await client.http.post(`/api/v3/communities/${communityId}/users`, { communityId, userIds });
35828
- fireEvent('local.community.userAdded', payload);
35829
- const data = prepareMembershipPayload(payload, 'communityUsers');
35830
- if (client.cache)
35831
- ingestInCache(data);
35832
- const { communityUsers } = data;
35833
- return !!communityUsers.find(communityUser => communityUser.communityId === communityId && communityUser.communityMembership === 'member');
35834
- };
35835
- /* end_public_function */
35836
-
35837
- /* begin_public_function
35838
- id: community.membership.remove_member
35839
- */
35840
- /**
35841
- * ```js
35842
- * import { CommunityRepository } from '@amityco/ts-sdk'
35843
- * const updated = await CommunityRepository.moderation.removeMembers(communityId, ['foo', 'bar'])
35844
- * ```
35845
- *
35846
- * Removes a list of {@link Amity.InternalUser} from a {@link Amity.Community}
35847
- *
35848
- * @param communityId The ID of the {@link Amity.Community} to edit
35849
- * @param userIds The list of IDs {@link Amity.InternalUser} to remove
35850
- * @returns A success boolean if the list of {@link Amity.InternalUser} were removed from the {@link Amity.Community}
35851
- *
35852
- * @category Community API
35853
- * @async
35854
- */
35855
- const removeMembers = async (communityId, userIds) => {
35856
- const client = getActiveClient();
35857
- client.log('community/moderation/removeMembers', communityId, userIds);
35858
- const { data: payload } = await client.http.delete(`/api/v3/communities/${communityId}/users`, { data: { communityId, userIds } });
35859
- fireEvent('local.community.userRemoved', payload);
35860
- const data = prepareMembershipPayload(payload, 'communityUsers');
35861
- if (client.cache)
35862
- ingestInCache(data);
35863
- const { communityUsers } = data;
35864
- return !!communityUsers.find(communityUser => communityUser.communityId === communityId && communityUser.communityMembership !== 'member');
35865
- };
35866
- /* end_public_function */
35867
-
35868
- /**
35869
- * TODO: handle cache receive cache option, and cache policy
35870
- * TODO: check if querybyIds is supported
35871
- */
35872
- class CommunityMembersPaginationController extends PaginationController {
35873
- async getRequest(queryParams, token) {
35874
- const { limit = COLLECTION_DEFAULT_PAGINATION_LIMIT, includeDeleted } = queryParams, params = __rest(queryParams, ["limit", "includeDeleted"]);
35875
- const options = token ? { token } : { limit };
35876
- const isDeleted = includeDeleted === false ? false : undefined;
35877
- const { data: queryResponse } = await this.http.get(`/api/v3/communities/${params.communityId}/users`, {
35878
- params: Object.assign(Object.assign({}, params), { options,
35879
- isDeleted }),
35880
- });
35881
- return queryResponse;
35882
- }
35883
- }
35884
-
35885
- class CommunityMembersQueryStreamController extends QueryStreamController {
35886
- constructor(query, cacheKey, notifyChange, preparePayload) {
35887
- super(query, cacheKey);
35888
- this.notifyChange = notifyChange;
35889
- this.preparePayload = preparePayload;
35890
- }
35891
- async saveToMainDB(response) {
35892
- const processedPayload = await this.preparePayload(response);
35893
- const client = getActiveClient();
35894
- const cachedAt = client.cache && Date.now();
35895
- if (client.cache) {
35896
- ingestInCache(processedPayload, { cachedAt });
35897
- }
35898
- }
35899
- appendToQueryStream(response, direction, refresh = false) {
35900
- var _a, _b;
35901
- if (refresh) {
35902
- pushToCache(this.cacheKey, {
35903
- data: response.communityUsers.map(({ communityId, userId }) => getResolver('communityUsers')({ communityId, userId })),
35904
- });
35905
- }
35906
- else {
35907
- const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
35908
- const communityUsers = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
35909
- pushToCache(this.cacheKey, Object.assign(Object.assign({}, collection), { data: [
35910
- ...new Set([
35911
- ...communityUsers,
35912
- ...response.communityUsers.map(({ communityId, userId }) => getResolver('communityUsers')({ communityId, userId })),
35913
- ]),
35914
- ] }));
35915
- }
35916
- }
35917
- reactor(action) {
35918
- return (community, communityMembers) => {
35919
- var _a;
35920
- const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
35921
- if (!collection)
35922
- return;
35923
- if (action === EnumCommunityMemberActions$1.OnCommunityUserRoleAdded &&
35924
- this.query.sortBy === 'displayName') {
35925
- return;
35926
- }
35927
- communityMembers.forEach(communityMember => {
35928
- const communityMemberCacheId = getResolver('communityUsers')({
35929
- communityId: this.query.communityId,
35930
- userId: communityMember.userId,
35931
- });
35932
- if (communityMember.communityMembership === 'none') {
35933
- collection.data = collection.data.filter(m => m !== communityMemberCacheId);
35934
- }
35935
- else if (!collection.data.includes(communityMemberCacheId)) {
35936
- collection.data = [communityMemberCacheId, ...collection.data];
35937
- }
35938
- });
35939
- pushToCache(this.cacheKey, collection);
35940
- this.notifyChange({ origin: "event" /* Amity.LiveDataOrigin.EVENT */, loading: false });
35941
- };
35942
- }
35943
- subscribeRTE(createSubscriber) {
35944
- return createSubscriber.map(subscriber => subscriber.fn(this.reactor(subscriber.action)));
35945
- }
35946
- }
35947
-
35948
34907
  /**
35949
34908
  * ```js
35950
34909
  * import { onLocalCommunityRoleRemoved } from '@amityco/ts-sdk'
@@ -36122,9 +35081,6 @@ class CommunityMembersLiveCollectionController extends LiveCollectionController
36122
35081
  return memberships.includes(communityMembership);
36123
35082
  });
36124
35083
  }
36125
- if (this.query.search) {
36126
- communityMembers = filterBySearchTerm(communityMembers, this.query.search);
36127
- }
36128
35084
  if (this.query.includeDeleted === false) {
36129
35085
  communityMembers = communityMembers.filter(({ user }) => (user === null || user === void 0 ? void 0 : user.isDeleted) !== true);
36130
35086
  }
@@ -36132,15 +35088,6 @@ class CommunityMembersLiveCollectionController extends LiveCollectionController
36132
35088
  case 'firstCreated':
36133
35089
  communityMembers = communityMembers.sort(sortByFirstCreated);
36134
35090
  break;
36135
- case 'displayName':
36136
- communityMembers = communityMembers.sort((a, b) => {
36137
- var _a, _b, _c, _d;
36138
- 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)) {
36139
- 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);
36140
- }
36141
- return 0;
36142
- });
36143
- break;
36144
35091
  case 'lastCreated':
36145
35092
  default:
36146
35093
  communityMembers = communityMembers.sort(sortByLastCreated);
@@ -36162,9 +35109,6 @@ const applyFilter = (data, params) => {
36162
35109
  return membership.includes(communityMembership);
36163
35110
  });
36164
35111
  }
36165
- if (params.search) {
36166
- communityMembers = filterBySearchTerm(communityMembers, params.search);
36167
- }
36168
35112
  const sortBy = params.sortBy ? params.sortBy : 'lastCreated';
36169
35113
  communityMembers = communityMembers.sort(sortBy === 'lastCreated' ? sortByLastCreated : sortByFirstCreated);
36170
35114
  return communityMembers;
@@ -36521,209 +35465,202 @@ class SearchCommunityLiveCollectionController extends LiveCollectionController {
36521
35465
  if (this.query.membership && userId) {
36522
35466
  communities = filterByCommunityMembership(communities, this.query.membership, userId);
36523
35467
  }
36524
- return communities;
36525
- }
36526
- }
36527
-
36528
- /* begin_public_function
36529
- id: community.query
36530
- */
36531
- /**
36532
- * ```js
36533
- * import { CommunityRepository } from '@amityco/ts-sdk'
36534
- *
36535
- * let communities = []
36536
- * const unsub = CommunityRepository.searchCommunities({
36537
- * displayName: Amity.Community['displayName'],
36538
- * }, response => merge(communities, response.data))
36539
- * ```
36540
- *
36541
- * Observe all mutations on a list of {@link Amity.Community}s
36542
- *
36543
- * @param params for querying communities
36544
- * @param callback the function to call when new data are available
36545
- * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the communities
36546
- *
36547
- * @category Community Live Collection
36548
- */
36549
- const searchCommunities = (params, callback, config) => {
36550
- const { log, cache } = getActiveClient();
36551
- if (!cache) {
36552
- console.log(ENABLE_CACHE_MESSAGE);
36553
- }
36554
- const timestamp = Date.now();
36555
- log(`searchCommunities(tmpid: ${timestamp}) > listen`);
36556
- const searchCommunitiesLiveCollection = new SearchCommunityLiveCollectionController(params, callback);
36557
- const disposers = searchCommunitiesLiveCollection.startSubscription();
36558
- const cacheKey = searchCommunitiesLiveCollection.getCacheKey();
36559
- disposers.push(() => dropFromCache(cacheKey));
36560
- return () => {
36561
- log(`searchCommunities(tmpid: ${timestamp}) > dispose`);
36562
- disposers.forEach(fn => fn());
36563
- };
36564
- };
36565
- /* end_public_function */
36566
-
36567
- /**
36568
- * TODO: handle cache receive cache option, and cache policy
36569
- * TODO: check if querybyIds is supported
36570
- */
36571
- class CommunitiesPaginationController extends PaginationController {
36572
- async getRequest(queryParams, token) {
36573
- const { limit = COLLECTION_DEFAULT_PAGINATION_LIMIT } = queryParams, params = __rest(queryParams, ["limit"]);
36574
- const options = token ? { token } : { limit };
36575
- const { data: queryResponse } = await this.http.get(`/api/v3/communities`, {
36576
- params: Object.assign(Object.assign({}, params), { isDeleted: inferIsDeleted(params.includeDeleted), keyword: params.displayName, filter: params.membership, options }),
36577
- });
36578
- return queryResponse;
36579
- }
36580
- }
36581
-
36582
- var EnumCommunityActions$3;
36583
- (function (EnumCommunityActions) {
36584
- EnumCommunityActions["OnCommunityCreated"] = "onCommunityCreated";
36585
- EnumCommunityActions["OnCommunityDeleted"] = "onCommunityDeleted";
36586
- EnumCommunityActions["OnCommunityUpdated"] = "onCommunityUpdated";
36587
- })(EnumCommunityActions$3 || (EnumCommunityActions$3 = {}));
36588
-
36589
- class CommunitiesQueryStreamController extends QueryStreamController {
36590
- constructor(query, cacheKey, notifyChange, preparePayload) {
36591
- super(query, cacheKey);
36592
- this.notifyChange = notifyChange;
36593
- this.preparePayload = preparePayload;
36594
- }
36595
- async saveToMainDB(response) {
36596
- const processedPayload = await this.preparePayload(response);
36597
- const client = getActiveClient();
36598
- const cachedAt = client.cache && Date.now();
36599
- if (client.cache) {
36600
- ingestInCache(processedPayload, { cachedAt });
36601
- saveCommunityUsers(response.communities, response.communityUsers);
36602
- }
36603
- }
36604
- appendToQueryStream(response, direction, refresh = false) {
36605
- var _a, _b;
36606
- if (refresh) {
36607
- pushToCache(this.cacheKey, {
36608
- data: response.communities.map(getResolver('community')),
36609
- });
36610
- }
36611
- else {
36612
- const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
36613
- const communities = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
36614
- pushToCache(this.cacheKey, Object.assign(Object.assign({}, collection), { data: [...new Set([...communities, ...response.communities.map(getResolver('community'))])] }));
36615
- }
36616
- }
36617
- reactor(action) {
36618
- return (community) => {
36619
- var _a;
36620
- const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
36621
- if (!collection)
36622
- return;
36623
- if (this.query.displayName && action === EnumCommunityActions$3.OnCommunityCreated) {
36624
- return;
36625
- }
36626
- /*
36627
- * Simply update a collection and let responder decide what to do with data
36628
- */
36629
- collection.data = [...new Set([community.communityId, ...collection.data])];
36630
- pushToCache(this.cacheKey, collection);
36631
- this.notifyChange({ origin: "event" /* Amity.LiveDataOrigin.EVENT */, loading: false });
36632
- };
36633
- }
36634
- subscribeRTE(createSubscriber) {
36635
- return createSubscriber.map(subscriber => subscriber.fn(this.reactor(subscriber.action)));
36636
- }
36637
- }
36638
-
36639
- class CommunityLiveCollectionController extends LiveCollectionController {
36640
- constructor(query, callback) {
36641
- const queryStreamId = hash(query);
36642
- const cacheKey = ['community', 'collection', queryStreamId];
36643
- const paginationController = new CommunitiesPaginationController(query);
36644
- super(paginationController, queryStreamId, cacheKey, callback);
36645
- this.query = query;
36646
- this.queryStreamController = new CommunitiesQueryStreamController(this.query, this.cacheKey, this.notifyChange.bind(this), prepareCommunityPayload);
36647
- this.callback = callback.bind(this);
36648
- this.loadPage({ initial: true });
36649
- }
36650
- setup() {
36651
- var _a;
36652
- const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
36653
- if (!collection) {
36654
- pushToCache(this.cacheKey, {
36655
- data: [],
36656
- params: {},
36657
- });
36658
- }
36659
- }
36660
- async persistModel(queryPayload) {
36661
- await this.queryStreamController.saveToMainDB(queryPayload);
36662
- }
36663
- persistQueryStream({ response, direction, refresh, }) {
36664
- this.queryStreamController.appendToQueryStream(response, direction, refresh);
36665
- }
36666
- startSubscription() {
36667
- return this.queryStreamController.subscribeRTE([
36668
- { fn: onCommunityCreated, action: EnumCommunityActions$3.OnCommunityCreated },
36669
- { fn: onCommunityDeleted, action: EnumCommunityActions$3.OnCommunityDeleted },
36670
- { fn: onCommunityUpdated, action: EnumCommunityActions$3.OnCommunityUpdated },
36671
- { fn: onCommunityJoined, action: EnumCommunityMemberActions$1.OnCommunityJoined },
36672
- { fn: onCommunityLeft, action: EnumCommunityMemberActions$1.OnCommunityLeft },
36673
- { fn: onCommunityUserChanged, action: EnumCommunityMemberActions$1.OnMemberCountChanged },
36674
- { fn: onLocalCommunityJoined, action: EnumCommunityMemberActions$1.OnCommunityJoined },
36675
- { fn: onLocalCommunityLeft, action: EnumCommunityMemberActions$1.OnCommunityLeft },
36676
- ]);
36677
- }
36678
- notifyChange({ origin, loading, error }) {
36679
- var _a, _b;
36680
- const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
36681
- if (!collection)
36682
- return;
36683
- const data = this.applyFilter((_b = collection.data
36684
- .map(id => pullFromCache(['community', 'get', id]))
36685
- .filter(isNonNullable)
36686
- .map(({ data }) => data)) !== null && _b !== void 0 ? _b : []);
36687
- if (!this.shouldNotify(data) && origin === 'event')
36688
- return;
36689
- this.callback({
36690
- onNextPage: () => this.loadPage({ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */ }),
36691
- data,
36692
- hasNextPage: !!this.paginationController.getNextToken(),
36693
- loading,
36694
- error,
36695
- });
36696
- }
36697
- applyFilter(data) {
36698
- const { userId } = getActiveClient();
36699
- let communities = data;
36700
- if (!this.query.includeDeleted) {
36701
- communities = filterByPropEquality(communities, 'isDeleted', false);
36702
- }
36703
- if (this.query.categoryId) {
36704
- communities = communities.filter(c => { var _a; return (_a = c.categoryIds) === null || _a === void 0 ? void 0 : _a.includes(this.query.categoryId); });
36705
- }
36706
- if (this.query.tags) {
36707
- communities = communities.filter(c => { var _a; return (_a = c.tags) === null || _a === void 0 ? void 0 : _a.some(t => { var _a; return (_a = this.query.tags) === null || _a === void 0 ? void 0 : _a.includes(t); }); });
36708
- }
36709
- if (this.query.membership && userId) {
36710
- communities = filterByCommunityMembership(communities, this.query.membership, userId);
36711
- }
36712
- if (!this.query.displayName) {
36713
- const sortFn = (() => {
36714
- switch (this.query.sortBy) {
36715
- case 'firstCreated':
36716
- return sortByFirstCreated;
36717
- case 'lastCreated':
36718
- return sortByLastCreated;
36719
- case 'displayName':
36720
- return sortByDisplayName;
36721
- default:
36722
- return sortByLastCreated;
36723
- }
36724
- })();
36725
- communities = communities.sort(sortFn);
35468
+ return communities;
35469
+ }
35470
+ }
35471
+
35472
+ /* begin_public_function
35473
+ id: community.query
35474
+ */
35475
+ /**
35476
+ * ```js
35477
+ * import { CommunityRepository } from '@amityco/ts-sdk'
35478
+ *
35479
+ * let communities = []
35480
+ * const unsub = CommunityRepository.searchCommunities({
35481
+ * displayName: Amity.Community['displayName'],
35482
+ * }, response => merge(communities, response.data))
35483
+ * ```
35484
+ *
35485
+ * Observe all mutations on a list of {@link Amity.Community}s
35486
+ *
35487
+ * @param params for querying communities
35488
+ * @param callback the function to call when new data are available
35489
+ * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the communities
35490
+ *
35491
+ * @category Community Live Collection
35492
+ */
35493
+ const searchCommunities = (params, callback, config) => {
35494
+ const { log, cache } = getActiveClient();
35495
+ if (!cache) {
35496
+ console.log(ENABLE_CACHE_MESSAGE);
35497
+ }
35498
+ const timestamp = Date.now();
35499
+ log(`searchCommunities(tmpid: ${timestamp}) > listen`);
35500
+ const searchCommunitiesLiveCollection = new SearchCommunityLiveCollectionController(params, callback);
35501
+ const disposers = searchCommunitiesLiveCollection.startSubscription();
35502
+ const cacheKey = searchCommunitiesLiveCollection.getCacheKey();
35503
+ disposers.push(() => dropFromCache(cacheKey));
35504
+ return () => {
35505
+ log(`searchCommunities(tmpid: ${timestamp}) > dispose`);
35506
+ disposers.forEach(fn => fn());
35507
+ };
35508
+ };
35509
+ /* end_public_function */
35510
+
35511
+ /**
35512
+ * TODO: handle cache receive cache option, and cache policy
35513
+ * TODO: check if querybyIds is supported
35514
+ */
35515
+ class CommunitiesPaginationController extends PaginationController {
35516
+ async getRequest(queryParams, token) {
35517
+ const { limit = COLLECTION_DEFAULT_PAGINATION_LIMIT } = queryParams, params = __rest(queryParams, ["limit"]);
35518
+ const options = token ? { token } : { limit };
35519
+ const { data: queryResponse } = await this.http.get(`/api/v3/communities`, {
35520
+ params: Object.assign(Object.assign({}, params), { isDeleted: inferIsDeleted(params.includeDeleted), filter: params.membership, options }),
35521
+ });
35522
+ return queryResponse;
35523
+ }
35524
+ }
35525
+
35526
+ class CommunitiesQueryStreamController extends QueryStreamController {
35527
+ constructor(query, cacheKey, notifyChange, preparePayload) {
35528
+ super(query, cacheKey);
35529
+ this.notifyChange = notifyChange;
35530
+ this.preparePayload = preparePayload;
35531
+ }
35532
+ async saveToMainDB(response) {
35533
+ const processedPayload = await this.preparePayload(response);
35534
+ const client = getActiveClient();
35535
+ const cachedAt = client.cache && Date.now();
35536
+ if (client.cache) {
35537
+ ingestInCache(processedPayload, { cachedAt });
35538
+ saveCommunityUsers(response.communities, response.communityUsers);
35539
+ }
35540
+ }
35541
+ appendToQueryStream(response, direction, refresh = false) {
35542
+ var _a, _b;
35543
+ if (refresh) {
35544
+ pushToCache(this.cacheKey, {
35545
+ data: response.communities.map(getResolver('community')),
35546
+ });
35547
+ }
35548
+ else {
35549
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
35550
+ const communities = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
35551
+ pushToCache(this.cacheKey, Object.assign(Object.assign({}, collection), { data: [...new Set([...communities, ...response.communities.map(getResolver('community'))])] }));
35552
+ }
35553
+ }
35554
+ reactor(action) {
35555
+ return (community) => {
35556
+ var _a;
35557
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
35558
+ if (!collection)
35559
+ return;
35560
+ /*
35561
+ * Simply update a collection and let responder decide what to do with data
35562
+ */
35563
+ collection.data = [...new Set([community.communityId, ...collection.data])];
35564
+ pushToCache(this.cacheKey, collection);
35565
+ this.notifyChange({ origin: "event" /* Amity.LiveDataOrigin.EVENT */, loading: false });
35566
+ };
35567
+ }
35568
+ subscribeRTE(createSubscriber) {
35569
+ return createSubscriber.map(subscriber => subscriber.fn(this.reactor(subscriber.action)));
35570
+ }
35571
+ }
35572
+
35573
+ var EnumCommunityActions$3;
35574
+ (function (EnumCommunityActions) {
35575
+ EnumCommunityActions["OnCommunityCreated"] = "onCommunityCreated";
35576
+ EnumCommunityActions["OnCommunityDeleted"] = "onCommunityDeleted";
35577
+ EnumCommunityActions["OnCommunityUpdated"] = "onCommunityUpdated";
35578
+ })(EnumCommunityActions$3 || (EnumCommunityActions$3 = {}));
35579
+
35580
+ class CommunityLiveCollectionController extends LiveCollectionController {
35581
+ constructor(query, callback) {
35582
+ const queryStreamId = hash(query);
35583
+ const cacheKey = ['community', 'collection', queryStreamId];
35584
+ const paginationController = new CommunitiesPaginationController(query);
35585
+ super(paginationController, queryStreamId, cacheKey, callback);
35586
+ this.query = query;
35587
+ this.queryStreamController = new CommunitiesQueryStreamController(this.query, this.cacheKey, this.notifyChange.bind(this), prepareCommunityPayload);
35588
+ this.callback = callback.bind(this);
35589
+ this.loadPage({ initial: true });
35590
+ }
35591
+ setup() {
35592
+ var _a;
35593
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
35594
+ if (!collection) {
35595
+ pushToCache(this.cacheKey, {
35596
+ data: [],
35597
+ params: {},
35598
+ });
35599
+ }
35600
+ }
35601
+ async persistModel(queryPayload) {
35602
+ await this.queryStreamController.saveToMainDB(queryPayload);
35603
+ }
35604
+ persistQueryStream({ response, direction, refresh, }) {
35605
+ this.queryStreamController.appendToQueryStream(response, direction, refresh);
35606
+ }
35607
+ startSubscription() {
35608
+ return this.queryStreamController.subscribeRTE([
35609
+ { fn: onCommunityCreated, action: EnumCommunityActions$3.OnCommunityCreated },
35610
+ { fn: onCommunityDeleted, action: EnumCommunityActions$3.OnCommunityDeleted },
35611
+ { fn: onCommunityUpdated, action: EnumCommunityActions$3.OnCommunityUpdated },
35612
+ { fn: onCommunityJoined, action: EnumCommunityMemberActions$1.OnCommunityJoined },
35613
+ { fn: onCommunityLeft, action: EnumCommunityMemberActions$1.OnCommunityLeft },
35614
+ { fn: onCommunityUserChanged, action: EnumCommunityMemberActions$1.OnMemberCountChanged },
35615
+ { fn: onLocalCommunityJoined, action: EnumCommunityMemberActions$1.OnCommunityJoined },
35616
+ { fn: onLocalCommunityLeft, action: EnumCommunityMemberActions$1.OnCommunityLeft },
35617
+ ]);
35618
+ }
35619
+ notifyChange({ origin, loading, error }) {
35620
+ var _a, _b;
35621
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
35622
+ if (!collection)
35623
+ return;
35624
+ const data = this.applyFilter((_b = collection.data
35625
+ .map(id => pullFromCache(['community', 'get', id]))
35626
+ .filter(isNonNullable)
35627
+ .map(({ data }) => data)) !== null && _b !== void 0 ? _b : []);
35628
+ if (!this.shouldNotify(data) && origin === 'event')
35629
+ return;
35630
+ this.callback({
35631
+ onNextPage: () => this.loadPage({ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */ }),
35632
+ data,
35633
+ hasNextPage: !!this.paginationController.getNextToken(),
35634
+ loading,
35635
+ error,
35636
+ });
35637
+ }
35638
+ applyFilter(data) {
35639
+ const { userId } = getActiveClient();
35640
+ let communities = data;
35641
+ if (!this.query.includeDeleted) {
35642
+ communities = filterByPropEquality(communities, 'isDeleted', false);
35643
+ }
35644
+ if (this.query.categoryId) {
35645
+ communities = communities.filter(c => { var _a; return (_a = c.categoryIds) === null || _a === void 0 ? void 0 : _a.includes(this.query.categoryId); });
35646
+ }
35647
+ if (this.query.tags) {
35648
+ communities = communities.filter(c => { var _a; return (_a = c.tags) === null || _a === void 0 ? void 0 : _a.some(t => { var _a; return (_a = this.query.tags) === null || _a === void 0 ? void 0 : _a.includes(t); }); });
35649
+ }
35650
+ if (this.query.membership && userId) {
35651
+ communities = filterByCommunityMembership(communities, this.query.membership, userId);
36726
35652
  }
35653
+ const sortFn = (() => {
35654
+ switch (this.query.sortBy) {
35655
+ case 'firstCreated':
35656
+ return sortByFirstCreated;
35657
+ case 'lastCreated':
35658
+ return sortByLastCreated;
35659
+ default:
35660
+ return sortByLastCreated;
35661
+ }
35662
+ })();
35663
+ communities = communities.sort(sortFn);
36727
35664
  return communities;
36728
35665
  }
36729
35666
  }
@@ -37477,11 +36414,9 @@ var index$9 = /*#__PURE__*/Object.freeze({
37477
36414
  deleteCommunity: deleteCommunity,
37478
36415
  joinCommunity: joinCommunity,
37479
36416
  leaveCommunity: leaveCommunity,
37480
- getTopTrendingCommunities: getTopTrendingCommunities,
37481
36417
  onCommunityCreated: onCommunityCreated,
37482
36418
  onCommunityUpdated: onCommunityUpdated,
37483
36419
  onCommunityDeleted: onCommunityDeleted,
37484
- observeCommunity: observeCommunity,
37485
36420
  searchCommunities: searchCommunities,
37486
36421
  getCommunities: getCommunities,
37487
36422
  getCommunity: getCommunity,
@@ -37731,21 +36666,10 @@ var index$8 = /*#__PURE__*/Object.freeze({
37731
36666
  const queryGlobalFeed = async (query) => {
37732
36667
  const client = getActiveClient();
37733
36668
  client.log('feed/queryGlobalFeed', query);
37734
- const _a = query !== null && query !== void 0 ? query : {}, { useCustomRanking, page, queryToken } = _a, params = __rest(_a, ["useCustomRanking", "page", "queryToken"]);
37735
- /*
37736
- * TODO: Remove useCustomRanking key from query
37737
- */
37738
- if (useCustomRanking)
37739
- console.warn('The param "useCustomRanking" has been deprecated. To get custom ranking feed use FeedRepository.getCustomRankingGlobalFeed instead');
37740
- if (page)
37741
- console.warn('The param "page" has been deprecated. Please use "queryToken" instead.');
36669
+ const _a = query !== null && query !== void 0 ? query : {}, { queryToken } = _a, params = __rest(_a, ["queryToken"]);
37742
36670
  const options = (() => {
37743
36671
  if (queryToken)
37744
36672
  return { token: queryToken };
37745
- if (page)
37746
- return {
37747
- token: toToken(page, 'skiplimit'),
37748
- };
37749
36673
  return undefined;
37750
36674
  })();
37751
36675
  const { data: queryPayload } = await client.http.get(`/api/v4/me/global-feeds`, {
@@ -37758,20 +36682,12 @@ const queryGlobalFeed = async (query) => {
37758
36682
  const cachedAt = client.cache && Date.now();
37759
36683
  if (client.cache) {
37760
36684
  ingestInCache(Object.assign(Object.assign({}, data), { communitis: processedCommunity }));
37761
- const cacheKey = [
37762
- 'globalFeed',
37763
- 'query',
37764
- Object.assign(Object.assign({}, params), { options: Object.assign({}, page) }),
37765
- ];
36685
+ const cacheKey = ['globalFeed', 'query', Object.assign(Object.assign({}, params), { options })];
37766
36686
  pushToCache(cacheKey, { posts: posts.map(getResolver('post')), paging });
37767
36687
  }
37768
- const nextPage = toPage(paging.next);
37769
- const prevPage = toPage(paging.previous);
37770
36688
  return {
37771
36689
  data: posts.map(LinkedObject.post),
37772
36690
  cachedAt,
37773
- prevPage,
37774
- nextPage,
37775
36691
  paging,
37776
36692
  };
37777
36693
  };
@@ -37796,12 +36712,8 @@ queryGlobalFeed.locally = (query) => {
37796
36712
  client.log('post/queryGlobalFeed.locally', query);
37797
36713
  if (!client.cache)
37798
36714
  return;
37799
- const _c = query !== null && query !== void 0 ? query : {}, { page } = _c, params = __rest(_c, ["page"]);
37800
- const queryKey = [
37801
- 'globalFeed',
37802
- 'query',
37803
- Object.assign(Object.assign({}, params), { options: Object.assign({}, page) }),
37804
- ];
36715
+ const params = __rest(query !== null && query !== void 0 ? query : {}, []);
36716
+ const queryKey = ['globalFeed', 'query', Object.assign({}, params)];
37805
36717
  const { data, cachedAt } = (_a = pullFromCache(queryKey)) !== null && _a !== void 0 ? _a : {};
37806
36718
  if (!(data === null || data === void 0 ? void 0 : data.posts.length))
37807
36719
  return;
@@ -37811,14 +36723,10 @@ queryGlobalFeed.locally = (query) => {
37811
36723
  .map(({ data }) => data)
37812
36724
  .map(LinkedObject.post);
37813
36725
  const { paging } = data;
37814
- const prevPage = toPage(data === null || data === void 0 ? void 0 : data.paging.previous);
37815
- const nextPage = toPage(data === null || data === void 0 ? void 0 : data.paging.next);
37816
36726
  return posts.length === ((_b = data === null || data === void 0 ? void 0 : data.posts) === null || _b === void 0 ? void 0 : _b.length)
37817
36727
  ? {
37818
36728
  data: posts,
37819
36729
  cachedAt,
37820
- prevPage,
37821
- nextPage,
37822
36730
  paging,
37823
36731
  }
37824
36732
  : undefined;
@@ -37844,14 +36752,10 @@ queryGlobalFeed.locally = (query) => {
37844
36752
  const getCustomRankingGlobalFeed = async (query) => {
37845
36753
  const client = getActiveClient();
37846
36754
  client.log('feed/getCustomRankingGlobalFeed', query);
37847
- const _a = query !== null && query !== void 0 ? query : {}, { page, queryToken, limit } = _a, params = __rest(_a, ["page", "queryToken", "limit"]);
36755
+ const _a = query !== null && query !== void 0 ? query : {}, { queryToken, limit } = _a, params = __rest(_a, ["queryToken", "limit"]);
37848
36756
  const options = (() => {
37849
36757
  if (queryToken)
37850
36758
  return { token: queryToken };
37851
- if (page)
37852
- return {
37853
- token: toToken(page, 'skiplimit'),
37854
- };
37855
36759
  return undefined;
37856
36760
  })();
37857
36761
  const { data: queryPayload } = await client.http.get(`/api/v5/me/global-feeds`, {
@@ -37863,16 +36767,10 @@ const getCustomRankingGlobalFeed = async (query) => {
37863
36767
  const cachedAt = client.cache && Date.now();
37864
36768
  if (client.cache) {
37865
36769
  ingestInCache(data);
37866
- const cacheKey = [
37867
- 'customGlobalFeed',
37868
- 'query',
37869
- Object.assign(Object.assign({}, params), { options: Object.assign({}, page) }),
37870
- ];
36770
+ const cacheKey = ['customGlobalFeed', 'query', Object.assign(Object.assign({}, params), { options })];
37871
36771
  pushToCache(cacheKey, { posts: posts.map(getResolver('post')), paging });
37872
36772
  }
37873
- const nextPage = toPage(paging.next);
37874
- const prevPage = toPage(paging.previous);
37875
- return { data: posts.map(LinkedObject.post), cachedAt, prevPage, nextPage, paging };
36773
+ return { data: posts.map(LinkedObject.post), cachedAt, paging };
37876
36774
  };
37877
36775
  /* end_public_function */
37878
36776
  /**
@@ -37895,12 +36793,8 @@ getCustomRankingGlobalFeed.locally = (query) => {
37895
36793
  client.log('post/getCustomRankingGlobalFeed.locally', query);
37896
36794
  if (!client.cache)
37897
36795
  return;
37898
- const _c = query !== null && query !== void 0 ? query : {}, { page } = _c, params = __rest(_c, ["page"]);
37899
- const queryKey = [
37900
- 'customGlobalFeed',
37901
- 'query',
37902
- Object.assign(Object.assign({}, params), { options: Object.assign({}, page) }),
37903
- ];
36796
+ const params = __rest(query !== null && query !== void 0 ? query : {}, []);
36797
+ const queryKey = ['customGlobalFeed', 'query', Object.assign({}, params)];
37904
36798
  const { data, cachedAt } = (_a = pullFromCache(queryKey)) !== null && _a !== void 0 ? _a : {};
37905
36799
  if (!(data === null || data === void 0 ? void 0 : data.posts.length))
37906
36800
  return;
@@ -37908,11 +36802,9 @@ getCustomRankingGlobalFeed.locally = (query) => {
37908
36802
  .map(postId => pullFromCache(['post', 'get', postId]))
37909
36803
  .filter(Boolean)
37910
36804
  .map(({ data }) => data);
37911
- const prevPage = toPage(data === null || data === void 0 ? void 0 : data.paging.previous);
37912
- const nextPage = toPage(data === null || data === void 0 ? void 0 : data.paging.next);
37913
36805
  const { paging } = data;
37914
36806
  return posts.length === ((_b = data === null || data === void 0 ? void 0 : data.posts) === null || _b === void 0 ? void 0 : _b.length)
37915
- ? { data: posts.map(LinkedObject.post), cachedAt, prevPage, nextPage, paging }
36807
+ ? { data: posts.map(LinkedObject.post), cachedAt, paging }
37916
36808
  : undefined;
37917
36809
  };
37918
36810
 
@@ -38043,44 +36935,6 @@ const createPost = async (bundle) => {
38043
36935
  };
38044
36936
  /* end_public_function */
38045
36937
 
38046
- /* begin_public_function
38047
- id: post.edit
38048
- */
38049
- /**
38050
- * ```js
38051
- * import { updatePost } from '@amityco/ts-sdk'
38052
- * const updated = await updatePost(postId, {
38053
- * data: { text: 'hello world' }
38054
- * })
38055
- * ```
38056
- *
38057
- * Updates an {@link Amity.Post}
38058
- *
38059
- * @param postId The ID of the {@link Amity.Post} to edit
38060
- * @param patch The patch data to apply
38061
- * @returns the updated {@link Amity.Post} object
38062
- *
38063
- * @category Post API
38064
- * @async
38065
- */
38066
- const updatePost = async (postId, patch) => {
38067
- const client = getActiveClient();
38068
- client.log('user/updatePost', patch);
38069
- console.warn('Deprecation: updatePost has been renamed to editPost. Update post API will be deprecated soon.');
38070
- const { data: payload } = await client.http.put(`/api/v4/posts/${encodeURIComponent(postId)}`, patch);
38071
- const data = prepareMembershipPayload(payload, 'communityUsers');
38072
- const cachedAt = client.cache && Date.now();
38073
- if (client.cache)
38074
- ingestInCache(data, { cachedAt });
38075
- fireEvent('local.post.updated', payload);
38076
- const { posts } = data;
38077
- return {
38078
- data: LinkedObject.post(posts.find(post => post.postId === postId)),
38079
- cachedAt,
38080
- };
38081
- };
38082
- /* end_public_function */
38083
-
38084
36938
  /* begin_public_function
38085
36939
  id: post.edit, post.edit.custom_post
38086
36940
  */
@@ -38398,91 +37252,6 @@ const isPostFlaggedByMe = async (postId) => {
38398
37252
  };
38399
37253
  /* end_public_function */
38400
37254
 
38401
- /**
38402
- * ```js
38403
- * import { PostRepository } from '@amityco/ts-sdk'
38404
- *
38405
- * let posts = []
38406
- * const unsub = PostRepository.observePosts({
38407
- * targetType: Amity.PostTargetType,
38408
- * targetId: Amity.InternalPost['targetId'],
38409
- * }, post => merge(posts, post))
38410
- * ```
38411
- *
38412
- * Observe all mutations on a list of {@link Amity.Post} for a given target object
38413
- *
38414
- * @param params
38415
- * @param callback the function to call when new data are available
38416
- * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the messages
38417
- *
38418
- * @category Post Observer
38419
- */
38420
- const observePosts = (params, callback) => {
38421
- const { log } = getActiveClient();
38422
- const timestamp = Date.now();
38423
- log(`observePosts(tmpid: ${timestamp}) > listen`);
38424
- const disposers = [];
38425
- const router = (post, action) => {
38426
- var _a, _b;
38427
- if (params.targetId !== post.targetId || params.targetType !== post.targetType)
38428
- return;
38429
- if (callback instanceof Function)
38430
- return callback(LinkedObject.post(post));
38431
- (_a = callback.onEvent) === null || _a === void 0 ? void 0 : _a.call(callback, action, LinkedObject.post(post));
38432
- (_b = callback[action]) === null || _b === void 0 ? void 0 : _b.call(callback, LinkedObject.post(post));
38433
- };
38434
- 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')));
38435
- return () => {
38436
- log(`observePosts(tmpid: ${timestamp}) > dispose`);
38437
- disposers.forEach(fn => fn());
38438
- };
38439
- };
38440
-
38441
- /**
38442
- * ```js
38443
- * import { observePost } from '@amityco/ts-sdk'
38444
- *
38445
- * let post = {}
38446
- * const dispose = observePost(postId, updated => post = updated)
38447
- * ```
38448
- *
38449
- * Observe all mutations on a given {@link Amity.Post}
38450
- *
38451
- * @param postId the ID of the post to observe
38452
- * @param callback the function to call when new data are available
38453
- * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the post
38454
- *
38455
- * @category Post Observer
38456
- */
38457
- const observePost = (postId, callback, policy = 'cache_then_server') => {
38458
- const { log } = getActiveClient();
38459
- const timestamp = Date.now();
38460
- log(`observePost(tmpid: ${timestamp}) > listen`);
38461
- // wrapper function to make sure
38462
- const router = (result, action) => {
38463
- var _a, _b;
38464
- if (callback instanceof Function)
38465
- return callback(result);
38466
- if (action !== 'onFetch')
38467
- (_a = callback.onEvent) === null || _a === void 0 ? void 0 : _a.call(callback, action, result);
38468
- (_b = callback[action]) === null || _b === void 0 ? void 0 : _b.call(callback, result);
38469
- };
38470
- const realtimeRouter = (result, action) => {
38471
- var _a;
38472
- if (((_a = result.data) === null || _a === void 0 ? void 0 : _a.postId) !== postId)
38473
- return;
38474
- router(Object.assign(Object.assign({}, result), { data: result.data && LinkedObject.post(result.data) }), action);
38475
- };
38476
- const disposers = [];
38477
- 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')));
38478
- runQuery(createQuery(getPost$2, postId), result => (result.data || result.error) &&
38479
- router(Object.assign(Object.assign({}, result), { data: result.data && LinkedObject.post(result.data) }), 'onFetch'), queryOptions(policy));
38480
- return () => {
38481
- log(`observePosts(tmpid: ${timestamp}) > dispose`);
38482
- disposers.forEach(fn => fn());
38483
- };
38484
- };
38485
-
38486
37255
  /* begin_public_function
38487
37256
  id: comment.get_by_ids
38488
37257
  */
@@ -38958,43 +37727,6 @@ const isCommentFlaggedByMe = async (commentId) => {
38958
37727
  };
38959
37728
  /* end_public_function */
38960
37729
 
38961
- /**
38962
- * ```js
38963
- * import { observeComments } from '@amityco/ts-sdk'
38964
- *
38965
- * let comments = []
38966
- * const unsub = observeComments(postId, comment => merge(comments, comment))
38967
- * ```
38968
- *
38969
- * Observe all mutations on a list of {@link Amity.InternalComment} for a given {@link Amity.Post} object
38970
- *
38971
- * @param postId the ID of the post where to observe the comments
38972
- * @param callback the function to call when new data are available
38973
- * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the comments
38974
- *
38975
- * @category InternalComment Observer
38976
- */
38977
- const observeComments = (postId, callback) => {
38978
- const { log } = getActiveClient();
38979
- const timestamp = Date.now();
38980
- log(`observeComments(tmpid: ${timestamp}) > listen`);
38981
- const disposers = [];
38982
- const router = (comment, action) => {
38983
- var _a, _b;
38984
- if (comment.referenceId !== postId)
38985
- return;
38986
- if (callback instanceof Function)
38987
- return callback(comment);
38988
- (_a = callback.onEvent) === null || _a === void 0 ? void 0 : _a.call(callback, action, comment);
38989
- (_b = callback[action]) === null || _b === void 0 ? void 0 : _b.call(callback, comment);
38990
- };
38991
- 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')));
38992
- return () => {
38993
- log(`observeComments(tmpid: ${timestamp}) > dispose`);
38994
- disposers.forEach(fn => fn());
38995
- };
38996
- };
38997
-
38998
37730
  const getComment$1 = async (commentId) => {
38999
37731
  const client = getActiveClient();
39000
37732
  client.log('comment/getComment', commentId);
@@ -39034,50 +37766,6 @@ getComment$1.locally = (commentId) => {
39034
37766
  };
39035
37767
  };
39036
37768
 
39037
- /**
39038
- * ```js
39039
- * import { observeComment } from '@amityco/ts-sdk'
39040
- *
39041
- * let comment = {}
39042
- * const dispose = observeComment(commentId, ({ data }) => comment = data)
39043
- * ```
39044
- *
39045
- * Observe all mutation on a given {@link Amity.InternalComment}
39046
- *
39047
- * @param commentId the ID of the comment to observe
39048
- * @param callback the function to call when new data are available
39049
- * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the comment
39050
- *
39051
- * @category InternalComment Observer
39052
- */
39053
- const observeComment = (commentId, callback, policy = 'cache_then_server') => {
39054
- const { log } = getActiveClient();
39055
- const timestamp = Date.now();
39056
- log(`observeComment(tmpid: ${timestamp}) > listen`);
39057
- // wrapper function to make sure
39058
- const router = (result, action) => {
39059
- var _a, _b;
39060
- if (callback instanceof Function)
39061
- return callback(result);
39062
- if (action !== 'onFetch')
39063
- (_a = callback.onEvent) === null || _a === void 0 ? void 0 : _a.call(callback, action, result);
39064
- (_b = callback[action]) === null || _b === void 0 ? void 0 : _b.call(callback, result);
39065
- };
39066
- const realtimeRouter = (result, action) => {
39067
- var _a;
39068
- if (((_a = result.data) === null || _a === void 0 ? void 0 : _a.commentId) !== commentId)
39069
- return;
39070
- router(result, action);
39071
- };
39072
- const disposers = [];
39073
- 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')));
39074
- runQuery(createQuery(getComment$1, commentId), result => (result.data || result.error) && router(result, 'onFetch'), queryOptions(policy));
39075
- return () => {
39076
- log(`observeComment(tmpid: ${timestamp}) > dispose`);
39077
- disposers.forEach(fn => fn());
39078
- };
39079
- };
39080
-
39081
37769
  /**
39082
37770
  * ```js
39083
37771
  * import { onCommentDeleteLocal } from '@amityco/ts-sdk'
@@ -39453,8 +38141,6 @@ var index$6 = /*#__PURE__*/Object.freeze({
39453
38141
  onCommentUnflagged: onCommentUnflagged,
39454
38142
  onCommentReactionAdded: onCommentReactionAdded,
39455
38143
  onCommentReactionRemoved: onCommentReactionRemoved,
39456
- observeComments: observeComments,
39457
- observeComment: observeComment,
39458
38144
  getComment: getComment,
39459
38145
  getComments: getComments
39460
38146
  });
@@ -40448,7 +39134,6 @@ var index$5 = /*#__PURE__*/Object.freeze({
40448
39134
  __proto__: null,
40449
39135
  getPostByIds: getPostByIds,
40450
39136
  createPost: createPost,
40451
- updatePost: updatePost,
40452
39137
  editPost: editPost,
40453
39138
  deletePost: deletePost,
40454
39139
  softDeletePost: softDeletePost,
@@ -40467,8 +39152,6 @@ var index$5 = /*#__PURE__*/Object.freeze({
40467
39152
  onPostUnflagged: onPostUnflagged,
40468
39153
  onPostReactionAdded: onPostReactionAdded,
40469
39154
  onPostReactionRemoved: onPostReactionRemoved,
40470
- observePosts: observePosts,
40471
- observePost: observePost,
40472
39155
  getPost: getPost$1,
40473
39156
  getPosts: getPosts,
40474
39157
  getPinnedPosts: getPinnedPosts,
@@ -40661,47 +39344,6 @@ const disposeStream = async (streamId) => {
40661
39344
  };
40662
39345
  /* end_public_function */
40663
39346
 
40664
- /* begin_public_function
40665
- id: stream.query
40666
- */
40667
- /**
40668
- * @deprecated This API renamed to `getStreams`.
40669
- * Please use getStreams() instead.
40670
- * ```js
40671
- * import { getStreams } from '@amityco/ts-sdk'
40672
- * const streams = await getStreams()
40673
- * ```
40674
- *
40675
- * Queries a paginable list of {@link Amity.InternalStream} objects
40676
- *
40677
- * @param query The query parameters
40678
- * @returns A page of {@link Amity.InternalStream} objects
40679
- *
40680
- * @category Stream API
40681
- * @async
40682
- */
40683
- const queryStreams = async (query) => {
40684
- const client = getActiveClient();
40685
- client.log('stream/queryStreams', query);
40686
- const _a = query !== null && query !== void 0 ? query : {}, { page } = _a, params = __rest(_a, ["page"]);
40687
- const { data } = await client.http.get(`/api/v3/video-streaming`, {
40688
- params: Object.assign(Object.assign({}, params), { options: {
40689
- token: toToken(page, 'skiplimit'),
40690
- } }),
40691
- });
40692
- // API-FIX: backend to response Amity.Response: const { paging, videoStreamings } = unwrapPayload(data)
40693
- // API-FIX: seems returned data has a results identifier on top of data, like no other apis, and this is beautiful
40694
- const { paging, results: payload } = data;
40695
- const { videoStreamings } = payload;
40696
- const cachedAt = client.cache && Date.now();
40697
- if (client.cache)
40698
- ingestInCache(payload, { cachedAt });
40699
- const nextPage = toPage(paging.next);
40700
- const prevPage = toPage(paging.previous);
40701
- return { data: videoStreamings, cachedAt, prevPage, nextPage };
40702
- };
40703
- /* end_public_function */
40704
-
40705
39347
  /**
40706
39348
  * ```js
40707
39349
  * import { onStreamStarted } from '@amityco/ts-sdk'
@@ -40723,7 +39365,7 @@ const onStreamStarted = (callback) => {
40723
39365
  ingestInCache(payload);
40724
39366
  callback(payload.videoStreamings[0]);
40725
39367
  };
40726
- return createEventSubscriber(client, 'stream/onStreamStarted', 'v3.video-streaming.didStart', filter);
39368
+ return createEventSubscriber(client, 'stream/onStreamStarted', 'video-streaming.didStart', filter);
40727
39369
  };
40728
39370
 
40729
39371
  /**
@@ -40747,7 +39389,7 @@ const onStreamStopped = (callback) => {
40747
39389
  ingestInCache(payload);
40748
39390
  callback(payload.videoStreamings[0]);
40749
39391
  };
40750
- return createEventSubscriber(client, 'stream/onStreamStropped', 'v3.video-streaming.didStop', filter);
39392
+ return createEventSubscriber(client, 'stream/onStreamStropped', 'video-streaming.didStop', filter);
40751
39393
  };
40752
39394
 
40753
39395
  /**
@@ -40771,7 +39413,7 @@ const onStreamRecorded = (callback) => {
40771
39413
  ingestInCache(payload);
40772
39414
  callback(payload.videoStreamings[0]);
40773
39415
  };
40774
- return createEventSubscriber(client, 'stream/onStreamRecorded', 'v3.video-streaming.didRecord', filter);
39416
+ return createEventSubscriber(client, 'stream/onStreamRecorded', 'video-streaming.didRecord', filter);
40775
39417
  };
40776
39418
 
40777
39419
  /**
@@ -40795,7 +39437,7 @@ const onStreamFlagged = (callback) => {
40795
39437
  ingestInCache(payload);
40796
39438
  callback(payload.videoStreamings[0]);
40797
39439
  };
40798
- return createEventSubscriber(client, 'stream/onStreamFlagged', 'v3.video-streaming.didFlag', filter);
39440
+ return createEventSubscriber(client, 'stream/onStreamFlagged', 'video-streaming.didFlag', filter);
40799
39441
  };
40800
39442
 
40801
39443
  /**
@@ -40819,7 +39461,7 @@ const onStreamTerminated = (callback) => {
40819
39461
  ingestInCache(payload);
40820
39462
  callback(payload.videoStreamings[0]);
40821
39463
  };
40822
- return createEventSubscriber(client, 'stream/onStreamTerminated', 'v3.video-streaming.didTerminate', filter);
39464
+ return createEventSubscriber(client, 'stream/onStreamTerminated', 'video-streaming.didTerminate', filter);
40823
39465
  };
40824
39466
 
40825
39467
  /* eslint-disable no-use-before-define */
@@ -41028,8 +39670,6 @@ var index$4 = /*#__PURE__*/Object.freeze({
41028
39670
  updateStream: updateStream,
41029
39671
  deleteStream: deleteStream,
41030
39672
  disposeStream: disposeStream,
41031
- queryStreams: queryStreams,
41032
- getStream: getStream,
41033
39673
  onStreamStarted: onStreamStarted,
41034
39674
  onStreamStopped: onStreamStopped,
41035
39675
  onStreamRecorded: onStreamRecorded,
@@ -41284,50 +39924,6 @@ const onPollDeleted = (callback) => {
41284
39924
  return createEventSubscriber(client, 'poll/onPollDeleted', 'poll.deleted', filter);
41285
39925
  };
41286
39926
 
41287
- /**
41288
- * ```js
41289
- * import { observePoll } from '@amityco/ts-sdk'
41290
- *
41291
- * let poll = {}
41292
- * const dispose = observePoll(pollId, updated => poll = updated)
41293
- * ```
41294
- *
41295
- * Observe all mutation on a given {@link Amity.Poll}
41296
- *
41297
- * @param pollId the ID of the poll to observe
41298
- * @param callback the function to call when new data are available
41299
- * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the poll
41300
- *
41301
- * @category Poll Observer
41302
- */
41303
- const observePoll = (pollId, callback, policy = 'cache_then_server') => {
41304
- const { log } = getActiveClient();
41305
- const timestamp = Date.now();
41306
- log(`observePoll(tmpid: ${timestamp}) > listen`);
41307
- // wrapper function to make sure
41308
- const router = (result, action) => {
41309
- var _a, _b;
41310
- if (callback instanceof Function)
41311
- return callback(result);
41312
- if (action !== 'onFetch')
41313
- (_a = callback.onEvent) === null || _a === void 0 ? void 0 : _a.call(callback, action, result);
41314
- (_b = callback[action]) === null || _b === void 0 ? void 0 : _b.call(callback, result);
41315
- };
41316
- const realtimeRouter = (result, action) => {
41317
- var _a;
41318
- if (((_a = result.data) === null || _a === void 0 ? void 0 : _a.pollId) !== pollId)
41319
- return;
41320
- router(result, action);
41321
- };
41322
- const disposers = [];
41323
- disposers.push(onPollUpdated(data => realtimeRouter({ data, loading: false, origin: 'event' }, 'onUpdate')), onPollDeleted(data => realtimeRouter({ data, loading: false, origin: 'event' }, 'onDelete')));
41324
- runQuery(createQuery(getPoll$1, pollId), result => (result.data || result.error) && router(result, 'onFetch'), queryOptions(policy));
41325
- return () => {
41326
- log(`observePoll(tmpid: ${timestamp}) > dispose`);
41327
- disposers.forEach(fn => fn());
41328
- };
41329
- };
41330
-
41331
39927
  /* begin_public_function
41332
39928
  id: poll.get
41333
39929
  */
@@ -41363,7 +39959,6 @@ var index$3 = /*#__PURE__*/Object.freeze({
41363
39959
  votePoll: votePoll,
41364
39960
  onPollUpdated: onPollUpdated,
41365
39961
  onPollDeleted: onPollDeleted,
41366
- observePoll: observePoll,
41367
39962
  getPoll: getPoll
41368
39963
  });
41369
39964
 
@@ -41821,7 +40416,7 @@ const createOptimisticTarget = async ({ targetId, targetType, }) => {
41821
40416
  optimisticTarget = Object.assign(Object.assign({}, optimisticTarget), { targetPublicId: community.data.communityId, targetUpdatedAt: (_a = community.data.updatedAt) !== null && _a !== void 0 ? _a : new Date().toISOString() });
41822
40417
  }
41823
40418
  if (targetType === 'user') {
41824
- const user = await getUser$2(targetId);
40419
+ const user = await getUser$1(targetId);
41825
40420
  optimisticTarget = Object.assign(Object.assign({}, optimisticTarget), { targetPublicId: user.data.userPublicId, targetUpdatedAt: (_b = user.data.updatedAt) !== null && _b !== void 0 ? _b : new Date().toISOString() });
41826
40421
  }
41827
40422
  pushToCache(["storyTarget" /* STORY_KEY_CACHE.STORY_TARGET */, 'get', targetId], optimisticTarget);
@@ -42964,4 +41559,4 @@ const createUserToken = async (apiKey, apiRegion, params) => {
42964
41559
  return { accessToken: data.accessToken };
42965
41560
  };
42966
41561
 
42967
- export { API_REGIONS, index as AdRepository, index$8 as CategoryRepository, index$c as ChannelRepository, index$l as Client, index$6 as CommentRepository, CommunityPostSettingMaps, CommunityPostSettings, index$9 as CommunityRepository, ContentFeedType, DefaultCommunityPostSetting, index$7 as FeedRepository, FileAccessTypeEnum, index$i as FileRepository, FileType, index$2 as LiveStreamPlayer, MessageContentType, index$g as MessageRepository, index$3 as PollRepository, PostContentType, index$5 as PostRepository, index$h as ReactionRepository, index$1 as StoryRepository, index$4 as StreamRepository, index$f as SubChannelRepository, SubscriptionLevels, index$j as UserRepository, VERSION, VideoResolution, VideoSize, VideoTranscodingStatus, backupCache, createQuery, createReport, createUserToken, deleteReport, disableCache, dropFromCache, enableCache, filterByChannelMembership, filterByCommunityMembership, filterByFeedType, filterByPostDataTypes, filterByPropEquality, filterByPropInclusion, filterByPropIntersection, filterBySearchTerm, filterByStringComparePartially, getChannelTopic, getCommentTopic, getCommunityStoriesTopic, getCommunityTopic, getMarkedMessageTopic, getMarkerUserFeedTopic, getMessageTopic, getMyFollowersTopic, getMyFollowingsTopic, getNetworkTopic, getPostTopic, getRole, getSmartFeedChannelTopic, getSmartFeedMessageTopic, getSmartFeedSubChannelTopic, getStoryTopic, getSubChannelTopic, getUserTopic, isAfterBefore, isAfterBeforeRaw, isCachable, isFetcher, isFresh, isLocal, isMutator, isOffline, isPaged, isReportedByMe, isSkip, mergeInCache, onChannelMarkerFetched, onFeedMarkerFetched, onFeedMarkerUpdated, onMessageMarked, onMessageMarkerFetched, onSubChannelMarkerFetched, onSubChannelMarkerUpdated, onUserMarkerFetched, onUserMarkerFetchedLegacy, pullFromCache, pushToCache, queryCache, queryOptions, queryRoles, restoreCache, runQuery, sortByChannelSegment, sortByDisplayName, sortByFirstCreated, sortByFirstUpdated, sortByLastActivity, sortByLastCreated, sortByLastUpdated, sortByLocalSortingDate, sortByName, sortBySegmentNumber, subscribeTopic, toPage, toPageRaw, toToken, upsertInCache, wipeCache };
41562
+ export { API_REGIONS, index as AdRepository, index$8 as CategoryRepository, index$c as ChannelRepository, index$l as Client, index$6 as CommentRepository, CommunityPostSettingMaps, CommunityPostSettings, index$9 as CommunityRepository, ContentFeedType, DefaultCommunityPostSetting, index$7 as FeedRepository, FileAccessTypeEnum, index$i as FileRepository, FileType, index$2 as LiveStreamPlayer, MessageContentType, index$g as MessageRepository, index$3 as PollRepository, PostContentType, index$5 as PostRepository, index$h as ReactionRepository, index$1 as StoryRepository, index$4 as StreamRepository, index$f as SubChannelRepository, SubscriptionLevels, index$j as UserRepository, VERSION, VideoResolution, VideoSize, VideoTranscodingStatus, backupCache, createQuery, createReport, createUserToken, deleteReport, disableCache, dropFromCache, enableCache, filterByChannelMembership, filterByCommunityMembership, filterByFeedType, filterByPostDataTypes, filterByPropEquality, filterByPropInclusion, filterByPropIntersection, filterBySearchTerm, filterByStringComparePartially, getChannelTopic, getCommentTopic, getCommunityStoriesTopic, getCommunityTopic, getLiveStreamTopic, getMarkedMessageTopic, getMarkerUserFeedTopic, getMessageTopic, getMyFollowersTopic, getMyFollowingsTopic, getNetworkTopic, getPostTopic, getRole, getSmartFeedChannelTopic, getSmartFeedMessageTopic, getSmartFeedSubChannelTopic, getStoryTopic, getSubChannelTopic, getUserTopic, isAfterBefore, isAfterBeforeRaw, isCachable, isFetcher, isFresh, isLocal, isMutator, isOffline, isPaged, isReportedByMe, isSkip, mergeInCache, onChannelMarkerFetched, onFeedMarkerFetched, onFeedMarkerUpdated, onMessageMarked, onMessageMarkerFetched, onSubChannelMarkerFetched, onSubChannelMarkerUpdated, onUserMarkerFetched, onUserMarkerFetchedLegacy, pullFromCache, pushToCache, queryCache, queryOptions, queryRoles, restoreCache, runQuery, sortByChannelSegment, sortByDisplayName, sortByFirstCreated, sortByFirstUpdated, sortByLastActivity, sortByLastCreated, sortByLastUpdated, sortByLocalSortingDate, sortByName, sortBySegmentNumber, subscribeTopic, toPage, toPageRaw, toToken, upsertInCache, wipeCache };