@amityco/ts-sdk-react-native 6.29.2 → 6.29.3-fe4e045.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 (373) hide show
  1. package/.env +26 -26
  2. package/dist/@types/core/events.d.ts +41 -11
  3. package/dist/@types/core/events.d.ts.map +1 -1
  4. package/dist/@types/core/model.d.ts +4 -0
  5. package/dist/@types/core/model.d.ts.map +1 -1
  6. package/dist/@types/core/payload.d.ts +32 -7
  7. package/dist/@types/core/payload.d.ts.map +1 -1
  8. package/dist/@types/core/permissions.d.ts +4 -4
  9. package/dist/@types/core/permissions.d.ts.map +1 -1
  10. package/dist/@types/domains/channel.d.ts +8 -0
  11. package/dist/@types/domains/channel.d.ts.map +1 -1
  12. package/dist/@types/domains/comment.d.ts +5 -4
  13. package/dist/@types/domains/comment.d.ts.map +1 -1
  14. package/dist/@types/domains/community.d.ts +32 -8
  15. package/dist/@types/domains/community.d.ts.map +1 -1
  16. package/dist/@types/domains/follow.d.ts +21 -3
  17. package/dist/@types/domains/follow.d.ts.map +1 -1
  18. package/dist/@types/domains/group.d.ts +13 -7
  19. package/dist/@types/domains/group.d.ts.map +1 -1
  20. package/dist/@types/domains/pin.d.ts +22 -0
  21. package/dist/@types/domains/pin.d.ts.map +1 -0
  22. package/dist/@types/domains/pinnedPost.d.ts +28 -0
  23. package/dist/@types/domains/pinnedPost.d.ts.map +1 -0
  24. package/dist/@types/domains/poll.d.ts +3 -1
  25. package/dist/@types/domains/poll.d.ts.map +1 -1
  26. package/dist/@types/domains/post.d.ts +8 -5
  27. package/dist/@types/domains/post.d.ts.map +1 -1
  28. package/dist/@types/domains/stream.d.ts +2 -1
  29. package/dist/@types/domains/stream.d.ts.map +1 -1
  30. package/dist/@types/domains/user.d.ts +34 -6
  31. package/dist/@types/domains/user.d.ts.map +1 -1
  32. package/dist/channelRepository/channelMembership/observers/getMembers/ChannelMemberLiveCollectionController.d.ts.map +1 -1
  33. package/dist/channelRepository/channelMembership/observers/getMembers/ChannelMemberPaginationController.d.ts +3 -2
  34. package/dist/channelRepository/channelMembership/observers/getMembers/ChannelMemberPaginationController.d.ts.map +1 -1
  35. package/dist/channelRepository/channelMembership/observers/searchMembers/SearchChannelMemberLiveCollectionController.d.ts +14 -0
  36. package/dist/channelRepository/channelMembership/observers/searchMembers/SearchChannelMemberLiveCollectionController.d.ts.map +1 -0
  37. package/dist/channelRepository/channelMembership/observers/searchMembers/SearchChannelMemberPaginationController.d.ts +14 -0
  38. package/dist/channelRepository/channelMembership/observers/searchMembers/SearchChannelMemberPaginationController.d.ts.map +1 -0
  39. package/dist/channelRepository/channelMembership/observers/searchMembers/SearchChannelMemberQueryStreamController.d.ts +14 -0
  40. package/dist/channelRepository/channelMembership/observers/searchMembers/SearchChannelMemberQueryStreamController.d.ts.map +1 -0
  41. package/dist/channelRepository/channelMembership/observers/searchMembers/index.d.ts +2 -0
  42. package/dist/channelRepository/channelMembership/observers/searchMembers/index.d.ts.map +1 -0
  43. package/dist/channelRepository/channelMembership/observers/searchMembers/searchMembers.d.ts +21 -0
  44. package/dist/channelRepository/channelMembership/observers/searchMembers/searchMembers.d.ts.map +1 -0
  45. package/dist/channelRepository/events/onUserDeleted.d.ts +2 -0
  46. package/dist/channelRepository/events/onUserDeleted.d.ts.map +1 -0
  47. package/dist/channelRepository/observers/getChannels/ChannelPaginationController.d.ts +3 -3
  48. package/dist/channelRepository/utils/prepareChannelPayload.d.ts.map +1 -1
  49. package/dist/channelRepository/utils/tests/prepareChannelPayload.test.d.ts +1 -1
  50. package/dist/channelRepository/utils/tests/prepareChannelPayload.test.d.ts.map +1 -1
  51. package/dist/client/api/index.d.ts +0 -2
  52. package/dist/client/api/index.d.ts.map +1 -1
  53. package/dist/commentRepository/api/createComment.d.ts.map +1 -1
  54. package/dist/commentRepository/api/deleteComment.d.ts.map +1 -1
  55. package/dist/commentRepository/events/onCommentCreatedLocal.d.ts +17 -0
  56. package/dist/commentRepository/events/onCommentCreatedLocal.d.ts.map +1 -0
  57. package/dist/commentRepository/events/onCommentDeletedLocal.d.ts +17 -0
  58. package/dist/commentRepository/events/onCommentDeletedLocal.d.ts.map +1 -0
  59. package/dist/commentRepository/events/onLocalCommentReactionAdded.d.ts +17 -0
  60. package/dist/commentRepository/events/onLocalCommentReactionAdded.d.ts.map +1 -0
  61. package/dist/commentRepository/events/onLocalCommentReactionRemoved.d.ts +17 -0
  62. package/dist/commentRepository/events/onLocalCommentReactionRemoved.d.ts.map +1 -0
  63. package/dist/commentRepository/events/utils.d.ts +1 -0
  64. package/dist/commentRepository/events/utils.d.ts.map +1 -1
  65. package/dist/commentRepository/observers/getComment.d.ts.map +1 -1
  66. package/dist/commentRepository/observers/getComments/CommentLiveCollectionController.d.ts.map +1 -1
  67. package/dist/communityRepository/communityMembership/events/index.d.ts +2 -0
  68. package/dist/communityRepository/communityMembership/events/index.d.ts.map +1 -1
  69. package/dist/communityRepository/communityMembership/events/onLocalCommunityUserAdded.d.ts +17 -0
  70. package/dist/communityRepository/communityMembership/events/onLocalCommunityUserAdded.d.ts.map +1 -0
  71. package/dist/communityRepository/communityMembership/events/onLocalCommunityUserRemoved.d.ts +17 -0
  72. package/dist/communityRepository/communityMembership/events/onLocalCommunityUserRemoved.d.ts.map +1 -0
  73. package/dist/communityRepository/communityMembership/events/onUserDeleted.d.ts +17 -0
  74. package/dist/communityRepository/communityMembership/events/onUserDeleted.d.ts.map +1 -0
  75. package/dist/communityRepository/communityMembership/events/utils.d.ts +1 -0
  76. package/dist/communityRepository/communityMembership/events/utils.d.ts.map +1 -1
  77. package/dist/communityRepository/communityMembership/observers/getMembers/CommunityMembersLiveCollectionController.d.ts.map +1 -1
  78. package/dist/communityRepository/communityMembership/observers/getMembers/CommunityMembersPaginationController.d.ts.map +1 -1
  79. package/dist/communityRepository/communityMembership/observers/getMembers/enums.d.ts +4 -1
  80. package/dist/communityRepository/communityMembership/observers/getMembers/enums.d.ts.map +1 -1
  81. package/dist/communityRepository/communityMembership/observers/searchMembers/SearchCommunityMembersLiveCollectionController.d.ts.map +1 -1
  82. package/dist/communityRepository/communityMembership/observers/searchMembers/SearchCommunityMembersPaginationController.d.ts.map +1 -1
  83. package/dist/communityRepository/communityModeration/api/addRoles.d.ts.map +1 -1
  84. package/dist/communityRepository/communityModeration/api/removeRoles.d.ts.map +1 -1
  85. package/dist/communityRepository/communityModeration/events/onLocalCommunityRoleAdded.d.ts +17 -0
  86. package/dist/communityRepository/communityModeration/events/onLocalCommunityRoleAdded.d.ts.map +1 -0
  87. package/dist/communityRepository/communityModeration/events/onLocalCommunityRoleRemoved.d.ts +17 -0
  88. package/dist/communityRepository/communityModeration/events/onLocalCommunityRoleRemoved.d.ts.map +1 -0
  89. package/dist/communityRepository/utils/payload.d.ts +3 -6
  90. package/dist/communityRepository/utils/payload.d.ts.map +1 -1
  91. package/dist/core/events.d.ts +3 -3
  92. package/dist/core/events.d.ts.map +1 -1
  93. package/dist/core/model/idResolvers.d.ts.map +1 -1
  94. package/dist/core/model/index.d.ts.map +1 -1
  95. package/dist/group/utils/withUser.d.ts +13 -0
  96. package/dist/group/utils/withUser.d.ts.map +1 -1
  97. package/dist/index.cjs.js +2242 -1228
  98. package/dist/index.esm.js +2422 -1408
  99. package/dist/index.umd.js +3 -3
  100. package/dist/pollRepository/observers/observePoll.d.ts +1 -1
  101. package/dist/pollRepository/observers/observePoll.d.ts.map +1 -1
  102. package/dist/postRepository/events/onLocalPostDeleted.d.ts +17 -0
  103. package/dist/postRepository/events/onLocalPostDeleted.d.ts.map +1 -0
  104. package/dist/postRepository/events/onLocalPostReactionAdded.d.ts +17 -0
  105. package/dist/postRepository/events/onLocalPostReactionAdded.d.ts.map +1 -0
  106. package/dist/postRepository/events/onLocalPostReactionRemoved.d.ts +17 -0
  107. package/dist/postRepository/events/onLocalPostReactionRemoved.d.ts.map +1 -0
  108. package/dist/postRepository/events/onPostUpdatedLocal.d.ts +17 -0
  109. package/dist/postRepository/events/onPostUpdatedLocal.d.ts.map +1 -0
  110. package/dist/postRepository/events/utils.d.ts +1 -0
  111. package/dist/postRepository/events/utils.d.ts.map +1 -1
  112. package/dist/postRepository/internalApi/index.d.ts +1 -12
  113. package/dist/postRepository/internalApi/index.d.ts.map +1 -1
  114. package/dist/postRepository/observers/getPinnedPosts/PinnedPostLiveCollectionController.d.ts +14 -0
  115. package/dist/postRepository/observers/getPinnedPosts/PinnedPostLiveCollectionController.d.ts.map +1 -0
  116. package/dist/postRepository/observers/getPinnedPosts/PinnedPostPaginationController.d.ts +13 -0
  117. package/dist/postRepository/observers/getPinnedPosts/PinnedPostPaginationController.d.ts.map +1 -0
  118. package/dist/postRepository/observers/getPinnedPosts/PinnedPostQueryStreamController.d.ts +9 -0
  119. package/dist/postRepository/observers/getPinnedPosts/PinnedPostQueryStreamController.d.ts.map +1 -0
  120. package/dist/postRepository/observers/getPinnedPosts.d.ts +12 -0
  121. package/dist/postRepository/observers/getPinnedPosts.d.ts.map +1 -0
  122. package/dist/postRepository/observers/getPost.d.ts.map +1 -1
  123. package/dist/postRepository/observers/getPosts/PostLiveCollectionController.d.ts.map +1 -1
  124. package/dist/postRepository/observers/index.d.ts +1 -0
  125. package/dist/postRepository/observers/index.d.ts.map +1 -1
  126. package/dist/postRepository/utils/payload.d.ts.map +1 -1
  127. package/dist/reactionRepository/api/addReaction.d.ts.map +1 -1
  128. package/dist/reactionRepository/api/removeReaction.d.ts.map +1 -1
  129. package/dist/report/api/createReport.d.ts +1 -2
  130. package/dist/report/api/createReport.d.ts.map +1 -1
  131. package/dist/report/api/deleteReport.d.ts +1 -2
  132. package/dist/report/api/deleteReport.d.ts.map +1 -1
  133. package/dist/report/api/isReportedByMe.d.ts +1 -2
  134. package/dist/report/api/isReportedByMe.d.ts.map +1 -1
  135. package/dist/streamRepository/observers/getStreams/GetStreamsPageController.d.ts +1 -1
  136. package/dist/userRepository/api/flagUser.d.ts.map +1 -1
  137. package/dist/userRepository/api/getUser.d.ts.map +1 -1
  138. package/dist/userRepository/api/getUserByIds.d.ts.map +1 -1
  139. package/dist/userRepository/api/queryBlockedUsers.d.ts.map +1 -1
  140. package/dist/userRepository/api/queryUsers.d.ts.map +1 -1
  141. package/dist/userRepository/api/unflagUser.d.ts.map +1 -1
  142. package/dist/userRepository/api/updateUser.d.ts.map +1 -1
  143. package/dist/userRepository/events/utils.d.ts.map +1 -1
  144. package/dist/userRepository/internalApi/getUser.d.ts.map +1 -1
  145. package/dist/userRepository/internalApi/queryUsers.d.ts.map +1 -1
  146. package/dist/userRepository/observers/enums.d.ts +8 -0
  147. package/dist/userRepository/observers/enums.d.ts.map +1 -0
  148. package/dist/userRepository/observers/getBlockedUsers/BlockedUserLiveCollectionController.d.ts +14 -0
  149. package/dist/userRepository/observers/getBlockedUsers/BlockedUserLiveCollectionController.d.ts.map +1 -0
  150. package/dist/userRepository/observers/getBlockedUsers/BlockedUserPaginationController.d.ts +5 -0
  151. package/dist/userRepository/observers/getBlockedUsers/BlockedUserPaginationController.d.ts.map +1 -0
  152. package/dist/userRepository/observers/getBlockedUsers/BlockedUserQueryStreamController.d.ts +15 -0
  153. package/dist/userRepository/observers/getBlockedUsers/BlockedUserQueryStreamController.d.ts.map +1 -0
  154. package/dist/userRepository/observers/getBlockedUsers.d.ts.map +1 -1
  155. package/dist/userRepository/observers/getUsers/UserLiveCollectionController.d.ts +14 -0
  156. package/dist/userRepository/observers/getUsers/UserLiveCollectionController.d.ts.map +1 -0
  157. package/dist/userRepository/observers/getUsers/UserPaginationController.d.ts +5 -0
  158. package/dist/userRepository/observers/getUsers/UserPaginationController.d.ts.map +1 -0
  159. package/dist/userRepository/observers/getUsers/UserQueryStreamController.d.ts +15 -0
  160. package/dist/userRepository/observers/getUsers/UserQueryStreamController.d.ts.map +1 -0
  161. package/dist/userRepository/observers/getUsers.d.ts +0 -1
  162. package/dist/userRepository/observers/getUsers.d.ts.map +1 -1
  163. package/dist/userRepository/observers/searchUserByDisplayName/SearchUserLiveCollectionController.d.ts +14 -0
  164. package/dist/userRepository/observers/searchUserByDisplayName/SearchUserLiveCollectionController.d.ts.map +1 -0
  165. package/dist/userRepository/observers/searchUserByDisplayName/SearchUserPaginationController.d.ts +5 -0
  166. package/dist/userRepository/observers/searchUserByDisplayName/SearchUserPaginationController.d.ts.map +1 -0
  167. package/dist/userRepository/observers/searchUserByDisplayName/SearchUserQueryStreamController.d.ts +15 -0
  168. package/dist/userRepository/observers/searchUserByDisplayName/SearchUserQueryStreamController.d.ts.map +1 -0
  169. package/dist/userRepository/observers/searchUserByDisplayName.d.ts.map +1 -1
  170. package/dist/userRepository/relationship/block/api/blockUser.d.ts.map +1 -1
  171. package/dist/userRepository/relationship/block/api/unBlockUser.d.ts.map +1 -1
  172. package/dist/userRepository/relationship/follow/api/acceptFollower.d.ts.map +1 -1
  173. package/dist/userRepository/relationship/follow/api/acceptMyFollower.d.ts.map +1 -1
  174. package/dist/userRepository/relationship/follow/api/declineFollower.d.ts.map +1 -1
  175. package/dist/userRepository/relationship/follow/api/declineMyFollower.d.ts.map +1 -1
  176. package/dist/userRepository/relationship/follow/api/follow.d.ts.map +1 -1
  177. package/dist/userRepository/relationship/follow/api/unfollow.d.ts.map +1 -1
  178. package/dist/userRepository/relationship/follow/api/utils.d.ts.map +1 -1
  179. package/dist/userRepository/relationship/follow/enums.d.ts +11 -0
  180. package/dist/userRepository/relationship/follow/enums.d.ts.map +1 -0
  181. package/dist/userRepository/relationship/follow/events/index.d.ts +5 -0
  182. package/dist/userRepository/relationship/follow/events/index.d.ts.map +1 -1
  183. package/dist/userRepository/relationship/follow/events/onFollowInfoUpdated.d.ts.map +1 -1
  184. package/dist/userRepository/relationship/follow/events/onFollowerUserDeleted.d.ts +4 -0
  185. package/dist/userRepository/relationship/follow/events/onFollowerUserDeleted.d.ts.map +1 -0
  186. package/dist/userRepository/relationship/follow/events/onFollowingUserDeleted.d.ts +4 -0
  187. package/dist/userRepository/relationship/follow/events/onFollowingUserDeleted.d.ts.map +1 -0
  188. package/dist/userRepository/relationship/follow/events/onLocalFollowRequestAccepted.d.ts +2 -0
  189. package/dist/userRepository/relationship/follow/events/onLocalFollowRequestAccepted.d.ts.map +1 -0
  190. package/dist/userRepository/relationship/follow/events/onLocalFollowRequestDeclined.d.ts +2 -0
  191. package/dist/userRepository/relationship/follow/events/onLocalFollowRequestDeclined.d.ts.map +1 -0
  192. package/dist/userRepository/relationship/follow/events/onLocalFollowerRequested.d.ts +2 -0
  193. package/dist/userRepository/relationship/follow/events/onLocalFollowerRequested.d.ts.map +1 -0
  194. package/dist/userRepository/relationship/follow/events/onLocalUserFollowed.d.ts +2 -0
  195. package/dist/userRepository/relationship/follow/events/onLocalUserFollowed.d.ts.map +1 -0
  196. package/dist/userRepository/relationship/follow/events/onLocalUserUnfollowed.d.ts +2 -0
  197. package/dist/userRepository/relationship/follow/events/onLocalUserUnfollowed.d.ts.map +1 -0
  198. package/dist/userRepository/relationship/follow/events/utils.d.ts +2 -1
  199. package/dist/userRepository/relationship/follow/events/utils.d.ts.map +1 -1
  200. package/dist/userRepository/relationship/follow/observers/getFollowers/FollowerLiveCollectionController.d.ts +14 -0
  201. package/dist/userRepository/relationship/follow/observers/getFollowers/FollowerLiveCollectionController.d.ts.map +1 -0
  202. package/dist/userRepository/relationship/follow/observers/getFollowers/FollowerPaginationController.d.ts +5 -0
  203. package/dist/userRepository/relationship/follow/observers/getFollowers/FollowerPaginationController.d.ts.map +1 -0
  204. package/dist/userRepository/relationship/follow/observers/getFollowers/FollowerQueryStreamController.d.ts +15 -0
  205. package/dist/userRepository/relationship/follow/observers/getFollowers/FollowerQueryStreamController.d.ts.map +1 -0
  206. package/dist/userRepository/relationship/follow/observers/getFollowers.d.ts.map +1 -1
  207. package/dist/userRepository/relationship/follow/observers/getFollowings/FollowingLiveCollectionController.d.ts +14 -0
  208. package/dist/userRepository/relationship/follow/observers/getFollowings/FollowingLiveCollectionController.d.ts.map +1 -0
  209. package/dist/userRepository/relationship/follow/observers/getFollowings/FollowingPaginationController.d.ts +5 -0
  210. package/dist/userRepository/relationship/follow/observers/getFollowings/FollowingPaginationController.d.ts.map +1 -0
  211. package/dist/userRepository/relationship/follow/observers/getFollowings/FollowingQueryStreamController.d.ts +15 -0
  212. package/dist/userRepository/relationship/follow/observers/getFollowings/FollowingQueryStreamController.d.ts.map +1 -0
  213. package/dist/userRepository/relationship/follow/observers/getFollowings.d.ts.map +1 -1
  214. package/dist/userRepository/relationship/follow/observers/observeFollowers.d.ts +1 -1
  215. package/dist/userRepository/relationship/follow/observers/observeFollowers.d.ts.map +1 -1
  216. package/dist/userRepository/relationship/follow/observers/observeFollowings.d.ts +1 -1
  217. package/dist/userRepository/relationship/follow/observers/observeFollowings.d.ts.map +1 -1
  218. package/dist/userRepository/relationship/follow/utils.d.ts +4 -0
  219. package/dist/userRepository/relationship/follow/utils.d.ts.map +1 -0
  220. package/dist/userRepository/utils/convertRawUserToInternalUser.d.ts +2 -0
  221. package/dist/userRepository/utils/convertRawUserToInternalUser.d.ts.map +1 -0
  222. package/dist/userRepository/utils/prepareBlockedUserPayload.d.ts +2 -0
  223. package/dist/userRepository/utils/prepareBlockedUserPayload.d.ts.map +1 -0
  224. package/dist/userRepository/utils/prepareUserPayload.d.ts +2 -0
  225. package/dist/userRepository/utils/prepareUserPayload.d.ts.map +1 -0
  226. package/dist/utils/linkedObject/commentLinkedObject.d.ts.map +1 -1
  227. package/dist/utils/linkedObject/index.d.ts +2 -1
  228. package/dist/utils/linkedObject/index.d.ts.map +1 -1
  229. package/dist/utils/linkedObject/pinnedPostLinkedObject.d.ts +2 -0
  230. package/dist/utils/linkedObject/pinnedPostLinkedObject.d.ts.map +1 -0
  231. package/dist/utils/tests/dummy/block.d.ts +2 -2
  232. package/dist/utils/tests/dummy/channel.d.ts +12 -12
  233. package/dist/utils/tests/dummy/channel.d.ts.map +1 -1
  234. package/dist/utils/tests/dummy/community.d.ts +2 -2
  235. package/dist/utils/tests/dummy/follow.d.ts +2 -2
  236. package/dist/utils/tests/dummy/user.d.ts +10 -2
  237. package/dist/utils/tests/dummy/user.d.ts.map +1 -1
  238. package/package.json +1 -1
  239. package/src/@types/core/events.ts +40 -13
  240. package/src/@types/core/model.ts +6 -0
  241. package/src/@types/core/payload.ts +39 -9
  242. package/src/@types/core/permissions.ts +4 -4
  243. package/src/@types/domains/channel.ts +13 -0
  244. package/src/@types/domains/comment.ts +6 -4
  245. package/src/@types/domains/community.ts +40 -12
  246. package/src/@types/domains/follow.ts +26 -12
  247. package/src/@types/domains/group.ts +14 -6
  248. package/src/@types/domains/pin.ts +27 -0
  249. package/src/@types/domains/pinnedPost.ts +35 -0
  250. package/src/@types/domains/poll.ts +5 -1
  251. package/src/@types/domains/post.ts +9 -5
  252. package/src/@types/domains/stream.ts +3 -1
  253. package/src/@types/domains/user.ts +49 -6
  254. package/src/channelRepository/channelMembership/observers/getMembers/ChannelMemberLiveCollectionController.ts +6 -0
  255. package/src/channelRepository/channelMembership/observers/getMembers/ChannelMemberPaginationController.ts +4 -1
  256. package/src/channelRepository/channelMembership/observers/searchMembers/SearchChannelMemberLiveCollectionController.ts +148 -0
  257. package/src/channelRepository/channelMembership/observers/searchMembers/SearchChannelMemberPaginationController.ts +31 -0
  258. package/src/channelRepository/channelMembership/observers/searchMembers/SearchChannelMemberQueryStreamController.ts +112 -0
  259. package/src/channelRepository/channelMembership/observers/searchMembers/index.ts +1 -0
  260. package/src/channelRepository/channelMembership/observers/searchMembers/searchMembers.ts +111 -0
  261. package/src/channelRepository/events/onUserDeleted.ts +46 -0
  262. package/src/channelRepository/utils/prepareChannelPayload.ts +8 -4
  263. package/src/client/api/index.ts +0 -3
  264. package/src/commentRepository/api/createComment.ts +16 -12
  265. package/src/commentRepository/api/deleteComment.ts +23 -13
  266. package/src/commentRepository/events/onCommentCreatedLocal.ts +22 -0
  267. package/src/commentRepository/events/onCommentDeletedLocal.ts +20 -0
  268. package/src/commentRepository/events/onLocalCommentReactionAdded.ts +42 -0
  269. package/src/commentRepository/events/onLocalCommentReactionRemoved.ts +42 -0
  270. package/src/commentRepository/events/utils.ts +77 -0
  271. package/src/commentRepository/observers/getComment.ts +6 -19
  272. package/src/commentRepository/observers/getComments/CommentLiveCollectionController.ts +8 -0
  273. package/src/communityRepository/communityMembership/api/addMembers.ts +1 -1
  274. package/src/communityRepository/communityMembership/api/removeMembers.ts +1 -1
  275. package/src/communityRepository/communityMembership/events/index.ts +2 -0
  276. package/src/communityRepository/communityMembership/events/onLocalCommunityUserAdded.ts +20 -0
  277. package/src/communityRepository/communityMembership/events/onLocalCommunityUserRemoved.ts +20 -0
  278. package/src/communityRepository/communityMembership/events/onUserDeleted.ts +64 -0
  279. package/src/communityRepository/communityMembership/events/utils.ts +50 -2
  280. package/src/communityRepository/communityMembership/observers/getMembers/CommunityMembersLiveCollectionController.ts +26 -1
  281. package/src/communityRepository/communityMembership/observers/getMembers/CommunityMembersPaginationController.ts +4 -1
  282. package/src/communityRepository/communityMembership/observers/getMembers/enums.ts +3 -0
  283. package/src/communityRepository/communityMembership/observers/searchMembers/SearchCommunityMembersLiveCollectionController.ts +14 -0
  284. package/src/communityRepository/communityMembership/observers/searchMembers/SearchCommunityMembersPaginationController.ts +4 -1
  285. package/src/communityRepository/communityModeration/api/addRoles.ts +5 -2
  286. package/src/communityRepository/communityModeration/api/removeRoles.ts +5 -2
  287. package/src/communityRepository/communityModeration/events/onLocalCommunityRoleAdded.ts +38 -0
  288. package/src/communityRepository/communityModeration/events/onLocalCommunityRoleRemoved.ts +38 -0
  289. package/src/communityRepository/utils/payload.ts +47 -53
  290. package/src/core/model/idResolvers.ts +3 -0
  291. package/src/core/model/index.ts +3 -0
  292. package/src/group/utils/withUser.ts +33 -0
  293. package/src/postRepository/api/deletePost.ts +9 -9
  294. package/src/postRepository/api/updatePost.ts +1 -1
  295. package/src/postRepository/events/onLocalPostDeleted.ts +20 -0
  296. package/src/postRepository/events/onLocalPostReactionAdded.ts +38 -0
  297. package/src/postRepository/events/onLocalPostReactionRemoved.ts +41 -0
  298. package/src/postRepository/events/onPostUpdatedLocal.ts +20 -0
  299. package/src/postRepository/events/utils.ts +41 -6
  300. package/src/postRepository/internalApi/index.ts +1 -16
  301. package/src/postRepository/observers/getPinnedPosts/PinnedPostLiveCollectionController.ts +104 -0
  302. package/src/postRepository/observers/getPinnedPosts/PinnedPostPaginationController.ts +23 -0
  303. package/src/postRepository/observers/getPinnedPosts/PinnedPostQueryStreamController.ts +61 -0
  304. package/src/postRepository/observers/getPinnedPosts.ts +41 -0
  305. package/src/postRepository/observers/getPost.ts +8 -0
  306. package/src/postRepository/observers/getPosts/PostLiveCollectionController.ts +8 -0
  307. package/src/postRepository/observers/index.ts +1 -0
  308. package/src/postRepository/utils/payload.ts +31 -7
  309. package/src/reactionRepository/api/addReaction.ts +27 -2
  310. package/src/reactionRepository/api/removeReaction.ts +27 -2
  311. package/src/report/api/createReport.ts +100 -31
  312. package/src/report/api/deleteReport.ts +100 -31
  313. package/src/report/api/isReportedByMe.ts +72 -11
  314. package/src/userRepository/api/flagUser.ts +5 -2
  315. package/src/userRepository/api/getUser.ts +4 -43
  316. package/src/userRepository/api/getUserByIds.ts +5 -2
  317. package/src/userRepository/api/queryBlockedUsers.ts +6 -6
  318. package/src/userRepository/api/queryUsers.ts +11 -87
  319. package/src/userRepository/api/unflagUser.ts +5 -2
  320. package/src/userRepository/api/updateUser.ts +5 -11
  321. package/src/userRepository/events/utils.ts +4 -1
  322. package/src/userRepository/internalApi/getUser.ts +12 -16
  323. package/src/userRepository/internalApi/queryUsers.ts +7 -4
  324. package/src/userRepository/observers/enums.ts +7 -0
  325. package/src/userRepository/observers/getBlockedUsers/BlockedUserLiveCollectionController.ts +106 -0
  326. package/src/userRepository/observers/getBlockedUsers/BlockedUserPaginationController.ts +24 -0
  327. package/src/userRepository/observers/getBlockedUsers/BlockedUserQueryStreamController.ts +76 -0
  328. package/src/userRepository/observers/getBlockedUsers.ts +8 -81
  329. package/src/userRepository/observers/getUsers/UserLiveCollectionController.ts +131 -0
  330. package/src/userRepository/observers/getUsers/UserPaginationController.ts +25 -0
  331. package/src/userRepository/observers/getUsers/UserQueryStreamController.ts +82 -0
  332. package/src/userRepository/observers/getUsers.ts +7 -137
  333. package/src/userRepository/observers/searchUserByDisplayName/SearchUserLiveCollectionController.ts +116 -0
  334. package/src/userRepository/observers/searchUserByDisplayName/SearchUserPaginationController.ts +25 -0
  335. package/src/userRepository/observers/searchUserByDisplayName/SearchUserQueryStreamController.ts +82 -0
  336. package/src/userRepository/observers/searchUserByDisplayName.ts +25 -1
  337. package/src/userRepository/relationship/block/api/blockUser.ts +4 -1
  338. package/src/userRepository/relationship/block/api/unBlockUser.ts +4 -1
  339. package/src/userRepository/relationship/follow/api/acceptFollower.ts +4 -1
  340. package/src/userRepository/relationship/follow/api/acceptMyFollower.ts +4 -1
  341. package/src/userRepository/relationship/follow/api/declineFollower.ts +5 -2
  342. package/src/userRepository/relationship/follow/api/declineMyFollower.ts +5 -2
  343. package/src/userRepository/relationship/follow/api/follow.ts +8 -1
  344. package/src/userRepository/relationship/follow/api/unfollow.ts +4 -1
  345. package/src/userRepository/relationship/follow/api/utils.ts +6 -2
  346. package/src/userRepository/relationship/follow/enums.ts +10 -0
  347. package/src/userRepository/relationship/follow/events/index.ts +6 -0
  348. package/src/userRepository/relationship/follow/events/onFollowInfoUpdated.ts +6 -1
  349. package/src/userRepository/relationship/follow/events/onFollowerUserDeleted.ts +33 -0
  350. package/src/userRepository/relationship/follow/events/onFollowingUserDeleted.ts +33 -0
  351. package/src/userRepository/relationship/follow/events/onLocalFollowRequestAccepted.ts +5 -0
  352. package/src/userRepository/relationship/follow/events/onLocalFollowRequestDeclined.ts +5 -0
  353. package/src/userRepository/relationship/follow/events/onLocalFollowerRequested.ts +5 -0
  354. package/src/userRepository/relationship/follow/events/onLocalUserFollowed.ts +5 -0
  355. package/src/userRepository/relationship/follow/events/onLocalUserUnfollowed.ts +5 -0
  356. package/src/userRepository/relationship/follow/events/utils.ts +25 -14
  357. package/src/userRepository/relationship/follow/observers/getFollowers/FollowerLiveCollectionController.ts +132 -0
  358. package/src/userRepository/relationship/follow/observers/getFollowers/FollowerPaginationController.ts +29 -0
  359. package/src/userRepository/relationship/follow/observers/getFollowers/FollowerQueryStreamController.ts +95 -0
  360. package/src/userRepository/relationship/follow/observers/getFollowers.ts +8 -106
  361. package/src/userRepository/relationship/follow/observers/getFollowings/FollowingLiveCollectionController.ts +136 -0
  362. package/src/userRepository/relationship/follow/observers/getFollowings/FollowingPaginationController.ts +29 -0
  363. package/src/userRepository/relationship/follow/observers/getFollowings/FollowingQueryStreamController.ts +95 -0
  364. package/src/userRepository/relationship/follow/observers/getFollowings.ts +6 -106
  365. package/src/userRepository/relationship/follow/observers/observeFollowers.ts +11 -0
  366. package/src/userRepository/relationship/follow/observers/observeFollowings.ts +11 -0
  367. package/src/userRepository/relationship/follow/utils.ts +36 -0
  368. package/src/userRepository/utils/convertRawUserToInternalUser.ts +6 -0
  369. package/src/userRepository/utils/prepareBlockedUserPayload.ts +19 -0
  370. package/src/userRepository/utils/prepareUserPayload.ts +8 -0
  371. package/src/utils/linkedObject/commentLinkedObject.ts +13 -16
  372. package/src/utils/linkedObject/index.ts +2 -0
  373. package/src/utils/linkedObject/pinnedPostLinkedObject.ts +28 -0
package/dist/index.cjs.js CHANGED
@@ -10,9 +10,8 @@ var HttpAgent = require('agentkeepalive');
10
10
  var io = require('socket.io-client');
11
11
  var AsyncStorage = require('@react-native-async-storage/async-storage');
12
12
  var uuid$1 = require('react-native-uuid');
13
- var reactNative = require('react-native');
14
- var mime = require('mime');
15
13
  var hash = require('object-hash');
14
+ var mime = require('mime');
16
15
  var Hls = require('hls.js');
17
16
 
18
17
  function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
@@ -42,8 +41,8 @@ var HttpAgent__default = /*#__PURE__*/_interopDefaultLegacy(HttpAgent);
42
41
  var io__default = /*#__PURE__*/_interopDefaultLegacy(io);
43
42
  var AsyncStorage__default = /*#__PURE__*/_interopDefaultLegacy(AsyncStorage);
44
43
  var uuid__default = /*#__PURE__*/_interopDefaultLegacy(uuid$1);
45
- var mime__default = /*#__PURE__*/_interopDefaultLegacy(mime);
46
44
  var hash__default = /*#__PURE__*/_interopDefaultLegacy(hash);
45
+ var mime__default = /*#__PURE__*/_interopDefaultLegacy(mime);
47
46
  var Hls__default = /*#__PURE__*/_interopDefaultLegacy(Hls);
48
47
 
49
48
  const FileType = Object.freeze({
@@ -563,6 +562,8 @@ const idResolvers = {
563
562
  storyTarget: ({ targetId }) => targetId,
564
563
  ad: ({ adId }) => adId,
565
564
  advertiser: ({ advertiserId }) => advertiserId,
565
+ pin: ({ referenceId }) => referenceId,
566
+ pinTarget: ({ targetId }) => targetId,
566
567
  };
567
568
  /**
568
569
  * Retrieve the id resolver matching a domain name
@@ -612,6 +613,8 @@ const PAYLOAD2MODEL = {
612
613
  feeds: 'feed',
613
614
  ads: 'ad',
614
615
  advertisers: 'advertiser',
616
+ pinTargets: 'pinTarget',
617
+ pins: 'pin',
615
618
  };
616
619
  /** hidden */
617
620
  const isOutdated = (prevData, nextData) => {
@@ -687,18 +690,6 @@ class ASCConnectionError extends ASCError {
687
690
  : 800210 /* Amity.ClientError.CONNECTION_ERROR */, "error" /* Amity.ErrorLevel.ERROR */);
688
691
  this.event = event;
689
692
  }
690
- }
691
- /**
692
- * Input sanitization related error
693
- * @category Errors
694
- */
695
- class ASCInvalidParameterError extends ASCError {
696
- /**
697
- * @param message A custom error message
698
- */
699
- constructor(message) {
700
- super(message, 800110 /* Amity.ClientError.INVALID_PARAMETERS */, "error" /* Amity.ErrorLevel.ERROR */);
701
- }
702
693
  }
703
694
 
704
695
  let activeClient = null;
@@ -4758,6 +4749,31 @@ function __classPrivateFieldSet(receiver, state, value, kind, f) {
4758
4749
  return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value;
4759
4750
  }
4760
4751
 
4752
+ /**
4753
+ * Attach user object to membership model
4754
+ * - If cache is not enabled, set user to undefined ({..., user: undefined})
4755
+ * - If user object is not found in cache, set user to undefined
4756
+ * ({..., user: undefined})
4757
+ * - If a user is found in the cache, it attaches the user from the cache
4758
+ * ({..., user: { userId, displayName,... }})
4759
+ *
4760
+ * @param member The membership model object
4761
+ * @returns The membership model object that is already mapped to user
4762
+ * @hidden
4763
+ */
4764
+ const convertRawMembershipToMembership = (member) => {
4765
+ return Object.assign(Object.assign({}, member), { get user() {
4766
+ var _a;
4767
+ const client = getActiveClient();
4768
+ if (!client.cache)
4769
+ return undefined;
4770
+ const userCache = (_a = pullFromCache(['user', 'get', member.userId])) === null || _a === void 0 ? void 0 : _a.data;
4771
+ if (!userCache) {
4772
+ return undefined;
4773
+ }
4774
+ return userCache;
4775
+ } });
4776
+ };
4761
4777
  /**
4762
4778
  * Attach user object to membership model
4763
4779
  * - If cache is not enabled, set user to undefined ({..., user: undefined})
@@ -5404,6 +5420,80 @@ const categoryLinkedObject = (category) => {
5404
5420
  } });
5405
5421
  };
5406
5422
 
5423
+ /**
5424
+ * ```js
5425
+ * import { isEqual } from '~/utils/isEqual'
5426
+ * const isEqual = isEqual(post1, post2)
5427
+ * ```
5428
+ *
5429
+ * Compares two Amity.Model
5430
+ *
5431
+ * @param x the Amity.Model to compare
5432
+ * @param y the Amity.Model to compare wit x
5433
+ * @returns a boolean based on equality
5434
+ *
5435
+ * @category utility
5436
+ * @private
5437
+ */
5438
+ function isEqual(x, y) {
5439
+ if (x === null || x === undefined || y === null || y === undefined) {
5440
+ return x === y;
5441
+ }
5442
+ // after this just checking type of one would be enough
5443
+ if (x.constructor !== y.constructor) {
5444
+ return false;
5445
+ }
5446
+ // if they are functions, they should exactly refer to same one (because of closures)
5447
+ if (x instanceof Function) {
5448
+ return x === y;
5449
+ }
5450
+ // if they are regexps, they should exactly refer to same one
5451
+ if (x instanceof RegExp) {
5452
+ return x === y;
5453
+ }
5454
+ if (x === y || x.valueOf() === y.valueOf()) {
5455
+ return true;
5456
+ }
5457
+ if (Array.isArray(x) && x.length !== y.length) {
5458
+ return false;
5459
+ }
5460
+ // check each element of the array for equality
5461
+ if (Array.isArray(x) && Array.isArray(y)) {
5462
+ if (x.length !== y.length)
5463
+ return false;
5464
+ for (let i = 0; i < x.length; i += 1) {
5465
+ if (!isEqual(x[i], y[i]))
5466
+ return false;
5467
+ }
5468
+ // if all elements are equal, the arrays are equal
5469
+ return true;
5470
+ }
5471
+ // if they are dates, they must had equal valueOf
5472
+ if (x instanceof Date) {
5473
+ return false;
5474
+ }
5475
+ // if they are strictly equal, they both need to be object at least
5476
+ if (!(x instanceof Object)) {
5477
+ return false;
5478
+ }
5479
+ if (!(y instanceof Object)) {
5480
+ return false;
5481
+ }
5482
+ // recursive object equality check
5483
+ const p = Object.keys(x);
5484
+ return (Object.keys(y).every(i => {
5485
+ // @ts-ignore
5486
+ return p.indexOf(i) !== -1;
5487
+ }) &&
5488
+ p.every(i => {
5489
+ return isEqual(x[i], y[i]);
5490
+ }));
5491
+ }
5492
+
5493
+ function isNonNullable(value) {
5494
+ return value != null;
5495
+ }
5496
+
5407
5497
  const commentLinkedObject = (comment) => {
5408
5498
  return Object.assign(Object.assign({}, comment), { get target() {
5409
5499
  const commentTypes = {
@@ -5434,7 +5524,7 @@ const commentLinkedObject = (comment) => {
5434
5524
  return undefined;
5435
5525
  },
5436
5526
  get childrenComment() {
5437
- return (comment.children
5527
+ return comment.children
5438
5528
  .map(childCommentId => {
5439
5529
  const commentCache = pullFromCache([
5440
5530
  'comment',
@@ -5445,10 +5535,8 @@ const commentLinkedObject = (comment) => {
5445
5535
  return;
5446
5536
  return commentCache === null || commentCache === void 0 ? void 0 : commentCache.data;
5447
5537
  })
5448
- .filter(item => item)
5449
- // Cannot include this loop in the first loop because
5450
- // TS always alert returned value is possibly undefined
5451
- .map(item => commentLinkedObject(item)));
5538
+ .filter(isNonNullable)
5539
+ .map(item => commentLinkedObject(item));
5452
5540
  } });
5453
5541
  };
5454
5542
 
@@ -5871,6 +5959,31 @@ const adLinkedObject = (ad) => {
5871
5959
  } });
5872
5960
  };
5873
5961
 
5962
+ const pinnedPostLinkedObject = (pinnedPost) => {
5963
+ var _a;
5964
+ const postCached = pullFromCache(['post', 'get', pinnedPost.referenceId]);
5965
+ const pinnedBy = (_a = queryCache(['user', 'get']).find(cache => {
5966
+ var _a;
5967
+ return ((_a = cache.data) === null || _a === void 0 ? void 0 : _a.userInternalId) === pinnedPost.pinnedBy;
5968
+ })) === null || _a === void 0 ? void 0 : _a.data;
5969
+ return Object.assign(Object.assign({}, pinnedPost), { pinnedBy,
5970
+ get post() {
5971
+ if (!(postCached === null || postCached === void 0 ? void 0 : postCached.data))
5972
+ return;
5973
+ return postLinkedObject(postCached.data);
5974
+ },
5975
+ get target() {
5976
+ const pinTarget = pullFromCache([
5977
+ 'pinTarget',
5978
+ 'get',
5979
+ postCached === null || postCached === void 0 ? void 0 : postCached.data.targetId,
5980
+ ]);
5981
+ if (!(pinTarget === null || pinTarget === void 0 ? void 0 : pinTarget.data))
5982
+ return;
5983
+ return pinTarget === null || pinTarget === void 0 ? void 0 : pinTarget.data;
5984
+ } });
5985
+ };
5986
+
5874
5987
  const LinkedObject = {
5875
5988
  ad: adLinkedObject,
5876
5989
  comment: commentLinkedObject,
@@ -5883,6 +5996,7 @@ const LinkedObject = {
5883
5996
  message: messageLinkedObject,
5884
5997
  reactor: reactorLinkedObject,
5885
5998
  channel: channelLinkedObject,
5999
+ pinnedPost: pinnedPostLinkedObject,
5886
6000
  };
5887
6001
 
5888
6002
  const getChannelMessagePreviewWithUser = (channel) => {
@@ -6251,6 +6365,10 @@ const getChannelIsMentioned = (channel, marker) => {
6251
6365
  : (_d = (_c = getCachedMarker(channel.channelPublicId)) === null || _c === void 0 ? void 0 : _c.hasMentioned) !== null && _d !== void 0 ? _d : false;
6252
6366
  };
6253
6367
 
6368
+ function convertRawUserToInternalUser(rawUser) {
6369
+ return Object.assign(Object.assign({}, rawUser), { isGlobalBanned: (rawUser === null || rawUser === void 0 ? void 0 : rawUser.isGlobalBan) || false });
6370
+ }
6371
+
6254
6372
  const MARKER_INCLUDED_CHANNEL_TYPE = ['broadcast', 'conversation', 'community'];
6255
6373
  const isUnreadCountSupport$2 = ({ type }) => MARKER_INCLUDED_CHANNEL_TYPE.includes(type);
6256
6374
  function convertFromRaw$2(channel, options = { isMessagePreviewUpdated: true }) {
@@ -6308,9 +6426,13 @@ const prepareChannelPayload = async (rawPayload, options = { isMessagePreviewUpd
6308
6426
  // attach marker to channel
6309
6427
  const channels = rawPayload.channels.map(payload => convertFromRaw$2(payload, { isMessagePreviewUpdated: options.isMessagePreviewUpdated }));
6310
6428
  // user marker to channel users
6311
- const channelUsers = withUsers(rawPayload.channelUsers);
6429
+ const channelUsers = rawPayload.channelUsers.map(channelUser => {
6430
+ return convertRawMembershipToMembership(channelUser);
6431
+ });
6432
+ const users = rawPayload.users.map(convertRawUserToInternalUser);
6312
6433
  const restRawPayload = __rest(rawPayload, ["messageFeedsInfo", "messagePreviews"]);
6313
- return Object.assign(Object.assign({}, restRawPayload), { channels,
6434
+ return Object.assign(Object.assign({}, restRawPayload), { users,
6435
+ channels,
6314
6436
  channelUsers });
6315
6437
  };
6316
6438
 
@@ -7747,9 +7869,17 @@ const onChannelMemberBanned = (callback) => {
7747
7869
  return createEventSubscriber(client, 'onChannelMemberBanned', 'channel.banned', filter);
7748
7870
  };
7749
7871
 
7872
+ function prepareUserPayload(response) {
7873
+ return {
7874
+ users: response.users.map(convertRawUserToInternalUser),
7875
+ files: response.files,
7876
+ };
7877
+ }
7878
+
7750
7879
  const createUserEventSubscriber = (event, callback) => {
7751
7880
  const client = getActiveClient();
7752
- const filter = (payload) => {
7881
+ const filter = (data) => {
7882
+ const payload = prepareUserPayload(data);
7753
7883
  if (client.cache) {
7754
7884
  ingestInCache(payload);
7755
7885
  }
@@ -7773,7 +7903,7 @@ const createUserEventSubscriber = (event, callback) => {
7773
7903
  *
7774
7904
  * @category User Events
7775
7905
  */
7776
- const onUserDeleted = (callback) => createUserEventSubscriber('user.deleted', callback);
7906
+ const onUserDeleted$2 = (callback) => createUserEventSubscriber('user.deleted', callback);
7777
7907
 
7778
7908
  var analyticsEngineOnLoginHandler = () => {
7779
7909
  const analyticsEngine = AnalyticsEngine$1.getInstance();
@@ -9050,7 +9180,7 @@ const login = async (params, sessionHandler, config) => {
9050
9180
  terminateClient();
9051
9181
  subscriptions.forEach(fn => fn());
9052
9182
  unsubWatcher();
9053
- }), onUserDeleted((user) => {
9183
+ }), onUserDeleted$2((user) => {
9054
9184
  if (user.userId === client.userId) {
9055
9185
  terminateClient("userDeleted" /* Amity.TokenTerminationReason.USER_DELETED */);
9056
9186
  subscriptions.forEach(fn => fn());
@@ -9332,43 +9462,6 @@ const isConnected = () => {
9332
9462
  client.ws.connected);
9333
9463
  };
9334
9464
 
9335
- const registerPushNotification = async (deviceToken) => {
9336
- const client = getActiveClient();
9337
- let platform;
9338
- if (reactNative.Platform.OS === 'ios' || reactNative.Platform.OS === 'android') {
9339
- platform = reactNative.Platform.OS;
9340
- }
9341
- else {
9342
- throw new ASCInvalidParameterError('Unsupported platform');
9343
- }
9344
- const deviceId = await getDeviceId();
9345
- const { data: { status, error }, } = await client.http.post('/v1/notification', {
9346
- userId: client.userId,
9347
- deviceId,
9348
- platform,
9349
- token: deviceToken,
9350
- }, { headers: { 'X-API-Key': client.apiKey } });
9351
- if (error) {
9352
- throw new ASCApiError(error, 500000 /* Amity.ServerError.BUSINESS_ERROR */, "error" /* Amity.ErrorLevel.ERROR */);
9353
- }
9354
- return status === 'success';
9355
- };
9356
-
9357
- const unregisterPushNotification = async () => {
9358
- const client = getActiveClient();
9359
- const deviceId = getDeviceId();
9360
- const { data: { status, error }, } = await client.http.delete('/v1/notification', {
9361
- data: {
9362
- deviceId,
9363
- },
9364
- headers: { 'X-API-Key': client.apiKey },
9365
- });
9366
- if (error) {
9367
- throw new ASCApiError(error, 500000 /* Amity.ServerError.BUSINESS_ERROR */, "error" /* Amity.ErrorLevel.ERROR */);
9368
- }
9369
- return status === 'success';
9370
- };
9371
-
9372
9465
  var _GlobalFileAccessType_fileAccessType;
9373
9466
  class GlobalFileAccessType {
9374
9467
  constructor() {
@@ -9639,76 +9732,6 @@ const removeFunctionProperties = (obj) => {
9639
9732
  return Object.fromEntries(entries);
9640
9733
  };
9641
9734
 
9642
- /**
9643
- * ```js
9644
- * import { isEqual } from '~/utils/isEqual'
9645
- * const isEqual = isEqual(post1, post2)
9646
- * ```
9647
- *
9648
- * Compares two Amity.Model
9649
- *
9650
- * @param x the Amity.Model to compare
9651
- * @param y the Amity.Model to compare wit x
9652
- * @returns a boolean based on equality
9653
- *
9654
- * @category utility
9655
- * @private
9656
- */
9657
- function isEqual(x, y) {
9658
- if (x === null || x === undefined || y === null || y === undefined) {
9659
- return x === y;
9660
- }
9661
- // after this just checking type of one would be enough
9662
- if (x.constructor !== y.constructor) {
9663
- return false;
9664
- }
9665
- // if they are functions, they should exactly refer to same one (because of closures)
9666
- if (x instanceof Function) {
9667
- return x === y;
9668
- }
9669
- // if they are regexps, they should exactly refer to same one
9670
- if (x instanceof RegExp) {
9671
- return x === y;
9672
- }
9673
- if (x === y || x.valueOf() === y.valueOf()) {
9674
- return true;
9675
- }
9676
- if (Array.isArray(x) && x.length !== y.length) {
9677
- return false;
9678
- }
9679
- // check each element of the array for equality
9680
- if (Array.isArray(x) && Array.isArray(y)) {
9681
- if (x.length !== y.length)
9682
- return false;
9683
- for (let i = 0; i < x.length; i += 1) {
9684
- if (!isEqual(x[i], y[i]))
9685
- return false;
9686
- }
9687
- // if all elements are equal, the arrays are equal
9688
- return true;
9689
- }
9690
- // if they are dates, they must had equal valueOf
9691
- if (x instanceof Date) {
9692
- return false;
9693
- }
9694
- // if they are strictly equal, they both need to be object at least
9695
- if (!(x instanceof Object)) {
9696
- return false;
9697
- }
9698
- if (!(y instanceof Object)) {
9699
- return false;
9700
- }
9701
- // recursive object equality check
9702
- const p = Object.keys(x);
9703
- return (Object.keys(y).every(i => {
9704
- // @ts-ignore
9705
- return p.indexOf(i) !== -1;
9706
- }) &&
9707
- p.every(i => {
9708
- return isEqual(x[i], y[i]);
9709
- }));
9710
- }
9711
-
9712
9735
  /**
9713
9736
  * @deprecated This function is deprecated
9714
9737
  */
@@ -9926,8 +9949,6 @@ var index$l = /*#__PURE__*/Object.freeze({
9926
9949
  renewal: renewal,
9927
9950
  markerSync: markerSync,
9928
9951
  enableUnreadCount: enableUnreadCount,
9929
- registerPushNotification: registerPushNotification,
9930
- unregisterPushNotification: unregisterPushNotification,
9931
9952
  setUploadedFileAccessType: setUploadedFileAccessType,
9932
9953
  onConnectionError: onConnectionError,
9933
9954
  onClientDisconnected: onClientDisconnected,
@@ -9947,6 +9968,19 @@ var index$l = /*#__PURE__*/Object.freeze({
9947
9968
  getMarkerSyncConsistentMode: getMarkerSyncConsistentMode
9948
9969
  });
9949
9970
 
9971
+ function prepareFollowersPayload(response) {
9972
+ const { users, follows } = response, rest = __rest(response, ["users", "follows"]);
9973
+ return Object.assign(Object.assign({}, rest), { follows, users: users.map(convertRawUserToInternalUser) });
9974
+ }
9975
+ function prepareFollowingsPayload(response) {
9976
+ const { users, follows } = response, rest = __rest(response, ["users", "follows"]);
9977
+ return Object.assign(Object.assign({}, rest), { follows, users: users.map(convertRawUserToInternalUser) });
9978
+ }
9979
+ function prepareFollowStatusPayload(response) {
9980
+ const { follows } = response, rest = __rest(response, ["follows"]);
9981
+ return Object.assign(Object.assign({}, rest), { follows });
9982
+ }
9983
+
9950
9984
  /* begin_public_function
9951
9985
  id: user.relationship.block
9952
9986
  */
@@ -9975,7 +10009,8 @@ const blockUser = async (userId) => {
9975
10009
  ingestInCache(followStatus, { cachedAt });
9976
10010
  upsertInCache(['followInfo', 'get', userId], followCounts[0], { cachedAt });
9977
10011
  }
9978
- fireEvent('follow.unfollowed', followStatus);
10012
+ const payload = prepareFollowStatusPayload(followStatus);
10013
+ fireEvent('local.follow.unfollowed', payload);
9979
10014
  return data;
9980
10015
  };
9981
10016
  /* end_public_function */
@@ -10008,89 +10043,366 @@ const unBlockUser = async (userId) => {
10008
10043
  ingestInCache(followStatus, { cachedAt });
10009
10044
  upsertInCache(['followInfo', 'get', userId], followCounts[0], { cachedAt });
10010
10045
  }
10011
- fireEvent('follow.created', followStatus);
10046
+ const payload = prepareFollowStatusPayload(followStatus);
10047
+ fireEvent('local.follow.created', payload);
10012
10048
  return data;
10013
10049
  };
10014
10050
  /* end_public_function */
10015
10051
 
10016
- /**
10017
- * ```js
10018
- * import { UserRepository } from '@amityco/ts-sdk-react-native'
10019
- * const { data: users, prevPage, nextPage, total } = await UserRepository.queryBlockedUsers({ page: Amity.PageRaw, limit: number })
10020
- * ```
10021
- *
10022
- * @param query The query parameters
10023
- * @returns A page of {@link Amity.User} objects
10024
- *
10025
- * @category Block API
10026
- * @async
10027
- */
10028
- const queryBlockedUsers = async (query) => {
10029
- const client = getActiveClient();
10030
- let params = {};
10031
- if (query) {
10032
- const { token, limit } = query;
10033
- params = {
10034
- limit,
10035
- token,
10036
- };
10052
+ class PaginationController {
10053
+ constructor(queryParams) {
10054
+ const { http } = getActiveClient();
10055
+ this.queryParams = queryParams;
10056
+ this.http = http;
10037
10057
  }
10038
- client.log('user/queryBlockedUsers');
10039
- const { data } = await client.http.get('/api/v4/me/user-blocks', {
10040
- params,
10041
- });
10042
- const { paging } = data, blockedUsers = __rest(data, ["paging"]);
10043
- const { users } = blockedUsers;
10044
- const cachedAt = client.cache && Date.now();
10045
- if (client.cache) {
10046
- ingestInCache(blockedUsers, { cachedAt });
10047
- const cacheKey = ['blockedUsers', 'query', params];
10048
- pushToCache(cacheKey, { users: users.map(getResolver('user')), paging });
10058
+ loadFirstPage() {
10059
+ return this.onFetch("first" /* Amity.LiveCollectionPageDirection.FIRST */);
10049
10060
  }
10050
- const { next, previous, total } = paging;
10051
- const nextPage = toPageRaw(next);
10052
- const prevPage = toPageRaw(previous);
10053
- return { data: users, prevPage, nextPage, total, cachedAt };
10054
- };
10055
- /**
10056
- * ```js
10057
- * import { queryBlockedUsers } from '@amityco/ts-sdk-react-native'
10058
- * const { data: users } = queryBlockedUsers.locally({ page: 'page_token' })
10059
- * ```
10060
- *
10061
- * Queries a paginable list of {@link Amity.User} objects from cache
10062
- * Search is performed by displayName such as `.startsWith(search)`
10063
- *
10064
- * @param query The query parameters
10065
- * @returns A page of {@link Amity.User} objects
10066
- *
10067
- * @category Block API
10068
- */
10069
- queryBlockedUsers.locally = (query = {}) => {
10070
- var _a, _b, _c;
10071
- const client = getActiveClient();
10072
- client.log('user/queryBlockedUsers.locally');
10073
- if (!client.cache)
10074
- return;
10075
- let params = {};
10076
- if (query) {
10077
- const { token, limit } = query;
10078
- params = {
10079
- token,
10080
- limit,
10081
- };
10061
+ loadNextPage() {
10062
+ return this.onFetch("next" /* Amity.LiveCollectionPageDirection.NEXT */);
10082
10063
  }
10083
- const cacheKey = ['blockedUsers', 'query', params];
10084
- const { data, cachedAt } = (_a = pullFromCache(cacheKey)) !== null && _a !== void 0 ? _a : {};
10085
- const users = (_b = data === null || data === void 0 ? void 0 : data.users.map(userId => pullFromCache(['user', 'get', userId])).filter(Boolean).map(({ data }) => data)) !== null && _b !== void 0 ? _b : [];
10086
- const nextPage = toPageRaw(data === null || data === void 0 ? void 0 : data.paging.next);
10087
- const prevPage = toPageRaw(data === null || data === void 0 ? void 0 : data.paging.previous);
10088
- return users.length > 0 && users.length === ((_c = data === null || data === void 0 ? void 0 : data.users) === null || _c === void 0 ? void 0 : _c.length)
10089
- ? { data: users, nextPage, prevPage, total: data === null || data === void 0 ? void 0 : data.paging.total, cachedAt }
10090
- : undefined;
10091
- };
10064
+ loadPreviousPage() {
10065
+ return this.onFetch("prev" /* Amity.LiveCollectionPageDirection.PREV */);
10066
+ }
10067
+ async onFetch(direction = "first" /* Amity.LiveCollectionPageDirection.FIRST */) {
10068
+ var _a, _b, _c, _d;
10069
+ if (direction === 'prev' && !this.previousToken)
10070
+ return;
10071
+ if (direction === 'next' && !this.nextToken)
10072
+ return;
10073
+ let token;
10074
+ if (direction === 'prev')
10075
+ token = this.previousToken;
10076
+ if (direction === 'next')
10077
+ token = this.nextToken;
10078
+ const queryResponse = await this.getRequest(this.queryParams, token);
10079
+ if (direction === 'first') {
10080
+ this.nextToken = (_a = queryResponse.paging) === null || _a === void 0 ? void 0 : _a.next;
10081
+ this.previousToken = (_b = queryResponse.paging) === null || _b === void 0 ? void 0 : _b.previous;
10082
+ }
10083
+ if (direction === 'prev')
10084
+ this.previousToken = (_c = queryResponse.paging) === null || _c === void 0 ? void 0 : _c.previous;
10085
+ if (direction === 'next')
10086
+ this.nextToken = (_d = queryResponse.paging) === null || _d === void 0 ? void 0 : _d.next;
10087
+ return queryResponse;
10088
+ }
10089
+ getNextToken() {
10090
+ return this.nextToken;
10091
+ }
10092
+ getPrevToken() {
10093
+ return this.previousToken;
10094
+ }
10095
+ }
10096
+
10097
+ class BlockedUserPaginationController extends PaginationController {
10098
+ async getRequest(queryParams, token) {
10099
+ const { limit = COLLECTION_DEFAULT_PAGINATION_LIMIT } = queryParams, params = __rest(queryParams, ["limit"]);
10100
+ const options = token ? { token } : { limit };
10101
+ const { data: queryResponse } = await this.http.get('/api/v4/me/user-blocks', {
10102
+ params: Object.assign(Object.assign({}, params), { options, isDeleted: false }),
10103
+ });
10104
+ return queryResponse;
10105
+ }
10106
+ }
10107
+
10108
+ class QueryStreamController {
10109
+ constructor(query, cacheKey) {
10110
+ this.query = query;
10111
+ this.cacheKey = cacheKey;
10112
+ }
10113
+ }
10114
+
10115
+ class BlockedUserQueryStreamController extends QueryStreamController {
10116
+ constructor(query, cacheKey, notifyChange, preparePayload) {
10117
+ super(query, cacheKey);
10118
+ this.notifyChange = notifyChange;
10119
+ this.preparePayload = preparePayload;
10120
+ }
10121
+ async saveToMainDB(response) {
10122
+ const processedPayload = await this.preparePayload(response);
10123
+ const client = getActiveClient();
10124
+ const cachedAt = client.cache && Date.now();
10125
+ if (client.cache) {
10126
+ ingestInCache(processedPayload, { cachedAt });
10127
+ }
10128
+ }
10129
+ appendToQueryStream(response, direction, refresh = false) {
10130
+ var _a, _b;
10131
+ if (refresh) {
10132
+ pushToCache(this.cacheKey, {
10133
+ data: response.users.map(getResolver('user')),
10134
+ });
10135
+ }
10136
+ else {
10137
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
10138
+ const users = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
10139
+ pushToCache(this.cacheKey, Object.assign(Object.assign({}, collection), { data: [...new Set([...users, ...response.users.map(getResolver('user'))])] }));
10140
+ }
10141
+ }
10142
+ reactor(action) {
10143
+ return (followStatus) => {
10144
+ var _a;
10145
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
10146
+ pushToCache(this.cacheKey, collection);
10147
+ this.notifyChange({ origin: "event" /* Amity.LiveDataOrigin.EVENT */, loading: false });
10148
+ };
10149
+ }
10150
+ subscribeRTE(createSubscriber) {
10151
+ return createSubscriber.map(subscriber => subscriber.fn(this.reactor(subscriber.action)));
10152
+ }
10153
+ }
10154
+
10155
+ class PaginationNoPageController {
10156
+ constructor(queryParams) {
10157
+ const { http } = getActiveClient();
10158
+ this.queryParams = queryParams;
10159
+ this.http = http;
10160
+ }
10161
+ async onFetch() {
10162
+ const queryResponse = await this.getRequest(this.queryParams);
10163
+ return queryResponse;
10164
+ }
10165
+ }
10166
+
10167
+ class LiveCollectionController {
10168
+ constructor(paginationController, queryStreamId, cacheKey, callback) {
10169
+ this.paginationController = paginationController;
10170
+ this.queryStreamId = queryStreamId;
10171
+ this.cacheKey = cacheKey;
10172
+ this.callback = callback;
10173
+ }
10174
+ async refresh() {
10175
+ try {
10176
+ let result;
10177
+ if (this.paginationController instanceof PaginationNoPageController) {
10178
+ result = await this.paginationController.onFetch();
10179
+ }
10180
+ else {
10181
+ result = await this.paginationController.loadFirstPage();
10182
+ }
10183
+ if (!result)
10184
+ return;
10185
+ await this.persistModel(result);
10186
+ this.persistQueryStream({
10187
+ response: result,
10188
+ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */,
10189
+ refresh: true,
10190
+ });
10191
+ this.notifyChange({ origin: "server" /* Amity.LiveDataOrigin.SERVER */, loading: false });
10192
+ }
10193
+ catch (e) {
10194
+ this.notifyChange({ origin: "server" /* Amity.LiveDataOrigin.SERVER */, loading: false, error: e });
10195
+ }
10196
+ }
10197
+ loadPage({ initial = false, direction = "next" /* Amity.LiveCollectionPageDirection.NEXT */, }) {
10198
+ this.setup();
10199
+ this.notifyChange({ origin: "local" /* Amity.LiveDataOrigin.LOCAL */, loading: true });
10200
+ if (initial) {
10201
+ this.refresh();
10202
+ }
10203
+ else if (direction === "prev" /* Amity.LiveCollectionPageDirection.PREV */) {
10204
+ this.loadPrevPage();
10205
+ }
10206
+ else if (direction === "next" /* Amity.LiveCollectionPageDirection.NEXT */) {
10207
+ this.loadNextPage();
10208
+ }
10209
+ }
10210
+ async loadNextPage() {
10211
+ try {
10212
+ if (this.paginationController instanceof PaginationNoPageController)
10213
+ return;
10214
+ const result = await this.paginationController.loadNextPage();
10215
+ if (!result)
10216
+ return;
10217
+ await this.persistModel(result);
10218
+ this.persistQueryStream({
10219
+ response: result,
10220
+ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */,
10221
+ });
10222
+ this.notifyChange({ origin: "server" /* Amity.LiveDataOrigin.SERVER */, loading: false });
10223
+ }
10224
+ catch (e) {
10225
+ this.notifyChange({ origin: "server" /* Amity.LiveDataOrigin.SERVER */, loading: false, error: e });
10226
+ }
10227
+ }
10228
+ async loadPrevPage() {
10229
+ try {
10230
+ if (this.paginationController instanceof PaginationNoPageController)
10231
+ return;
10232
+ const result = await this.paginationController.loadPreviousPage();
10233
+ if (!result)
10234
+ return;
10235
+ await this.persistModel(result);
10236
+ this.persistQueryStream({
10237
+ response: result,
10238
+ direction: "prev" /* Amity.LiveCollectionPageDirection.PREV */,
10239
+ });
10240
+ this.notifyChange({ origin: "server" /* Amity.LiveDataOrigin.SERVER */, loading: false });
10241
+ }
10242
+ catch (e) {
10243
+ this.notifyChange({ origin: "server" /* Amity.LiveDataOrigin.SERVER */, loading: false, error: e });
10244
+ }
10245
+ }
10246
+ shouldNotify(data) {
10247
+ const newData = data.map(convertGetterPropsToStatic).map(removeFunctionProperties);
10248
+ if (isEqual(this.snapshot, newData))
10249
+ return false;
10250
+ this.snapshot = newData;
10251
+ return true;
10252
+ }
10253
+ getCacheKey() {
10254
+ return this.cacheKey;
10255
+ }
10256
+ }
10257
+
10258
+ function prepareBlockedUserPayload(response) {
10259
+ const { users, follows } = response, rest = __rest(response, ["users", "follows"]);
10260
+ return Object.assign(Object.assign({}, rest), { follows: follows.map(follow => {
10261
+ const followUser = users.find(user => user.userId === follow.from);
10262
+ return Object.assign(Object.assign({}, follow), { user: convertRawUserToInternalUser(followUser) });
10263
+ }), users: users.map(convertRawUserToInternalUser) });
10264
+ }
10265
+
10266
+ /**
10267
+ * ```js
10268
+ * import { onUserUpdated } from '@amityco/ts-sdk-react-native'
10269
+ * const dispose = onUserUpdated(user => {
10270
+ * // ...
10271
+ * })
10272
+ * ```
10273
+ *
10274
+ * Fired when a {@link Amity.InternalUser} has been updated
10275
+ *
10276
+ * @param callback The function to call when the event was fired
10277
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
10278
+ *
10279
+ * @category User Events
10280
+ */
10281
+ const onUserUpdated = (callback) => createUserEventSubscriber('user.updated', callback);
10282
+
10283
+ /**
10284
+ * ```js
10285
+ * import { onUserFlagged } from '@amityco/ts-sdk-react-native'
10286
+ * const dispose = onUserFlagged(user => {
10287
+ * // ...
10288
+ * })
10289
+ * ```
10290
+ *
10291
+ * Fired when a {@link Amity.InternalUser} has been flagged
10292
+ *
10293
+ * @param callback The function to call when the event was fired
10294
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
10295
+ *
10296
+ * @category User Events
10297
+ */
10298
+ const onUserFlagged = (callback) => createUserEventSubscriber('user.flagged', callback);
10299
+
10300
+ /**
10301
+ * ```js
10302
+ * import { onUserUnflagged } from '@amityco/ts-sdk-react-native'
10303
+ * const dispose = onUserUnflagged(user => {
10304
+ * // ...
10305
+ * })
10306
+ * ```
10307
+ *
10308
+ * Fired when a flag has been removed from a {@link Amity.InternalUser}
10309
+ *
10310
+ * @param callback The function to call when the event was fired
10311
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
10312
+ *
10313
+ * @category User Events
10314
+ */
10315
+ const onUserUnflagged = (callback) => createUserEventSubscriber('user.unflagged', callback);
10316
+
10317
+ /**
10318
+ * ```js
10319
+ * import { onUserFlagCleared } from '@amityco/ts-sdk-react-native'
10320
+ * const dispose = onUserFlagCleared(user => {
10321
+ * // ...
10322
+ * })
10323
+ * ```
10324
+ *
10325
+ * Fired when flags have been cleared for a {@link Amity.InternalUser}
10326
+ *
10327
+ * @param callback The function to call when the event was fired
10328
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
10329
+ *
10330
+ * @category User Events
10331
+ */
10332
+ const onUserFlagCleared = (callback) => createUserEventSubscriber('user.flagCleared', callback);
10333
+
10334
+ var EnumUserActions;
10335
+ (function (EnumUserActions) {
10336
+ EnumUserActions["OnUserDeleted"] = "onUserDeleted";
10337
+ EnumUserActions["OnUserUpdated"] = "onUserUpdated";
10338
+ EnumUserActions["OnUserFlagged"] = "onUserFlagged";
10339
+ EnumUserActions["OnUserUnflagged"] = "onUserUnflagged";
10340
+ EnumUserActions["OnUserFlagCleared"] = "onUserFlagCleared";
10341
+ })(EnumUserActions || (EnumUserActions = {}));
10342
+
10343
+ class BlockedUserLiveCollectionController extends LiveCollectionController {
10344
+ constructor(query, callback) {
10345
+ const queryStreamId = hash__default["default"](query);
10346
+ const cacheKey = ['blockedUsers', 'collection', queryStreamId];
10347
+ const paginationController = new BlockedUserPaginationController(query);
10348
+ super(paginationController, queryStreamId, cacheKey, callback);
10349
+ this.query = query;
10350
+ this.queryStreamController = new BlockedUserQueryStreamController(this.query, this.cacheKey, this.notifyChange.bind(this), prepareBlockedUserPayload);
10351
+ this.callback = callback.bind(this);
10352
+ this.loadPage({ initial: true });
10353
+ }
10354
+ setup() {
10355
+ var _a;
10356
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
10357
+ if (!collection) {
10358
+ pushToCache(this.cacheKey, {
10359
+ data: [],
10360
+ params: {},
10361
+ });
10362
+ }
10363
+ }
10364
+ async persistModel(queryPayload) {
10365
+ await this.queryStreamController.saveToMainDB(queryPayload);
10366
+ }
10367
+ persistQueryStream({ response, direction, refresh, }) {
10368
+ this.queryStreamController.appendToQueryStream(response, direction, refresh);
10369
+ }
10370
+ startSubscription() {
10371
+ return this.queryStreamController.subscribeRTE([
10372
+ {
10373
+ fn: onUserDeleted$2,
10374
+ action: EnumUserActions.OnUserDeleted,
10375
+ },
10376
+ ]);
10377
+ }
10378
+ notifyChange({ origin, loading, error }) {
10379
+ var _a, _b;
10380
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
10381
+ if (!collection)
10382
+ return;
10383
+ const data = this.applyFilter((_b = collection.data
10384
+ .map(id => pullFromCache(['user', 'get', id]))
10385
+ .filter(isNonNullable)
10386
+ .map(({ data }) => data)
10387
+ .map(LinkedObject.user)) !== null && _b !== void 0 ? _b : []);
10388
+ if (!this.shouldNotify(data) && origin === 'event')
10389
+ return;
10390
+ this.callback({
10391
+ onNextPage: () => this.loadPage({ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */ }),
10392
+ data,
10393
+ hasNextPage: !!this.paginationController.getNextToken(),
10394
+ loading,
10395
+ error,
10396
+ });
10397
+ }
10398
+ // eslint-disable-next-line class-methods-use-this
10399
+ applyFilter(data) {
10400
+ let users = data;
10401
+ users = users.filter(user => user.isDeleted == null || user.isDeleted === false);
10402
+ return users;
10403
+ }
10404
+ }
10092
10405
 
10093
- /* eslint-disable no-use-before-define */
10094
10406
  /* begin_public_function
10095
10407
  id: user.get_blocked_users
10096
10408
  */
@@ -10116,63 +10428,12 @@ const getBlockedUsers$1 = (params, callback, config) => {
10116
10428
  }
10117
10429
  const timestamp = Date.now();
10118
10430
  log(`getBlockedUsers(tmpid: ${timestamp}) > listen`);
10119
- const { limit: queryLimit } = params;
10120
- const limit = queryLimit !== null && queryLimit !== void 0 ? queryLimit : COLLECTION_DEFAULT_PAGINATION_LIMIT;
10121
- const { policy = COLLECTION_DEFAULT_CACHING_POLICY } = config !== null && config !== void 0 ? config : {};
10122
- const disposers = [];
10123
- const cacheKey = ['blockedUsers', 'collection', {}];
10124
- const responder = (data) => {
10125
- var _a, _b;
10126
- const users = (_a = data.data
10127
- .map(userId => pullFromCache(['user', 'get', userId]))
10128
- .filter(Boolean)
10129
- .map(({ data }) => LinkedObject.user(data))) !== null && _a !== void 0 ? _a : [];
10130
- callback({
10131
- onNextPage: onFetch,
10132
- data: users,
10133
- hasNextPage: !!((_b = data.params) === null || _b === void 0 ? void 0 : _b.page),
10134
- loading: data.loading,
10135
- error: data.error,
10136
- });
10137
- };
10138
- /*
10139
- * const realtimeRouter = () => {
10140
- * @TODO: At the time of creating this api blocked user do not have any
10141
- * observers
10142
- *};
10143
- */
10144
- const onFetch = (initial = false) => {
10145
- var _a, _b;
10146
- const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
10147
- const users = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
10148
- if (!initial && users.length > 0 && !(collection === null || collection === void 0 ? void 0 : collection.params.page))
10149
- return;
10150
- const query = createQuery(queryBlockedUsers, {
10151
- limit,
10152
- token: toToken(!initial ? collection === null || collection === void 0 ? void 0 : collection.params.page : undefined, 'afterbeforeraw'),
10153
- });
10154
- runQuery(query,
10155
- // @ts-ignore
10156
- ({ data: result, loading, error, nextPage: page, total }) => {
10157
- const data = {
10158
- loading,
10159
- error,
10160
- params: { page, total },
10161
- data: users,
10162
- };
10163
- if (result) {
10164
- data.data = [...new Set([...users, ...result.map(getResolver('user'))])];
10165
- }
10166
- pushToCache(cacheKey, data);
10167
- responder(data);
10168
- }, queryOptions(policy, CACHE_SHORTEN_LIFESPAN));
10169
- };
10170
- disposers.push(() => {
10171
- // @TODO -> update once observers added
10172
- });
10173
- onFetch(true);
10431
+ const blockedUserLiveCollection = new BlockedUserLiveCollectionController(params, callback);
10432
+ const disposers = blockedUserLiveCollection.startSubscription();
10433
+ const cacheKey = blockedUserLiveCollection.getCacheKey();
10434
+ disposers.push(() => dropFromCache(cacheKey));
10174
10435
  return () => {
10175
- log(`getCategories(tmpid: ${timestamp}) > dispose`);
10436
+ log(`getBlockedUsers(tmpid: ${timestamp}) > dispose`);
10176
10437
  disposers.forEach(fn => fn());
10177
10438
  dropFromCache(cacheKey);
10178
10439
  };
@@ -10182,7 +10443,7 @@ const getBlockedUsers$1 = (params, callback, config) => {
10182
10443
  /* eslint-disable no-use-before-define */
10183
10444
  const getBlockedUsers = (params, callback, config) => {
10184
10445
  console.log('Deprecation Notice: UserRepository.Relationship.getBlockedUsers will be deprecated on 9th June 2023, please use UserRepository.getBlockedUsers instead.');
10185
- return getBlockedUsers$1(params, callback, config);
10446
+ return getBlockedUsers$1(params, callback);
10186
10447
  };
10187
10448
 
10188
10449
  /* begin_public_function
@@ -10210,7 +10471,13 @@ const follow = async (userId) => {
10210
10471
  if (client.cache) {
10211
10472
  ingestInCache(data, { cachedAt });
10212
10473
  }
10213
- fireEvent(data.follows[0].status === 'accepted' ? 'follow.created' : 'follow.requested', data);
10474
+ const payload = prepareFollowStatusPayload(data);
10475
+ if (data.follows[0].status === 'accepted') {
10476
+ fireEvent('local.follow.created', payload);
10477
+ }
10478
+ else {
10479
+ fireEvent('local.follow.requested', payload);
10480
+ }
10214
10481
  return {
10215
10482
  data: data.follows[0],
10216
10483
  cachedAt,
@@ -10242,7 +10509,8 @@ const unfollow = async (userId) => {
10242
10509
  if (client.cache) {
10243
10510
  ingestInCache(data);
10244
10511
  }
10245
- fireEvent('follow.unfollowed', data);
10512
+ const payload = prepareFollowStatusPayload(data);
10513
+ fireEvent('local.follow.unfollowed', payload);
10246
10514
  return true;
10247
10515
  };
10248
10516
  /* end_public_function */
@@ -10271,7 +10539,8 @@ const acceptFollower = async (userId) => {
10271
10539
  if (client.cache) {
10272
10540
  ingestInCache(data);
10273
10541
  }
10274
- fireEvent('follow.accepted', data);
10542
+ const payload = prepareFollowStatusPayload(data);
10543
+ fireEvent('local.follow.accepted', payload);
10275
10544
  return true;
10276
10545
  };
10277
10546
 
@@ -10299,7 +10568,8 @@ const acceptMyFollower = async (userId) => {
10299
10568
  if (client.cache) {
10300
10569
  ingestInCache(data);
10301
10570
  }
10302
- fireEvent('follow.accepted', data);
10571
+ const payload = prepareFollowStatusPayload(data);
10572
+ fireEvent('local.follow.accepted', payload);
10303
10573
  return true;
10304
10574
  };
10305
10575
  /* end_public_function */
@@ -10328,7 +10598,8 @@ const declineFollower = async (userId) => {
10328
10598
  if (client.cache) {
10329
10599
  ingestInCache(data);
10330
10600
  }
10331
- fireEvent('follow.requestDeclined', data);
10601
+ const payload = prepareFollowStatusPayload(data);
10602
+ fireEvent('local.follow.requestDeclined', payload);
10332
10603
  return true;
10333
10604
  };
10334
10605
 
@@ -10356,29 +10627,35 @@ const declineMyFollower = async (userId) => {
10356
10627
  if (client.cache) {
10357
10628
  ingestInCache(data);
10358
10629
  }
10359
- fireEvent('follow.requestDeclined', data);
10630
+ const payload = prepareFollowStatusPayload(data);
10631
+ fireEvent('local.follow.requestDeclined', payload);
10360
10632
  return true;
10361
10633
  };
10362
- /* end_public_function */
10363
-
10364
- const createFollowEventSubscriber = (event, callback) => {
10634
+ /* end_public_function */
10635
+
10636
+ const createFollowEventSubscriber = (event, callback) => {
10637
+ const client = getActiveClient();
10638
+ const filter = (data) => {
10639
+ const payload = prepareFollowersPayload(data);
10640
+ if (!client.cache) {
10641
+ callback(payload.follows[0]);
10642
+ }
10643
+ else {
10644
+ ingestInCache(payload);
10645
+ callback(payload.follows[0]);
10646
+ }
10647
+ };
10648
+ return createEventSubscriber(client, event, event, filter);
10649
+ };
10650
+ const createLocalFollowEventSubscriber = (event, callback) => {
10365
10651
  const client = getActiveClient();
10366
- const filter = (payload) => {
10367
- var _a, _b;
10652
+ const filter = (data) => {
10653
+ const payload = prepareFollowStatusPayload(data);
10368
10654
  if (!client.cache) {
10369
10655
  callback(payload.follows[0]);
10370
10656
  }
10371
10657
  else {
10372
10658
  ingestInCache(payload);
10373
- const queries = [
10374
- ...((_a = queryCache(['followers', 'query'])) !== null && _a !== void 0 ? _a : []),
10375
- ...((_b = queryCache(['followings', 'query'])) !== null && _b !== void 0 ? _b : []),
10376
- ];
10377
- queries
10378
- .filter(({ key }) =>
10379
- // @ts-ignore
10380
- key[2].userId === payload.follows[0].from || key[2].userId === payload.follows[0].to)
10381
- .forEach(({ key, data }) => upsertInCache(key, data, { cachedAt: -1 }));
10382
10659
  callback(payload.follows[0]);
10383
10660
  }
10384
10661
  };
@@ -10597,12 +10874,27 @@ const onFollowInfoUpdated = (callback) => {
10597
10874
  createFollowEventSubscriber('follow.requestCanceled', handler),
10598
10875
  createFollowEventSubscriber('follow.requestDeclined', handler),
10599
10876
  createFollowEventSubscriber('follow.followerDeleted', handler),
10877
+ createLocalFollowEventSubscriber('local.follow.created', handler),
10878
+ createLocalFollowEventSubscriber('local.follow.requested', handler),
10879
+ createLocalFollowEventSubscriber('local.follow.accepted', handler),
10880
+ createLocalFollowEventSubscriber('local.follow.unfollowed', handler),
10881
+ createLocalFollowEventSubscriber('local.follow.requestDeclined', handler),
10600
10882
  ];
10601
10883
  return () => {
10602
10884
  disposers.forEach(fn => fn());
10603
10885
  };
10604
10886
  };
10605
10887
 
10888
+ const onLocalUserFollowed = (callback) => createLocalFollowEventSubscriber('local.follow.created', callback);
10889
+
10890
+ const onLocalUserUnfollowed = (callback) => createLocalFollowEventSubscriber('local.follow.unfollowed', callback);
10891
+
10892
+ const onLocalFollowerRequested = (callback) => createLocalFollowEventSubscriber('local.follow.requested', callback);
10893
+
10894
+ const onLocalFollowRequestAccepted = (callback) => createLocalFollowEventSubscriber('local.follow.accepted', callback);
10895
+
10896
+ const onLocalFollowRequestDeclined = (callback) => createLocalFollowEventSubscriber('local.follow.requestDeclined', callback);
10897
+
10606
10898
  /**
10607
10899
  * ```js
10608
10900
  * import { observeFollowInfo } from '@amityco/ts-sdk-react-native'
@@ -10675,7 +10967,7 @@ const observeFollowers = (userId, callback) => {
10675
10967
  (_a = callback.onEvent) === null || _a === void 0 ? void 0 : _a.call(callback, action, status);
10676
10968
  (_b = callback[action]) === null || _b === void 0 ? void 0 : _b.call(callback, status);
10677
10969
  };
10678
- 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')));
10970
+ 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')));
10679
10971
  return () => {
10680
10972
  log(`observeFollowers(tmpid: ${timestamp}) > dispose`);
10681
10973
  disposers.forEach(fn => fn());
@@ -10711,92 +11003,190 @@ const observeFollowings = (userId, callback) => {
10711
11003
  (_a = callback.onEvent) === null || _a === void 0 ? void 0 : _a.call(callback, action, status);
10712
11004
  (_b = callback[action]) === null || _b === void 0 ? void 0 : _b.call(callback, status);
10713
11005
  };
10714
- 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')));
11006
+ 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')));
10715
11007
  return () => {
10716
11008
  log(`observeFollowings(tmpid: ${timestamp}) > dispose`);
10717
11009
  disposers.forEach(fn => fn());
10718
11010
  };
10719
11011
  };
10720
11012
 
10721
- const queryFollows = async (key, query) => {
10722
- const client = getActiveClient();
10723
- client.log(`follow/queryF${key.substring(1)}`, query);
10724
- const { userId, page } = query, params = __rest(query, ["userId", "page"]);
10725
- const { data } = await client.http.get(client.userId === userId ? `/api/v4/me/${key}` : `/api/v4/users/${userId}/${key}`, {
10726
- params: Object.assign(Object.assign({}, params), { token: toToken(page, 'afterbeforeraw') }),
10727
- });
10728
- const { paging } = data, payload = __rest(data, ["paging"]);
10729
- const { follows } = payload;
10730
- const cachedAt = client.cache && Date.now();
10731
- if (client.cache) {
10732
- ingestInCache(payload, { cachedAt });
10733
- const cacheKey = [
10734
- 'follow',
10735
- 'query',
10736
- Object.assign(Object.assign({}, params), { userId, options: Object.assign({}, page), type: key }),
10737
- ];
10738
- pushToCache(cacheKey, { follows: follows.map(getResolver('follow')), paging });
11013
+ class FollowerPaginationController extends PaginationController {
11014
+ async getRequest(queryParams, token) {
11015
+ const { limit = COLLECTION_DEFAULT_PAGINATION_LIMIT, userId } = queryParams, params = __rest(queryParams, ["limit", "userId"]);
11016
+ const options = token ? { token } : { limit };
11017
+ const client = getActiveClient();
11018
+ const path = client.userId === userId ? `/api/v4/me/followers` : `/api/v4/users/${userId}/followers`;
11019
+ const { data: queryResponse } = await this.http.get(path, {
11020
+ params: Object.assign(Object.assign({}, params), { options, isDeleted: false }),
11021
+ });
11022
+ return queryResponse;
10739
11023
  }
10740
- const nextPage = toPageRaw(paging.next);
10741
- const prevPage = toPageRaw(paging.previous);
10742
- return { data: follows, cachedAt, prevPage, nextPage };
10743
- };
10744
- queryFollows.locally = (key, query) => {
10745
- var _a, _b;
10746
- const client = getActiveClient();
10747
- client.log(`follow/queryF${key.substring(1)}.locally`, query);
10748
- if (!client.cache)
10749
- return;
10750
- const { page } = query, params = __rest(query, ["page"]);
10751
- const queryKey = [
10752
- 'follow',
10753
- 'query',
10754
- Object.assign(Object.assign({}, params), { options: Object.assign({}, page), type: key }),
10755
- ];
10756
- const { data, cachedAt } = (_a = pullFromCache(queryKey)) !== null && _a !== void 0 ? _a : {};
10757
- if (!(data === null || data === void 0 ? void 0 : data.follows.length)) {
10758
- return;
11024
+ }
11025
+
11026
+ var EnumFollowActions;
11027
+ (function (EnumFollowActions) {
11028
+ EnumFollowActions["OnRequested"] = "onRequested";
11029
+ EnumFollowActions["OnAccepted"] = "onAccepted";
11030
+ EnumFollowActions["OnDeclined"] = "onDeclined";
11031
+ EnumFollowActions["OnCanceled"] = "onCanceled";
11032
+ EnumFollowActions["OnFollowed"] = "onFollowed";
11033
+ EnumFollowActions["OnUnfollowed"] = "onUnfollowed";
11034
+ EnumFollowActions["OnDeleted"] = "onDeleted";
11035
+ EnumFollowActions["OnUserDeleted"] = "onUserDeleted";
11036
+ })(EnumFollowActions || (EnumFollowActions = {}));
11037
+
11038
+ class FollowerQueryStreamController extends QueryStreamController {
11039
+ constructor(query, cacheKey, notifyChange, preparePayload) {
11040
+ super(query, cacheKey);
11041
+ this.notifyChange = notifyChange;
11042
+ this.preparePayload = preparePayload;
10759
11043
  }
10760
- const follows = data.follows
10761
- .map(key => pullFromCache(['follow', 'get', key]))
10762
- .filter(Boolean)
10763
- .map(({ data }) => data);
10764
- const prevPage = toPageRaw(data === null || data === void 0 ? void 0 : data.paging.previous);
10765
- const nextPage = toPageRaw(data === null || data === void 0 ? void 0 : data.paging.next);
10766
- return follows.length === ((_b = data === null || data === void 0 ? void 0 : data.follows) === null || _b === void 0 ? void 0 : _b.length)
10767
- ? { data: follows, cachedAt, prevPage, nextPage }
10768
- : undefined;
11044
+ async saveToMainDB(response) {
11045
+ const processedPayload = await this.preparePayload(response);
11046
+ const client = getActiveClient();
11047
+ const cachedAt = client.cache && Date.now();
11048
+ if (client.cache) {
11049
+ ingestInCache(processedPayload, { cachedAt });
11050
+ }
11051
+ }
11052
+ appendToQueryStream(response, direction, refresh = false) {
11053
+ var _a, _b;
11054
+ if (refresh) {
11055
+ pushToCache(this.cacheKey, {
11056
+ data: response.follows.map(getResolver('follow')),
11057
+ });
11058
+ }
11059
+ else {
11060
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
11061
+ const follows = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
11062
+ pushToCache(this.cacheKey, Object.assign(Object.assign({}, collection), { data: [...new Set([...follows, ...response.follows.map(getResolver('follow'))])] }));
11063
+ }
11064
+ }
11065
+ reactor(action) {
11066
+ return (followStatus) => {
11067
+ var _a;
11068
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
11069
+ if (this.query.userId !== followStatus.to || !collection)
11070
+ return;
11071
+ switch (action) {
11072
+ case EnumFollowActions.OnDeclined:
11073
+ case EnumFollowActions.OnCanceled:
11074
+ case EnumFollowActions.OnUnfollowed:
11075
+ case EnumFollowActions.OnDeleted:
11076
+ collection.data = collection.data.filter(p => p !== getResolver('follow')(followStatus));
11077
+ break;
11078
+ case EnumFollowActions.OnRequested:
11079
+ case EnumFollowActions.OnAccepted:
11080
+ case EnumFollowActions.OnFollowed:
11081
+ collection.data = [...new Set([getResolver('follow')(followStatus), ...collection.data])];
11082
+ break;
11083
+ }
11084
+ pushToCache(this.cacheKey, collection);
11085
+ this.notifyChange({ origin: "event" /* Amity.LiveDataOrigin.EVENT */, loading: false });
11086
+ };
11087
+ }
11088
+ subscribeRTE(createSubscriber) {
11089
+ return createSubscriber.map(subscriber => subscriber.fn(this.reactor(subscriber.action)));
11090
+ }
11091
+ }
11092
+
11093
+ const onFollowerUserDeleted = ({ userId }) => (callback) => {
11094
+ const client = getActiveClient();
11095
+ const filter = (data) => {
11096
+ const userPayload = prepareUserPayload(data);
11097
+ ingestInCache(userPayload);
11098
+ const cacheData = pullFromCache([
11099
+ 'follow',
11100
+ 'get',
11101
+ getResolver('follow')({
11102
+ from: userPayload.users[0].userId,
11103
+ to: userId,
11104
+ }),
11105
+ ]);
11106
+ if (!cacheData)
11107
+ return;
11108
+ callback(cacheData === null || cacheData === void 0 ? void 0 : cacheData.data);
11109
+ };
11110
+ return createEventSubscriber(client, 'user.deleted', 'user.deleted', filter);
10769
11111
  };
10770
11112
 
10771
- /**
10772
- * ```js
10773
- * import { queryFollowers } from '@amityco/ts-sdk-react-native'
10774
- * const { data: followers, prevPage, nextPage } = await queryFollowers({ userId })
10775
- * ```
10776
- *
10777
- * Queries a paginable list of {@link Amity.FollowStatus}
10778
- *
10779
- * @param query The query parameters
10780
- * @returns followers
10781
- *
10782
- * @category Follow API
10783
- * @async
10784
- */
10785
- const queryFollowers = async (query) => queryFollows('followers', query);
10786
- /**
10787
- * ```js
10788
- * import { queryFollowers } from '@amityco/ts-sdk-react-native'
10789
- * const { data: followers, prevPage, nextPage } = queryFollowers.locally({ userId })
10790
- * ```
10791
- *
10792
- * Queries a paginable list of {@link Amity.FollowStatus} objects from cache
10793
- *
10794
- * @param query The query parameters
10795
- * @returns followers
10796
- *
10797
- * @category Post API
10798
- */
10799
- queryFollowers.locally = (query) => queryFollows.locally('followers', query);
11113
+ class FollowerLiveCollectionController extends LiveCollectionController {
11114
+ constructor(query, callback) {
11115
+ const queryStreamId = hash__default["default"](query);
11116
+ const cacheKey = ['follow', 'collection', queryStreamId];
11117
+ const paginationController = new FollowerPaginationController(query);
11118
+ super(paginationController, queryStreamId, cacheKey, callback);
11119
+ this.query = query;
11120
+ this.queryStreamController = new FollowerQueryStreamController(this.query, this.cacheKey, this.notifyChange.bind(this), prepareFollowersPayload);
11121
+ this.callback = callback.bind(this);
11122
+ this.loadPage({ initial: true });
11123
+ }
11124
+ setup() {
11125
+ var _a;
11126
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
11127
+ if (!collection) {
11128
+ pushToCache(this.cacheKey, {
11129
+ data: [],
11130
+ params: {},
11131
+ });
11132
+ }
11133
+ }
11134
+ async persistModel(queryPayload) {
11135
+ await this.queryStreamController.saveToMainDB(queryPayload);
11136
+ }
11137
+ persistQueryStream({ response, direction, refresh, }) {
11138
+ this.queryStreamController.appendToQueryStream(response, direction, refresh);
11139
+ }
11140
+ startSubscription() {
11141
+ return this.queryStreamController.subscribeRTE([
11142
+ { fn: onUserFollowed, action: EnumFollowActions.OnFollowed },
11143
+ { fn: onUserUnfollowed, action: EnumFollowActions.OnUnfollowed },
11144
+ { fn: onFollowRequestAccepted, action: EnumFollowActions.OnAccepted },
11145
+ { fn: onFollowRequestDeclined, action: EnumFollowActions.OnDeclined },
11146
+ { fn: onFollowRequestCanceled, action: EnumFollowActions.OnCanceled },
11147
+ { fn: onFollowerDeleted, action: EnumFollowActions.OnDeleted },
11148
+ { fn: onLocalFollowRequestAccepted, action: EnumFollowActions.OnAccepted },
11149
+ { fn: onLocalFollowRequestDeclined, action: EnumFollowActions.OnDeclined },
11150
+ { fn: onLocalUserFollowed, action: EnumFollowActions.OnFollowed },
11151
+ { fn: onLocalUserUnfollowed, action: EnumFollowActions.OnUnfollowed },
11152
+ {
11153
+ fn: onFollowerUserDeleted({ userId: this.query.userId }),
11154
+ action: EnumFollowActions.OnUserDeleted,
11155
+ },
11156
+ ]);
11157
+ }
11158
+ notifyChange({ origin, loading, error }) {
11159
+ var _a, _b;
11160
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
11161
+ if (!collection)
11162
+ return;
11163
+ const data = this.applyFilter((_b = collection.data
11164
+ .map(id => pullFromCache(['follow', 'get', id]))
11165
+ .filter(isNonNullable)
11166
+ .map(({ data }) => data)) !== null && _b !== void 0 ? _b : []);
11167
+ if (!this.shouldNotify(data) && origin === 'event')
11168
+ return;
11169
+ this.callback({
11170
+ onNextPage: () => this.loadPage({ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */ }),
11171
+ data,
11172
+ hasNextPage: !!this.paginationController.getNextToken(),
11173
+ loading,
11174
+ error,
11175
+ });
11176
+ }
11177
+ applyFilter(data) {
11178
+ let followers = data;
11179
+ if (this.query.status && this.query.status !== "all" /* Amity.FollowStatusTypeEnum.All */) {
11180
+ followers = followers.filter(follower => follower.status === this.query.status);
11181
+ }
11182
+ followers = followers.filter(follower => {
11183
+ var _a;
11184
+ const fromUser = (_a = pullFromCache(['user', 'get', follower.from])) === null || _a === void 0 ? void 0 : _a.data;
11185
+ return (fromUser === null || fromUser === void 0 ? void 0 : fromUser.isDeleted) == null || (fromUser === null || fromUser === void 0 ? void 0 : fromUser.isDeleted) === false;
11186
+ });
11187
+ return followers;
11188
+ }
11189
+ }
10800
11190
 
10801
11191
  /* begin_public_function
10802
11192
  id: user.relationship.query_my_followers, user.relationship.query_followers
@@ -10822,105 +11212,188 @@ queryFollowers.locally = (query) => queryFollows.locally('followers', query);
10822
11212
  const getFollowers = (params, callback, config) => {
10823
11213
  const { log, cache } = getActiveClient();
10824
11214
  if (!cache) {
10825
- console.log('For using Live Collection feature you need to enable Cache!');
11215
+ console.log(ENABLE_CACHE_MESSAGE);
10826
11216
  }
10827
11217
  const timestamp = Date.now();
10828
11218
  log(`getFollowers(tmpid: ${timestamp}) > listen`);
10829
- const { limit: queryLimit } = params, queryParams = __rest(params, ["limit"]);
10830
- const limit = queryLimit !== null && queryLimit !== void 0 ? queryLimit : COLLECTION_DEFAULT_PAGINATION_LIMIT;
10831
- const { policy = COLLECTION_DEFAULT_CACHING_POLICY } = config !== null && config !== void 0 ? config : {};
10832
- const disposers = [];
10833
- const cacheKey = ['follow', 'collection', { userId: params.userId, type: 'follower' }];
10834
- const responder = (data) => {
11219
+ const followerLiveCollection = new FollowerLiveCollectionController(params, callback);
11220
+ const disposers = followerLiveCollection.startSubscription();
11221
+ const cacheKey = followerLiveCollection.getCacheKey();
11222
+ disposers.push(() => dropFromCache(cacheKey));
11223
+ return () => {
11224
+ log(`getFollowers(tmpid: ${timestamp}) > dispose`);
11225
+ disposers.forEach(fn => fn());
11226
+ };
11227
+ };
11228
+ /* end_public_function */
11229
+
11230
+ class FollowingPaginationController extends PaginationController {
11231
+ async getRequest(queryParams, token) {
11232
+ const { limit = COLLECTION_DEFAULT_PAGINATION_LIMIT, userId } = queryParams, params = __rest(queryParams, ["limit", "userId"]);
11233
+ const options = token ? { token } : { limit };
11234
+ const client = getActiveClient();
11235
+ const path = client.userId === userId ? `/api/v4/me/following` : `/api/v4/users/${userId}/following`;
11236
+ const { data: queryResponse } = await this.http.get(path, {
11237
+ params: Object.assign(Object.assign({}, params), { options, isDeleted: false }),
11238
+ });
11239
+ return queryResponse;
11240
+ }
11241
+ }
11242
+
11243
+ class FollowingQueryStreamController extends QueryStreamController {
11244
+ constructor(query, cacheKey, notifyChange, preparePayload) {
11245
+ super(query, cacheKey);
11246
+ this.notifyChange = notifyChange;
11247
+ this.preparePayload = preparePayload;
11248
+ }
11249
+ async saveToMainDB(response) {
11250
+ const processedPayload = await this.preparePayload(response);
11251
+ const client = getActiveClient();
11252
+ const cachedAt = client.cache && Date.now();
11253
+ if (client.cache) {
11254
+ ingestInCache(processedPayload, { cachedAt });
11255
+ }
11256
+ }
11257
+ appendToQueryStream(response, direction, refresh = false) {
11258
+ var _a, _b;
11259
+ if (refresh) {
11260
+ pushToCache(this.cacheKey, {
11261
+ data: response.follows.map(getResolver('follow')),
11262
+ });
11263
+ }
11264
+ else {
11265
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
11266
+ const follows = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
11267
+ pushToCache(this.cacheKey, Object.assign(Object.assign({}, collection), { data: [...new Set([...follows, ...response.follows.map(getResolver('follow'))])] }));
11268
+ }
11269
+ }
11270
+ reactor(action) {
11271
+ return (followStatus) => {
11272
+ var _a;
11273
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
11274
+ if (this.query.userId !== followStatus.from || !collection)
11275
+ return;
11276
+ switch (action) {
11277
+ case EnumFollowActions.OnDeclined:
11278
+ case EnumFollowActions.OnCanceled:
11279
+ case EnumFollowActions.OnUnfollowed:
11280
+ case EnumFollowActions.OnDeleted:
11281
+ collection.data = collection.data.filter(p => p !== getResolver('follow')(followStatus));
11282
+ break;
11283
+ case EnumFollowActions.OnRequested:
11284
+ case EnumFollowActions.OnAccepted:
11285
+ case EnumFollowActions.OnFollowed:
11286
+ collection.data = [...new Set([getResolver('follow')(followStatus), ...collection.data])];
11287
+ break;
11288
+ }
11289
+ pushToCache(this.cacheKey, collection);
11290
+ this.notifyChange({ origin: "event" /* Amity.LiveDataOrigin.EVENT */, loading: false });
11291
+ };
11292
+ }
11293
+ subscribeRTE(createSubscriber) {
11294
+ return createSubscriber.map(subscriber => subscriber.fn(this.reactor(subscriber.action)));
11295
+ }
11296
+ }
11297
+
11298
+ const onFollowingUserDeleted = ({ userId }) => (callback) => {
11299
+ const client = getActiveClient();
11300
+ const filter = (data) => {
11301
+ const userPayload = prepareUserPayload(data);
11302
+ ingestInCache(userPayload);
11303
+ const cacheData = pullFromCache([
11304
+ 'follow',
11305
+ 'get',
11306
+ getResolver('follow')({
11307
+ from: userId,
11308
+ to: userPayload.users[0].userId,
11309
+ }),
11310
+ ]);
11311
+ if (!cacheData)
11312
+ return;
11313
+ callback(cacheData === null || cacheData === void 0 ? void 0 : cacheData.data);
11314
+ };
11315
+ return createEventSubscriber(client, 'user.deleted', 'user.deleted', filter);
11316
+ };
11317
+
11318
+ class FollowingLiveCollectionController extends LiveCollectionController {
11319
+ constructor(query, callback) {
11320
+ const queryStreamId = hash__default["default"](query);
11321
+ const cacheKey = ['follow', 'collection', queryStreamId];
11322
+ const paginationController = new FollowingPaginationController(query);
11323
+ super(paginationController, queryStreamId, cacheKey, callback);
11324
+ this.query = query;
11325
+ this.queryStreamController = new FollowingQueryStreamController(this.query, this.cacheKey, this.notifyChange.bind(this), prepareFollowingsPayload);
11326
+ this.callback = callback.bind(this);
11327
+ this.loadPage({ initial: true });
11328
+ }
11329
+ setup() {
11330
+ var _a;
11331
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
11332
+ if (!collection) {
11333
+ pushToCache(this.cacheKey, {
11334
+ data: [],
11335
+ params: {},
11336
+ });
11337
+ }
11338
+ }
11339
+ async persistModel(queryPayload) {
11340
+ await this.queryStreamController.saveToMainDB(queryPayload);
11341
+ }
11342
+ persistQueryStream({ response, direction, refresh, }) {
11343
+ this.queryStreamController.appendToQueryStream(response, direction, refresh);
11344
+ }
11345
+ startSubscription() {
11346
+ return this.queryStreamController.subscribeRTE([
11347
+ { fn: onFollowerRequested, action: EnumFollowActions.OnRequested },
11348
+ { fn: onFollowRequestAccepted, action: EnumFollowActions.OnAccepted },
11349
+ { fn: onFollowRequestDeclined, action: EnumFollowActions.OnDeclined },
11350
+ { fn: onFollowRequestCanceled, action: EnumFollowActions.OnCanceled },
11351
+ { fn: onUserFollowed, action: EnumFollowActions.OnFollowed },
11352
+ { fn: onUserUnfollowed, action: EnumFollowActions.OnUnfollowed },
11353
+ { fn: onFollowerDeleted, action: EnumFollowActions.OnDeleted },
11354
+ { fn: onLocalFollowerRequested, action: EnumFollowActions.OnRequested },
11355
+ { fn: onLocalFollowRequestAccepted, action: EnumFollowActions.OnAccepted },
11356
+ { fn: onLocalFollowRequestDeclined, action: EnumFollowActions.OnDeclined },
11357
+ { fn: onLocalUserFollowed, action: EnumFollowActions.OnFollowed },
11358
+ { fn: onLocalUserUnfollowed, action: EnumFollowActions.OnUnfollowed },
11359
+ {
11360
+ fn: onFollowingUserDeleted({ userId: this.query.userId }),
11361
+ action: EnumFollowActions.OnUserDeleted,
11362
+ },
11363
+ ]);
11364
+ }
11365
+ notifyChange({ origin, loading, error }) {
10835
11366
  var _a, _b;
10836
- let followers = (_a = data.data
10837
- .map(key => pullFromCache(['follow', 'get', key]))
10838
- .filter(Boolean)
10839
- .map(({ data }) => data)) !== null && _a !== void 0 ? _a : [];
10840
- if (params.status && params.status !== 'all') {
10841
- followers = filterByPropEquality(followers, 'status', params.status);
10842
- }
10843
- callback({
10844
- onNextPage: onFetch,
10845
- data: followers,
10846
- hasNextPage: !!((_b = data.params) === null || _b === void 0 ? void 0 : _b.page),
10847
- loading: data.loading,
10848
- error: data.error,
10849
- });
10850
- };
10851
- const realtimeRouter = (action) => (followStatus) => {
10852
- var _a;
10853
- const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
10854
- if (params.userId !== followStatus.to || !collection)
11367
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
11368
+ if (!collection)
10855
11369
  return;
10856
- if (['onDeclined', 'onCanceled', 'onUnfollowed', 'onDeleted'].includes(action)) {
10857
- collection.data = collection.data.filter(p => p !== getResolver('follow')(followStatus));
10858
- }
10859
- else if (['onRequested', 'onAccepted', 'onFollowed'].includes(action)) {
10860
- collection.data = [...new Set([getResolver('follow')(followStatus), ...collection.data])];
10861
- }
10862
- pushToCache(cacheKey, collection);
10863
- responder(collection);
10864
- };
10865
- const onFetch = (initial = false) => {
10866
- var _a, _b, _c, _d;
10867
- const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
10868
- const followers = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
10869
- if (!initial && followers.length > 0 && !((_c = collection === null || collection === void 0 ? void 0 : collection.params) === null || _c === void 0 ? void 0 : _c.page))
11370
+ const data = this.applyFilter((_b = collection.data
11371
+ .map(id => pullFromCache(['follow', 'get', id]))
11372
+ .filter(isNonNullable)
11373
+ .map(({ data }) => data)) !== null && _b !== void 0 ? _b : []);
11374
+ if (!this.shouldNotify(data) && origin === 'event')
10870
11375
  return;
10871
- const query = createQuery(queryFollowers, Object.assign(Object.assign({}, queryParams), { page: (_d = (!initial ? collection === null || collection === void 0 ? void 0 : collection.params.page : undefined)) !== null && _d !== void 0 ? _d : { limit } }));
10872
- runQuery(query, ({ data: result, error, loading, nextPage: page }) => {
10873
- const data = {
10874
- loading,
10875
- error,
10876
- params: { page },
10877
- data: followers,
10878
- };
10879
- if (result) {
10880
- data.data = [...new Set([...followers, ...result.map(getResolver('follow'))])];
10881
- }
10882
- pushToCache(cacheKey, data);
10883
- responder(data);
10884
- }, queryOptions(policy));
10885
- };
10886
- disposers.push(onFollowerRequested(realtimeRouter('onRequested')), onFollowRequestAccepted(realtimeRouter('onAccepted')), onFollowRequestDeclined(realtimeRouter('onDeclined')), onFollowRequestCanceled(realtimeRouter('onCanceled')), onUserFollowed(realtimeRouter('onFollowed')), onUserUnfollowed(realtimeRouter('onUnfollowed')), onFollowerDeleted(realtimeRouter('onDeleted')));
10887
- onFetch(true);
10888
- return () => {
10889
- log(`getFollowers(tmpid: ${timestamp}) > dispose`);
10890
- disposers.forEach(fn => fn());
10891
- };
10892
- };
10893
- /* end_public_function */
10894
-
10895
- /**
10896
- * ```js
10897
- * import { queryFollowings } from '@amityco/ts-sdk-react-native'
10898
- * const { data: followings, prevPage, nextPage } = await queryFollowings({ userId })
10899
- * ```
10900
- *
10901
- * Queries a paginable list of {@link Amity.FollowStatus}
10902
- *
10903
- * @param query The query parameters
10904
- * @returns followings
10905
- *
10906
- * @category Follow API
10907
- * @async
10908
- */
10909
- const queryFollowings = async (query) => queryFollows('following', query);
10910
- /**
10911
- * ```js
10912
- * import { queryFollowings } from '@amityco/ts-sdk-react-native'
10913
- * const { data: followings, prevPage, nextPage } = queryFollowings.locally({ userId })
10914
- * ```
10915
- *
10916
- * Queries a paginable list of {@link Amity.FollowStatus} objects from cache
10917
- *
10918
- * @param query The query parameters
10919
- * @returns followings
10920
- *
10921
- * @category Post API
10922
- */
10923
- queryFollowings.locally = (query) => queryFollows.locally('following', query);
11376
+ this.callback({
11377
+ onNextPage: () => this.loadPage({ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */ }),
11378
+ data,
11379
+ hasNextPage: !!this.paginationController.getNextToken(),
11380
+ loading,
11381
+ error,
11382
+ });
11383
+ }
11384
+ applyFilter(data) {
11385
+ let followings = data;
11386
+ if (this.query.status && this.query.status !== "all" /* Amity.FollowStatusTypeEnum.All */) {
11387
+ followings = followings.filter(following => following.status === this.query.status);
11388
+ }
11389
+ followings = followings.filter(following => {
11390
+ var _a;
11391
+ const toUser = (_a = pullFromCache(['user', 'get', following.to])) === null || _a === void 0 ? void 0 : _a.data;
11392
+ return (toUser === null || toUser === void 0 ? void 0 : toUser.isDeleted) == null || (toUser === null || toUser === void 0 ? void 0 : toUser.isDeleted) === false;
11393
+ });
11394
+ return followings;
11395
+ }
11396
+ }
10924
11397
 
10925
11398
  /* begin_public_function
10926
11399
  id: user.relationship.query_my_followings, user.relationship.query_followings
@@ -10950,65 +11423,10 @@ const getFollowings = (params, callback, config) => {
10950
11423
  }
10951
11424
  const timestamp = Date.now();
10952
11425
  log(`getFollowings(tmpid: ${timestamp}) > listen`);
10953
- const { limit: queryLimit } = params, queryParams = __rest(params, ["limit"]);
10954
- const limit = queryLimit !== null && queryLimit !== void 0 ? queryLimit : COLLECTION_DEFAULT_PAGINATION_LIMIT;
10955
- const { policy = COLLECTION_DEFAULT_CACHING_POLICY } = config !== null && config !== void 0 ? config : {};
10956
- const disposers = [];
10957
- const cacheKey = ['follow', 'collection', { userId: params.userId, type: 'following' }];
10958
- const responder = (data) => {
10959
- var _a, _b;
10960
- let followings = (_a = data.data
10961
- .map(key => pullFromCache(['follow', 'get', key]))
10962
- .filter(Boolean)
10963
- .map(({ data }) => data)) !== null && _a !== void 0 ? _a : [];
10964
- if (params.status && params.status !== 'all') {
10965
- followings = filterByPropEquality(followings, 'status', params.status);
10966
- }
10967
- callback({
10968
- onNextPage: onFetch,
10969
- data: followings,
10970
- hasNextPage: !!((_b = data.params) === null || _b === void 0 ? void 0 : _b.page),
10971
- loading: data.loading,
10972
- error: data.error,
10973
- });
10974
- };
10975
- const realtimeRouter = (action) => (followStatus) => {
10976
- var _a;
10977
- const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
10978
- if (params.userId !== followStatus.from || !collection)
10979
- return;
10980
- if (['onDeclined', 'onCanceled', 'onUnfollowed', 'onDeleted'].includes(action)) {
10981
- collection.data = collection.data.filter(p => p !== getResolver('follow')(followStatus));
10982
- }
10983
- else if (['onRequested', 'onAccepted', 'onFollowed'].includes(action)) {
10984
- collection.data = [...new Set([getResolver('follow')(followStatus), ...collection.data])];
10985
- }
10986
- pushToCache(cacheKey, collection);
10987
- responder(collection);
10988
- };
10989
- const onFetch = (initial = false) => {
10990
- var _a, _b, _c, _d;
10991
- const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
10992
- const followings = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
10993
- if (!initial && followings.length > 0 && !((_c = collection === null || collection === void 0 ? void 0 : collection.params) === null || _c === void 0 ? void 0 : _c.page))
10994
- return;
10995
- const query = createQuery(queryFollowings, Object.assign(Object.assign({}, queryParams), { page: (_d = (!initial ? collection === null || collection === void 0 ? void 0 : collection.params.page : undefined)) !== null && _d !== void 0 ? _d : { limit } }));
10996
- runQuery(query, ({ data: result, error, loading, nextPage: page }) => {
10997
- const data = {
10998
- loading,
10999
- error,
11000
- params: { page },
11001
- data: followings,
11002
- };
11003
- if (result) {
11004
- data.data = [...new Set([...followings, ...result.map(getResolver('follow'))])];
11005
- }
11006
- pushToCache(cacheKey, data);
11007
- responder(data);
11008
- }, queryOptions(policy));
11009
- };
11010
- disposers.push(onFollowerRequested(realtimeRouter('onRequested')), onFollowRequestAccepted(realtimeRouter('onAccepted')), onFollowRequestDeclined(realtimeRouter('onDeclined')), onFollowRequestCanceled(realtimeRouter('onCanceled')), onUserFollowed(realtimeRouter('onFollowed')), onUserUnfollowed(realtimeRouter('onUnfollowed')), onFollowerDeleted(realtimeRouter('onDeleted')));
11011
- onFetch(true);
11426
+ const followingLiveCollection = new FollowingLiveCollectionController(params, callback);
11427
+ const disposers = followingLiveCollection.startSubscription();
11428
+ const cacheKey = followingLiveCollection.getCacheKey();
11429
+ disposers.push(() => dropFromCache(cacheKey));
11012
11430
  return () => {
11013
11431
  log(`getFollowings(tmpid: ${timestamp}) > dispose`);
11014
11432
  disposers.forEach(fn => fn());
@@ -11096,6 +11514,11 @@ var index$k = /*#__PURE__*/Object.freeze({
11096
11514
  onFollowRequestAccepted: onFollowRequestAccepted,
11097
11515
  onFollowRequestDeclined: onFollowRequestDeclined,
11098
11516
  onFollowInfoUpdated: onFollowInfoUpdated,
11517
+ onLocalUserFollowed: onLocalUserFollowed,
11518
+ onLocalUserUnfollowed: onLocalUserUnfollowed,
11519
+ onLocalFollowerRequested: onLocalFollowerRequested,
11520
+ onLocalFollowRequestAccepted: onLocalFollowRequestAccepted,
11521
+ onLocalFollowRequestDeclined: onLocalFollowRequestDeclined,
11099
11522
  observeFollowInfo: observeFollowInfo,
11100
11523
  observeFollowers: observeFollowers,
11101
11524
  observeFollowings: observeFollowings,
@@ -11130,12 +11553,13 @@ const getUserByIds = async (userIds) => {
11130
11553
  const { data } = await client.http.get(`/api/v3/users/list`, {
11131
11554
  params: { userIds: encodedUserIds },
11132
11555
  });
11556
+ const payload = prepareUserPayload(data);
11133
11557
  const cachedAt = client.cache && Date.now();
11134
11558
  if (client.cache)
11135
- ingestInCache(data, { cachedAt });
11559
+ ingestInCache(payload, { cachedAt });
11136
11560
  fireEvent('user.fetched', data);
11137
11561
  return {
11138
- data: data.users.map(user => LinkedObject.user(user)),
11562
+ data: payload.users.map(user => LinkedObject.user(user)),
11139
11563
  cachedAt,
11140
11564
  };
11141
11565
  };
@@ -11193,20 +11617,14 @@ getUserByIds.locally = (userIds) => {
11193
11617
  const updateUser = async (userId, patch) => {
11194
11618
  const client = getActiveClient();
11195
11619
  client.log('user/updateUser', userId, patch);
11196
- // API-FIX: Endpoint is malformed, userId should be a url param.
11197
- /*
11198
- const { data } = await client.http.put<Amity.Response<UserPayload>>(
11199
- `/api/v3/users/${userId}`, patch,
11200
- )
11201
- */
11202
11620
  const { data } = await client.http.put(`/api/v3/users/`, Object.assign(Object.assign({ userId }, patch), { createNewUserWhenNotFound: false }));
11621
+ const payload = prepareUserPayload(data);
11203
11622
  const cachedAt = client.cache && Date.now();
11204
11623
  if (client.cache)
11205
- ingestInCache(data, { cachedAt });
11206
- const { users } = data;
11624
+ ingestInCache(payload, { cachedAt });
11207
11625
  fireEvent('user.updated', data);
11208
11626
  return {
11209
- data: users.find(user => user.userId === userId),
11627
+ data: payload.users.find(user => user.userId === userId),
11210
11628
  cachedAt,
11211
11629
  };
11212
11630
  };
@@ -11230,11 +11648,12 @@ const updateUser = async (userId, patch) => {
11230
11648
  const flagUser = async (userId) => {
11231
11649
  const client = getActiveClient();
11232
11650
  client.log('user/flagUser', userId);
11233
- const { data: payload } = await client.http.post(`api/v4/me/flags/${encodeURIComponent(userId)}`);
11651
+ const { data } = await client.http.post(`api/v4/me/flags/${encodeURIComponent(userId)}`);
11652
+ const payload = prepareUserPayload(data);
11234
11653
  if (client.cache) {
11235
11654
  ingestInCache(payload);
11236
11655
  }
11237
- fireEvent('user.flagged', payload);
11656
+ fireEvent('user.flagged', data);
11238
11657
  return !!payload;
11239
11658
  };
11240
11659
  /* end_public_function */
@@ -11257,11 +11676,12 @@ const flagUser = async (userId) => {
11257
11676
  const unflagUser = async (userId) => {
11258
11677
  const client = getActiveClient();
11259
11678
  client.log('user/unflag', userId);
11260
- const { data: payload } = await client.http.delete(`/api/v4/me/flags/${encodeURIComponent(userId)}`);
11679
+ const { data } = await client.http.delete(`/api/v4/me/flags/${encodeURIComponent(userId)}`);
11680
+ const payload = prepareUserPayload(data);
11261
11681
  if (client.cache) {
11262
11682
  ingestInCache(payload);
11263
11683
  }
11264
- fireEvent('user.unflagged', payload);
11684
+ fireEvent('user.unflagged', data);
11265
11685
  return !!payload;
11266
11686
  };
11267
11687
  /* end_public_function */
@@ -11289,74 +11709,6 @@ const isUserFlaggedByMe = async (userId) => {
11289
11709
  };
11290
11710
  /* end_public_function */
11291
11711
 
11292
- /**
11293
- * ```js
11294
- * import { onUserUpdated } from '@amityco/ts-sdk-react-native'
11295
- * const dispose = onUserUpdated(user => {
11296
- * // ...
11297
- * })
11298
- * ```
11299
- *
11300
- * Fired when a {@link Amity.InternalUser} has been updated
11301
- *
11302
- * @param callback The function to call when the event was fired
11303
- * @returns an {@link Amity.Unsubscriber} function to stop listening
11304
- *
11305
- * @category User Events
11306
- */
11307
- const onUserUpdated = (callback) => createUserEventSubscriber('user.updated', callback);
11308
-
11309
- /**
11310
- * ```js
11311
- * import { onUserFlagged } from '@amityco/ts-sdk-react-native'
11312
- * const dispose = onUserFlagged(user => {
11313
- * // ...
11314
- * })
11315
- * ```
11316
- *
11317
- * Fired when a {@link Amity.InternalUser} has been flagged
11318
- *
11319
- * @param callback The function to call when the event was fired
11320
- * @returns an {@link Amity.Unsubscriber} function to stop listening
11321
- *
11322
- * @category User Events
11323
- */
11324
- const onUserFlagged = (callback) => createUserEventSubscriber('user.flagged', callback);
11325
-
11326
- /**
11327
- * ```js
11328
- * import { onUserUnflagged } from '@amityco/ts-sdk-react-native'
11329
- * const dispose = onUserUnflagged(user => {
11330
- * // ...
11331
- * })
11332
- * ```
11333
- *
11334
- * Fired when a flag has been removed from a {@link Amity.InternalUser}
11335
- *
11336
- * @param callback The function to call when the event was fired
11337
- * @returns an {@link Amity.Unsubscriber} function to stop listening
11338
- *
11339
- * @category User Events
11340
- */
11341
- const onUserUnflagged = (callback) => createUserEventSubscriber('user.unflagged', callback);
11342
-
11343
- /**
11344
- * ```js
11345
- * import { onUserFlagCleared } from '@amityco/ts-sdk-react-native'
11346
- * const dispose = onUserFlagCleared(user => {
11347
- * // ...
11348
- * })
11349
- * ```
11350
- *
11351
- * Fired when flags have been cleared for a {@link Amity.InternalUser}
11352
- *
11353
- * @param callback The function to call when the event was fired
11354
- * @returns an {@link Amity.Unsubscriber} function to stop listening
11355
- *
11356
- * @category User Events
11357
- */
11358
- const onUserFlagCleared = (callback) => createUserEventSubscriber('user.flagCleared', callback);
11359
-
11360
11712
  /**
11361
11713
  * ```js
11362
11714
  * import { onUserFetched } from '@amityco/ts-sdk-react-native'
@@ -11392,10 +11744,17 @@ const getUser$2 = async (userId) => {
11392
11744
  const client = getActiveClient();
11393
11745
  client.log('user/getUser', userId);
11394
11746
  isInTombstone('user', userId);
11395
- let data;
11396
11747
  try {
11397
- const response = await client.http.get(`/api/v3/users/${encodeURIComponent(userId)}`);
11398
- data = response.data;
11748
+ const { data } = await client.http.get(`/api/v3/users/${encodeURIComponent(userId)}`);
11749
+ const cachedAt = client.cache && Date.now();
11750
+ const payload = prepareUserPayload(data);
11751
+ if (client.cache)
11752
+ ingestInCache(payload, { cachedAt });
11753
+ fireEvent('user.fetched', data);
11754
+ return {
11755
+ data: payload.users.find(user => user.userId === userId),
11756
+ cachedAt,
11757
+ };
11399
11758
  }
11400
11759
  catch (error) {
11401
11760
  if (checkIfShouldGoesToTombstone(error === null || error === void 0 ? void 0 : error.code)) {
@@ -11403,15 +11762,6 @@ const getUser$2 = async (userId) => {
11403
11762
  }
11404
11763
  throw error;
11405
11764
  }
11406
- const cachedAt = client.cache && Date.now();
11407
- if (client.cache)
11408
- ingestInCache(data, { cachedAt });
11409
- const { users } = data;
11410
- fireEvent('user.fetched', data);
11411
- return {
11412
- data: users.find(user => user.userId === userId),
11413
- cachedAt,
11414
- };
11415
11765
  };
11416
11766
  /**
11417
11767
  * ```js
@@ -11469,7 +11819,7 @@ const getUser$1 = (userId, callback) => {
11469
11819
  return liveObject(userId, reactor, 'userId', getUser$2, [
11470
11820
  onUserFetched,
11471
11821
  onUserUpdated,
11472
- onUserDeleted,
11822
+ onUserDeleted$2,
11473
11823
  onUserFlagged,
11474
11824
  onUserUnflagged,
11475
11825
  onUserFlagCleared,
@@ -11477,114 +11827,144 @@ const getUser$1 = (userId, callback) => {
11477
11827
  };
11478
11828
  /* end_public_function */
11479
11829
 
11480
- /**
11481
- * ```js
11482
- * import { queryUsers } from '@amityco/ts-sdk-react-native'
11483
- * const { data: users, prevPage, nextPage } = await queryUsers({ displayName: 'foo' })
11484
- * ```
11485
- *
11486
- * Queries a paginable list of {@link Amity.InternalUser} objects
11487
- * Search is performed by displayName such as `.startsWith(search)`
11488
- *
11489
- * @param query The query parameters
11490
- * @returns A page of {@link Amity.InternalUser} objects
11491
- *
11492
- * @category User API
11493
- * @async
11494
- */
11495
- const queryUsers = async (query = {}) => {
11496
- const client = getActiveClient();
11497
- client.log('user/queryUsers', query);
11498
- const { page, limit = 10, displayName, filter = 'all', sortBy = 'displayName' } = query, params = __rest(query, ["page", "limit", "displayName", "filter", "sortBy"]);
11499
- const { data } = await client.http.get(`/api/v3/users`, {
11500
- params: Object.assign(Object.assign({}, params), { keyword: displayName, filter,
11501
- sortBy, options: page ? { token: page } : { limit } }),
11502
- });
11503
- // unpacking
11504
- const { paging } = data, payload = __rest(data, ["paging"]);
11505
- const { users } = payload;
11506
- const cachedAt = client.cache && Date.now();
11507
- if (client.cache) {
11508
- ingestInCache(payload, { cachedAt });
11509
- /*
11510
- * using a query as a cache key over params because if the keyword, filter, sort
11511
- * change the API will NOT cache results, when it should
11512
- */
11513
- const cacheKey = [
11514
- 'user',
11515
- 'query',
11516
- Object.assign(Object.assign({}, query), { options: { limit, token: page } }),
11517
- ];
11518
- pushToCache(cacheKey, { users: users.map(getResolver('user')), paging });
11830
+ class UserPaginationController extends PaginationController {
11831
+ async getRequest(queryParams, token) {
11832
+ const { limit = COLLECTION_DEFAULT_PAGINATION_LIMIT, displayName } = queryParams, params = __rest(queryParams, ["limit", "displayName"]);
11833
+ const options = token ? { token } : { limit };
11834
+ const { data: queryResponse } = await this.http.get(`/api/v3/users`, {
11835
+ params: Object.assign(Object.assign({}, params), { keyword: displayName, options, isDeleted: false }),
11836
+ });
11837
+ return queryResponse;
11838
+ }
11839
+ }
11840
+
11841
+ class UserQueryStreamController extends QueryStreamController {
11842
+ constructor(query, cacheKey, notifyChange, preparePayload) {
11843
+ super(query, cacheKey);
11844
+ this.notifyChange = notifyChange;
11845
+ this.preparePayload = preparePayload;
11846
+ }
11847
+ async saveToMainDB(response) {
11848
+ const processedPayload = await this.preparePayload(response);
11849
+ const client = getActiveClient();
11850
+ const cachedAt = client.cache && Date.now();
11851
+ if (client.cache) {
11852
+ ingestInCache(processedPayload, { cachedAt });
11853
+ }
11854
+ }
11855
+ appendToQueryStream(response, direction, refresh = false) {
11856
+ var _a, _b;
11857
+ if (refresh) {
11858
+ pushToCache(this.cacheKey, {
11859
+ data: response.users.map(getResolver('user')),
11860
+ });
11861
+ }
11862
+ else {
11863
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
11864
+ const users = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
11865
+ pushToCache(this.cacheKey, Object.assign(Object.assign({}, collection), { data: [...new Set([...users, ...response.users.map(getResolver('user'))])] }));
11866
+ }
11867
+ }
11868
+ reactor(action) {
11869
+ return (user) => {
11870
+ var _a;
11871
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
11872
+ if (!collection)
11873
+ return;
11874
+ /*
11875
+ * Simply update a collection and let responder decide what to do with data
11876
+ */
11877
+ collection.data = [...new Set([user.userId, ...collection.data])];
11878
+ pushToCache(this.cacheKey, collection);
11879
+ this.notifyChange({ origin: "event" /* Amity.LiveDataOrigin.EVENT */, loading: false });
11880
+ };
11881
+ }
11882
+ subscribeRTE(createSubscriber) {
11883
+ return createSubscriber.map(subscriber => subscriber.fn(this.reactor(subscriber.action)));
11884
+ }
11885
+ }
11886
+
11887
+ class UserLiveCollectionController extends LiveCollectionController {
11888
+ constructor(query, callback) {
11889
+ const queryStreamId = hash__default["default"](query);
11890
+ const cacheKey = ['user', 'collection', queryStreamId];
11891
+ const paginationController = new UserPaginationController(query);
11892
+ super(paginationController, queryStreamId, cacheKey, callback);
11893
+ this.query = query;
11894
+ this.queryStreamController = new UserQueryStreamController(this.query, this.cacheKey, this.notifyChange.bind(this), prepareUserPayload);
11895
+ this.callback = callback.bind(this);
11896
+ this.loadPage({ initial: true });
11519
11897
  }
11520
- fireEvent('user.fetched', data);
11521
- return {
11522
- data: users,
11523
- cachedAt,
11524
- paging,
11525
- };
11526
- };
11527
- /**
11528
- * ```js
11529
- * import { queryUsers } from '@amityco/ts-sdk-react-native'
11530
- * const { data: users } = queryUsers.locally({ keyword: 'foo' })
11531
- * ```
11532
- *
11533
- * Queries a paginable list of {@link Amity.InternalUser} objects from cache
11534
- * Search is performed by displayName such as `.startsWith(search)`
11535
- *
11536
- * @param query The query parameters
11537
- * @returns A page of {@link Amity.InternalUser} objects
11538
- *
11539
- * @category User API
11540
- */
11541
- queryUsers.locally = (query = {}) => {
11542
- var _a, _b, _c;
11543
- const client = getActiveClient();
11544
- client.log('user/queryUsers.locally', query);
11545
- if (!client.cache)
11546
- return;
11547
- const { limit = 10, page } = query !== null && query !== void 0 ? query : {};
11548
- const cacheKey = [
11549
- 'user',
11550
- 'query',
11551
- Object.assign(Object.assign({}, query), { options: {
11552
- limit,
11553
- token: page,
11554
- } }),
11555
- ];
11556
- const { data, cachedAt } = (_a = pullFromCache(cacheKey)) !== null && _a !== void 0 ? _a : {};
11557
- const users = (_b = data === null || data === void 0 ? void 0 : data.users.map(userId => pullFromCache(['user', 'get', userId])).filter(Boolean).map(({ data }) => data)) !== null && _b !== void 0 ? _b : [];
11558
- return users.length > 0 && users.length === ((_c = data === null || data === void 0 ? void 0 : data.users) === null || _c === void 0 ? void 0 : _c.length)
11559
- ? {
11560
- data: users,
11561
- cachedAt,
11562
- paging: data === null || data === void 0 ? void 0 : data.paging,
11898
+ setup() {
11899
+ var _a;
11900
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
11901
+ if (!collection) {
11902
+ pushToCache(this.cacheKey, {
11903
+ data: [],
11904
+ params: {},
11905
+ });
11563
11906
  }
11564
- : undefined;
11565
- };
11566
-
11567
- /*
11568
- * Exported for testing
11569
- * @hidden
11570
- */
11571
- const applyFilter$2 = (data, params) => {
11572
- let users = filterByStringComparePartially(data, 'displayName', params.displayName);
11573
- switch (params.sortBy) {
11574
- case 'firstCreated':
11575
- users = users.sort(sortByFirstCreated);
11576
- break;
11577
- case 'lastCreated':
11578
- users = users.sort(sortByLastCreated);
11579
- break;
11580
- default:
11581
- users = users
11582
- // this needs to be aligned with the backend data type
11583
- .map(u => (u.displayName ? u : Object.assign(Object.assign({}, u), { displayName: '' })))
11584
- .sort(sortByDisplayName);
11585
11907
  }
11586
- return users;
11587
- };
11908
+ async persistModel(queryPayload) {
11909
+ await this.queryStreamController.saveToMainDB(queryPayload);
11910
+ }
11911
+ persistQueryStream({ response, direction, refresh, }) {
11912
+ this.queryStreamController.appendToQueryStream(response, direction, refresh);
11913
+ }
11914
+ startSubscription() {
11915
+ return this.queryStreamController.subscribeRTE([
11916
+ { fn: onUserDeleted$2, action: EnumUserActions.OnUserDeleted },
11917
+ { fn: onUserUpdated, action: EnumUserActions.OnUserUpdated },
11918
+ { fn: onUserFlagged, action: EnumUserActions.OnUserFlagged },
11919
+ { fn: onUserUnflagged, action: EnumUserActions.OnUserUnflagged },
11920
+ { fn: onUserFlagCleared, action: EnumUserActions.OnUserFlagCleared },
11921
+ ]);
11922
+ }
11923
+ notifyChange({ origin, loading, error }) {
11924
+ var _a, _b;
11925
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
11926
+ if (!collection)
11927
+ return;
11928
+ const data = this.applyFilter((_b = collection.data
11929
+ .map(id => pullFromCache(['user', 'get', id]))
11930
+ .filter(isNonNullable)
11931
+ .map(({ data }) => data)
11932
+ .map(LinkedObject.user)) !== null && _b !== void 0 ? _b : []);
11933
+ if (!this.shouldNotify(data) && origin === 'event')
11934
+ return;
11935
+ this.callback({
11936
+ onNextPage: () => this.loadPage({ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */ }),
11937
+ data,
11938
+ hasNextPage: !!this.paginationController.getNextToken(),
11939
+ loading,
11940
+ error,
11941
+ });
11942
+ }
11943
+ applyFilter(data) {
11944
+ let users = data;
11945
+ if (!this.query.displayName) {
11946
+ const sortFn = (() => {
11947
+ switch (this.query.sortBy) {
11948
+ case 'firstCreated':
11949
+ return sortByFirstCreated;
11950
+ case 'lastCreated':
11951
+ return sortByLastCreated;
11952
+ case 'displayName':
11953
+ return sortByDisplayName;
11954
+ default:
11955
+ return sortByLastCreated;
11956
+ }
11957
+ })();
11958
+ users = users.sort(sortFn);
11959
+ }
11960
+ if (this.query.filter === 'flagged') {
11961
+ users = users.filter(user => !!user.hashFlag);
11962
+ }
11963
+ users = users.filter(user => user.isDeleted == null || user.isDeleted === false);
11964
+ return users;
11965
+ }
11966
+ }
11967
+
11588
11968
  /* begin_public_function
11589
11969
  id: user.query
11590
11970
  */
@@ -11612,63 +11992,10 @@ const getUsers = (params, callback, config) => {
11612
11992
  }
11613
11993
  const timestamp = Date.now();
11614
11994
  log(`liveUsers(tmpid: ${timestamp}) > listen`);
11615
- const { limit: queryLimit } = params, queryParams = __rest(params, ["limit"]);
11616
- const limit = queryLimit !== null && queryLimit !== void 0 ? queryLimit : COLLECTION_DEFAULT_PAGINATION_LIMIT;
11617
- const { policy = COLLECTION_DEFAULT_CACHING_POLICY } = config !== null && config !== void 0 ? config : {};
11618
- const disposers = [];
11619
- const cacheKey = ['user', 'collection', uuid()];
11620
- const responder = (data, isEventModel = false) => {
11621
- var _a, _b;
11622
- const users = (_a = data.data
11623
- .map(userId => pullFromCache(['user', 'get', userId]))
11624
- .filter(Boolean)
11625
- .map(({ data }) => LinkedObject.user(data))) !== null && _a !== void 0 ? _a : [];
11626
- callback({
11627
- onNextPage: onFetch,
11628
- /*
11629
- * Only apply filter to RTE Model
11630
- */
11631
- data: isEventModel ? applyFilter$2(users, params) : users,
11632
- hasNextPage: !!((_b = data.params) === null || _b === void 0 ? void 0 : _b.page),
11633
- loading: data.loading,
11634
- error: data.error,
11635
- });
11636
- };
11637
- const realtimeRouter = (_) => (user) => {
11638
- var _a;
11639
- const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
11640
- if (!collection)
11641
- return;
11642
- collection.data = [...new Set([user.userId, ...collection.data])];
11643
- pushToCache(cacheKey, collection);
11644
- responder(collection, true);
11645
- };
11646
- const onFetch = (initial = false) => {
11647
- var _a, _b;
11648
- const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
11649
- const users = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
11650
- if (!initial && users.length > 0 && !(collection === null || collection === void 0 ? void 0 : collection.params.page))
11651
- return;
11652
- const pagingCondition = initial ? { limit } : { page: collection === null || collection === void 0 ? void 0 : collection.params.page };
11653
- const query = createQuery(queryUsers, Object.assign(Object.assign({}, queryParams), pagingCondition));
11654
- runQuery(query, ({ data: result, error, loading, paging }) => {
11655
- const data = {
11656
- loading,
11657
- error,
11658
- params: { page: paging === null || paging === void 0 ? void 0 : paging.next },
11659
- data: users,
11660
- };
11661
- if (result) {
11662
- data.data = initial
11663
- ? result.map(getResolver('user'))
11664
- : [...new Set([...users, ...result.map(getResolver('user'))])];
11665
- }
11666
- pushToCache(cacheKey, data);
11667
- responder(data);
11668
- }, queryOptions(policy));
11669
- };
11670
- disposers.push(onUserUpdated(realtimeRouter()), onUserDeleted(realtimeRouter()), onUserFlagged(realtimeRouter()), onUserUnflagged(realtimeRouter()), onUserFlagCleared(realtimeRouter()));
11671
- onFetch(true);
11995
+ const usersLiveCollection = new UserLiveCollectionController(params, callback);
11996
+ const disposers = usersLiveCollection.startSubscription();
11997
+ const cacheKey = usersLiveCollection.getCacheKey();
11998
+ disposers.push(() => dropFromCache(cacheKey));
11672
11999
  return () => {
11673
12000
  log(`liveUsers(tmpid: ${timestamp}) > dispose`);
11674
12001
  disposers.forEach(fn => fn());
@@ -11691,27 +12018,9 @@ const getUsers = (params, callback, config) => {
11691
12018
  * @async
11692
12019
  */
11693
12020
  const getUser = async (userId) => {
11694
- const client = getActiveClient();
11695
- client.log('user/getUser', userId);
11696
- isInTombstone('user', userId);
11697
- let data;
11698
- try {
11699
- const response = await client.http.get(`/api/v3/users/${encodeURIComponent(userId)}`);
11700
- data = response.data;
11701
- }
11702
- catch (error) {
11703
- if (checkIfShouldGoesToTombstone(error === null || error === void 0 ? void 0 : error.code)) {
11704
- pushToTombstone('user', userId);
11705
- }
11706
- throw error;
11707
- }
11708
- const cachedAt = client.cache && Date.now();
11709
- if (client.cache)
11710
- ingestInCache(data, { cachedAt });
11711
- const { users } = data;
11712
- fireEvent('user.fetched', data);
12021
+ const { data, cachedAt } = await getUser$2(userId);
11713
12022
  return {
11714
- data: LinkedObject.user(users.find(user => user.userId === userId)),
12023
+ data: LinkedObject.user(data),
11715
12024
  cachedAt,
11716
12025
  };
11717
12026
  };
@@ -11729,11 +12038,7 @@ const getUser = async (userId) => {
11729
12038
  * @category User API
11730
12039
  */
11731
12040
  getUser.locally = (userId) => {
11732
- const client = getActiveClient();
11733
- client.log('user/getUser.locally', userId);
11734
- if (!client.cache)
11735
- return;
11736
- const cached = pullFromCache(['user', 'get', userId]);
12041
+ const cached = getUser$2.locally(userId);
11737
12042
  if (!cached)
11738
12043
  return;
11739
12044
  return {
@@ -11767,21 +12072,145 @@ const observeUser = (userId, callback) => {
11767
12072
  // filter function
11768
12073
  if (((_a = result.data) === null || _a === void 0 ? void 0 : _a.userId) !== userId)
11769
12074
  return;
11770
- const newResult = Object.assign(Object.assign({}, result), { data: LinkedObject.user(result.data) });
11771
- if (callback instanceof Function)
11772
- return callback(newResult);
11773
- if (action !== 'onFetch')
11774
- (_b = callback.onEvent) === null || _b === void 0 ? void 0 : _b.call(callback, action, newResult);
11775
- (_c = callback[action]) === null || _c === void 0 ? void 0 : _c.call(callback, newResult);
11776
- };
11777
- const disposers = [];
11778
- disposers.push(onUserUpdated(data => router({ data, loading: false, origin: 'event' }, 'onUpdate')), onUserDeleted(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')));
11779
- runQuery(createQuery(getUser, userId), result => result.data && router(result, 'onFetch'));
11780
- return () => {
11781
- log(`observeUser(tmpid: ${timestamp}) > dispose`);
11782
- disposers.forEach(fn => fn());
11783
- };
11784
- };
12075
+ const newResult = Object.assign(Object.assign({}, result), { data: LinkedObject.user(result.data) });
12076
+ if (callback instanceof Function)
12077
+ return callback(newResult);
12078
+ if (action !== 'onFetch')
12079
+ (_b = callback.onEvent) === null || _b === void 0 ? void 0 : _b.call(callback, action, newResult);
12080
+ (_c = callback[action]) === null || _c === void 0 ? void 0 : _c.call(callback, newResult);
12081
+ };
12082
+ const disposers = [];
12083
+ 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')));
12084
+ runQuery(createQuery(getUser, userId), result => result.data && router(result, 'onFetch'));
12085
+ return () => {
12086
+ log(`observeUser(tmpid: ${timestamp}) > dispose`);
12087
+ disposers.forEach(fn => fn());
12088
+ };
12089
+ };
12090
+
12091
+ class SearchUserPaginationController extends PaginationController {
12092
+ async getRequest(queryParams, token) {
12093
+ const { limit = COLLECTION_DEFAULT_PAGINATION_LIMIT, displayName } = queryParams, params = __rest(queryParams, ["limit", "displayName"]);
12094
+ const options = token ? { token } : { limit };
12095
+ const { data: queryResponse } = await this.http.get(`/api/v3/users`, {
12096
+ params: Object.assign(Object.assign({}, params), { keyword: displayName, options, isDeleted: false }),
12097
+ });
12098
+ return queryResponse;
12099
+ }
12100
+ }
12101
+
12102
+ class SearchUserQueryStreamController extends QueryStreamController {
12103
+ constructor(query, cacheKey, notifyChange, preparePayload) {
12104
+ super(query, cacheKey);
12105
+ this.notifyChange = notifyChange;
12106
+ this.preparePayload = preparePayload;
12107
+ }
12108
+ async saveToMainDB(response) {
12109
+ const processedPayload = await this.preparePayload(response);
12110
+ const client = getActiveClient();
12111
+ const cachedAt = client.cache && Date.now();
12112
+ if (client.cache) {
12113
+ ingestInCache(processedPayload, { cachedAt });
12114
+ }
12115
+ }
12116
+ appendToQueryStream(response, direction, refresh = false) {
12117
+ var _a, _b;
12118
+ if (refresh) {
12119
+ pushToCache(this.cacheKey, {
12120
+ data: response.users.map(getResolver('user')),
12121
+ });
12122
+ }
12123
+ else {
12124
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
12125
+ const users = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
12126
+ pushToCache(this.cacheKey, Object.assign(Object.assign({}, collection), { data: [...new Set([...users, ...response.users.map(getResolver('user'))])] }));
12127
+ }
12128
+ }
12129
+ reactor(action) {
12130
+ return (user) => {
12131
+ var _a;
12132
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
12133
+ if (!collection)
12134
+ return;
12135
+ /*
12136
+ * Simply update a collection and let responder decide what to do with data
12137
+ */
12138
+ collection.data = [...new Set([user.userId, ...collection.data])];
12139
+ pushToCache(this.cacheKey, collection);
12140
+ this.notifyChange({ origin: "event" /* Amity.LiveDataOrigin.EVENT */, loading: false });
12141
+ };
12142
+ }
12143
+ subscribeRTE(createSubscriber) {
12144
+ return createSubscriber.map(subscriber => subscriber.fn(this.reactor(subscriber.action)));
12145
+ }
12146
+ }
12147
+
12148
+ class SearchUserLiveCollectionController extends LiveCollectionController {
12149
+ constructor(query, callback) {
12150
+ var _a;
12151
+ const queryStreamId = hash__default["default"](query);
12152
+ const cacheKey = ['user', 'collection', queryStreamId];
12153
+ const paginationController = new SearchUserPaginationController(query);
12154
+ super(paginationController, queryStreamId, cacheKey, callback);
12155
+ this.query = Object.assign(Object.assign({}, query), { filter: (_a = query.filter) !== null && _a !== void 0 ? _a : 'all' });
12156
+ this.queryStreamController = new SearchUserQueryStreamController(this.query, this.cacheKey, this.notifyChange.bind(this), prepareUserPayload);
12157
+ this.callback = callback.bind(this);
12158
+ this.loadPage({ initial: true });
12159
+ }
12160
+ setup() {
12161
+ var _a;
12162
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
12163
+ if (!collection) {
12164
+ pushToCache(this.cacheKey, {
12165
+ data: [],
12166
+ params: {},
12167
+ });
12168
+ }
12169
+ }
12170
+ async persistModel(queryPayload) {
12171
+ await this.queryStreamController.saveToMainDB(queryPayload);
12172
+ }
12173
+ persistQueryStream({ response, direction, refresh, }) {
12174
+ this.queryStreamController.appendToQueryStream(response, direction, refresh);
12175
+ }
12176
+ startSubscription() {
12177
+ return this.queryStreamController.subscribeRTE([
12178
+ { fn: onUserDeleted$2, action: EnumUserActions.OnUserDeleted },
12179
+ { fn: onUserUpdated, action: EnumUserActions.OnUserUpdated },
12180
+ { fn: onUserFlagged, action: EnumUserActions.OnUserFlagged },
12181
+ { fn: onUserUnflagged, action: EnumUserActions.OnUserUnflagged },
12182
+ { fn: onUserFlagCleared, action: EnumUserActions.OnUserFlagCleared },
12183
+ ]);
12184
+ }
12185
+ notifyChange({ origin, loading, error }) {
12186
+ var _a, _b;
12187
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
12188
+ if (!collection)
12189
+ return;
12190
+ const data = this.applyFilter((_b = collection.data
12191
+ .map(id => pullFromCache(['user', 'get', id]))
12192
+ .filter(isNonNullable)
12193
+ .map(({ data }) => data)
12194
+ .map(LinkedObject.user)) !== null && _b !== void 0 ? _b : []);
12195
+ if (!this.shouldNotify(data) && origin === 'event')
12196
+ return;
12197
+ this.callback({
12198
+ onNextPage: () => this.loadPage({ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */ }),
12199
+ data,
12200
+ hasNextPage: !!this.paginationController.getNextToken(),
12201
+ loading,
12202
+ error,
12203
+ });
12204
+ }
12205
+ applyFilter(data) {
12206
+ let users = data;
12207
+ if (this.query.filter === 'flagged') {
12208
+ users = users.filter(user => !!user.hashFlag);
12209
+ }
12210
+ users = users.filter(user => user.isDeleted == null || user.isDeleted === false);
12211
+ return users;
12212
+ }
12213
+ }
11785
12214
 
11786
12215
  /* begin_public_function
11787
12216
  id: user.search
@@ -11804,7 +12233,21 @@ const observeUser = (userId, callback) => {
11804
12233
  * @category Category Live Collection
11805
12234
  */
11806
12235
  const searchUserByDisplayName = (params, callback, config) => {
11807
- return getUsers(Object.assign(Object.assign({}, params), { filter: 'all' }), callback, config);
12236
+ const { log, cache } = getActiveClient();
12237
+ if (!cache) {
12238
+ // eslint-disable-next-line no-console
12239
+ console.log(ENABLE_CACHE_MESSAGE);
12240
+ }
12241
+ const timestamp = Date.now();
12242
+ log(`liveSearchUsers(tmpid: ${timestamp}) > listen`);
12243
+ const searchUsersLiveCollection = new SearchUserLiveCollectionController(params, callback);
12244
+ const disposers = searchUsersLiveCollection.startSubscription();
12245
+ const cacheKey = searchUsersLiveCollection.getCacheKey();
12246
+ disposers.push(() => dropFromCache(cacheKey));
12247
+ return () => {
12248
+ log(`liveSearchUsers(tmpid: ${timestamp}) > dispose`);
12249
+ disposers.forEach(fn => fn());
12250
+ };
11808
12251
  };
11809
12252
  /* end_public_function */
11810
12253
 
@@ -11973,7 +12416,7 @@ var index$j = /*#__PURE__*/Object.freeze({
11973
12416
  unflagUser: unflagUser,
11974
12417
  isUserFlaggedByMe: isUserFlaggedByMe,
11975
12418
  onUserUpdated: onUserUpdated,
11976
- onUserDeleted: onUserDeleted,
12419
+ onUserDeleted: onUserDeleted$2,
11977
12420
  onUserFlagged: onUserFlagged,
11978
12421
  onUserUnflagged: onUserUnflagged,
11979
12422
  onUserFlagCleared: onUserFlagCleared,
@@ -12895,6 +13338,7 @@ const prepareCommentFromFlaggedEvent = (payload) => {
12895
13338
  * @async
12896
13339
  * */
12897
13340
  const addReaction = async (referenceType, referenceId, reactionName) => {
13341
+ var _a, _b;
12898
13342
  const client = getActiveClient();
12899
13343
  client.log('reaction/createReaction', {
12900
13344
  referenceId,
@@ -12913,8 +13357,21 @@ const addReaction = async (referenceType, referenceId, reactionName) => {
12913
13357
  'get',
12914
13358
  referenceId,
12915
13359
  ]);
12916
- (model === null || model === void 0 ? void 0 : model.data) &&
12917
- pushToCache([referenceType, 'get', referenceId], model.data, { cachedAt: Date.now() });
13360
+ if (!model)
13361
+ return true;
13362
+ const updatedModel = Object.assign(Object.assign({}, model.data), { reactionsCount: model.data.reactionsCount + 1, myReactions: [...((_a = model.data.myReactions) !== null && _a !== void 0 ? _a : []), reactionName], reactions: Object.assign(Object.assign({}, model.data.reactions), { [reactionName]: ((_b = model.data.reactions[reactionName]) !== null && _b !== void 0 ? _b : 0) + 1 }) });
13363
+ if (referenceType === 'comment') {
13364
+ fireEvent('local.comment.addReaction', {
13365
+ comment: updatedModel,
13366
+ });
13367
+ return true;
13368
+ }
13369
+ if (referenceType === 'post') {
13370
+ fireEvent('local.post.addReaction', {
13371
+ post: updatedModel,
13372
+ });
13373
+ return true;
13374
+ }
12918
13375
  }
12919
13376
  return true;
12920
13377
  };
@@ -12979,6 +13436,7 @@ addReaction.optimistically = (referenceType, referenceId, reactionName) => {
12979
13436
  * @async
12980
13437
  * */
12981
13438
  const removeReaction = async (referenceType, referenceId, reactionName) => {
13439
+ var _a, _b;
12982
13440
  const client = getActiveClient();
12983
13441
  client.log('reaction/removeReaction', {
12984
13442
  referenceId,
@@ -12999,8 +13457,21 @@ const removeReaction = async (referenceType, referenceId, reactionName) => {
12999
13457
  'get',
13000
13458
  referenceId,
13001
13459
  ]);
13002
- (model === null || model === void 0 ? void 0 : model.data) &&
13003
- pushToCache([referenceType, 'get', referenceId], model.data, { cachedAt: Date.now() });
13460
+ if (!model)
13461
+ return true;
13462
+ const updatedModel = Object.assign(Object.assign({}, model.data), { reactionsCount: Math.max(0, model.data.reactionsCount - 1), myReactions: ((_a = model.data.myReactions) !== null && _a !== void 0 ? _a : []).filter(item => item !== reactionName), reactions: Object.assign(Object.assign({}, model.data.reactions), { [reactionName]: Math.max(0, ((_b = model.data.reactions[reactionName]) !== null && _b !== void 0 ? _b : 0) - 1) }) });
13463
+ if (referenceType === 'comment') {
13464
+ fireEvent('local.comment.removeReaction', {
13465
+ comment: updatedModel,
13466
+ });
13467
+ return true;
13468
+ }
13469
+ if (referenceType === 'post') {
13470
+ fireEvent('local.post.removeReaction', {
13471
+ post: updatedModel,
13472
+ });
13473
+ return true;
13474
+ }
13004
13475
  }
13005
13476
  return true;
13006
13477
  };
@@ -13045,6 +13516,66 @@ removeReaction.optimistically = (referenceType, referenceId, reactionName) => {
13045
13516
  return (_e = !((_d = reaction === null || reaction === void 0 ? void 0 : reaction.myReactions) === null || _d === void 0 ? void 0 : _d.includes(reactionName))) !== null && _e !== void 0 ? _e : false;
13046
13517
  };
13047
13518
 
13519
+ const getMatchPostSetting = (value) => {
13520
+ var _a;
13521
+ return (_a = Object.keys(CommunityPostSettingMaps).find(key => value.needApprovalOnPostCreation ===
13522
+ CommunityPostSettingMaps[key].needApprovalOnPostCreation &&
13523
+ value.onlyAdminCanPost === CommunityPostSettingMaps[key].onlyAdminCanPost)) !== null && _a !== void 0 ? _a : DefaultCommunityPostSetting;
13524
+ };
13525
+ function addPostSetting({ communities }) {
13526
+ return communities.map((_a) => {
13527
+ var { needApprovalOnPostCreation, onlyAdminCanPost } = _a, restCommunityPayload = __rest(_a, ["needApprovalOnPostCreation", "onlyAdminCanPost"]);
13528
+ return (Object.assign({ postSetting: getMatchPostSetting({
13529
+ needApprovalOnPostCreation,
13530
+ onlyAdminCanPost,
13531
+ }) }, restCommunityPayload));
13532
+ });
13533
+ }
13534
+ const prepareCommunityPayload = (rawPayload) => {
13535
+ const communitiesWithPostSetting = addPostSetting({ communities: rawPayload.communities });
13536
+ // map users with community
13537
+ const mappedCommunityUsers = rawPayload.communityUsers.map(communityUser => {
13538
+ const user = rawPayload.users.find(user => user.userId === communityUser.userId);
13539
+ return Object.assign(Object.assign({}, communityUser), { user });
13540
+ });
13541
+ const communityWithMembershipStatus = updateMembershipStatus(communitiesWithPostSetting, mappedCommunityUsers);
13542
+ return Object.assign(Object.assign({}, rawPayload), { communities: communityWithMembershipStatus, communityUsers: mappedCommunityUsers });
13543
+ };
13544
+ const prepareCommunityMembershipPayload = (rawPayload) => {
13545
+ const communitiesWithPostSetting = addPostSetting({ communities: rawPayload.communities });
13546
+ // map users with community
13547
+ const mappedCommunityUsers = rawPayload.communityUsers.map(communityUser => {
13548
+ const user = rawPayload.users.find(user => user.userId === communityUser.userId);
13549
+ return Object.assign(Object.assign({}, communityUser), { user });
13550
+ });
13551
+ const communityWithMembershipStatus = updateMembershipStatus(communitiesWithPostSetting, mappedCommunityUsers);
13552
+ return Object.assign(Object.assign({}, rawPayload), { communities: communityWithMembershipStatus, communityUsers: mappedCommunityUsers });
13553
+ };
13554
+ const prepareCommunityRequest = (params) => {
13555
+ const { postSetting = undefined, storySetting } = params, restParam = __rest(params, ["postSetting", "storySetting"]);
13556
+ return Object.assign(Object.assign(Object.assign({}, restParam), (postSetting ? CommunityPostSettingMaps[postSetting] : undefined)), {
13557
+ // Convert story setting to the actual value. (Allow by default)
13558
+ allowCommentInStory: typeof (storySetting === null || storySetting === void 0 ? void 0 : storySetting.enableComment) === 'boolean' ? storySetting.enableComment : true });
13559
+ };
13560
+
13561
+ const preparePostPayload = (postPayload) => {
13562
+ // Unpack community payload by mapping payload field to postSetting value.
13563
+ const communitiesWithPostSetting = addPostSetting({ communities: postPayload.communities });
13564
+ // map users with community
13565
+ const mappedCommunityUsers = postPayload.communityUsers.map(communityUser => {
13566
+ const user = postPayload.users.find(user => user.userId === communityUser.userId);
13567
+ return Object.assign(Object.assign({}, communityUser), { user });
13568
+ });
13569
+ const communityWithMembershipStatus = updateMembershipStatus(communitiesWithPostSetting, mappedCommunityUsers);
13570
+ // feed type
13571
+ const posts = postPayload.posts.map(post => {
13572
+ var _a;
13573
+ const feedType = (_a = postPayload.feeds.find(feed => feed.feedId === post.feedId)) === null || _a === void 0 ? void 0 : _a.feedType;
13574
+ return Object.assign(Object.assign({}, post), { feedType });
13575
+ });
13576
+ return Object.assign(Object.assign({}, postPayload), { posts, communities: communityWithMembershipStatus, communityUsers: mappedCommunityUsers });
13577
+ };
13578
+
13048
13579
  const createPostEventSubscriber = (event, callback) => {
13049
13580
  const client = getActiveClient();
13050
13581
  const filter = (payload) => {
@@ -13053,8 +13584,8 @@ const createPostEventSubscriber = (event, callback) => {
13053
13584
  callback(payload.posts[0]);
13054
13585
  }
13055
13586
  else {
13056
- const { communities } = payload, others = __rest(payload, ["communities"]);
13057
- const data = prepareMembershipPayload(others, 'communityUsers');
13587
+ const data = preparePostPayload(payload);
13588
+ const { communities } = data;
13058
13589
  ingestInCache(data);
13059
13590
  if ((communities === null || communities === void 0 ? void 0 : communities[0]) && !['post.updated'].includes(event)) {
13060
13591
  fireEvent('community.updated', {
@@ -13081,7 +13612,7 @@ const createPostEventSubscriber = (event, callback) => {
13081
13612
  // But if it is hard delete, it will pushed into tombstone before fire an event to BE. it means it will stay in tombstone already
13082
13613
  // and will got skip to notify in a previous code block
13083
13614
  if (postedUserId !== client.userId) {
13084
- pushToTombstone('post', postId);
13615
+ dropFromCache(['post', 'get', postId]);
13085
13616
  }
13086
13617
  return callback(payload.posts[0]);
13087
13618
  }
@@ -13098,6 +13629,32 @@ const createPostEventSubscriber = (event, callback) => {
13098
13629
  }
13099
13630
  };
13100
13631
  return createEventSubscriber(client, event, event, filter);
13632
+ };
13633
+ const createLocalPostEventSubscriber = (event, callback) => {
13634
+ const client = getActiveClient();
13635
+ const filter = (payload) => {
13636
+ if (!client.cache) {
13637
+ callback(payload.posts[0]);
13638
+ }
13639
+ else {
13640
+ const data = preparePostPayload(payload);
13641
+ const { communities } = data;
13642
+ ingestInCache(data);
13643
+ if ((communities === null || communities === void 0 ? void 0 : communities[0]) && !['local.post.updated'].includes(event)) {
13644
+ fireEvent('community.updated', {
13645
+ communities,
13646
+ categories: [],
13647
+ communityUsers: data.communityUsers,
13648
+ feeds: [],
13649
+ files: [],
13650
+ users: [],
13651
+ });
13652
+ }
13653
+ const post = pullFromCache(['post', 'get', payload.posts[0].postId]);
13654
+ callback(post.data);
13655
+ }
13656
+ };
13657
+ return createEventSubscriber(client, event, event, filter);
13101
13658
  };
13102
13659
 
13103
13660
  /**
@@ -13304,6 +13861,9 @@ const createCommentEventSubscriber = (event, callback) => {
13304
13861
  comments[0].commentId,
13305
13862
  ]);
13306
13863
  if (['comment.created'].includes(event)) {
13864
+ // NOTE: skip adding comment to parent comment children if it's the same user since we use the local event to update instead.
13865
+ if (event === 'comment.created' && comment.data.userId === client.userId)
13866
+ return;
13307
13867
  if (comments[0].parentId) {
13308
13868
  const parentComment = pullFromCache([
13309
13869
  'comment',
@@ -13325,6 +13885,58 @@ const createCommentEventSubscriber = (event, callback) => {
13325
13885
  }
13326
13886
  };
13327
13887
  return createEventSubscriber(client, event, event, filter);
13888
+ };
13889
+ const createLocalCommentEventSubscriber = (event, callback) => {
13890
+ const client = getActiveClient();
13891
+ const filter = (payload) => {
13892
+ var _a;
13893
+ if (!client.cache) {
13894
+ // TODO: here we are missing specific properties here!
13895
+ callback(LinkedObject.comment(payload.comments[0]));
13896
+ }
13897
+ else {
13898
+ const processed = payload;
13899
+ ingestInCache(processed);
13900
+ const { comments } = processed;
13901
+ if (comments.length > 0) {
13902
+ const comment = pullFromCache([
13903
+ 'comment',
13904
+ 'get',
13905
+ comments[0].commentId,
13906
+ ]);
13907
+ if (['local.comment.created'].includes(event)) {
13908
+ if (comments[0].parentId) {
13909
+ const parentComment = pullFromCache([
13910
+ 'comment',
13911
+ 'get',
13912
+ comments[0].parentId,
13913
+ ]);
13914
+ if (parentComment === null || parentComment === void 0 ? void 0 : parentComment.data) {
13915
+ // Skip to update parent childComment if current comment already exists
13916
+ if (!parentComment.data.children.includes(comments[0].commentId)) {
13917
+ const newParentComment = Object.assign(Object.assign({}, parentComment.data), { childrenNumber: parentComment.data.childrenNumber + 1, children: [...new Set([...parentComment.data.children, comments[0].commentId])] });
13918
+ pushToCache(['comment', 'get', comments[0].parentId], newParentComment);
13919
+ setTimeout(() => {
13920
+ // NOTE: This is workaround solution for emitting event not work properly.
13921
+ fireEvent('comment.updated', {
13922
+ comments: [newParentComment],
13923
+ commentChildren: [],
13924
+ files: [],
13925
+ users: [],
13926
+ communityUsers: [],
13927
+ });
13928
+ }, 200);
13929
+ }
13930
+ }
13931
+ }
13932
+ const queries = (_a = queryCache(['comment', 'query'])) === null || _a === void 0 ? void 0 : _a.filter(({ key }) => { var _a; return ((_a = key[2]) === null || _a === void 0 ? void 0 : _a.referenceId) === comment.data.referenceId; });
13933
+ queries === null || queries === void 0 ? void 0 : queries.map(({ key, data }) => upsertInCache(key, data, { cachedAt: -1 }));
13934
+ }
13935
+ callback(LinkedObject.comment(comment.data));
13936
+ }
13937
+ }
13938
+ };
13939
+ return createEventSubscriber(client, event, event, filter);
13328
13940
  };
13329
13941
 
13330
13942
  /**
@@ -13884,29 +14496,53 @@ var index$h = /*#__PURE__*/Object.freeze({
13884
14496
  getReactions: getReactions
13885
14497
  });
13886
14498
 
13887
- var REFERENCE_TYPES = {
13888
- post: {
13889
- domainName: 'posts',
13890
- eventName: 'v3/post.isflagbyme',
13891
- primaryKey: 'postId',
13892
- },
13893
- comment: {
13894
- domainName: 'comments',
13895
- eventName: 'v3/comment.isflagbyme',
13896
- primaryKey: 'commentId',
13897
- },
13898
- message: {
13899
- domainName: 'messages',
13900
- eventName: 'v3/message.isFlaggedByMe',
13901
- primaryKey: 'messageId',
13902
- },
13903
- user: {
13904
- domainName: 'users',
13905
- eventName: 'user.isFlagByMe',
13906
- primaryKey: 'userId',
13907
- },
13908
- };
14499
+ function prepareCommentPayload(commentPayload) {
14500
+ const { comments } = commentPayload;
14501
+ return Object.assign(Object.assign({}, commentPayload), { comments: comments.map(comment => {
14502
+ if (comment.hasOwnProperty('myReactions'))
14503
+ return comment;
14504
+ // Sometimes `myReactions` field will not come with BE response because that field is empty
14505
+ // We need to put it with an empty array manually to make it show up in client side
14506
+ return Object.assign({ myReactions: [] }, comment);
14507
+ }) });
14508
+ }
13909
14509
 
14510
+ const createMessageReport = async ({ client, referenceId, }) => {
14511
+ const { data: payload } = await client.http.post(`/api/v5/messages/${encodeURIComponent(referenceId)}/flags`);
14512
+ if (client.cache) {
14513
+ const messagePayload = await prepareMessagePayload(payload);
14514
+ ingestInCache(messagePayload);
14515
+ }
14516
+ fireEvent(`message.flagged`, payload);
14517
+ return !!payload;
14518
+ };
14519
+ const createPostReport = async ({ client, referenceId, }) => {
14520
+ const { data: payload } = await client.http.post(`/api/v3/post/${encodeURIComponent(referenceId)}/flag`);
14521
+ if (client.cache) {
14522
+ const postPayload = await preparePostPayload(payload);
14523
+ ingestInCache(postPayload);
14524
+ }
14525
+ fireEvent(`post.flagged`, payload);
14526
+ return !!payload;
14527
+ };
14528
+ const createUserReport = async ({ client, referenceId, }) => {
14529
+ const { data: payload } = await client.http.post(`/api/v4/me/flags/${encodeURIComponent(referenceId)}`);
14530
+ if (client.cache) {
14531
+ const userPayload = await prepareUserPayload(payload);
14532
+ ingestInCache(userPayload);
14533
+ }
14534
+ fireEvent(`user.flagged`, payload);
14535
+ return !!payload;
14536
+ };
14537
+ const createCommentReport = async ({ client, referenceId, }) => {
14538
+ const { data: payload } = await client.http.post(`/api/v3/comment/${encodeURIComponent(referenceId)}/flag`);
14539
+ if (client.cache) {
14540
+ const commentPayload = await prepareCommentPayload(payload);
14541
+ ingestInCache(commentPayload);
14542
+ }
14543
+ fireEvent(`comment.flagged`, payload);
14544
+ return !!payload;
14545
+ };
13910
14546
  /**
13911
14547
  * ```js
13912
14548
  * import { createReport } from '@amityco/ts-sdk-react-native'
@@ -13923,33 +14559,57 @@ var REFERENCE_TYPES = {
13923
14559
  const createReport = async (referenceType, referenceId) => {
13924
14560
  const client = getActiveClient();
13925
14561
  client.log('report/createReport', { referenceType, referenceId });
13926
- const getAPIUrl = () => {
13927
- if (referenceType === 'user') {
13928
- return `/api/v4/me/flags/${encodeURIComponent(referenceId)}`;
13929
- }
13930
- if (referenceType === 'message') {
13931
- return `/api/v5/messages/${encodeURIComponent(referenceId)}/flags`;
13932
- }
13933
- const { domainName } = REFERENCE_TYPES[referenceType];
13934
- return `/api/v3/${domainName}/${encodeURIComponent(referenceId)}/flag`;
13935
- };
13936
- const { data: payload } = await client.http.post(getAPIUrl());
13937
- if (client.cache) {
13938
- if (referenceType === 'message') {
13939
- const messagePayload = await prepareMessagePayload(payload);
13940
- ingestInCache(messagePayload);
13941
- }
13942
- else if (referenceType === 'post') {
13943
- ingestInCache(prepareMembershipPayload(payload, 'communityUsers'));
13944
- }
13945
- else {
13946
- ingestInCache(payload);
13947
- }
14562
+ if (referenceType === 'user') {
14563
+ return createUserReport({ client, referenceId });
13948
14564
  }
13949
- fireEvent(`${referenceType}.flagged`, payload);
13950
- return !!payload;
14565
+ if (referenceType === 'message') {
14566
+ return createMessageReport({ client, referenceId });
14567
+ }
14568
+ if (referenceType === 'post') {
14569
+ return createPostReport({ client, referenceId });
14570
+ }
14571
+ if (referenceType === 'comment') {
14572
+ return createCommentReport({ client, referenceId });
14573
+ }
14574
+ return false;
13951
14575
  };
13952
14576
 
14577
+ const deleteMessageReport = async ({ client, referenceId, }) => {
14578
+ const { data: payload } = await client.http.delete(`/api/v5/messages/${encodeURIComponent(referenceId)}/flags`);
14579
+ if (client.cache) {
14580
+ const messagePayload = await prepareMessagePayload(payload);
14581
+ ingestInCache(messagePayload);
14582
+ }
14583
+ fireEvent(`message.unflagged`, payload);
14584
+ return !!payload;
14585
+ };
14586
+ const deletePostReport = async ({ client, referenceId, }) => {
14587
+ const { data: payload } = await client.http.delete(`/api/v3/post/${encodeURIComponent(referenceId)}/flag`);
14588
+ if (client.cache) {
14589
+ const postPayload = await preparePostPayload(payload);
14590
+ ingestInCache(postPayload);
14591
+ }
14592
+ fireEvent(`post.unflagged`, payload);
14593
+ return !!payload;
14594
+ };
14595
+ const deleteUserReport = async ({ client, referenceId, }) => {
14596
+ const { data: payload } = await client.http.delete(`/api/v4/me/flags/${encodeURIComponent(referenceId)}`);
14597
+ if (client.cache) {
14598
+ const userPayload = await prepareUserPayload(payload);
14599
+ ingestInCache(userPayload);
14600
+ }
14601
+ fireEvent(`user.unflagged`, payload);
14602
+ return !!payload;
14603
+ };
14604
+ const deleteCommentReport = async ({ client, referenceId, }) => {
14605
+ const { data: payload } = await client.http.delete(`/api/v3/comment/${encodeURIComponent(referenceId)}/flag`);
14606
+ if (client.cache) {
14607
+ const commentPayload = await prepareCommentPayload(payload);
14608
+ ingestInCache(commentPayload);
14609
+ }
14610
+ fireEvent(`comment.unflagged`, payload);
14611
+ return !!payload;
14612
+ };
13953
14613
  /**
13954
14614
  * ```js
13955
14615
  * import { deleteReport } from '@amityco/ts-sdk-react-native'
@@ -13965,35 +14625,46 @@ const createReport = async (referenceType, referenceId) => {
13965
14625
  * */
13966
14626
  const deleteReport = async (referenceType, referenceId) => {
13967
14627
  const client = getActiveClient();
13968
- client.log('report/deleteReport', { referenceType, referenceId });
13969
- const getAPIUrl = () => {
13970
- if (referenceType === 'user') {
13971
- return `/api/v4/me/flags/${encodeURIComponent(referenceId)}`;
13972
- }
13973
- if (referenceType === 'message') {
13974
- return `/api/v5/messages/${encodeURIComponent(referenceId)}/flags`;
13975
- }
13976
- const { domainName } = REFERENCE_TYPES[referenceType];
13977
- return `/api/v3/${domainName}/${encodeURIComponent(referenceId)}/unflag`;
13978
- };
13979
- const { data: payload } = await client.http.delete(getAPIUrl());
13980
- if (client.cache) {
13981
- if (referenceType === 'message') {
13982
- const messagePayload = await prepareMessagePayload(payload);
13983
- ingestInCache(messagePayload);
13984
- }
13985
- else if (referenceType === 'post') {
13986
- ingestInCache(prepareMembershipPayload(payload, 'communityUsers'));
13987
- }
13988
- else {
13989
- ingestInCache(payload);
13990
- }
14628
+ client.log('report/deleteReport', { referenceType, referenceId });
14629
+ if (referenceType === 'user') {
14630
+ return deleteUserReport({ client, referenceId });
13991
14631
  }
13992
- // @ts-ignore
13993
- fireEvent(`${referenceType}.unflagged`, payload);
13994
- return !!payload;
14632
+ if (referenceType === 'message') {
14633
+ return deleteMessageReport({ client, referenceId });
14634
+ }
14635
+ if (referenceType === 'post') {
14636
+ return deletePostReport({ client, referenceId });
14637
+ }
14638
+ if (referenceType === 'comment') {
14639
+ return deleteCommentReport({ client, referenceId });
14640
+ }
14641
+ return false;
13995
14642
  };
13996
14643
 
14644
+ const getMessageReport = async ({ client, referenceId, }) => {
14645
+ var _a;
14646
+ const { data } = await client.http.get(`/api/v5/messages/${encodeURIComponent(referenceId)}/flags`);
14647
+ const { result, isFlagByMe } = data !== null && data !== void 0 ? data : {};
14648
+ return (_a = result !== null && result !== void 0 ? result : isFlagByMe) !== null && _a !== void 0 ? _a : false;
14649
+ };
14650
+ const getPostReport = async ({ client, referenceId, }) => {
14651
+ var _a;
14652
+ const { data } = await client.http.get(`/api/v3/user/${referenceId}/isflagbyme`);
14653
+ const { result, isFlagByMe } = data !== null && data !== void 0 ? data : {};
14654
+ return (_a = result !== null && result !== void 0 ? result : isFlagByMe) !== null && _a !== void 0 ? _a : false;
14655
+ };
14656
+ const getUserReport = async ({ client, referenceId, }) => {
14657
+ var _a;
14658
+ const { data } = await client.http.get(`/api/v3/user/${referenceId}/isflagbyme`);
14659
+ const { result, isFlagByMe } = data !== null && data !== void 0 ? data : {};
14660
+ return (_a = result !== null && result !== void 0 ? result : isFlagByMe) !== null && _a !== void 0 ? _a : false;
14661
+ };
14662
+ const getCommentReport = async ({ client, referenceId, }) => {
14663
+ var _a;
14664
+ const { data } = await client.http.get(`/api/v3/comment/${referenceId}/isflagbyme`);
14665
+ const { result, isFlagByMe } = data !== null && data !== void 0 ? data : {};
14666
+ return (_a = result !== null && result !== void 0 ? result : isFlagByMe) !== null && _a !== void 0 ? _a : false;
14667
+ };
13997
14668
  /**
13998
14669
  * ```js
13999
14670
  * import { isReportedByMe } from '@amityco/ts-sdk-react-native'
@@ -14008,17 +14679,21 @@ const deleteReport = async (referenceType, referenceId) => {
14008
14679
  * @async
14009
14680
  * */
14010
14681
  const isReportedByMe = async (referenceType, referenceId) => {
14011
- var _a;
14012
14682
  const client = getActiveClient();
14013
14683
  client.log('report/isReportedByMe', { referenceType, referenceId });
14014
- const { domainName } = REFERENCE_TYPES[referenceType];
14684
+ if (referenceType === 'user') {
14685
+ return getUserReport({ client, referenceId });
14686
+ }
14015
14687
  if (referenceType === 'message') {
14016
- const { data } = await client.http.get(`/api/v5/messages/${encodeURIComponent(referenceId)}/flags`);
14017
- return data.result;
14688
+ return getMessageReport({ client, referenceId });
14018
14689
  }
14019
- const { data } = await client.http.get(`/api/v3/${domainName}/${referenceId}/isflagbyme`);
14020
- const { result, isFlagByMe } = data !== null && data !== void 0 ? data : {};
14021
- return (_a = result !== null && result !== void 0 ? result : isFlagByMe) !== null && _a !== void 0 ? _a : false;
14690
+ if (referenceType === 'post') {
14691
+ return getPostReport({ client, referenceId });
14692
+ }
14693
+ if (referenceType === 'comment') {
14694
+ return getCommentReport({ client, referenceId });
14695
+ }
14696
+ return false;
14022
14697
  };
14023
14698
 
14024
14699
  /* begin_public_function
@@ -15539,116 +16214,6 @@ const getMessage$1 = (messageId, callback) => {
15539
16214
  };
15540
16215
  /* end_public_function */
15541
16216
 
15542
- class PaginationNoPageController {
15543
- constructor(queryParams) {
15544
- const { http } = getActiveClient();
15545
- this.queryParams = queryParams;
15546
- this.http = http;
15547
- }
15548
- async onFetch() {
15549
- const queryResponse = await this.getRequest(this.queryParams);
15550
- return queryResponse;
15551
- }
15552
- }
15553
-
15554
- class LiveCollectionController {
15555
- constructor(paginationController, queryStreamId, cacheKey, callback) {
15556
- this.paginationController = paginationController;
15557
- this.queryStreamId = queryStreamId;
15558
- this.cacheKey = cacheKey;
15559
- this.callback = callback;
15560
- }
15561
- async refresh() {
15562
- try {
15563
- let result;
15564
- if (this.paginationController instanceof PaginationNoPageController) {
15565
- result = await this.paginationController.onFetch();
15566
- }
15567
- else {
15568
- result = await this.paginationController.loadFirstPage();
15569
- }
15570
- if (!result)
15571
- return;
15572
- await this.persistModel(result);
15573
- this.persistQueryStream({
15574
- response: result,
15575
- direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */,
15576
- refresh: true,
15577
- });
15578
- this.notifyChange({ origin: "server" /* Amity.LiveDataOrigin.SERVER */, loading: false });
15579
- }
15580
- catch (e) {
15581
- this.notifyChange({ origin: "server" /* Amity.LiveDataOrigin.SERVER */, loading: false, error: e });
15582
- }
15583
- }
15584
- loadPage({ initial = false, direction = "next" /* Amity.LiveCollectionPageDirection.NEXT */, }) {
15585
- this.setup();
15586
- this.notifyChange({ origin: "local" /* Amity.LiveDataOrigin.LOCAL */, loading: true });
15587
- if (initial) {
15588
- this.refresh();
15589
- }
15590
- else if (direction === "prev" /* Amity.LiveCollectionPageDirection.PREV */) {
15591
- this.loadPrevPage();
15592
- }
15593
- else if (direction === "next" /* Amity.LiveCollectionPageDirection.NEXT */) {
15594
- this.loadNextPage();
15595
- }
15596
- }
15597
- async loadNextPage() {
15598
- try {
15599
- if (this.paginationController instanceof PaginationNoPageController)
15600
- return;
15601
- const result = await this.paginationController.loadNextPage();
15602
- if (!result)
15603
- return;
15604
- await this.persistModel(result);
15605
- this.persistQueryStream({
15606
- response: result,
15607
- direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */,
15608
- });
15609
- this.notifyChange({ origin: "server" /* Amity.LiveDataOrigin.SERVER */, loading: false });
15610
- }
15611
- catch (e) {
15612
- this.notifyChange({ origin: "server" /* Amity.LiveDataOrigin.SERVER */, loading: false, error: e });
15613
- }
15614
- }
15615
- async loadPrevPage() {
15616
- try {
15617
- if (this.paginationController instanceof PaginationNoPageController)
15618
- return;
15619
- const result = await this.paginationController.loadPreviousPage();
15620
- if (!result)
15621
- return;
15622
- await this.persistModel(result);
15623
- this.persistQueryStream({
15624
- response: result,
15625
- direction: "prev" /* Amity.LiveCollectionPageDirection.PREV */,
15626
- });
15627
- this.notifyChange({ origin: "server" /* Amity.LiveDataOrigin.SERVER */, loading: false });
15628
- }
15629
- catch (e) {
15630
- this.notifyChange({ origin: "server" /* Amity.LiveDataOrigin.SERVER */, loading: false, error: e });
15631
- }
15632
- }
15633
- shouldNotify(data) {
15634
- const newData = data.map(convertGetterPropsToStatic).map(removeFunctionProperties);
15635
- if (isEqual(this.snapshot, newData))
15636
- return false;
15637
- this.snapshot = newData;
15638
- return true;
15639
- }
15640
- getCacheKey() {
15641
- return this.cacheKey;
15642
- }
15643
- }
15644
-
15645
- class QueryStreamController {
15646
- constructor(query, cacheKey) {
15647
- this.query = query;
15648
- this.cacheKey = cacheKey;
15649
- }
15650
- }
15651
-
15652
16217
  /* eslint-disable no-use-before-define */
15653
16218
  class MessageQueryStreamController extends QueryStreamController {
15654
16219
  constructor(query, cacheKey, notifyChange, preparePayload, paginationController) {
@@ -15731,51 +16296,6 @@ class MessageQueryStreamController extends QueryStreamController {
15731
16296
  }
15732
16297
  }
15733
16298
 
15734
- class PaginationController {
15735
- constructor(queryParams) {
15736
- const { http } = getActiveClient();
15737
- this.queryParams = queryParams;
15738
- this.http = http;
15739
- }
15740
- loadFirstPage() {
15741
- return this.onFetch("first" /* Amity.LiveCollectionPageDirection.FIRST */);
15742
- }
15743
- loadNextPage() {
15744
- return this.onFetch("next" /* Amity.LiveCollectionPageDirection.NEXT */);
15745
- }
15746
- loadPreviousPage() {
15747
- return this.onFetch("prev" /* Amity.LiveCollectionPageDirection.PREV */);
15748
- }
15749
- async onFetch(direction = "first" /* Amity.LiveCollectionPageDirection.FIRST */) {
15750
- var _a, _b, _c, _d;
15751
- if (direction === 'prev' && !this.previousToken)
15752
- return;
15753
- if (direction === 'next' && !this.nextToken)
15754
- return;
15755
- let token;
15756
- if (direction === 'prev')
15757
- token = this.previousToken;
15758
- if (direction === 'next')
15759
- token = this.nextToken;
15760
- const queryResponse = await this.getRequest(this.queryParams, token);
15761
- if (direction === 'first') {
15762
- this.nextToken = (_a = queryResponse.paging) === null || _a === void 0 ? void 0 : _a.next;
15763
- this.previousToken = (_b = queryResponse.paging) === null || _b === void 0 ? void 0 : _b.previous;
15764
- }
15765
- if (direction === 'prev')
15766
- this.previousToken = (_c = queryResponse.paging) === null || _c === void 0 ? void 0 : _c.previous;
15767
- if (direction === 'next')
15768
- this.nextToken = (_d = queryResponse.paging) === null || _d === void 0 ? void 0 : _d.next;
15769
- return queryResponse;
15770
- }
15771
- getNextToken() {
15772
- return this.nextToken;
15773
- }
15774
- getPrevToken() {
15775
- return this.previousToken;
15776
- }
15777
- }
15778
-
15779
16299
  /* eslint-disable no-use-before-define */
15780
16300
  /**
15781
16301
  * TODO: handle cache receive cache option, and cache policy
@@ -17567,10 +18087,12 @@ const removeMembers$1 = async (channelId, userIds) => {
17567
18087
  */
17568
18088
  class ChannelMemberPaginationController extends PaginationController {
17569
18089
  async getRequest(queryParams, token) {
17570
- const { limit = COLLECTION_DEFAULT_PAGINATION_LIMIT } = queryParams, params = __rest(queryParams, ["limit"]);
18090
+ const { limit = COLLECTION_DEFAULT_PAGINATION_LIMIT, includeDeleted } = queryParams, params = __rest(queryParams, ["limit", "includeDeleted"]);
17571
18091
  const options = token ? { token } : { limit };
18092
+ const isDeleted = includeDeleted === false ? false : undefined;
17572
18093
  const { data: queryResponse } = await this.http.get(`/api/v4/channels/${encodeURIComponent(params.channelId)}/users`, {
17573
- params: Object.assign(Object.assign({}, params), { options }),
18094
+ params: Object.assign(Object.assign({}, params), { options,
18095
+ isDeleted }),
17574
18096
  });
17575
18097
  return queryResponse;
17576
18098
  }
@@ -17636,6 +18158,33 @@ class ChannelMemberQueryStreamController extends QueryStreamController {
17636
18158
  }
17637
18159
  }
17638
18160
 
18161
+ const onUserDeleted$1 = (channelId) => (callback) => {
18162
+ const client = getActiveClient();
18163
+ const filter = (payload) => {
18164
+ var _a, _b;
18165
+ const userPayload = prepareUserPayload(payload);
18166
+ if (userPayload.users.length === 0)
18167
+ return;
18168
+ const user = userPayload.users[0];
18169
+ ingestInCache(userPayload);
18170
+ const channelUserCacheKey = getResolver('channelUsers')({
18171
+ channelId,
18172
+ userId: user.userId,
18173
+ });
18174
+ const cacheData = (_a = pullFromCache([
18175
+ 'channelUsers',
18176
+ 'get',
18177
+ channelUserCacheKey,
18178
+ ])) === null || _a === void 0 ? void 0 : _a.data;
18179
+ upsertInCache(['channelUsers', 'get', channelUserCacheKey], Object.assign(Object.assign({}, cacheData), { user }));
18180
+ const channel = (_b = pullFromCache(['channel', 'get', channelId])) === null || _b === void 0 ? void 0 : _b.data;
18181
+ if (!channel)
18182
+ return;
18183
+ callback(channel, cacheData);
18184
+ };
18185
+ return createEventSubscriber(client, 'user.deleted', 'user.deleted', filter);
18186
+ };
18187
+
17639
18188
  /* eslint-disable no-use-before-define */
17640
18189
  class ChannelMemberLiveCollectionController extends LiveCollectionController {
17641
18190
  constructor(query, callback) {
@@ -17674,6 +18223,7 @@ class ChannelMemberLiveCollectionController extends LiveCollectionController {
17674
18223
  { fn: onChannelMemberUnbanned, action: 'onChannelMemberUnbanned' },
17675
18224
  { fn: onChannelMemberRoleAdded, action: 'onChannelMemberRoleAdded' },
17676
18225
  { fn: onChannelMemberRoleRemoved, action: 'onChannelMemberRoleRemoved' },
18226
+ { fn: onUserDeleted$1(this.query.channelId), action: 'onChannelMemberChanged' },
17677
18227
  ]);
17678
18228
  }
17679
18229
  notifyChange({ origin, loading, error }) {
@@ -17720,6 +18270,9 @@ class ChannelMemberLiveCollectionController extends LiveCollectionController {
17720
18270
  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.');
17721
18271
  channelMembers = filterBySearchTerm(channelMembers, this.query.search);
17722
18272
  }
18273
+ if (this.query.includeDeleted === false) {
18274
+ channelMembers = channelMembers.filter(member => { var _a; return ((_a = member.user) === null || _a === void 0 ? void 0 : _a.isDeleted) !== true; });
18275
+ }
17723
18276
  // sort, 'lastCreated' is the default sort order
17724
18277
  const sortBy = this.query.sortBy ? this.query.sortBy : 'lastCreated';
17725
18278
  channelMembers = channelMembers.sort(sortBy === 'lastCreated' ? sortByLastCreated : sortByFirstCreated);
@@ -18087,57 +18640,6 @@ const saveCommunityUsers = (communities, communityUsers) => {
18087
18640
  });
18088
18641
  };
18089
18642
 
18090
- const getMatchPostSetting = (value) => {
18091
- var _a;
18092
- return (_a = Object.keys(CommunityPostSettingMaps).find(key => value.needApprovalOnPostCreation ===
18093
- CommunityPostSettingMaps[key].needApprovalOnPostCreation &&
18094
- value.onlyAdminCanPost === CommunityPostSettingMaps[key].onlyAdminCanPost)) !== null && _a !== void 0 ? _a : DefaultCommunityPostSetting;
18095
- };
18096
- const convertCommunityUsersToUniqueObject = (communityUsers) => {
18097
- if (!communityUsers)
18098
- return communityUsers;
18099
- const result = {};
18100
- communityUsers.forEach(user => {
18101
- result[`${user.userId}#${user.communityId}`] = user;
18102
- });
18103
- return result;
18104
- };
18105
- const convertCommunityPayload = (rawPayload) => {
18106
- // Unpack community payload by mapping payload field to postSetting value.
18107
- const communities = rawPayload.communities.map((_a) => {
18108
- var { needApprovalOnPostCreation, onlyAdminCanPost } = _a, restCommunityPayload = __rest(_a, ["needApprovalOnPostCreation", "onlyAdminCanPost"]);
18109
- return (Object.assign({ postSetting: getMatchPostSetting({
18110
- needApprovalOnPostCreation,
18111
- onlyAdminCanPost,
18112
- }) }, restCommunityPayload));
18113
- });
18114
- const mergeCommunityUsers = communities.reduce((acc, { communityId }) => {
18115
- var _a;
18116
- const users = (_a = pullFromCache([
18117
- 'communityUsers',
18118
- 'collection',
18119
- communityId,
18120
- ])) === null || _a === void 0 ? void 0 : _a.data;
18121
- if (!users)
18122
- return acc;
18123
- return Object.assign(Object.assign({}, convertCommunityUsersToUniqueObject(users)), acc);
18124
- }, convertCommunityUsersToUniqueObject(rawPayload.communityUsers));
18125
- const communityUsers = withUsers(Object.values(mergeCommunityUsers));
18126
- const communityWithMembershipStatus = updateMembershipStatus(communities, communityUsers);
18127
- return Object.assign(Object.assign({}, rawPayload), { communities: communityWithMembershipStatus, communityUsers });
18128
- };
18129
- const prepareCommunityPayload = (rawPayload) => {
18130
- const { communities, communityUsers } = convertCommunityPayload(rawPayload);
18131
- return Object.assign(Object.assign({}, rawPayload), { communities,
18132
- communityUsers });
18133
- };
18134
- const prepareCommunityRequest = (params) => {
18135
- const { postSetting = undefined, storySetting } = params, restParam = __rest(params, ["postSetting", "storySetting"]);
18136
- return Object.assign(Object.assign(Object.assign({}, restParam), (postSetting ? CommunityPostSettingMaps[postSetting] : undefined)), {
18137
- // Convert story setting to the actual value. (Allow by default)
18138
- allowCommentInStory: typeof (storySetting === null || storySetting === void 0 ? void 0 : storySetting.enableComment) === 'boolean' ? storySetting.enableComment : true });
18139
- };
18140
-
18141
18643
  /**
18142
18644
  * ```js
18143
18645
  * import { getCommunities } from '@amityco/ts-sdk-react-native'
@@ -18573,10 +19075,6 @@ const onCommunityUpdated = (callback) => createCommunityEventSubscriber('communi
18573
19075
  */
18574
19076
  const onCommunityDeleted = (callback) => createCommunityEventSubscriber('community.deleted', callback);
18575
19077
 
18576
- function isNonNullable(value) {
18577
- return value != null;
18578
- }
18579
-
18580
19078
  function hasPermission(member, payload, permission) {
18581
19079
  if (member.permissions.some(x => x === permission)) {
18582
19080
  return true;
@@ -18591,7 +19089,7 @@ function getEventRelatedMember(event, payload) {
18591
19089
  }
18592
19090
  // NOTE: backend returns the one who took the action and the one on whom
18593
19091
  // the action was taken. We need the 2nd one
18594
- if (event === 'community.userRemoved') {
19092
+ if (event === 'community.userRemoved' || event === 'local.community.userRemoved') {
18595
19093
  return payload.communityUsers.filter(x => x.communityMembership === 'none');
18596
19094
  }
18597
19095
  if (event === 'community.userBanned') {
@@ -18639,6 +19137,43 @@ const createCommunityMemberEventSubscriber = (event, callback) => {
18639
19137
  }
18640
19138
  };
18641
19139
  return createEventSubscriber(client, event, event, filter);
19140
+ };
19141
+ const createLocalCommunityMemberEventSubscriber = (event, callback) => {
19142
+ const client = getActiveClient();
19143
+ const filter = (payload) => {
19144
+ const preparedPayload = prepareCommunityPayload(payload);
19145
+ const { communities, communityUsers } = preparedPayload;
19146
+ /*
19147
+ * community.isJoined is not part of the communityMembership payload, and needs
19148
+ * to be calculated based on the communityMembership value
19149
+ */
19150
+ const communitiesWithMembership = updateMembershipStatus(communities, communityUsers);
19151
+ preparedPayload.communities = communitiesWithMembership;
19152
+ if (!client.cache) {
19153
+ // TODO: here we are missing specific properties here!
19154
+ callback(preparedPayload.communities[0], getEventRelatedMember(event, preparedPayload));
19155
+ }
19156
+ else {
19157
+ ingestInCache(preparedPayload);
19158
+ const community = pullFromCache([
19159
+ 'community',
19160
+ 'get',
19161
+ preparedPayload.communities[0].communityId,
19162
+ ]);
19163
+ const members = getEventRelatedMember(event, preparedPayload)
19164
+ .map(member => {
19165
+ const memberCache = pullFromCache([
19166
+ 'communityUsers',
19167
+ 'get',
19168
+ getResolver('communityUsers')(member),
19169
+ ]);
19170
+ return memberCache === null || memberCache === void 0 ? void 0 : memberCache.data;
19171
+ })
19172
+ .filter(isNonNullable);
19173
+ callback(community.data, members);
19174
+ }
19175
+ };
19176
+ return createEventSubscriber(client, event, event, filter);
18642
19177
  };
18643
19178
 
18644
19179
  /**
@@ -18760,6 +19295,40 @@ const onCommunityUserRoleAdded = (callback) => createCommunityMemberEventSubscri
18760
19295
  */
18761
19296
  const onCommunityUserRoleRemoved = (callback) => createCommunityMemberEventSubscriber('community.roleRemoved', callback);
18762
19297
 
19298
+ /**
19299
+ * ```js
19300
+ * import { onLocalCommunityUserAdded } from '@amityco/ts-sdk-react-native'
19301
+ * const dispose = onLocalCommunityUserAdded((community, member) => {
19302
+ * // ...
19303
+ * })
19304
+ * ```
19305
+ *
19306
+ * Fired when a user has been added to a {@link Amity.Community}
19307
+ *
19308
+ * @param callback The function to call when the event was fired
19309
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
19310
+ *
19311
+ * @category Community Events
19312
+ */
19313
+ const onLocalCommunityUserAdded = (callback) => createLocalCommunityMemberEventSubscriber('local.community.userAdded', callback);
19314
+
19315
+ /**
19316
+ * ```js
19317
+ * import { onLocalCommunityUserRemoved } from '@amityco/ts-sdk-react-native'
19318
+ * const dispose = onLocalCommunityUserRemoved((community, member) => {
19319
+ * // ...
19320
+ * })
19321
+ * ```
19322
+ *
19323
+ * Fired when a user has been removed from a {@link Amity.Community}
19324
+ *
19325
+ * @param callback The function to call when the event was fired
19326
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
19327
+ *
19328
+ * @category Community Events
19329
+ */
19330
+ const onLocalCommunityUserRemoved = (callback) => createLocalCommunityMemberEventSubscriber('local.community.userRemoved', callback);
19331
+
18763
19332
  /**
18764
19333
  * ```js
18765
19334
  * import { onCommunityJoined } from '@amityco/ts-sdk-react-native'
@@ -18912,6 +19481,9 @@ var EnumCommunityMemberActions$1;
18912
19481
  EnumCommunityMemberActions["OnCommunityUserRoleRemoved"] = "onCommunityUserRoleRemoved";
18913
19482
  EnumCommunityMemberActions["OnCommunityUserUnbanned"] = "onCommunityUserUnbanned";
18914
19483
  EnumCommunityMemberActions["OnMemberCountChanged"] = "OnMemberCountChanged";
19484
+ EnumCommunityMemberActions["OnCommunityUserAdded"] = "OnCommunityUserAdded";
19485
+ EnumCommunityMemberActions["onCommunityUserRemoved"] = "onCommunityUserRemoved";
19486
+ EnumCommunityMemberActions["OnUserDeleted"] = "OnUserDeleted";
18915
19487
  })(EnumCommunityMemberActions$1 || (EnumCommunityMemberActions$1 = {}));
18916
19488
 
18917
19489
  /* begin_public_function
@@ -18936,7 +19508,7 @@ const addMembers = async (communityId, userIds) => {
18936
19508
  const client = getActiveClient();
18937
19509
  client.log('community/moderation/addMembers', communityId, userIds);
18938
19510
  const { data: payload } = await client.http.post(`/api/v3/communities/${communityId}/users`, { communityId, userIds });
18939
- fireEvent('community.userAdded', payload);
19511
+ fireEvent('local.community.userAdded', payload);
18940
19512
  const data = prepareMembershipPayload(payload, 'communityUsers');
18941
19513
  if (client.cache)
18942
19514
  ingestInCache(data);
@@ -18967,7 +19539,7 @@ const removeMembers = async (communityId, userIds) => {
18967
19539
  const client = getActiveClient();
18968
19540
  client.log('community/moderation/removeMembers', communityId, userIds);
18969
19541
  const { data: payload } = await client.http.delete(`/api/v3/communities/${communityId}/users`, { data: { communityId, userIds } });
18970
- fireEvent('community.userRemoved', payload);
19542
+ fireEvent('local.community.userRemoved', payload);
18971
19543
  const data = prepareMembershipPayload(payload, 'communityUsers');
18972
19544
  if (client.cache)
18973
19545
  ingestInCache(data);
@@ -18982,10 +19554,12 @@ const removeMembers = async (communityId, userIds) => {
18982
19554
  */
18983
19555
  class CommunityMembersPaginationController extends PaginationController {
18984
19556
  async getRequest(queryParams, token) {
18985
- const { limit = COLLECTION_DEFAULT_PAGINATION_LIMIT } = queryParams, params = __rest(queryParams, ["limit"]);
19557
+ const { limit = COLLECTION_DEFAULT_PAGINATION_LIMIT, includeDeleted } = queryParams, params = __rest(queryParams, ["limit", "includeDeleted"]);
18986
19558
  const options = token ? { token } : { limit };
19559
+ const isDeleted = includeDeleted === false ? false : undefined;
18987
19560
  const { data: queryResponse } = await this.http.get(`/api/v3/communities/${params.communityId}/users`, {
18988
- params: Object.assign(Object.assign({}, params), { options }),
19561
+ params: Object.assign(Object.assign({}, params), { options,
19562
+ isDeleted }),
18989
19563
  });
18990
19564
  return queryResponse;
18991
19565
  }
@@ -19054,6 +19628,96 @@ class CommunityMembersQueryStreamController extends QueryStreamController {
19054
19628
  }
19055
19629
  }
19056
19630
 
19631
+ /**
19632
+ * ```js
19633
+ * import { onLocalCommunityRoleRemoved } from '@amityco/ts-sdk-react-native'
19634
+ * const dispose = onLocalCommunityRoleRemoved((community, member) => {
19635
+ * // ...
19636
+ * })
19637
+ * ```
19638
+ *
19639
+ * Fired when any {@link Amity.communityUsers} 's role has been added to any {@link Amity.Community}
19640
+ *
19641
+ * @param callback The function to call when the event was fired
19642
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
19643
+ *
19644
+ * @category Community Events
19645
+ */
19646
+ const onLocalCommunityRoleRemoved = (callback) => {
19647
+ const client = getActiveClient();
19648
+ const filter = async (payload) => {
19649
+ const { communities, communityUsers } = payload;
19650
+ callback(communities[0], communityUsers.filter(communityUser => communityUser.communityMembership === 'member'));
19651
+ };
19652
+ return createEventSubscriber(client, 'onLocalCommunityRoleRemoved', 'local.community.roleRemoved', filter);
19653
+ };
19654
+
19655
+ /**
19656
+ * ```js
19657
+ * import { onLocalCommunityRoleAdded } from '@amityco/ts-sdk-react-native'
19658
+ * const dispose = onLocalCommunityRoleAdded((community, member) => {
19659
+ * // ...
19660
+ * })
19661
+ * ```
19662
+ *
19663
+ * Fired when any {@link Amity.communityUsers} 's role has been added to any {@link Amity.Community}
19664
+ *
19665
+ * @param callback The function to call when the event was fired
19666
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
19667
+ *
19668
+ * @category Community Events
19669
+ */
19670
+ const onLocalCommunityRoleAdded = (callback) => {
19671
+ const client = getActiveClient();
19672
+ const filter = async (payload) => {
19673
+ const { communities, communityUsers } = payload;
19674
+ callback(communities[0], communityUsers.filter(communityUser => communityUser.communityMembership === 'member'));
19675
+ };
19676
+ return createEventSubscriber(client, 'onLocalCommunityRoleAdded', 'local.community.roleAdded', filter);
19677
+ };
19678
+
19679
+ /**
19680
+ * ```js
19681
+ * import { onUserDeleted } from '@amityco/ts-sdk'
19682
+ * const dispose = onUserDeleted((community, member) => {
19683
+ * // ...
19684
+ * })
19685
+ * ```
19686
+ *
19687
+ * Fired when a {@link Amity.Community} has been joined
19688
+ *
19689
+ * @param callback The function to call when the event was fired
19690
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
19691
+ *
19692
+ * @category Community Events
19693
+ */
19694
+ const onUserDeleted = (communityId) => (callback) => {
19695
+ const client = getActiveClient();
19696
+ const filter = (payload) => {
19697
+ var _a, _b;
19698
+ const userPayload = prepareUserPayload(payload);
19699
+ if (userPayload.users.length === 0)
19700
+ return;
19701
+ const user = userPayload.users[0];
19702
+ ingestInCache(userPayload);
19703
+ const communityUserCacheKey = getResolver('communityUsers')({
19704
+ communityId,
19705
+ userId: user.userId,
19706
+ });
19707
+ const cacheData = (_a = pullFromCache([
19708
+ 'communityUsers',
19709
+ 'get',
19710
+ communityUserCacheKey,
19711
+ ])) === null || _a === void 0 ? void 0 : _a.data;
19712
+ pushToCache(['communityUsers', 'get', communityUserCacheKey], Object.assign(Object.assign({}, cacheData), { user }));
19713
+ const community = (_b = pullFromCache(['community', 'get', communityId])) === null || _b === void 0 ? void 0 : _b.data;
19714
+ callback(community, [
19715
+ Object.assign(Object.assign({}, cacheData), { user }),
19716
+ ]);
19717
+ };
19718
+ return createEventSubscriber(client, 'user.deleted', 'user.deleted', filter);
19719
+ };
19720
+
19057
19721
  class CommunityMembersLiveCollectionController extends LiveCollectionController {
19058
19722
  constructor(query, callback) {
19059
19723
  const queryStreamId = hash__default["default"](query);
@@ -19092,7 +19756,24 @@ class CommunityMembersLiveCollectionController extends LiveCollectionController
19092
19756
  fn: onCommunityUserRoleRemoved,
19093
19757
  action: EnumCommunityMemberActions$1.OnCommunityUserRoleRemoved,
19094
19758
  },
19759
+ {
19760
+ fn: onLocalCommunityRoleAdded,
19761
+ action: EnumCommunityMemberActions$1.OnCommunityUserRoleAdded,
19762
+ },
19763
+ {
19764
+ fn: onLocalCommunityRoleRemoved,
19765
+ action: EnumCommunityMemberActions$1.OnCommunityUserRoleRemoved,
19766
+ },
19095
19767
  { fn: onCommunityUserUnbanned, action: EnumCommunityMemberActions$1.OnCommunityUserUnbanned },
19768
+ { fn: onLocalCommunityUserAdded, action: EnumCommunityMemberActions$1.OnCommunityUserAdded },
19769
+ {
19770
+ fn: onLocalCommunityUserRemoved,
19771
+ action: EnumCommunityMemberActions$1.onCommunityUserRemoved,
19772
+ },
19773
+ {
19774
+ fn: onUserDeleted(this.query.communityId),
19775
+ action: EnumCommunityMemberActions$1.OnCommunityUserChanged,
19776
+ },
19096
19777
  ]);
19097
19778
  }
19098
19779
  notifyChange({ origin, loading, error }) {
@@ -19125,6 +19806,9 @@ class CommunityMembersLiveCollectionController extends LiveCollectionController
19125
19806
  if (this.query.search) {
19126
19807
  communityMembers = filterBySearchTerm(communityMembers, this.query.search);
19127
19808
  }
19809
+ if (this.query.includeDeleted === false) {
19810
+ communityMembers = communityMembers.filter(({ user }) => (user === null || user === void 0 ? void 0 : user.isDeleted) !== true);
19811
+ }
19128
19812
  switch (this.query.sortBy) {
19129
19813
  case 'firstCreated':
19130
19814
  communityMembers = communityMembers.sort(sortByFirstCreated);
@@ -19215,10 +19899,12 @@ const getMembers = (params, callback, config) => {
19215
19899
  */
19216
19900
  class SearchCommunityMembersPaginationController extends PaginationController {
19217
19901
  async getRequest(queryParams, token) {
19218
- const { limit = COLLECTION_DEFAULT_PAGINATION_LIMIT } = queryParams, params = __rest(queryParams, ["limit"]);
19902
+ const { limit = COLLECTION_DEFAULT_PAGINATION_LIMIT, includeDeleted } = queryParams, params = __rest(queryParams, ["limit", "includeDeleted"]);
19219
19903
  const options = token ? { token } : { limit };
19904
+ const isDeleted = includeDeleted === false ? false : undefined;
19220
19905
  const { data: queryResponse } = await this.http.get(`/api/v3/communities/${params.communityId}/users`, {
19221
- params: Object.assign(Object.assign({}, params), { options }),
19906
+ params: Object.assign(Object.assign({}, params), { options,
19907
+ isDeleted }),
19222
19908
  });
19223
19909
  return queryResponse;
19224
19910
  }
@@ -19325,11 +20011,19 @@ class SearchCommunityMembersLiveCollectionController extends LiveCollectionContr
19325
20011
  { fn: onCommunityLeft, action: EnumCommunityMemberActions.OnCommunityLeft },
19326
20012
  { fn: onCommunityUserBanned, action: EnumCommunityMemberActions.OnCommunityUserBanned },
19327
20013
  { fn: onCommunityUserChanged, action: EnumCommunityMemberActions.OnCommunityUserChanged },
20014
+ {
20015
+ fn: onLocalCommunityRoleRemoved,
20016
+ action: EnumCommunityMemberActions.OnCommunityUserRoleRemoved,
20017
+ },
19328
20018
  {
19329
20019
  fn: onCommunityUserRoleRemoved,
19330
20020
  action: EnumCommunityMemberActions.OnCommunityUserRoleRemoved,
19331
20021
  },
19332
20022
  { fn: onCommunityUserUnbanned, action: EnumCommunityMemberActions.OnCommunityUserUnbanned },
20023
+ {
20024
+ fn: onUserDeleted(this.query.communityId),
20025
+ action: EnumCommunityMemberActions.OnCommunityUserChanged,
20026
+ },
19333
20027
  ]);
19334
20028
  }
19335
20029
  notifyChange({ origin, loading, error }) {
@@ -19362,6 +20056,9 @@ class SearchCommunityMembersLiveCollectionController extends LiveCollectionContr
19362
20056
  if (this.query.search) {
19363
20057
  communityMembers = filterBySearchTerm(communityMembers, this.query.search);
19364
20058
  }
20059
+ if (this.query.includeDeleted === false) {
20060
+ communityMembers = communityMembers.filter(({ user }) => (user === null || user === void 0 ? void 0 : user.isDeleted) !== true);
20061
+ }
19365
20062
  return communityMembers;
19366
20063
  }
19367
20064
  }
@@ -19423,6 +20120,8 @@ var index$b = /*#__PURE__*/Object.freeze({
19423
20120
  onCommunityUserUnbanned: onCommunityUserUnbanned,
19424
20121
  onCommunityUserRoleAdded: onCommunityUserRoleAdded,
19425
20122
  onCommunityUserRoleRemoved: onCommunityUserRoleRemoved,
20123
+ onLocalCommunityUserAdded: onLocalCommunityUserAdded,
20124
+ onLocalCommunityUserRemoved: onLocalCommunityUserRemoved,
19426
20125
  onCommunityJoined: onCommunityJoined,
19427
20126
  onCommunityLeft: onCommunityLeft
19428
20127
  });
@@ -20079,9 +20778,10 @@ const addRoles = async (communityId, roleIds, userIds) => {
20079
20778
  const client = getActiveClient();
20080
20779
  client.log('community/moderation/addRoles', communityId, roleIds, userIds);
20081
20780
  const { data: payload } = await client.http.post(`/api/v4/communities/${communityId}/users/roles`, { communityId, roles: roleIds, userIds });
20082
- const data = prepareMembershipPayload(payload, 'communityUsers');
20781
+ const data = prepareCommunityMembershipPayload(payload);
20083
20782
  if (client.cache)
20084
20783
  ingestInCache(data);
20784
+ fireEvent('local.community.roleAdded', data);
20085
20785
  const { communityUsers } = data;
20086
20786
  return !!communityUsers.find(communityUser => communityUser.communityId === communityId &&
20087
20787
  roleIds.some(role => communityUser.roles.includes(role)));
@@ -20111,9 +20811,10 @@ const removeRoles = async (communityId, roleIds, userIds) => {
20111
20811
  const client = getActiveClient();
20112
20812
  client.log('community/moderation/removeRoles', communityId, roleIds, userIds);
20113
20813
  const { data: payload } = await client.http.delete(`/api/v4/communities/${communityId}/users/roles`, { data: { communityId, roles: roleIds, userIds } });
20114
- const data = prepareMembershipPayload(payload, 'communityUsers');
20814
+ const data = prepareCommunityMembershipPayload(payload);
20115
20815
  if (client.cache)
20116
20816
  ingestInCache(data);
20817
+ fireEvent('local.community.roleRemoved', data);
20117
20818
  const { communityUsers } = data;
20118
20819
  return !!communityUsers.find(communityUser => communityUser.communityId === communityId &&
20119
20820
  !roleIds.some(role => communityUser.roles.includes(role)));
@@ -20800,7 +21501,7 @@ const updatePost = async (postId, patch) => {
20800
21501
  const cachedAt = client.cache && Date.now();
20801
21502
  if (client.cache)
20802
21503
  ingestInCache(data, { cachedAt });
20803
- fireEvent('local.post.updated', data);
21504
+ fireEvent('local.post.updated', payload);
20804
21505
  const { posts } = data;
20805
21506
  return {
20806
21507
  data: LinkedObject.post(posts.find(post => post.postId === postId)),
@@ -20900,7 +21601,15 @@ const deletePost = async (postId, permanent = false) => {
20900
21601
  }
20901
21602
  // to support hard deletion
20902
21603
  const deleted = Object.assign(Object.assign({}, post.data), { isDeleted: true });
20903
- fireEvent('post.deleted', {
21604
+ if (permanent) {
21605
+ setTimeout(() => {
21606
+ pushToTombstone('post', postId);
21607
+ }, 0);
21608
+ }
21609
+ else {
21610
+ upsertInCache(['post', 'get', postId], { isDeleted: true });
21611
+ }
21612
+ fireEvent('local.post.deleted', {
20904
21613
  posts: [deleted],
20905
21614
  categories: [],
20906
21615
  comments: [],
@@ -20911,14 +21620,6 @@ const deletePost = async (postId, permanent = false) => {
20911
21620
  postChildren: [],
20912
21621
  users: [],
20913
21622
  });
20914
- if (permanent) {
20915
- setTimeout(() => {
20916
- pushToTombstone('post', postId);
20917
- }, 0);
20918
- }
20919
- else {
20920
- upsertInCache(['post', 'get', postId], { isDeleted: true });
20921
- }
20922
21623
  return LinkedObject.post(deleted);
20923
21624
  };
20924
21625
 
@@ -21306,6 +22007,7 @@ getCommentByIds.locally = (commentIds) => {
21306
22007
  * @async
21307
22008
  */
21308
22009
  const createComment = async (bundle) => {
22010
+ var _a;
21309
22011
  const client = getActiveClient();
21310
22012
  client.log('comment/createComment', bundle);
21311
22013
  const { data } = await client.http.post('/api/v3/comments', bundle);
@@ -21317,18 +22019,21 @@ const createComment = async (bundle) => {
21317
22019
  if (client.cache)
21318
22020
  ingestInCache(data, { cachedAt });
21319
22021
  if (['post', 'content'].includes(bundle.referenceType)) {
21320
- const post = await getPost$2(bundle.referenceId);
21321
- fireEvent('local.post.updated', {
21322
- posts: [post.data],
21323
- categories: [],
21324
- comments: [],
21325
- communities: [],
21326
- communityUsers: [],
21327
- feeds: [],
21328
- files: [],
21329
- postChildren: [],
21330
- users: [],
21331
- });
22022
+ const post = (_a = pullFromCache(['post', 'get', bundle.referenceId])) === null || _a === void 0 ? void 0 : _a.data;
22023
+ if (post) {
22024
+ post.commentsCount += 1;
22025
+ fireEvent('local.post.updated', {
22026
+ posts: [post],
22027
+ categories: [],
22028
+ comments: [],
22029
+ communities: [],
22030
+ communityUsers: data.communityUsers,
22031
+ feeds: [],
22032
+ files: data.files,
22033
+ postChildren: [],
22034
+ users: data.users,
22035
+ });
22036
+ }
21332
22037
  }
21333
22038
  else if (bundle.referenceType === 'story') {
21334
22039
  const storyIndex = pullFromCache([
@@ -21487,6 +22192,7 @@ getStoryByStoryId$1.locally = (storyId) => {
21487
22192
  * @async
21488
22193
  */
21489
22194
  const deleteComment = async (commentId, permanent = false) => {
22195
+ var _a;
21490
22196
  const client = getActiveClient();
21491
22197
  const comment = await getComment$2(commentId);
21492
22198
  // API-FIX: This endpoint has not been implemented yet.
@@ -21511,18 +22217,28 @@ const deleteComment = async (commentId, permanent = false) => {
21511
22217
  });
21512
22218
  }
21513
22219
  else {
21514
- const post = await getPost$2(comment.data.referenceId);
21515
- fireEvent('local.post.updated', {
21516
- posts: [post.data],
21517
- categories: [],
21518
- comments: [],
21519
- communities: [],
21520
- communityUsers: [],
21521
- feeds: [],
21522
- files: [],
21523
- postChildren: [],
21524
- users: [],
21525
- });
22220
+ const post = (_a = pullFromCache(['post', 'get', comment.data.referenceId])) === null || _a === void 0 ? void 0 : _a.data;
22221
+ if (post) {
22222
+ let removeCount;
22223
+ if (!deleted.parentId) {
22224
+ // NOTE: delete the parent comment will remove all children comments
22225
+ removeCount = deleted.childrenNumber + 1;
22226
+ }
22227
+ else
22228
+ removeCount = 1;
22229
+ post.commentsCount -= removeCount;
22230
+ fireEvent('local.post.updated', {
22231
+ posts: [post],
22232
+ categories: [],
22233
+ comments: [],
22234
+ communities: [],
22235
+ communityUsers: [],
22236
+ feeds: [],
22237
+ files: [],
22238
+ postChildren: [],
22239
+ users: [],
22240
+ });
22241
+ }
21526
22242
  }
21527
22243
  fireEvent('local.comment.deleted', {
21528
22244
  comments: [deleted],
@@ -21746,46 +22462,121 @@ getComment$1.locally = (commentId) => {
21746
22462
 
21747
22463
  /**
21748
22464
  * ```js
21749
- * import { observeComment } from '@amityco/ts-sdk-react-native'
21750
- *
21751
- * let comment = {}
21752
- * const dispose = observeComment(commentId, ({ data }) => comment = data)
22465
+ * import { observeComment } from '@amityco/ts-sdk-react-native'
22466
+ *
22467
+ * let comment = {}
22468
+ * const dispose = observeComment(commentId, ({ data }) => comment = data)
22469
+ * ```
22470
+ *
22471
+ * Observe all mutation on a given {@link Amity.InternalComment}
22472
+ *
22473
+ * @param commentId the ID of the comment to observe
22474
+ * @param callback the function to call when new data are available
22475
+ * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the comment
22476
+ *
22477
+ * @category InternalComment Observer
22478
+ */
22479
+ const observeComment = (commentId, callback, policy = 'cache_then_server') => {
22480
+ const { log } = getActiveClient();
22481
+ const timestamp = Date.now();
22482
+ log(`observeComment(tmpid: ${timestamp}) > listen`);
22483
+ // wrapper function to make sure
22484
+ const router = (result, action) => {
22485
+ var _a, _b;
22486
+ if (callback instanceof Function)
22487
+ return callback(result);
22488
+ if (action !== 'onFetch')
22489
+ (_a = callback.onEvent) === null || _a === void 0 ? void 0 : _a.call(callback, action, result);
22490
+ (_b = callback[action]) === null || _b === void 0 ? void 0 : _b.call(callback, result);
22491
+ };
22492
+ const realtimeRouter = (result, action) => {
22493
+ var _a;
22494
+ if (((_a = result.data) === null || _a === void 0 ? void 0 : _a.commentId) !== commentId)
22495
+ return;
22496
+ router(result, action);
22497
+ };
22498
+ const disposers = [];
22499
+ 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')));
22500
+ runQuery(createQuery(getComment$1, commentId), result => (result.data || result.error) && router(result, 'onFetch'), queryOptions(policy));
22501
+ return () => {
22502
+ log(`observeComment(tmpid: ${timestamp}) > dispose`);
22503
+ disposers.forEach(fn => fn());
22504
+ };
22505
+ };
22506
+
22507
+ /**
22508
+ * ```js
22509
+ * import { onCommentDeleteLocal } from '@amityco/ts-sdk-react-native'
22510
+ * const dispose = onCommentDeleteLocal(comment => {
22511
+ * // ...
22512
+ * })
22513
+ * ```
22514
+ *
22515
+ * Fired when a {@link Amity.InternalComment} has been deleted
22516
+ *
22517
+ * @param callback The function to call when the event was fired
22518
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
22519
+ *
22520
+ * @category Comment Events
22521
+ */
22522
+ const onCommentDeleteLocal = (callback) => createLocalCommentEventSubscriber('local.comment.deleted', callback);
22523
+
22524
+ /**
22525
+ * ```js
22526
+ * import { onLocalCommentReactionAdded } from '@amityco/ts-sdk-react-native'
22527
+ * const dispose = onLocalCommentReactionAdded(comment => {
22528
+ * // ...
22529
+ * })
22530
+ * ```
22531
+ *
22532
+ * Fired when a {@link Amity.InternalComment} has been reacted
22533
+ *
22534
+ * @param callback The function to call when the event was fired
22535
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
22536
+ *
22537
+ * @category Comment Events
22538
+ */
22539
+ const onLocalCommentReactionAdded = (callback) => {
22540
+ const client = getActiveClient();
22541
+ const filter = ({ comment }) => {
22542
+ if (!client.cache) {
22543
+ callback(comment);
22544
+ }
22545
+ else {
22546
+ upsertInCache(['comment', 'get', comment.commentId], comment);
22547
+ callback(commentLinkedObject(comment));
22548
+ }
22549
+ };
22550
+ return createEventSubscriber(client, 'local.comment.addReaction', 'local.comment.addReaction', filter);
22551
+ };
22552
+
22553
+ /**
22554
+ * ```js
22555
+ * import { onLocalCommentReactionRemoved } from '@amityco/ts-sdk-react-native'
22556
+ * const dispose = onLocalCommentReactionRemoved(comment => {
22557
+ * // ...
22558
+ * })
21753
22559
  * ```
21754
22560
  *
21755
- * Observe all mutation on a given {@link Amity.InternalComment}
22561
+ * Fired when a {@link Amity.InternalComment} has been reacted
21756
22562
  *
21757
- * @param commentId the ID of the comment to observe
21758
- * @param callback the function to call when new data are available
21759
- * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the comment
22563
+ * @param callback The function to call when the event was fired
22564
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
21760
22565
  *
21761
- * @category InternalComment Observer
22566
+ * @category Comment Events
21762
22567
  */
21763
- const observeComment = (commentId, callback, policy = 'cache_then_server') => {
21764
- const { log } = getActiveClient();
21765
- const timestamp = Date.now();
21766
- log(`observeComment(tmpid: ${timestamp}) > listen`);
21767
- // wrapper function to make sure
21768
- const router = (result, action) => {
21769
- var _a, _b;
21770
- if (callback instanceof Function)
21771
- return callback(result);
21772
- if (action !== 'onFetch')
21773
- (_a = callback.onEvent) === null || _a === void 0 ? void 0 : _a.call(callback, action, result);
21774
- (_b = callback[action]) === null || _b === void 0 ? void 0 : _b.call(callback, result);
21775
- };
21776
- const realtimeRouter = (result, action) => {
21777
- var _a;
21778
- if (((_a = result.data) === null || _a === void 0 ? void 0 : _a.commentId) !== commentId)
21779
- return;
21780
- router(result, action);
21781
- };
21782
- const disposers = [];
21783
- 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')));
21784
- runQuery(createQuery(getComment$1, commentId), result => (result.data || result.error) && router(result, 'onFetch'), queryOptions(policy));
21785
- return () => {
21786
- log(`observeComment(tmpid: ${timestamp}) > dispose`);
21787
- disposers.forEach(fn => fn());
22568
+ const onLocalCommentReactionRemoved = (callback) => {
22569
+ const client = getActiveClient();
22570
+ const filter = ({ comment }) => {
22571
+ if (!client.cache) {
22572
+ callback(comment);
22573
+ }
22574
+ else {
22575
+ upsertInCache(['comment', 'get', comment.commentId], comment);
22576
+ callback(commentLinkedObject(comment));
22577
+ }
21788
22578
  };
22579
+ return createEventSubscriber(client, 'local.comment.removeReaction', 'local.comment.removeReaction', filter);
21789
22580
  };
21790
22581
 
21791
22582
  /* begin_public_function
@@ -21812,26 +22603,15 @@ const observeComment = (commentId, callback, policy = 'cache_then_server') => {
21812
22603
  */
21813
22604
  const getComment = (commentId, callback) => {
21814
22605
  return liveObject(commentId, callback, 'commentId', getComment$1, [
22606
+ onCommentDeleteLocal,
21815
22607
  onCommentDeleted,
21816
22608
  onCommentFlagged,
21817
22609
  onCommentReactionAdded,
21818
22610
  onCommentReactionRemoved,
21819
22611
  onCommentUnflagged,
21820
22612
  onCommentUpdated,
21821
- (callback) => {
21822
- return onCommentCreated((comment) => {
21823
- if (comment.parentId !== commentId)
21824
- return;
21825
- const cacheParent = pullFromCache([
21826
- 'comment',
21827
- 'get',
21828
- comment.parentId,
21829
- ]);
21830
- if (!(cacheParent === null || cacheParent === void 0 ? void 0 : cacheParent.data))
21831
- return;
21832
- callback(Object.assign(Object.assign({}, cacheParent.data), { childrenNumber: cacheParent.data.childrenNumber + 1, children: [...new Set([...cacheParent.data.children, comment.commentId])] }));
21833
- });
21834
- },
22613
+ onLocalCommentReactionAdded,
22614
+ onLocalCommentReactionRemoved,
21835
22615
  ]);
21836
22616
  };
21837
22617
  /* end_public_function */
@@ -21915,16 +22695,24 @@ class CommentQueryStreamController extends QueryStreamController {
21915
22695
  }
21916
22696
  }
21917
22697
 
21918
- function prepareCommentPayload(commentPayload) {
21919
- const { comments } = commentPayload;
21920
- return Object.assign(Object.assign({}, commentPayload), { comments: comments.map(comment => {
21921
- if (comment.hasOwnProperty('myReactions'))
21922
- return comment;
21923
- // Sometimes `myReactions` field will not come with BE response because that field is empty
21924
- // We need to put it with an empty array manually to make it show up in client side
21925
- return Object.assign({ myReactions: [] }, comment);
21926
- }) });
21927
- }
22698
+ /**
22699
+ * ```js
22700
+ * import { onCommentCreated } from '@amityco/ts-sdk-react-native'
22701
+ * const dispose = onCommentCreated(comment => {
22702
+ * // ...
22703
+ * })
22704
+ * ```
22705
+ *
22706
+ * Fired when a {@link Amity.InternalComment} has been created
22707
+ *
22708
+ * @param callback The function to call when the event was fired
22709
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
22710
+ *
22711
+ * @category Comment Events
22712
+ */
22713
+ const onCommentCreatedLocal = (callback) => {
22714
+ return createLocalCommentEventSubscriber('local.comment.created', callback);
22715
+ };
21928
22716
 
21929
22717
  class CommentLiveCollectionController extends LiveCollectionController {
21930
22718
  constructor(query, callback) {
@@ -21955,6 +22743,8 @@ class CommentLiveCollectionController extends LiveCollectionController {
21955
22743
  }
21956
22744
  startSubscription() {
21957
22745
  return this.queryStreamController.subscribeRTE([
22746
+ { fn: onCommentCreatedLocal, action: EnumCommentActions.OnCommentCreated },
22747
+ { fn: onCommentDeleteLocal, action: EnumCommentActions.OnCommentDeleted },
21958
22748
  { fn: onCommentCreated, action: EnumCommentActions.OnCommentCreated },
21959
22749
  { fn: onCommentUpdated, action: EnumCommentActions.OnCommentUpdated },
21960
22750
  { fn: onCommentDeleted, action: EnumCommentActions.OnCommentDeleted },
@@ -21962,6 +22752,8 @@ class CommentLiveCollectionController extends LiveCollectionController {
21962
22752
  { fn: onCommentUnflagged, action: EnumCommentActions.OnCommentUnflagged },
21963
22753
  { fn: onCommentReactionAdded, action: EnumCommentActions.OnCommentReactionAdded },
21964
22754
  { fn: onCommentReactionRemoved, action: EnumCommentActions.OnCommentReactionRemoved },
22755
+ { fn: onLocalCommentReactionAdded, action: EnumCommentActions.OnCommentReactionAdded },
22756
+ { fn: onLocalCommentReactionRemoved, action: EnumCommentActions.OnCommentReactionRemoved },
21965
22757
  ]);
21966
22758
  }
21967
22759
  notifyChange({ origin, loading, error }) {
@@ -22093,6 +22885,98 @@ var index$6 = /*#__PURE__*/Object.freeze({
22093
22885
  getComments: getComments
22094
22886
  });
22095
22887
 
22888
+ /**
22889
+ * ```js
22890
+ * import { onPostUpdatedLocal } from '@amityco/ts-sdk-react-native'
22891
+ * const dispose = onPostUpdatedLocal(post => {
22892
+ * // ...
22893
+ * })
22894
+ * ```
22895
+ *
22896
+ * Fired when a {@link Amity.InternalPost} has been updated
22897
+ *
22898
+ * @param callback The function to call when the event was fired
22899
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
22900
+ *
22901
+ * @category Post Events
22902
+ */
22903
+ const onPostUpdatedLocal = (callback) => createLocalPostEventSubscriber('local.post.updated', callback);
22904
+
22905
+ /**
22906
+ * ```js
22907
+ * import { onLocalPostReactionAdded } from '@amityco/ts-sdk-react-native'
22908
+ * const dispose = onPostReactionAdded(post => {
22909
+ * // ...
22910
+ * })
22911
+ * ```
22912
+ *
22913
+ * Fired when a {@link Amity.InternalPost} has been reacted
22914
+ *
22915
+ * @param callback The function to call when the event was fired
22916
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
22917
+ *
22918
+ * @category Post Events
22919
+ */
22920
+ const onLocalPostReactionAdded = (callback) => {
22921
+ const client = getActiveClient();
22922
+ const filter = ({ post }) => {
22923
+ if (!client.cache) {
22924
+ callback(post);
22925
+ }
22926
+ else {
22927
+ upsertInCache(['post', 'get', post.postId], post);
22928
+ callback(post);
22929
+ }
22930
+ };
22931
+ return createEventSubscriber(client, 'local.post.addReaction', 'local.post.addReaction', filter);
22932
+ };
22933
+
22934
+ /**
22935
+ * ```js
22936
+ * import { onLocalPostReactionRemoved } from '@amityco/ts-sdk-react-native'
22937
+ * const dispose = onPostReactionRemoved(post => {
22938
+ * // ...
22939
+ * })
22940
+ * ```
22941
+ *
22942
+ * Fired when a {@link Amity.InternalPost} has been reacted
22943
+ *
22944
+ * @param callback The function to call when the event was fired
22945
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
22946
+ *
22947
+ * @category Post Events
22948
+ */
22949
+ const onLocalPostReactionRemoved = (callback) => {
22950
+ const client = getActiveClient();
22951
+ const filter = ({ post }) => {
22952
+ if (!client.cache) {
22953
+ callback(post);
22954
+ }
22955
+ else {
22956
+ upsertInCache(['post', 'get', post.postId], post);
22957
+ callback(post);
22958
+ }
22959
+ };
22960
+ return createEventSubscriber(client, 'local.post.removeReaction', 'local.post.removeReaction', filter);
22961
+ };
22962
+
22963
+ /**
22964
+ * ```js
22965
+ * import { onLocalPostDeleted } from '@amityco/ts-sdk-react-native'
22966
+ * const dispose = onLocalPostDeleted(post => {
22967
+ * // ...
22968
+ * })
22969
+ * ```
22970
+ *
22971
+ * Fired when a {@link Amity.InternalPost} has been deleted
22972
+ *
22973
+ * @param callback The function to call when the event was fired
22974
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
22975
+ *
22976
+ * @category Post Events
22977
+ */
22978
+ const onLocalPostDeleted = (callback) => createLocalPostEventSubscriber('local.post.deleted', callback);
22979
+
22096
22980
  /* begin_public_function
22097
22981
  id: post.get
22098
22982
  */
@@ -22123,6 +23007,8 @@ const getPost$1 = (postId, callback) => {
22123
23007
  return liveObject(postId, responder, 'postId', getPost$2, [
22124
23008
  onPostApproved,
22125
23009
  onPostDeclined,
23010
+ onLocalPostReactionAdded,
23011
+ onLocalPostReactionRemoved,
22126
23012
  (callback) => {
22127
23013
  return onPostDeleted((post) => {
22128
23014
  var _a;
@@ -22157,6 +23043,8 @@ const getPost$1 = (postId, callback) => {
22157
23043
  },
22158
23044
  onPostUnflagged,
22159
23045
  onPostUpdated,
23046
+ onPostUpdatedLocal,
23047
+ onLocalPostDeleted,
22160
23048
  convertEventPayload((callback) => {
22161
23049
  return onCommentCreated(async (comment) => {
22162
23050
  if (comment.referenceId === postId) {
@@ -22278,17 +23166,6 @@ class PostQueryStreamController extends QueryStreamController {
22278
23166
  }
22279
23167
  }
22280
23168
 
22281
- const preparePostPayload = (postPayload) => {
22282
- const { posts } = postPayload;
22283
- const { communities, communityUsers } = convertCommunityPayload({
22284
- communities: postPayload.communities,
22285
- communityUsers: postPayload.communityUsers,
22286
- });
22287
- return Object.assign(Object.assign({}, postPayload), { posts,
22288
- communities,
22289
- communityUsers });
22290
- };
22291
-
22292
23169
  const getPost = async (postId) => {
22293
23170
  const client = getActiveClient();
22294
23171
  client.log('post/getPost', postId);
@@ -22361,6 +23238,7 @@ class PostLiveCollectionController extends LiveCollectionController {
22361
23238
  return this.queryStreamController.subscribeRTE([
22362
23239
  { fn: onPostCreated, action: EnumPostActions.OnPostCreated },
22363
23240
  { fn: onPostUpdated, action: EnumPostActions.OnPostUpdated },
23241
+ { fn: onPostUpdatedLocal, action: EnumPostActions.OnPostUpdated },
22364
23242
  { fn: onPostDeleted, action: EnumPostActions.OnPostDeleted },
22365
23243
  { fn: onPostFlagged, action: EnumPostActions.OnPostFlagged },
22366
23244
  { fn: onPostUnflagged, action: EnumPostActions.OnPostUnflagged },
@@ -22368,6 +23246,9 @@ class PostLiveCollectionController extends LiveCollectionController {
22368
23246
  { fn: onPostDeclined, action: EnumPostActions.OnPostDeclined },
22369
23247
  { fn: onPostReactionAdded, action: EnumPostActions.OnPostReactionAdded },
22370
23248
  { fn: onPostReactionRemoved, action: EnumPostActions.OnPostReactionRemoved },
23249
+ { fn: onLocalPostReactionAdded, action: EnumPostActions.OnPostReactionAdded },
23250
+ { fn: onLocalPostReactionRemoved, action: EnumPostActions.OnPostReactionRemoved },
23251
+ { fn: onLocalPostDeleted, action: EnumPostActions.OnPostDeleted },
22371
23252
  {
22372
23253
  fn: convertEventPayload((callback) => {
22373
23254
  return onCommentCreated(async (comment) => {
@@ -22485,6 +23366,138 @@ const getPosts = (params, callback, config) => {
22485
23366
  };
22486
23367
  /* end_public_function */
22487
23368
 
23369
+ class PinnedPostPaginationController extends PaginationController {
23370
+ async getRequest(queryParams, token) {
23371
+ const params = __rest(queryParams, ["limit"]);
23372
+ const { communityId, placement } = params;
23373
+ const path = placement
23374
+ ? `/api/v1/pinned-posts/communities/${communityId}/${placement}`
23375
+ : `/api/v1/pinned-posts/communities/${communityId}`;
23376
+ const { data: queryResponse } = await this.http.get(path);
23377
+ return queryResponse;
23378
+ }
23379
+ }
23380
+
23381
+ class PinnedPostQueryStreamController extends QueryStreamController {
23382
+ constructor(query, cacheKey, notifyChange, preparePayload) {
23383
+ super(query, cacheKey);
23384
+ this.notifyChange = notifyChange;
23385
+ this.preparePayload = preparePayload;
23386
+ }
23387
+ // eslint-disable-next-line class-methods-use-this
23388
+ async saveToMainDB(response) {
23389
+ const client = getActiveClient();
23390
+ const cachedAt = client.cache && Date.now();
23391
+ if (client.cache) {
23392
+ ingestInCache(response, { cachedAt });
23393
+ }
23394
+ }
23395
+ appendToQueryStream(response, direction, refresh = false) {
23396
+ var _a, _b;
23397
+ if (refresh) {
23398
+ pushToCache(this.cacheKey, {
23399
+ data: response.pins.map(getResolver('pin')),
23400
+ });
23401
+ }
23402
+ else {
23403
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
23404
+ const pinnedPosts = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
23405
+ pushToCache(this.cacheKey, Object.assign(Object.assign({}, collection), { data: [...new Set([...pinnedPosts, ...response.pins.map(getResolver('pin'))])] }));
23406
+ this.notifyChange({
23407
+ origin: "server" /* Amity.LiveDataOrigin.SERVER */,
23408
+ loading: false,
23409
+ });
23410
+ }
23411
+ }
23412
+ }
23413
+
23414
+ class PinnedPostLiveCollectionController extends LiveCollectionController {
23415
+ constructor(query, callback) {
23416
+ const queryStreamId = hash__default["default"](query);
23417
+ const cacheKey = ['pinnedPosts', 'collection', queryStreamId];
23418
+ const paginationController = new PinnedPostPaginationController(query);
23419
+ super(paginationController, queryStreamId, cacheKey, callback);
23420
+ this.query = query;
23421
+ this.queryStreamController = new PinnedPostQueryStreamController(this.query, this.cacheKey, this.notifyChange.bind(this), response => response);
23422
+ this.callback = callback.bind(this);
23423
+ this.loadPage({ initial: true });
23424
+ }
23425
+ setup() {
23426
+ var _a;
23427
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
23428
+ if (!collection) {
23429
+ pushToCache(this.cacheKey, {
23430
+ data: [],
23431
+ params: {},
23432
+ });
23433
+ }
23434
+ }
23435
+ async persistModel(queryPayload) {
23436
+ await this.queryStreamController.saveToMainDB(queryPayload);
23437
+ }
23438
+ persistQueryStream({ response, direction, refresh, }) {
23439
+ this.queryStreamController.appendToQueryStream(response, direction, refresh);
23440
+ }
23441
+ // eslint-disable-next-line class-methods-use-this
23442
+ startSubscription() {
23443
+ return [];
23444
+ }
23445
+ notifyChange({ origin, loading, error }) {
23446
+ var _a, _b;
23447
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
23448
+ if (!collection)
23449
+ return;
23450
+ let data = ((_b = collection.data
23451
+ .map(id => pullFromCache(['pin', 'get', id]))
23452
+ .filter(isNonNullable)
23453
+ .map(({ data }) => data)) !== null && _b !== void 0 ? _b : []).map(LinkedObject.pinnedPost);
23454
+ data = this.applyFilter(data);
23455
+ if (!this.shouldNotify(data) && origin === 'event')
23456
+ return;
23457
+ this.callback({
23458
+ data,
23459
+ loading,
23460
+ error,
23461
+ });
23462
+ }
23463
+ applyFilter(data) {
23464
+ let pinnedPost = data;
23465
+ switch (this.query.sortBy) {
23466
+ case 'lastCreated':
23467
+ pinnedPost = pinnedPost.sort(({ post: postA }, { post: postB }) => sortByLastCreated({ createdAt: postA === null || postA === void 0 ? void 0 : postA.createdAt }, { createdAt: postB === null || postB === void 0 ? void 0 : postB.createdAt }));
23468
+ break;
23469
+ }
23470
+ return pinnedPost;
23471
+ }
23472
+ }
23473
+
23474
+ /**
23475
+ * Get pinned posts for a community
23476
+ *
23477
+ * @param communityId the ID of the community
23478
+ * @param placement the placement of the pinned post ('announcement' or 'default'), or null to fetch all pinned posts
23479
+ * @returns the associated pinned post(s)
23480
+ *
23481
+ * @category Pined Posts Live Collection
23482
+ *
23483
+ */
23484
+ const getPinnedPosts = (params, callback, config) => {
23485
+ const { log, cache } = getActiveClient();
23486
+ if (!cache) {
23487
+ console.log(ENABLE_CACHE_MESSAGE);
23488
+ }
23489
+ const timestamp = Date.now();
23490
+ log(`getPinnedPosts(tmpid: ${timestamp}) > listen`);
23491
+ const pinnedPostLiveCollection = new PinnedPostLiveCollectionController(params, callback);
23492
+ const disposers = pinnedPostLiveCollection.startSubscription();
23493
+ const cacheKey = pinnedPostLiveCollection.getCacheKey();
23494
+ disposers.push(() => dropFromCache(cacheKey));
23495
+ return () => {
23496
+ log(`getPinnedPosts(tmpid: ${timestamp}) > dispose`);
23497
+ disposers.forEach(fn => fn());
23498
+ };
23499
+ };
23500
+
22488
23501
  var index$5 = /*#__PURE__*/Object.freeze({
22489
23502
  __proto__: null,
22490
23503
  getPostByIds: getPostByIds,
@@ -22511,7 +23524,8 @@ var index$5 = /*#__PURE__*/Object.freeze({
22511
23524
  observePosts: observePosts,
22512
23525
  observePost: observePost,
22513
23526
  getPost: getPost$1,
22514
- getPosts: getPosts
23527
+ getPosts: getPosts,
23528
+ getPinnedPosts: getPinnedPosts
22515
23529
  });
22516
23530
 
22517
23531
  /* begin_public_function
@@ -23400,7 +24414,7 @@ var index$3 = /*#__PURE__*/Object.freeze({
23400
24414
  getPoll: getPoll
23401
24415
  });
23402
24416
 
23403
- const privateKey = "-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDHo80SecH7FuF2\nhFYnb+l26/VN8UMLXAQFLnxciNTEwkGVFMpdezlH8rU2HtUJL4RETogbAOLVY0XM\njs6sPn8G1nALmh9qeDpUtVqFOVtBHxEZ910TLOtQiunjqJKO5nWdqZ71EC3OFluR\niGQkO84BiIFbv37ub7xl3S8XarbtKoLcyVpkDHi+1wx1pgCAn6gtBUgckPL5NR8j\nLseabl3HAXQfhTCKo4tmOFM2Dxwl1IUMmIJrJg/aIU/U0tj/1Eoo7mG0JcNWX19l\nW3EecCbi0ncCJOrkUdwlBrcjaMayaX/ubEwyUeTGiLdyc4L3GRLHjyK8xgVNXRMH\nbZWJ2a5NAgMBAAECggEASxuE+35zTFO/XydKgmvIGcWL9FbgMlXb7Vcf0nBoG945\nbiz0NVc2paraIhJXc608xbYF3qLmtAE1MVBI0ORyRdBHNxY024l/6H6SH60Ed+uI\nM4ysp5ourY6Vj+DLwpdRiI9YDjqYAQDIUmhNxJP7XPhOMoZI6st+xZQBM34ic/bv\nAMSJm9OZphSp3+qXVkFZztr2mxD2EZSJJLYxi8BCdgM2qhazalbcJ6zDKHCZWVWm\n8RRxDGldyMb/237JxETzP40tAlzOZDmBAbUgEnurDJ93RVDIE3rbZUshwgeQd18a\nem096mWgvB1AIKYgsTAR3pw+V19YWAjq/glP6fz8wQKBgQD/oQq+ukKF0PRgBeM5\ngeTjSwsdGppQLmf5ndujvoiz/TpdjDEPu6R8kigQr1rG2t4K/yfdZoI8RdmJD1al\n3Q7N9hofooSy4rj6E3txzWZCHJjHad2cnCp/O26HiReGAl7wTcfTmNdiFHhZQzm5\nJBkvWAiwuvQMNfEbnXxw6/vIDwKBgQDH7fX8gsc77JLvAWgp1MaQN/sbqVb6JeT1\nFQfR8E/WFCSmzQBtNzd5KgYuCeelwr/8DyYytvN2BzCYZXp73gI1jF3YlW5jVn74\nOY6TwQ095digwo6Z0yuxopdIOApKgAkL9PRKgNrqAf3NAyMua6lOGifzjDojC3KU\nfylQmxMn4wKBgHp2B9O/H0dEBw5JQ8W0+JX6yWQz7mEjGiR2/1W+XXb8hQ1zr709\nw1r6Gb+EghRpnZ3fBpYGGbYOMFx8wKHM+N6qW3F0ReX8v2juFGE8aRSa5oYBrWzt\nU16Idjbv8hj84cZ1PJmdyvDtpYn9rpWHOZl4rxEbPvbqkIsOMyNVqdT5AoGAOSge\nmwIIU2le2FVeohbibXiToWTYKMuMmURZ5/r72AgKMmWJKbAPe+Q3wBG01/7FRBpQ\noU8Ma0HC8s6QJbliiEyIx9JwrJWd1vkdecBHONrtA4ibm/5zD2WcOllLF+FitLhi\n3qnX6+6F0IaFGFBPJrTzlv0P4dTz/OAdv52V7GECgYEA2TttOKBAqWllgOaZOkql\nLVMJVmgR7s6tLi1+cEP8ZcapV9aRbRzTAKXm4f8AEhtlG9F9kCOvHYCYGi6JaiWJ\nZkHjeex3T+eE6Di6y5Bm/Ift5jtVhJ4jCVwHOKTMej79NPUFTJfv8hCo29haBDv6\nRXFrv+T21KCcw8k3sJeJWWQ=\n-----END PRIVATE KEY-----";
24417
+ const privateKey = "-----BEGIN PRIVATE KEY-----\nMIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQDAARz+hmBgi8pJ\nQb8LeY41gtHhk+ACMwRfhsn7GqpqRQNG2qU0755mzZuVDUqjQMGSo8THJB7O+OJs\nflbZRkFXlFoFOVNw1UpNOgwEQZ6wB9oRwzepTJAfF1sVhm/o/ixvXh1zDFNDy6yZ\npXyiiJHUVxqyjllZhxnwdvjoVtDs6hW6awG09bB9nh/TTejlUKXoAgzqVwu/1QMu\nUVViET495elEe19aUarEy+oL2iKeXCEvqda/pWNBdbieFyJvvZ08HN8dPuT88wq2\njZLEAth1vrwQ2IAa4ktaLcBQdLJgIkrbDvAiVZ8lQAjS/bq5vXQikTGvoPlC5bbn\nvuOM/3eLAgMBAAECggEAVZ+peHAghq2QVj71nX5lxsNCKaCyYwixSJBpfouTt7Rz\nE6PpzMOXFi1W1o+I22jDakuSM2SOQKqI/u0QefB0r0O/KVk5NrZHXk0mkrdYtxOp\nUgaGyf8UvmjB+8VqHrNKyZdk9qtmbnNj01kTTcAtmE4H39zPR7eR/8Rul94vaZbs\nwCnKJS3mLT3JxyGug6lxanveKkjG+CKC1nJQYWaxCJxaFSzbwXQPvDhB+TvrIbee\npd5v4EAyEJohpr+T9oDGGJkb/KARBZCtwLyB976PKJwwBA8MRVL1i5QwawuMiMq5\nUtnOnbGKtCeFzaLbNU0Qi8bqyims84EQxC6DOu1fkQKBgQDdvsoBsEhsOXV7hlIJ\naEd0eSJZVkdqimxH8uGoMM2FeNaOrcB6yBXqTSP0R3OIyf8eaY6yjRvP30ZNXcll\n/gD3O1Mu6YmWQdt1W2WA6pKOsUuPXasf0pdOF7IiFZKlSabz5YHXFqwVuqm8loaj\nsXel3YWqPVdHiankE7tz+3ssnQKBgQDdqi4TNdD1MdEpihx19jr0QjUiXW3939FK\nqp30HESPEGDGQzXdmJgif9HhZb+cJSuWaHEbjgBrYahvgCF+y6LbEpOD+D/dmT+s\nDEAQaR84sah6dokwPjV8fjBSrcVFjCS+doxv0d3p/9OUEeyUhFrY03nxtIEYkLIE\n/Zvn37b4RwKBgQCLENVFe9XfsaVhQ5r9dV2iyTlmh7qgMZG5CbTFs12hQGhm8McO\n+Z7s41YSJCFr/yq1WwP4LJDtrBw99vyQr1zRsG35tNLp3gGRNzGQSQyC2uQFVHw2\np+7mNewsfhUK/gbrXNsyFnDz6635rPlhfbII3sWuP2wWXFqkxE9CbMwR7QKBgQC6\nawDMzxmo2/iYArrkyevSuEuPVxvFwpF1RgAI6C0QVCnPE38dmdN4UB7mfHekje4W\nVEercMURidPp0cxZolCYBQtilUjAyL0vqC3In1/Ogjq6oy3FEMxSop1pKxMY5j+Q\nnoqFD+6deLUrddeNH7J3X4LSr4dSbX4JjG+tlgt+yQKBgQCuwTL4hA6KqeInQ0Ta\n9VQX5Qr8hFlqJz1gpymi/k63tW/Ob8yedbg3WWNWyShwRMFYyY9S81ITFWM95uL6\nvF3x9rmRjwElJw9PMwVu6dmf/CO0Z1wzXSp2VVD12gbrUD/0/d7MUoJ9LgC8X8f/\nn0txLHYGHbx+nf95+JUg6lV3hg==\n-----END PRIVATE KEY-----";
23404
24418
  /*
23405
24419
  * The crypto algorithm used for importing key and signing string
23406
24420
  */