@amityco/ts-sdk 7.4.1-d23fab2f.0 → 7.4.1-fd0f791a.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 (188) hide show
  1. package/dist/@types/core/events.d.ts +7 -3
  2. package/dist/@types/core/events.d.ts.map +1 -1
  3. package/dist/@types/core/model.d.ts +2 -0
  4. package/dist/@types/core/model.d.ts.map +1 -1
  5. package/dist/@types/core/payload.d.ts +30 -1
  6. package/dist/@types/core/payload.d.ts.map +1 -1
  7. package/dist/@types/domains/community.d.ts +32 -2
  8. package/dist/@types/domains/community.d.ts.map +1 -1
  9. package/dist/@types/domains/invitation.d.ts +48 -3
  10. package/dist/@types/domains/invitation.d.ts.map +1 -1
  11. package/dist/@types/domains/joinRequest.d.ts +53 -0
  12. package/dist/@types/domains/joinRequest.d.ts.map +1 -0
  13. package/dist/@types/index.d.ts +1 -0
  14. package/dist/@types/index.d.ts.map +1 -1
  15. package/dist/communityRepository/api/getCommunities.d.ts +1 -1
  16. package/dist/communityRepository/api/getCommunities.d.ts.map +1 -1
  17. package/dist/communityRepository/api/getCommunity.d.ts +1 -1
  18. package/dist/communityRepository/api/getCommunity.d.ts.map +1 -1
  19. package/dist/communityRepository/api/getRecommendedCommunities.d.ts +3 -1
  20. package/dist/communityRepository/api/getRecommendedCommunities.d.ts.map +1 -1
  21. package/dist/communityRepository/api/getTrendingCommunities.d.ts +3 -1
  22. package/dist/communityRepository/api/getTrendingCommunities.d.ts.map +1 -1
  23. package/dist/communityRepository/api/joinCommunity.d.ts +3 -0
  24. package/dist/communityRepository/api/joinCommunity.d.ts.map +1 -1
  25. package/dist/communityRepository/api/updateCommunity.d.ts +2 -2
  26. package/dist/communityRepository/api/updateCommunity.d.ts.map +1 -1
  27. package/dist/communityRepository/internalAPI/getMyJoinRequest.d.ts +16 -0
  28. package/dist/communityRepository/internalAPI/getMyJoinRequest.d.ts.map +1 -0
  29. package/dist/communityRepository/internalAPI/joinCommunity.d.ts +16 -0
  30. package/dist/communityRepository/internalAPI/joinCommunity.d.ts.map +1 -0
  31. package/dist/communityRepository/joinRequest/events/index.d.ts +4 -0
  32. package/dist/communityRepository/joinRequest/events/index.d.ts.map +1 -0
  33. package/dist/communityRepository/joinRequest/events/onJoinRequestCreated.d.ts +17 -0
  34. package/dist/communityRepository/joinRequest/events/onJoinRequestCreated.d.ts.map +1 -0
  35. package/dist/communityRepository/joinRequest/events/onJoinRequestDeleted.d.ts +17 -0
  36. package/dist/communityRepository/joinRequest/events/onJoinRequestDeleted.d.ts.map +1 -0
  37. package/dist/communityRepository/joinRequest/events/onJoinRequestUpdated.d.ts +17 -0
  38. package/dist/communityRepository/joinRequest/events/onJoinRequestUpdated.d.ts.map +1 -0
  39. package/dist/communityRepository/joinRequest/internalAPI/approveJoinRequest.d.ts +16 -0
  40. package/dist/communityRepository/joinRequest/internalAPI/approveJoinRequest.d.ts.map +1 -0
  41. package/dist/communityRepository/joinRequest/internalAPI/cancelJoinRequest.d.ts +16 -0
  42. package/dist/communityRepository/joinRequest/internalAPI/cancelJoinRequest.d.ts.map +1 -0
  43. package/dist/communityRepository/joinRequest/internalAPI/rejectJoinRequest.d.ts +16 -0
  44. package/dist/communityRepository/joinRequest/internalAPI/rejectJoinRequest.d.ts.map +1 -0
  45. package/dist/communityRepository/observers/getJoinRequests/JoinRequestsLiveCollectionController.d.ts +14 -0
  46. package/dist/communityRepository/observers/getJoinRequests/JoinRequestsLiveCollectionController.d.ts.map +1 -0
  47. package/dist/communityRepository/observers/getJoinRequests/JoinRequestsPaginationController.d.ts +9 -0
  48. package/dist/communityRepository/observers/getJoinRequests/JoinRequestsPaginationController.d.ts.map +1 -0
  49. package/dist/communityRepository/observers/getJoinRequests/JoinRequestsQueryStreamController.d.ts +15 -0
  50. package/dist/communityRepository/observers/getJoinRequests/JoinRequestsQueryStreamController.d.ts.map +1 -0
  51. package/dist/communityRepository/observers/getJoinRequests/enum.d.ts +6 -0
  52. package/dist/communityRepository/observers/getJoinRequests/enum.d.ts.map +1 -0
  53. package/dist/communityRepository/observers/getJoinRequests.d.ts +12 -0
  54. package/dist/communityRepository/observers/getJoinRequests.d.ts.map +1 -0
  55. package/dist/communityRepository/observers/getRecommendedCommunities/RecommendedCommunitiesLiveCollectionController.d.ts.map +1 -1
  56. package/dist/communityRepository/observers/getTrendingCommunities/TrendingCommunitiesLiveCollectionController.d.ts.map +1 -1
  57. package/dist/communityRepository/observers/searchCommunities/SearchCommunitiesPaginationController.d.ts.map +1 -1
  58. package/dist/communityRepository/utils/payload.d.ts +1 -0
  59. package/dist/communityRepository/utils/payload.d.ts.map +1 -1
  60. package/dist/core/events.d.ts +3 -3
  61. package/dist/core/events.d.ts.map +1 -1
  62. package/dist/core/model/idResolvers.d.ts.map +1 -1
  63. package/dist/core/model/index.d.ts.map +1 -1
  64. package/dist/index.cjs.js +2608 -1576
  65. package/dist/index.esm.js +2432 -1400
  66. package/dist/index.umd.js +4 -4
  67. package/dist/invitationRepository/events/index.d.ts +2 -0
  68. package/dist/invitationRepository/events/index.d.ts.map +1 -1
  69. package/dist/invitationRepository/events/onLocalInvitationCreated.d.ts +1 -1
  70. package/dist/invitationRepository/events/onLocalInvitationCreated.d.ts.map +1 -1
  71. package/dist/invitationRepository/events/onLocalInvitationDeleted.d.ts +1 -1
  72. package/dist/invitationRepository/events/onLocalInvitationDeleted.d.ts.map +1 -1
  73. package/dist/invitationRepository/events/onLocalInvitationUpdated.d.ts +1 -1
  74. package/dist/invitationRepository/events/onLocalInvitationUpdated.d.ts.map +1 -1
  75. package/dist/invitationRepository/index.d.ts +1 -0
  76. package/dist/invitationRepository/index.d.ts.map +1 -1
  77. package/dist/invitationRepository/internalApi/createInvitations.d.ts.map +1 -1
  78. package/dist/invitationRepository/internalApi/getInvitation.d.ts +17 -0
  79. package/dist/invitationRepository/internalApi/getInvitation.d.ts.map +1 -0
  80. package/dist/invitationRepository/observers/getInvitations/InvitationsLiveCollectionController.d.ts +14 -0
  81. package/dist/invitationRepository/observers/getInvitations/InvitationsLiveCollectionController.d.ts.map +1 -0
  82. package/dist/invitationRepository/observers/getInvitations/InvitationsPaginationController.d.ts +5 -0
  83. package/dist/invitationRepository/observers/getInvitations/InvitationsPaginationController.d.ts.map +1 -0
  84. package/dist/invitationRepository/observers/getInvitations/InvitationsQueryStreamController.d.ts +15 -0
  85. package/dist/invitationRepository/observers/getInvitations/InvitationsQueryStreamController.d.ts.map +1 -0
  86. package/dist/invitationRepository/observers/getInvitations/enums.d.ts +6 -0
  87. package/dist/invitationRepository/observers/getInvitations/enums.d.ts.map +1 -0
  88. package/dist/invitationRepository/observers/getInvitations.d.ts +12 -0
  89. package/dist/invitationRepository/observers/getInvitations.d.ts.map +1 -0
  90. package/dist/invitationRepository/observers/getMyCommunityInvitations.d.ts +12 -0
  91. package/dist/invitationRepository/observers/getMyCommunityInvitations.d.ts.map +1 -0
  92. package/dist/invitationRepository/observers/getMyInvitations/MyInvitationsLiveCollectionController.d.ts +14 -0
  93. package/dist/invitationRepository/observers/getMyInvitations/MyInvitationsLiveCollectionController.d.ts.map +1 -0
  94. package/dist/invitationRepository/observers/getMyInvitations/MyInvitationsPaginationController.d.ts +5 -0
  95. package/dist/invitationRepository/observers/getMyInvitations/MyInvitationsPaginationController.d.ts.map +1 -0
  96. package/dist/invitationRepository/observers/getMyInvitations/MyInvitationsQueryStreamController.d.ts +15 -0
  97. package/dist/invitationRepository/observers/getMyInvitations/MyInvitationsQueryStreamController.d.ts.map +1 -0
  98. package/dist/invitationRepository/observers/index.d.ts +2 -0
  99. package/dist/invitationRepository/observers/index.d.ts.map +1 -0
  100. package/dist/invitationRepository/utils/convertRawInvitationToInternalInvitation.d.ts +2 -0
  101. package/dist/invitationRepository/utils/convertRawInvitationToInternalInvitation.d.ts.map +1 -0
  102. package/dist/invitationRepository/utils/index.d.ts +2 -0
  103. package/dist/invitationRepository/utils/index.d.ts.map +1 -0
  104. package/dist/invitationRepository/utils/prepareInvitationPayload.d.ts +2 -0
  105. package/dist/invitationRepository/utils/prepareInvitationPayload.d.ts.map +1 -0
  106. package/dist/invitationRepository/utils/prepareMyInvitationsPayload.d.ts +2 -0
  107. package/dist/invitationRepository/utils/prepareMyInvitationsPayload.d.ts.map +1 -0
  108. package/dist/postRepository/observers/getGlobalPinnedPosts/GlobalPinnedPostQueryStreamController.d.ts.map +1 -1
  109. package/dist/postRepository/observers/getPinnedPosts/PinnedPostQueryStreamController.d.ts.map +1 -1
  110. package/dist/subChannelRepository/utils/prepareSubChannelPayload.d.ts.map +1 -1
  111. package/dist/utils/linkedObject/communityLinkedObject.d.ts +1 -1
  112. package/dist/utils/linkedObject/communityLinkedObject.d.ts.map +1 -1
  113. package/dist/utils/linkedObject/index.d.ts +3 -2
  114. package/dist/utils/linkedObject/index.d.ts.map +1 -1
  115. package/dist/utils/linkedObject/invitationLinkedObject.d.ts +1 -1
  116. package/dist/utils/linkedObject/invitationLinkedObject.d.ts.map +1 -1
  117. package/dist/utils/linkedObject/joinRequestLinkedObject.d.ts +2 -0
  118. package/dist/utils/linkedObject/joinRequestLinkedObject.d.ts.map +1 -0
  119. package/dist/utils/tests/dummy/comment.d.ts +1 -1
  120. package/package.json +1 -1
  121. package/src/@types/core/events.ts +10 -4
  122. package/src/@types/core/model.ts +3 -0
  123. package/src/@types/core/payload.ts +39 -1
  124. package/src/@types/domains/community.ts +45 -2
  125. package/src/@types/domains/invitation.ts +67 -3
  126. package/src/@types/domains/joinRequest.ts +66 -0
  127. package/src/@types/index.ts +1 -0
  128. package/src/communityRepository/api/getCommunities.ts +5 -1
  129. package/src/communityRepository/api/getCommunity.ts +9 -1
  130. package/src/communityRepository/api/getRecommendedCommunities.ts +9 -3
  131. package/src/communityRepository/api/getTrendingCommunities.ts +9 -3
  132. package/src/communityRepository/api/joinCommunity.ts +4 -1
  133. package/src/communityRepository/api/updateCommunity.ts +9 -2
  134. package/src/communityRepository/internalAPI/getMyJoinRequest.ts +43 -0
  135. package/src/communityRepository/internalAPI/joinCommunity.ts +51 -0
  136. package/src/communityRepository/joinRequest/events/index.ts +3 -0
  137. package/src/communityRepository/joinRequest/events/onJoinRequestCreated.ts +33 -0
  138. package/src/communityRepository/joinRequest/events/onJoinRequestDeleted.ts +33 -0
  139. package/src/communityRepository/joinRequest/events/onJoinRequestUpdated.ts +33 -0
  140. package/src/communityRepository/joinRequest/internalAPI/approveJoinRequest.ts +52 -0
  141. package/src/communityRepository/joinRequest/internalAPI/cancelJoinRequest.ts +46 -0
  142. package/src/communityRepository/joinRequest/internalAPI/rejectJoinRequest.ts +52 -0
  143. package/src/communityRepository/observers/getJoinRequests/JoinRequestsLiveCollectionController.ts +126 -0
  144. package/src/communityRepository/observers/getJoinRequests/JoinRequestsPaginationController.ts +26 -0
  145. package/src/communityRepository/observers/getJoinRequests/JoinRequestsQueryStreamController.ts +108 -0
  146. package/src/communityRepository/observers/getJoinRequests/enum.ts +5 -0
  147. package/src/communityRepository/observers/getJoinRequests.ts +44 -0
  148. package/src/communityRepository/observers/getRecommendedCommunities/RecommendedCommunitiesLiveCollectionController.ts +2 -1
  149. package/src/communityRepository/observers/getTrendingCommunities/TrendingCommunitiesLiveCollectionController.ts +2 -1
  150. package/src/communityRepository/observers/searchCommunities/SearchCommunitiesPaginationController.ts +1 -0
  151. package/src/communityRepository/utils/communityWithMembership.ts +1 -1
  152. package/src/communityRepository/utils/payload.ts +27 -1
  153. package/src/core/liveCollection/PaginationController.ts +1 -1
  154. package/src/core/liveCollection/PaginationNoPageController.ts +1 -1
  155. package/src/core/model/idResolvers.ts +1 -0
  156. package/src/core/model/index.ts +1 -0
  157. package/src/invitationRepository/events/index.ts +2 -0
  158. package/src/invitationRepository/events/onLocalInvitationCreated.ts +1 -1
  159. package/src/invitationRepository/events/onLocalInvitationDeleted.ts +1 -1
  160. package/src/invitationRepository/events/onLocalInvitationUpdated.ts +1 -1
  161. package/src/invitationRepository/index.ts +1 -0
  162. package/src/invitationRepository/internalApi/acceptInvitation.ts +1 -1
  163. package/src/invitationRepository/internalApi/cancelInvitation.ts +1 -1
  164. package/src/invitationRepository/internalApi/createInvitations.ts +8 -2
  165. package/src/invitationRepository/internalApi/getInvitation.ts +47 -0
  166. package/src/invitationRepository/internalApi/rejectInvitation.ts +1 -1
  167. package/src/invitationRepository/observers/getInvitations/InvitationsLiveCollectionController.ts +148 -0
  168. package/src/invitationRepository/observers/getInvitations/InvitationsPaginationController.ts +19 -0
  169. package/src/invitationRepository/observers/getInvitations/InvitationsQueryStreamController.ts +97 -0
  170. package/src/invitationRepository/observers/getInvitations/enums.ts +5 -0
  171. package/src/invitationRepository/observers/getInvitations.ts +44 -0
  172. package/src/invitationRepository/observers/getMyCommunityInvitations.ts +48 -0
  173. package/src/invitationRepository/observers/getMyInvitations/MyInvitationsLiveCollectionController.ts +148 -0
  174. package/src/invitationRepository/observers/getMyInvitations/MyInvitationsPaginationController.ts +22 -0
  175. package/src/invitationRepository/observers/getMyInvitations/MyInvitationsQueryStreamController.ts +105 -0
  176. package/src/invitationRepository/observers/index.ts +1 -0
  177. package/src/invitationRepository/utils/convertRawInvitationToInternalInvitation.ts +8 -0
  178. package/src/invitationRepository/utils/index.ts +1 -0
  179. package/src/invitationRepository/utils/prepareInvitationPayload.ts +12 -0
  180. package/src/invitationRepository/utils/prepareMyInvitationsPayload.ts +12 -0
  181. package/src/messagePreview/utils/getChannelMessagePreviewWithUser.ts +3 -3
  182. package/src/postRepository/observers/getGlobalPinnedPosts/GlobalPinnedPostQueryStreamController.ts +7 -1
  183. package/src/postRepository/observers/getPinnedPosts/PinnedPostQueryStreamController.ts +7 -1
  184. package/src/subChannelRepository/utils/prepareSubChannelPayload.ts +4 -0
  185. package/src/utils/linkedObject/communityLinkedObject.ts +43 -1
  186. package/src/utils/linkedObject/index.ts +2 -0
  187. package/src/utils/linkedObject/invitationLinkedObject.ts +25 -1
  188. package/src/utils/linkedObject/joinRequestLinkedObject.ts +31 -0
package/dist/index.cjs.js CHANGED
@@ -129,7 +129,25 @@ exports.InvitationStatusEnum = void 0;
129
129
  InvitationStatusEnum["Approved"] = "approved";
130
130
  InvitationStatusEnum["Rejected"] = "rejected";
131
131
  InvitationStatusEnum["Cancelled"] = "cancelled";
132
- })(exports.InvitationStatusEnum || (exports.InvitationStatusEnum = {}));
132
+ })(exports.InvitationStatusEnum || (exports.InvitationStatusEnum = {}));
133
+ exports.InvitationSortByEnum = void 0;
134
+ (function (InvitationSortByEnum) {
135
+ InvitationSortByEnum["FirstCreated"] = "firstCreated";
136
+ InvitationSortByEnum["LastCreated"] = "lastCreated";
137
+ })(exports.InvitationSortByEnum || (exports.InvitationSortByEnum = {}));
138
+
139
+ exports.JoinRequestStatusEnum = void 0;
140
+ (function (JoinRequestStatusEnum) {
141
+ JoinRequestStatusEnum["Pending"] = "pending";
142
+ JoinRequestStatusEnum["Approved"] = "approved";
143
+ JoinRequestStatusEnum["Rejected"] = "rejected";
144
+ JoinRequestStatusEnum["Cancelled"] = "cancelled";
145
+ })(exports.JoinRequestStatusEnum || (exports.JoinRequestStatusEnum = {}));
146
+ exports.JoinResultStatusEnum = void 0;
147
+ (function (JoinResultStatusEnum) {
148
+ JoinResultStatusEnum["Success"] = "success";
149
+ JoinResultStatusEnum["Pending"] = "pending";
150
+ })(exports.JoinResultStatusEnum || (exports.JoinResultStatusEnum = {}));
133
151
 
134
152
  function getVersion() {
135
153
  try {
@@ -578,6 +596,7 @@ const idResolvers = {
578
596
  notificationTrayItem: ({ _id }) => _id,
579
597
  notificationTraySeen: ({ userId }) => userId,
580
598
  invitation: ({ _id }) => _id,
599
+ joinRequest: ({ joinRequestId }) => joinRequestId,
581
600
  };
582
601
  /**
583
602
  * Retrieve the id resolver matching a domain name
@@ -631,6 +650,7 @@ const PAYLOAD2MODEL = {
631
650
  pins: 'pin',
632
651
  notificationTrayItems: 'notificationTrayItem',
633
652
  invitations: 'invitation',
653
+ joinRequests: 'joinRequest',
634
654
  };
635
655
  /** hidden */
636
656
  const isOutdated = (prevData, nextData) => {
@@ -4898,6 +4918,1103 @@ const getChannelMessagePreview = (channelId) => {
4898
4918
  return ((_b = (_a = pullFromCache(['messagePreviewChannel', 'get', channelId])) === null || _a === void 0 ? void 0 : _a.data) !== null && _b !== void 0 ? _b : null);
4899
4919
  };
4900
4920
 
4921
+ const userLinkedObject = (user) => {
4922
+ return Object.assign(Object.assign({}, user), { get avatar() {
4923
+ var _a;
4924
+ if (!user.avatarFileId)
4925
+ return undefined;
4926
+ const avatar = (_a = pullFromCache([
4927
+ 'file',
4928
+ 'get',
4929
+ `${user.avatarFileId}`,
4930
+ ])) === null || _a === void 0 ? void 0 : _a.data;
4931
+ return avatar;
4932
+ } });
4933
+ };
4934
+
4935
+ const getChannelMessagePreviewWithUser = (channel) => {
4936
+ var _a;
4937
+ const messagePreview = channel.messagePreviewId
4938
+ ? getChannelMessagePreview(channel.channelId)
4939
+ : null;
4940
+ const internalUser = (_a = pullFromCache([
4941
+ 'user',
4942
+ 'get',
4943
+ messagePreview === null || messagePreview === void 0 ? void 0 : messagePreview.creatorId,
4944
+ ])) === null || _a === void 0 ? void 0 : _a.data;
4945
+ const messagePreviewWithUser = messagePreview
4946
+ ? Object.assign(Object.assign({}, messagePreview), { user: internalUser ? userLinkedObject(internalUser) : undefined }) : null;
4947
+ return Object.assign(Object.assign({}, channel), { messagePreview: messagePreviewWithUser });
4948
+ };
4949
+
4950
+ const updateChannelMessagePreviewCache = (rawPayload) => {
4951
+ var _a, _b;
4952
+ const withMessageFeedInfo = (messagePreview) => {
4953
+ var _a;
4954
+ const messageFeedInfo = (_a = rawPayload.messageFeedsInfo) === null || _a === void 0 ? void 0 : _a.find(messageFeed => {
4955
+ return messageFeed.messageFeedId === messagePreview.messageFeedId;
4956
+ });
4957
+ const { channelPublicId: channelId, messageFeedId: subChannelId, data, dataType, isDeleted, segment, creatorPublicId: creatorId, createdAt, updatedAt, } = messagePreview;
4958
+ return {
4959
+ channelId,
4960
+ subChannelId,
4961
+ data,
4962
+ dataType,
4963
+ isDeleted,
4964
+ segment,
4965
+ creatorId,
4966
+ createdAt,
4967
+ updatedAt,
4968
+ subChannelName: messageFeedInfo === null || messageFeedInfo === void 0 ? void 0 : messageFeedInfo.name,
4969
+ messagePreviewId: messageFeedInfo === null || messageFeedInfo === void 0 ? void 0 : messageFeedInfo.messagePreviewId,
4970
+ subChannelUpdatedAt: messageFeedInfo === null || messageFeedInfo === void 0 ? void 0 : messageFeedInfo.updatedAt,
4971
+ };
4972
+ };
4973
+ const newData = {
4974
+ messagePreviewChannel: (_b = (_a = rawPayload.messagePreviews) === null || _a === void 0 ? void 0 : _a.map(messagePreview => withMessageFeedInfo(messagePreview))) !== null && _b !== void 0 ? _b : [],
4975
+ };
4976
+ ingestInCache(newData);
4977
+ };
4978
+
4979
+ const getSubChannelMessagePreview = (subChannelId) => {
4980
+ var _a, _b;
4981
+ return ((_b = (_a = pullFromCache(['messagePreviewSubChannel', 'get', subChannelId])) === null || _a === void 0 ? void 0 : _a.data) !== null && _b !== void 0 ? _b : null);
4982
+ };
4983
+
4984
+ const getSubChannelMessagePreviewWithUser = (subChannel) => {
4985
+ var _a;
4986
+ const messagePreview = subChannel.messagePreviewId
4987
+ ? getSubChannelMessagePreview(subChannel.subChannelId)
4988
+ : null;
4989
+ const messagePreviewWithUser = messagePreview
4990
+ ? Object.assign(Object.assign({}, messagePreview), { user: (_a = pullFromCache(['user', 'get', messagePreview === null || messagePreview === void 0 ? void 0 : messagePreview.creatorId])) === null || _a === void 0 ? void 0 : _a.data }) : null;
4991
+ return Object.assign(Object.assign({}, subChannel), { messagePreview: messagePreviewWithUser });
4992
+ };
4993
+
4994
+ const updateSubChannelMessagePreviewCache = (rawPayload) => {
4995
+ var _a, _b;
4996
+ const withMessageFeedInfo = (messagePreview) => {
4997
+ var _a;
4998
+ const messageFeedInfo = (_a = rawPayload.messageFeeds) === null || _a === void 0 ? void 0 : _a.find(messageFeed => {
4999
+ return messageFeed.messageFeedId === messagePreview.messageFeedId;
5000
+ });
5001
+ const { channelPublicId: channelId, messageFeedId: subChannelId, messageId: messagePreviewId, creatorPublicId: creatorId, data, dataType, isDeleted, segment, createdAt, updatedAt, } = messagePreview;
5002
+ return {
5003
+ messagePreviewId,
5004
+ channelId,
5005
+ subChannelId,
5006
+ data,
5007
+ dataType,
5008
+ isDeleted,
5009
+ segment,
5010
+ creatorId,
5011
+ createdAt,
5012
+ updatedAt,
5013
+ subChannelName: messageFeedInfo === null || messageFeedInfo === void 0 ? void 0 : messageFeedInfo.name,
5014
+ subChannelUpdatedAt: messageFeedInfo === null || messageFeedInfo === void 0 ? void 0 : messageFeedInfo.updatedAt,
5015
+ };
5016
+ };
5017
+ const newData = {
5018
+ messagePreviewSubChannel: (_b = (_a = rawPayload.messages) === null || _a === void 0 ? void 0 : _a.map(messagePreview => withMessageFeedInfo(messagePreview))) !== null && _b !== void 0 ? _b : [],
5019
+ };
5020
+ ingestInCache(newData);
5021
+ };
5022
+
5023
+ /**
5024
+ * ```js
5025
+ * import { shallowClone } from '~/utils/shallowClone'
5026
+ * const newObj = shallowClone(obj)
5027
+ * ```
5028
+ *
5029
+ * Clone an object with same prototype and properties
5030
+ *
5031
+ * @param obj the object to clone
5032
+ * @returns new object with same prototype and properties
5033
+ *
5034
+ * @category utility
5035
+ * @private
5036
+ */
5037
+ function shallowClone(source, target) {
5038
+ return Object.create(Object.getPrototypeOf(source), Object.assign(Object.assign({}, Object.getOwnPropertyDescriptors(source)), Object.getOwnPropertyDescriptors(target)));
5039
+ }
5040
+
5041
+ function updateSubChannelCache(subChannelId, subChannel, params) {
5042
+ pushToCache(['subChannel', 'get', subChannelId],
5043
+ // eslint-disable-next-line prefer-object-spread
5044
+ shallowClone(subChannel, params));
5045
+ }
5046
+
5047
+ /**
5048
+ * ```js
5049
+ * import { isInTombstone } from '@amityco/ts-sdk'
5050
+ * const user = isInTombstone(["message", "messageId"])
5051
+ * ```
5052
+ *
5053
+ * Checks if the {@link Amity.TombstoneCacheOptions} exists
5054
+ * in cache and it's not expired means it's in tombstone
5055
+ * and we throw an Error
5056
+ *
5057
+ * @param model the model to check
5058
+ * @param modelId the object id to check
5059
+ * @returns the matching cache entry, or undefined.
5060
+ *
5061
+ * @category Cache API
5062
+ */
5063
+ const isInTombstone = (model, modelId) => {
5064
+ const { log, cache } = getActiveClient();
5065
+ const key = [model, CACHE_KEY_TOMBSTONE, modelId];
5066
+ if (!cache)
5067
+ return;
5068
+ log('cache/api/isInTombstone', key);
5069
+ const isInTombstone = pullFromCache(key);
5070
+ const { lifeSpan } = queryOptions('cache_then_server', CACHE_LIFESPAN_TOMBSTONE);
5071
+ if (isInTombstone && isFresh(isInTombstone.data, lifeSpan)) {
5072
+ throw new ASCApiError('Item not found!', 400400 /* Amity.ServerError.ITEM_NOT_FOUND */, "error" /* Amity.ErrorLevel.ERROR */);
5073
+ }
5074
+ };
5075
+
5076
+ /**
5077
+ * ```js
5078
+ * import { getMessageMarkers } from '@amityco/ts-sdk'
5079
+ * const messageMarkers = await getMessageMarkers(['sch1', 'sch2'])
5080
+ * ```
5081
+ *
5082
+ * Fetches a list of {@link Amity.MessageMarker} by messageIds
5083
+ *
5084
+ * @param messageIds the feed IDs of the {@link Amity.RawMessage} marker to fetch
5085
+ * @returns A list of {@link Amity.MessageMarker} by messageIds
5086
+ *
5087
+ * @category Channel API
5088
+ * @async
5089
+ * @private
5090
+ */
5091
+ const getMessageMarkers = async (messageIds) => {
5092
+ const client = getActiveClient();
5093
+ client.log('channel/getMessageMarkers', messageIds);
5094
+ const { data: queryPayload } = await client.http.get(`/api/v1/markers/messages`, {
5095
+ params: {
5096
+ messageIds,
5097
+ },
5098
+ });
5099
+ const { contentMarkers, feedMarkers, userMarkers } = queryPayload;
5100
+ const cachedAt = client.cache && Date.now();
5101
+ if (client.cache)
5102
+ ingestInCache({ contentMarkers, feedMarkers, userMarkers }, { cachedAt });
5103
+ fireEvent('local.feedMarker.fetched', { feedMarkers });
5104
+ fireEvent('local.messageMarker.fetched', { contentMarkers });
5105
+ fireEvent('local.userMarker.fetched', { userMarkers });
5106
+ return { data: contentMarkers, cachedAt };
5107
+ };
5108
+
5109
+ const reCalculateChannelUnreadInfo = (channelId) => {
5110
+ var _a;
5111
+ const cacheKeyChannelUnread = ['channelUnreadInfo', 'get', channelId];
5112
+ const cacheChannelUnreadInfo = (_a = pullFromCache(cacheKeyChannelUnread)) === null || _a === void 0 ? void 0 : _a.data;
5113
+ const cacheKeySubChannelUnread = ['subChannelUnreadInfo', 'get'];
5114
+ const cachedSubChannelUnreadInfo = queryCache(cacheKeySubChannelUnread);
5115
+ let channelUnreads = 0;
5116
+ let isMentioned = false;
5117
+ if (cachedSubChannelUnreadInfo && (cachedSubChannelUnreadInfo === null || cachedSubChannelUnreadInfo === void 0 ? void 0 : cachedSubChannelUnreadInfo.length) > 0) {
5118
+ const subChannelUnreadsInfo = cachedSubChannelUnreadInfo === null || cachedSubChannelUnreadInfo === void 0 ? void 0 : cachedSubChannelUnreadInfo.filter(({ data }) => {
5119
+ return data.channelId === channelId && !data.isDeleted;
5120
+ });
5121
+ channelUnreads = subChannelUnreadsInfo
5122
+ .map(({ data }) => data.unreadCount)
5123
+ .reduce((acc, cur) => acc + cur, 0);
5124
+ isMentioned = subChannelUnreadsInfo.some(({ data }) => data.isMentioned);
5125
+ }
5126
+ const channelUnreadInfo = Object.assign(Object.assign({}, (cacheChannelUnreadInfo !== null && cacheChannelUnreadInfo !== void 0 ? cacheChannelUnreadInfo : {
5127
+ channelId,
5128
+ createdAt: new Date().toISOString(),
5129
+ })), { updatedAt: new Date().toISOString(), unreadCount: channelUnreads, isMentioned });
5130
+ pushToCache(cacheKeyChannelUnread, channelUnreadInfo);
5131
+ return channelUnreadInfo;
5132
+ };
5133
+
5134
+ const persistUnreadCountInfo = (payload) => {
5135
+ const { feedMarkers, userFeedMarkers } = payload;
5136
+ // calculate sub channel unread info and channel unread info
5137
+ if (feedMarkers.length > 0 && userFeedMarkers.length > 0) {
5138
+ const channelIds = [];
5139
+ const feedMarkerMap = new Map(feedMarkers.map(fm => [fm.feedId, fm]));
5140
+ userFeedMarkers.forEach(userFeedMarker => {
5141
+ const feedMarker = feedMarkerMap.get(userFeedMarker.feedId);
5142
+ if (!feedMarker)
5143
+ return;
5144
+ if (feedMarker.feedId === userFeedMarker.feedId) {
5145
+ const unreadCount = feedMarker.lastSegment - userFeedMarker.readToSegment;
5146
+ const subChannelUnreadInfo = {
5147
+ subChannelId: feedMarker.feedId,
5148
+ channelId: feedMarker.entityId,
5149
+ readToSegment: userFeedMarker.readToSegment,
5150
+ lastSegment: feedMarker.lastSegment,
5151
+ lastMentionSegment: userFeedMarker.lastMentionSegment,
5152
+ unreadCount: Math.max(0, unreadCount),
5153
+ isMentioned: userFeedMarker.isMentioned,
5154
+ isDeleted: feedMarker.isDeleted,
5155
+ createdAt: userFeedMarker.createdAt,
5156
+ updatedAt: userFeedMarker.updatedAt,
5157
+ };
5158
+ // update sub channel unread info in cache
5159
+ ingestInCache({ subChannelUnreadInfo: [subChannelUnreadInfo] });
5160
+ if (!channelIds.includes(feedMarker.entityId)) {
5161
+ channelIds.push(feedMarker.entityId);
5162
+ }
5163
+ }
5164
+ });
5165
+ // re-calculate channel unread info in cache
5166
+ channelIds.forEach(channelId => {
5167
+ reCalculateChannelUnreadInfo(channelId);
5168
+ });
5169
+ }
5170
+ };
5171
+
5172
+ /**
5173
+ * ```js
5174
+ * import { getSubChannelMarkers } from '@amityco/ts-sdk'
5175
+ * const subChannelMarkers = await getSubChannelMarkers(['sch1', 'sch2'])
5176
+ * ```
5177
+ *
5178
+ * Fetches a paginable list of {@link Amity.SubChannelMarker} objects
5179
+ *
5180
+ * @param messageFeedIds the feed IDs of the {@link Amity.RawSubChannel} marker to fetch
5181
+ * @param page
5182
+ * @returns A page of {@link Amity.SubChannelMarker} objects
5183
+ *
5184
+ * @category Channel API
5185
+ * @async
5186
+ * @private
5187
+ */
5188
+ const getSubChannelMarkers = async (messageFeedIds, page = { limit: 100 }) => {
5189
+ const client = getActiveClient();
5190
+ client.log('channel/getSubChannelMarkers', messageFeedIds, page);
5191
+ const { data: queryPayload } = await client.http.get(`/api/v1/markers/message-feeds`, {
5192
+ params: {
5193
+ messageFeedIds,
5194
+ options: {
5195
+ token: toToken(page, 'skiplimit'),
5196
+ },
5197
+ },
5198
+ });
5199
+ const { paging } = queryPayload, payload = __rest(queryPayload, ["paging"]);
5200
+ const { userEntityMarkers: userEntityMarkersPayload, userFeedMarkers: userFeedMarkersPayload, userMarkers, feedMarkers: feedMarkersPayload, } = payload;
5201
+ // if consistent mode is enabled, persist the unread count info to the cache
5202
+ if (client.isUnreadCountEnabled && client.getMarkerSyncConsistentMode()) {
5203
+ persistUnreadCountInfo({
5204
+ feedMarkers: feedMarkersPayload,
5205
+ userFeedMarkers: userFeedMarkersPayload,
5206
+ });
5207
+ }
5208
+ const userEntityMarkers = convertChannelMarkerResponse(userEntityMarkersPayload);
5209
+ const userFeedMarkers = convertSubChannelMarkerResponse(userFeedMarkersPayload);
5210
+ const cachedAt = client.cache && Date.now();
5211
+ if (client.cache)
5212
+ ingestInCache({ userEntityMarkers, userFeedMarkers, userMarkers }, { cachedAt });
5213
+ fireEvent('local.channelMarker.fetched', { userEntityMarkers });
5214
+ fireEvent('local.subChannelMarker.fetched', { userFeedMarkers });
5215
+ fireEvent('local.userMarker.fetched', { userMarkers });
5216
+ const nextPage = toPage(paging.next);
5217
+ const prevPage = toPage(paging.previous);
5218
+ return { data: userFeedMarkers, cachedAt, prevPage, nextPage };
5219
+ };
5220
+
5221
+ const getUserMarker = async () => {
5222
+ const client = getActiveClient();
5223
+ client.log('channel/getUserMarker');
5224
+ const { data: payload } = await client.http.get(`/api/v1/markers/userMarker`);
5225
+ const { userMarkers } = payload;
5226
+ const cachedAt = client.cache && Date.now();
5227
+ if (client.cache)
5228
+ ingestInCache({ userMarkers }, { cachedAt });
5229
+ fireEvent('local.userMarker.fetched', { userMarkers });
5230
+ const latestUserMarker = userMarkers.reduce((maxUserMarker, userMarker) => {
5231
+ if (maxUserMarker == null ||
5232
+ new Date(maxUserMarker.lastSyncAt).getTime() < new Date(userMarker.lastSyncAt).getTime()) {
5233
+ return userMarker;
5234
+ }
5235
+ return maxUserMarker;
5236
+ }, undefined);
5237
+ return { data: latestUserMarker, cachedAt };
5238
+ };
5239
+
5240
+ /** @hidden */
5241
+ /*
5242
+ * @param message payload from http request without myReactions
5243
+ * add myReactions to http response if the event was a reaction event
5244
+ */
5245
+ const prepareMessagePayloadForCache = (payload, reactors, event) => {
5246
+ const client = getActiveClient();
5247
+ const cached = pullFromCache(['message', 'get', payload.messageId]);
5248
+ // '[]' in cases where the new reaction is the first one
5249
+ const myReactions = (cached === null || cached === void 0 ? void 0 : cached.data.myReactions) || [];
5250
+ // add myReactions to the payload
5251
+ Object.assign(payload, { myReactions });
5252
+ // check if there are any updates to the reactions
5253
+ const latestReaction = reactors[0];
5254
+ const isLatestReactionMine = latestReaction && latestReaction.userId === client.userId;
5255
+ if (!isLatestReactionMine) {
5256
+ return;
5257
+ }
5258
+ // new reaction added
5259
+ if (event === 'message.reactionAdded' && !myReactions.includes(latestReaction.reactionName)) {
5260
+ Object.assign(payload, {
5261
+ myReactions: [...myReactions, latestReaction.reactionName],
5262
+ });
5263
+ }
5264
+ // existing reaction removed
5265
+ if (event === 'message.reactionRemoved' && myReactions.includes(latestReaction.reactionName)) {
5266
+ Object.assign(payload, {
5267
+ myReactions: myReactions.filter(x => x !== latestReaction.reactionName),
5268
+ });
5269
+ }
5270
+ };
5271
+
5272
+ /*
5273
+ * This is a simple utility that infers the value of isDeleted based on the
5274
+ * value of includeDeleted
5275
+ *
5276
+ * There are two important things to note here:
5277
+ * 1. `includeDeleted` is purely client side query param and not recognized by
5278
+ * the server
5279
+ * 2. The only values we wish to expose with regards to `isDeleted` (the server
5280
+ * param for queries) is false | undefined and want to disallow users to query
5281
+ * for deleted entities
5282
+ *
5283
+ * Although this is a very simple utility, it's only purpose is to keep things
5284
+ * DRY
5285
+ */
5286
+ const inferIsDeleted = (includeDeleted) => includeDeleted === true ? undefined : false;
5287
+
5288
+ function getSubChannelIsMentioned(channelId, subChannelId, marker) {
5289
+ var _a, _b;
5290
+ // Look for `unreadCount` in the marker param first
5291
+ if (marker) {
5292
+ return marker.hasMentioned;
5293
+ }
5294
+ const client = getActiveClient();
5295
+ // If consistent mode is enabled, look in the SubChannelUnreadCountInfo cache
5296
+ if (client.isUnreadCountEnabled && client.getMarkerSyncConsistentMode()) {
5297
+ const cachedUnreadCount = (_a = pullFromCache([
5298
+ 'subChannelUnreadInfo',
5299
+ 'get',
5300
+ subChannelId,
5301
+ ])) === null || _a === void 0 ? void 0 : _a.data;
5302
+ if (cachedUnreadCount) {
5303
+ return cachedUnreadCount.isMentioned;
5304
+ }
5305
+ return false;
5306
+ }
5307
+ const key = {
5308
+ entityId: channelId,
5309
+ feedId: subChannelId,
5310
+ userId: getActiveUser()._id,
5311
+ };
5312
+ // If the marker param is not set, look in the cache
5313
+ const cachedMarker = (_b = pullFromCache([
5314
+ 'subChannelMarker',
5315
+ 'get',
5316
+ getResolver('subChannelMarker')(key),
5317
+ ])) === null || _b === void 0 ? void 0 : _b.data;
5318
+ if (cachedMarker) {
5319
+ return cachedMarker.hasMentioned;
5320
+ }
5321
+ // and if not found in cache use default value `false`
5322
+ return false;
5323
+ }
5324
+
5325
+ function getSubChannelUnreadCount(channelId, subChannelId, marker) {
5326
+ var _a, _b;
5327
+ // Look for `unreadCount` in the marker param first
5328
+ if (marker) {
5329
+ return marker.unreadCount;
5330
+ }
5331
+ const client = getActiveClient();
5332
+ // If consistent mode is enabled, look in the SubChannelUnreadCountInfo cache
5333
+ if (client.isUnreadCountEnabled && client.getMarkerSyncConsistentMode()) {
5334
+ const cachedUnreadCount = (_a = pullFromCache([
5335
+ 'subChannelUnreadInfo',
5336
+ 'get',
5337
+ subChannelId,
5338
+ ])) === null || _a === void 0 ? void 0 : _a.data;
5339
+ if (cachedUnreadCount) {
5340
+ return cachedUnreadCount.isDeleted ? 0 : cachedUnreadCount.unreadCount;
5341
+ }
5342
+ return 0;
5343
+ }
5344
+ const key = {
5345
+ entityId: channelId,
5346
+ feedId: subChannelId,
5347
+ userId: getActiveUser()._id,
5348
+ };
5349
+ // If the marker param is not set, look in the cache
5350
+ const cachedMarker = (_b = pullFromCache([
5351
+ 'subChannelMarker',
5352
+ 'get',
5353
+ getResolver('subChannelMarker')(key),
5354
+ ])) === null || _b === void 0 ? void 0 : _b.data;
5355
+ if (cachedMarker) {
5356
+ return cachedMarker.unreadCount;
5357
+ }
5358
+ // and if not found in cache use default value `0`
5359
+ return 0;
5360
+ }
5361
+
5362
+ const MARKER_INCLUDED_SUB_CHANNEL_TYPE$1 = ['broadcast', 'conversation', 'community'];
5363
+ const isUnreadCountSupport$2 = ({ channelType }) => MARKER_INCLUDED_SUB_CHANNEL_TYPE$1.includes(channelType);
5364
+ function convertFromRaw$2(_a) {
5365
+ var { channelId, channelPublicId, channelType, childCount, creatorId, creatorPublicId, lastMessageId, lastMessageTimestamp, messageFeedId, name } = _a, rest = __rest(_a, ["channelId", "channelPublicId", "channelType", "childCount", "creatorId", "creatorPublicId", "lastMessageId", "lastMessageTimestamp", "messageFeedId", "name"]);
5366
+ return Object.assign(Object.assign({ get unreadCount() {
5367
+ return getSubChannelUnreadCount(channelId, messageFeedId);
5368
+ },
5369
+ get hasMentioned() {
5370
+ return getSubChannelIsMentioned(channelId, messageFeedId);
5371
+ },
5372
+ get isMentioned() {
5373
+ return getSubChannelIsMentioned(channelId, messageFeedId);
5374
+ } }, rest), { channelId: channelPublicId, creatorId: creatorPublicId, displayName: name, lastActivity: lastMessageTimestamp, latestMessageId: lastMessageId, messageCount: childCount, subChannelId: messageFeedId, isUnreadCountSupport: isUnreadCountSupport$2({ channelType }) });
5375
+ }
5376
+
5377
+ const mergePayloadWithLocal = (payload) => {
5378
+ var _a, _b, _c;
5379
+ const localMessage = (_b = (_a = queryCache(['message', 'get'])) === null || _a === void 0 ? void 0 : _a.find(({ data }) => data.messageId === payload.messageId)) === null || _b === void 0 ? void 0 : _b.data;
5380
+ if (localMessage) {
5381
+ return Object.assign(Object.assign(Object.assign({}, localMessage), payload), {
5382
+ // NOTE: referenceId is missing in the some payload event. If we have local message data with referenceId, use it instead.
5383
+ referenceId: (_c = localMessage.referenceId) !== null && _c !== void 0 ? _c : payload.referenceId });
5384
+ }
5385
+ return payload;
5386
+ };
5387
+ function convertFromRaw$1(message, reactors, event) {
5388
+ var _a;
5389
+ const mergeMessage = mergePayloadWithLocal(message);
5390
+ const { channelPublicId, childCount, creatorPublicId, mentionedUsers, messageFeedId, myReactions, reactionCount, reactions, referenceId, segment, messageId, creatorId } = mergeMessage, rest = __rest(mergeMessage, ["channelPublicId", "childCount", "creatorPublicId", "mentionedUsers", "messageFeedId", "myReactions", "reactionCount", "reactions", "referenceId", "segment", "messageId", "creatorId"]);
5391
+ let cache;
5392
+ if (referenceId) {
5393
+ cache = pullFromCache(['message', 'get', referenceId]);
5394
+ }
5395
+ if (!cache) {
5396
+ cache = pullFromCache(['message', 'get', messageId]);
5397
+ }
5398
+ const out = Object.assign(Object.assign({}, rest), { messageId, channelId: channelPublicId, channelSegment: segment, childrenNumber: childCount, creatorId: creatorPublicId, creatorPrivateId: message.creatorId, reactions: reactions !== null && reactions !== void 0 ? reactions : {},
5399
+ /*
5400
+ * Previously, myReactions were added only if it was part of the payload.
5401
+ * So empty myReactions were not present. So I've edited the payload to add
5402
+ * a default for those cases.
5403
+ *
5404
+ * Check git blame for previous iteration
5405
+ */
5406
+ myReactions: myReactions || ((_a = cache === null || cache === void 0 ? void 0 : cache.data.myReactions) !== null && _a !== void 0 ? _a : []), reactionsCount: reactionCount, subChannelId: messageFeedId, uniqueId: cache ? cache.data.uniqueId : messageId, referenceId, syncState: "synced" /* Amity.SyncState.Synced */ });
5407
+ if (mentionedUsers) {
5408
+ out.mentionees = mentionedUsers.map(mention => {
5409
+ if (mention.type === 'channel') {
5410
+ return mention;
5411
+ }
5412
+ return { type: 'user', userIds: mention.userPublicIds };
5413
+ });
5414
+ }
5415
+ if (reactors && reactors.length && event) {
5416
+ // mqtt event
5417
+ prepareMessagePayloadForCache(out, reactors, event);
5418
+ }
5419
+ return out;
5420
+ }
5421
+ const preUpdateMessageCache = (rawPayload) => {
5422
+ ingestInCache({
5423
+ messages: rawPayload.messages.map(message => convertFromRaw$1(message, rawPayload.reactions)),
5424
+ });
5425
+ };
5426
+ const DEBOUNCE_TIME = 2000;
5427
+ const currentDebounceMap = {};
5428
+ const prepareMessagePayload = async (payload, event) => {
5429
+ const markerIds = payload.messages.map(({ messageId }) => messageId);
5430
+ if (markerIds.length > 0) {
5431
+ // since the get markers method requires a channel cache to function with the reducer.
5432
+ preUpdateMessageCache(payload);
5433
+ const markerIdsKey = markerIds.join('');
5434
+ if (currentDebounceMap[markerIdsKey]) {
5435
+ clearTimeout(currentDebounceMap[markerIdsKey]);
5436
+ }
5437
+ currentDebounceMap[markerIdsKey] = setTimeout(() => {
5438
+ try {
5439
+ getMessageMarkers(markerIds);
5440
+ }
5441
+ catch (_error) {
5442
+ // do nothing
5443
+ }
5444
+ }, DEBOUNCE_TIME);
5445
+ }
5446
+ const { messageFeeds } = payload, restPayload = __rest(payload, ["messageFeeds"]);
5447
+ // upsert messageFeeds to subchannel cache because messageFeeds from event payload not include messagePreviewId
5448
+ if (messageFeeds && messageFeeds.length > 0) {
5449
+ messageFeeds === null || messageFeeds === void 0 ? void 0 : messageFeeds.forEach(messageFeed => {
5450
+ var _a, _b;
5451
+ const subChannelCache = (_b = (_a = pullFromCache(['subChannel', 'get', messageFeed.messageFeedId])) === null || _a === void 0 ? void 0 : _a.data) !== null && _b !== void 0 ? _b : {};
5452
+ // exclude getter properties from existing subChannel cache, update only other properties to existing subChannel cache
5453
+ const _c = convertFromRaw$2(messageFeed), restSubChannel = __rest(_c, ["unreadCount", "isMentioned"]);
5454
+ updateSubChannelCache(messageFeed.messageFeedId, subChannelCache, restSubChannel);
5455
+ });
5456
+ }
5457
+ return Object.assign(Object.assign({}, restPayload), { messages: payload.messages.map(m => convertFromRaw$1(m, payload.reactions, event)) });
5458
+ };
5459
+ function convertParams(_a) {
5460
+ var { subChannelId, mentionees, dataType, data } = _a, rest = __rest(_a, ["subChannelId", "mentionees", "dataType", "data"]);
5461
+ if (dataType === MessageContentType.IMAGE || dataType === MessageContentType.FILE) {
5462
+ return Object.assign({ messageFeedId: subChannelId, mentionedUsers: mentionees, dataType, data: Object.assign({ caption: '' }, data) }, rest);
5463
+ }
5464
+ return Object.assign({ messageFeedId: subChannelId, mentionedUsers: mentionees, dataType, data }, rest);
5465
+ }
5466
+ function convertQueryParams$1(_a) {
5467
+ var { sortBy, subChannelId, includingTags, excludingTags, includeDeleted, aroundMessageId, limit, type } = _a, rest = __rest(_a, ["sortBy", "subChannelId", "includingTags", "excludingTags", "includeDeleted", "aroundMessageId", "limit", "type"]);
5468
+ const out = Object.assign(Object.assign({}, rest), { messageFeedId: subChannelId, isDeleted: inferIsDeleted(includeDeleted), options: {
5469
+ sortBy,
5470
+ limit: limit || COLLECTION_DEFAULT_PAGINATION_LIMIT,
5471
+ around: aroundMessageId,
5472
+ } });
5473
+ if (includingTags) {
5474
+ out.includeTags = includingTags;
5475
+ }
5476
+ if (type) {
5477
+ out.dataType = type;
5478
+ }
5479
+ if (excludingTags) {
5480
+ out.excludeTags = excludingTags;
5481
+ }
5482
+ return out;
5483
+ }
5484
+
5485
+ function convertRawUserToInternalUser(rawUser) {
5486
+ return Object.assign(Object.assign({}, rawUser), { isGlobalBanned: (rawUser === null || rawUser === void 0 ? void 0 : rawUser.isGlobalBan) || false });
5487
+ }
5488
+
5489
+ const MARKER_INCLUDED_SUB_CHANNEL_TYPE = ['broadcast', 'conversation', 'community'];
5490
+ /**
5491
+ * Filter sub channel by type. Only conversation, community and broadcast type are included.
5492
+ */
5493
+ const isUnreadCountSupport$1 = ({ channelType }) => MARKER_INCLUDED_SUB_CHANNEL_TYPE.includes(channelType);
5494
+ const preUpdateSubChannelCache = (rawPayload) => {
5495
+ ingestInCache({
5496
+ messageFeeds: rawPayload.messageFeeds.map(messageFeed => convertFromRaw$2(messageFeed)),
5497
+ });
5498
+ };
5499
+ const prepareSubChannelPayload = async (rawPayload) => {
5500
+ const markerIds = rawPayload.messageFeeds
5501
+ .filter(isUnreadCountSupport$1)
5502
+ .map(({ messageFeedId }) => messageFeedId);
5503
+ if (markerIds.length > 0) {
5504
+ // since the get markers method requires a channel cache to function with the reducer.
5505
+ preUpdateSubChannelCache(rawPayload);
5506
+ try {
5507
+ await getSubChannelMarkers(markerIds);
5508
+ }
5509
+ catch (e) {
5510
+ // empty block (from the spec, allow marker fetch to fail without having to do anything)
5511
+ }
5512
+ }
5513
+ updateSubChannelMessagePreviewCache(rawPayload);
5514
+ // attach marker to sub channel
5515
+ const messageFeeds = rawPayload.messageFeeds.map(convertFromRaw$2);
5516
+ const messages = rawPayload.messages.map(m => convertFromRaw$1(m));
5517
+ const user = rawPayload.users.map(convertRawUserToInternalUser);
5518
+ return Object.assign(Object.assign({}, rawPayload), { messageFeeds,
5519
+ messages, users: user });
5520
+ };
5521
+ function convertQueryParams(_a) {
5522
+ var { excludeDefaultSubChannel } = _a, rest = __rest(_a, ["excludeDefaultSubChannel"]);
5523
+ const out = Object.assign({}, rest);
5524
+ if (excludeDefaultSubChannel !== undefined) {
5525
+ out.excludeDefaultMessageFeed = excludeDefaultSubChannel;
5526
+ }
5527
+ return out;
5528
+ }
5529
+
5530
+ /**
5531
+ * ```js
5532
+ * import { getSubChannel } from '@amityco/ts-sdk'
5533
+ * const subChannel = await getSubChannel('foobar')
5534
+ * ```
5535
+ *
5536
+ * Fetches a {@link Amity.SubChannel} object
5537
+ *
5538
+ * @param subChannelId the ID of the {@link Amity.SubChannel} to fetch
5539
+ * @returns the associated {@link Amity.SubChannel} object
5540
+ *
5541
+ * @category Channel API
5542
+ * @async
5543
+ */
5544
+ const getSubChannel$1 = async (subChannelId) => {
5545
+ const client = getActiveClient();
5546
+ client.log('channel/getSubChannel', subChannelId);
5547
+ isInTombstone('subChannel', subChannelId);
5548
+ try {
5549
+ const response = await client.http.get(`/api/v5/message-feeds/${encodeURIComponent(subChannelId)}`);
5550
+ const data = await prepareSubChannelPayload(response.data);
5551
+ const cachedAt = client.cache && Date.now();
5552
+ if (client.cache)
5553
+ ingestInCache(data, { cachedAt });
5554
+ fireEvent('local.message-feed.fetched', data);
5555
+ return {
5556
+ data: data.messageFeeds[0],
5557
+ cachedAt,
5558
+ };
5559
+ }
5560
+ catch (error) {
5561
+ if (checkIfShouldGoesToTombstone(error === null || error === void 0 ? void 0 : error.code)) {
5562
+ pushToTombstone('subChannel', subChannelId);
5563
+ }
5564
+ throw error;
5565
+ }
5566
+ };
5567
+ /**
5568
+ * ```js
5569
+ * import { getSubChannel } from '@amityco/ts-sdk'
5570
+ * const subChannel = getSubChannel.locally('foobar')
5571
+ * ```
5572
+ *
5573
+ * Fetches a {@link Amity.SubChannel} object from cache
5574
+ *
5575
+ * @param subChannelId the ID of the {@link Amity.SubChannel} to fetch
5576
+ * @returns the associated {@link Amity.SubChannel} object
5577
+ *
5578
+ * @category Channel API
5579
+ */
5580
+ getSubChannel$1.locally = (subChannelId) => {
5581
+ const client = getActiveClient();
5582
+ client.log('channel/getSubChannel.locally', subChannelId);
5583
+ if (!client.cache)
5584
+ return;
5585
+ const cached = pullFromCache(['subChannel', 'get', subChannelId]);
5586
+ if (!cached)
5587
+ return;
5588
+ return {
5589
+ data: cached.data,
5590
+ cachedAt: cached.cachedAt,
5591
+ };
5592
+ };
5593
+
5594
+ const convertDateStringToTimestamp = (dateString) => {
5595
+ return new Date(dateString).getTime();
5596
+ };
5597
+
5598
+ const getMessagePreviewSetting$1 = async () => {
5599
+ const client = getActiveClient();
5600
+ return client.getMessagePreviewSetting(false);
5601
+ };
5602
+ const getSubChannelCache = async (subChannelId) => {
5603
+ var _a;
5604
+ let subChannelCache = (_a = pullFromCache(['subChannel', 'get', subChannelId])) === null || _a === void 0 ? void 0 : _a.data;
5605
+ if (!subChannelCache) {
5606
+ subChannelCache = (await getSubChannel$1(subChannelId)).data;
5607
+ }
5608
+ return subChannelCache;
5609
+ };
5610
+ const isLastestMessageOnSubchannel = (message) => {
5611
+ var _a;
5612
+ const cache = (_a = pullFromCache([
5613
+ 'messagePreviewSubChannel',
5614
+ 'get',
5615
+ message.subChannelId,
5616
+ ])) === null || _a === void 0 ? void 0 : _a.data;
5617
+ // The message payload from optimistic created event has no segment, so we check createdAt instead.
5618
+ return (!cache ||
5619
+ cache.segment <= message.channelSegment ||
5620
+ convertDateStringToTimestamp(cache.createdAt) <= convertDateStringToTimestamp(message.createdAt));
5621
+ };
5622
+ const isLastestMessageOnChannel = (message) => {
5623
+ var _a;
5624
+ const cache = (_a = pullFromCache([
5625
+ 'messagePreviewChannel',
5626
+ 'get',
5627
+ message.channelId,
5628
+ ])) === null || _a === void 0 ? void 0 : _a.data;
5629
+ return (!cache ||
5630
+ convertDateStringToTimestamp(cache.createdAt) <= convertDateStringToTimestamp(message.createdAt));
5631
+ };
5632
+ const handleMessageCreatedOnSubChannel = async (message) => {
5633
+ const messagePreviewSetting = await getMessagePreviewSetting$1();
5634
+ const { channelId, messageId: messagePreviewId, creatorId, createdAt, updatedAt, data, dataType, subChannelId, channelSegment: segment, isDeleted, } = message;
5635
+ // 1. get subChannel from cache, if not exist fetch from server
5636
+ const subChannelCache = await getSubChannelCache(subChannelId);
5637
+ // 2. if messagePreviewSetting is NO_MESSAGE_PREVEIW, update only lastActiviy in subChannel cache
5638
+ if (messagePreviewSetting === "no-message-preview" /* Amity.MessagePreviewSetting.NO_MESSAGE_PREVIEW */) {
5639
+ // 2.1 if the message is the latest message, update lastActivity to be createdAt in subChannel cache
5640
+ if (convertDateStringToTimestamp(subChannelCache.lastActivity) <
5641
+ convertDateStringToTimestamp(createdAt))
5642
+ updateSubChannelCache(message.subChannelId, subChannelCache, {
5643
+ lastActivity: createdAt,
5644
+ });
5645
+ return;
5646
+ }
5647
+ // 3. if messagePreviewSetting is `NOT` NO_MESSAGE_PREVEIW, update messagePreviewSubChannel and subChannel cache
5648
+ // 3.1 check if the message is the latest message, if not ignore the message.
5649
+ if (!isLastestMessageOnSubchannel(message))
5650
+ return;
5651
+ // 3.2 if the message is the latest message, update messagePreviewSubChannel and subChannel cache
5652
+ pushToCache(['messagePreviewSubChannel', 'get', message.subChannelId], {
5653
+ channelId,
5654
+ creatorId,
5655
+ messagePreviewId,
5656
+ createdAt,
5657
+ updatedAt,
5658
+ subChannelId,
5659
+ data,
5660
+ dataType,
5661
+ segment,
5662
+ isDeleted,
5663
+ subChannelUpdatedAt: subChannelCache === null || subChannelCache === void 0 ? void 0 : subChannelCache.updatedAt,
5664
+ subChannelName: subChannelCache === null || subChannelCache === void 0 ? void 0 : subChannelCache.displayName,
5665
+ });
5666
+ updateSubChannelCache(message.subChannelId, subChannelCache, {
5667
+ lastActivity: createdAt,
5668
+ messagePreviewId,
5669
+ });
5670
+ };
5671
+ const handleMessageUpdatedOnSubChannel = async (message) => {
5672
+ var _a;
5673
+ const { channelId, messageId: messagePreviewId, creatorId, createdAt, updatedAt, data, dataType, subChannelId, channelSegment: segment, isDeleted, } = message;
5674
+ const messagePreviewSubChannelCache = (_a = pullFromCache([
5675
+ 'messagePreviewSubChannel',
5676
+ 'get',
5677
+ message.subChannelId,
5678
+ ])) === null || _a === void 0 ? void 0 : _a.data;
5679
+ // if messagePreviewSubChannel is not exist, ignore the message.
5680
+ if (messagePreviewSubChannelCache &&
5681
+ messagePreviewSubChannelCache.messagePreviewId === message.messageId) {
5682
+ const subChannelCache = await getSubChannelCache(subChannelId);
5683
+ pushToCache(['messagePreviewSubChannel', 'get', message.subChannelId], {
5684
+ channelId,
5685
+ creatorId,
5686
+ messagePreviewId,
5687
+ createdAt,
5688
+ updatedAt,
5689
+ subChannelId,
5690
+ data,
5691
+ dataType,
5692
+ segment,
5693
+ isDeleted,
5694
+ subChannelUpdatedAt: subChannelCache.updatedAt,
5695
+ subChannelName: messagePreviewSubChannelCache.subChannelName,
5696
+ });
5697
+ }
5698
+ };
5699
+ const handleMessageCreated = async (message) => {
5700
+ const { channelId, messageId: messagePreviewId, creatorId, createdAt, updatedAt, data, dataType, subChannelId, channelSegment: segment, isDeleted, } = message;
5701
+ if (isLastestMessageOnChannel(message)) {
5702
+ const subChannelCache = await getSubChannelCache(subChannelId);
5703
+ pushToCache(['messagePreviewChannel', 'get', message.channelId], {
5704
+ channelId,
5705
+ creatorId,
5706
+ messagePreviewId,
5707
+ createdAt,
5708
+ updatedAt,
5709
+ subChannelId,
5710
+ data,
5711
+ dataType,
5712
+ segment,
5713
+ isDeleted,
5714
+ subChannelUpdatedAt: subChannelCache === null || subChannelCache === void 0 ? void 0 : subChannelCache.updatedAt,
5715
+ subChannelName: subChannelCache === null || subChannelCache === void 0 ? void 0 : subChannelCache.displayName,
5716
+ });
5717
+ }
5718
+ };
5719
+ const handleMessageUpdated = async (message) => {
5720
+ /**
5721
+ * Channel Case
5722
+ */
5723
+ var _a;
5724
+ const { channelId, messageId: messagePreviewId, creatorId, createdAt, updatedAt, data, dataType, subChannelId, channelSegment: segment, isDeleted, } = message;
5725
+ const messagePreviewChannelCache = (_a = pullFromCache([
5726
+ 'messagePreviewChannel',
5727
+ 'get',
5728
+ message.channelId,
5729
+ ])) === null || _a === void 0 ? void 0 : _a.data;
5730
+ if (messagePreviewChannelCache &&
5731
+ messagePreviewChannelCache.messagePreviewId === message.messageId) {
5732
+ const subChannelCache = await getSubChannelCache(subChannelId);
5733
+ pushToCache(['messagePreviewChannel', 'get', message.channelId], {
5734
+ channelId,
5735
+ creatorId,
5736
+ messagePreviewId,
5737
+ createdAt,
5738
+ updatedAt,
5739
+ subChannelId,
5740
+ data,
5741
+ dataType,
5742
+ segment,
5743
+ isDeleted,
5744
+ subChannelUpdatedAt: subChannelCache.updatedAt,
5745
+ subChannelName: messagePreviewChannelCache.subChannelName,
5746
+ });
5747
+ }
5748
+ };
5749
+ const handleSubChannelUpdated = async (subChannel) => {
5750
+ var _a, _b, _c, _d;
5751
+ const { channelId, subChannelId } = subChannel;
5752
+ /** Channel Case */
5753
+ const messagePreviewChannelCache = (_a = pullFromCache([
5754
+ 'messagePreviewChannel',
5755
+ 'get',
5756
+ channelId,
5757
+ ])) === null || _a === void 0 ? void 0 : _a.data;
5758
+ if ((messagePreviewChannelCache === null || messagePreviewChannelCache === void 0 ? void 0 : messagePreviewChannelCache.subChannelId) === subChannelId) {
5759
+ const subChannelCache = (_b = pullFromCache([
5760
+ 'subChannel',
5761
+ 'get',
5762
+ subChannelId,
5763
+ ])) === null || _b === void 0 ? void 0 : _b.data;
5764
+ pushToCache(['messagePreviewChannel', 'get', channelId], Object.assign(Object.assign({}, messagePreviewChannelCache), { subChannelName: subChannelCache === null || subChannelCache === void 0 ? void 0 : subChannelCache.displayName, subChannelUpdatedAt: subChannelCache === null || subChannelCache === void 0 ? void 0 : subChannelCache.updatedAt }));
5765
+ }
5766
+ /** SubChannel Case */
5767
+ const messagePreviewSubChannelCache = (_c = pullFromCache([
5768
+ 'messagePreviewSubChannel',
5769
+ 'get',
5770
+ subChannelId,
5771
+ ])) === null || _c === void 0 ? void 0 : _c.data;
5772
+ if (messagePreviewSubChannelCache &&
5773
+ new Date(messagePreviewSubChannelCache.updatedAt).valueOf() >
5774
+ new Date(subChannel.updatedAt).valueOf()) {
5775
+ const subChannelCache = (_d = pullFromCache([
5776
+ 'subChannel',
5777
+ 'get',
5778
+ subChannelId,
5779
+ ])) === null || _d === void 0 ? void 0 : _d.data;
5780
+ pushToCache(['messagePreviewSubChannel', 'get', subChannelId], Object.assign(Object.assign({}, messagePreviewSubChannelCache), { subChannelName: subChannelCache === null || subChannelCache === void 0 ? void 0 : subChannelCache.displayName, subChannelUpdatedAt: subChannelCache === null || subChannelCache === void 0 ? void 0 : subChannelCache.updatedAt }));
5781
+ }
5782
+ };
5783
+
5784
+ const MARKER_INCLUDED_CHANNEL_TYPE = ['broadcast', 'conversation', 'community'];
5785
+ const isUnreadCountSupport = ({ type }) => MARKER_INCLUDED_CHANNEL_TYPE.includes(type);
5786
+ function convertFromRaw(channel, options = { isMessagePreviewUpdated: true }) {
5787
+ var _a;
5788
+ let { messagePreviewId } = channel;
5789
+ const messagePreviewChannelCache = (_a = pullFromCache([
5790
+ 'messagePreviewChannel',
5791
+ 'get',
5792
+ channel.channelId,
5793
+ ])) === null || _a === void 0 ? void 0 : _a.data;
5794
+ if ((messagePreviewChannelCache === null || messagePreviewChannelCache === void 0 ? void 0 : messagePreviewChannelCache.messagePreviewId) && !options.isMessagePreviewUpdated) {
5795
+ messagePreviewId = messagePreviewChannelCache.messagePreviewId;
5796
+ }
5797
+ return Object.assign(Object.assign({}, channel), { defaultSubChannelId: channel.channelInternalId, isUnreadCountSupport: isUnreadCountSupport(channel), messagePreviewId });
5798
+ }
5799
+ const preUpdateChannelCache = (rawPayload, options = { isMessagePreviewUpdated: true }) => {
5800
+ ingestInCache({
5801
+ channels: rawPayload.channels.map(channel => convertFromRaw(channel, { isMessagePreviewUpdated: options.isMessagePreviewUpdated })),
5802
+ });
5803
+ };
5804
+ const updateChannelUnread = ({ currentUserId, channels, channelUsers, }) => {
5805
+ for (let i = 0; i < channels.length; i += 1) {
5806
+ const cacheKey = ['channelUnread', 'get', channels[i].channelId];
5807
+ const channelUser = channelUsers.find(channelUser => channelUser.channelId === channels[i].channelId && channelUser.userId === currentUserId);
5808
+ let unreadCount = 0;
5809
+ let readToSegment = null;
5810
+ let lastMentionedSegment = null;
5811
+ let isMentioned = false;
5812
+ if (channelUser) {
5813
+ readToSegment = channelUser.readToSegment;
5814
+ lastMentionedSegment = channelUser.lastMentionedSegment;
5815
+ unreadCount = Math.max(channels[i].messageCount - readToSegment, 0);
5816
+ isMentioned = lastMentionedSegment > readToSegment;
5817
+ }
5818
+ const cacheChannelUnread = {
5819
+ channelId: channels[i].channelId,
5820
+ lastSegment: channels[i].messageCount,
5821
+ readToSegment,
5822
+ lastMentionedSegment,
5823
+ unreadCount,
5824
+ isMentioned,
5825
+ isDeleted: channels[i].isDeleted || false,
5826
+ };
5827
+ pushToCache(cacheKey, cacheChannelUnread);
5828
+ }
5829
+ };
5830
+ const prepareChannelPayload = async (rawPayload, options = { isMessagePreviewUpdated: true }) => {
5831
+ const client = getActiveClient();
5832
+ const networkPreviewSetting = await client.getMessagePreviewSetting(false);
5833
+ if (options.isMessagePreviewUpdated &&
5834
+ networkPreviewSetting !== "no-message-preview" /* Amity.MessagePreviewSetting.NO_MESSAGE_PREVIEW */ &&
5835
+ rawPayload.messagePreviews &&
5836
+ rawPayload.messagePreviews.length > 0) {
5837
+ updateChannelMessagePreviewCache(rawPayload);
5838
+ }
5839
+ if (client.useLegacyUnreadCount) {
5840
+ updateChannelUnread({
5841
+ channels: rawPayload.channels,
5842
+ channelUsers: rawPayload.channelUsers,
5843
+ currentUserId: client.userId,
5844
+ });
5845
+ }
5846
+ else {
5847
+ const markerIds = rawPayload.channels
5848
+ // filter channel by type. Only conversation, community and broadcast type are included.
5849
+ .filter(isUnreadCountSupport)
5850
+ .map(({ channelInternalId }) => channelInternalId);
5851
+ if (markerIds.length > 0) {
5852
+ // since the get markers method requires a channel cache to function with the reducer.
5853
+ preUpdateChannelCache(rawPayload, {
5854
+ isMessagePreviewUpdated: options.isMessagePreviewUpdated,
5855
+ });
5856
+ try {
5857
+ await getChannelMarkers(markerIds);
5858
+ }
5859
+ catch (e) {
5860
+ // empty block (from the spec, allow marker fetch to fail without having to do anything)
5861
+ }
5862
+ }
5863
+ }
5864
+ // convert raw channel to internal channel
5865
+ const channels = rawPayload.channels.map(payload => convertFromRaw(payload, { isMessagePreviewUpdated: options.isMessagePreviewUpdated }));
5866
+ // convert raw channel user to membership (add user object)
5867
+ const channelUsers = rawPayload.channelUsers.map(channelUser => {
5868
+ return convertRawMembershipToMembership(channelUser);
5869
+ });
5870
+ const users = rawPayload.users.map(convertRawUserToInternalUser);
5871
+ const restRawPayload = __rest(rawPayload, ["messageFeedsInfo", "messagePreviews"]);
5872
+ return Object.assign(Object.assign({}, restRawPayload), { users,
5873
+ channels,
5874
+ channelUsers });
5875
+ };
5876
+
5877
+ /**
5878
+ * ```js
5879
+ * import { getSubChannelMarkers } from '@amityco/ts-sdk'
5880
+ * const subChannelMarkers = await getSubChannelMarkers(['sch1', 'sch2'])
5881
+ * ```
5882
+ *
5883
+ * Fetches a paginable list of {@link Amity.SubChannelMarker} objects
5884
+ *
5885
+ * @param messageFeedIds the feed IDs of the {@link Amity.RawSubChannel} marker to fetch
5886
+ * @param page
5887
+ * @returns A page of {@link Amity.SubChannelMarker} objects
5888
+ *
5889
+ * @category Channel API
5890
+ * @async
5891
+ * @private
5892
+ */
5893
+ const getUserMessageFeedMakers = async (channelIds) => {
5894
+ const client = getActiveClient();
5895
+ client.log('channel/getUserMessageFeedMakers', channelIds);
5896
+ const { data } = await client.http.get(`/api/v1/markers/user-message-feed`, {
5897
+ params: {
5898
+ channelIds,
5899
+ },
5900
+ });
5901
+ fireEvent('local.userMessageFeedMarker.fetched', { userMessageFeedMarker: data });
5902
+ return data;
5903
+ };
5904
+
5905
+ const prepareUnreadCountInfo = async (rawPayload) => {
5906
+ const client = getActiveClient();
5907
+ // if consistent mode is enabled, persist the unread count info to the cache
5908
+ // Marker service API uses channelInternalId as channelId
5909
+ const queryPayload = await getUserMessageFeedMakers(rawPayload.channels.map(({ channelInternalId }) => channelInternalId));
5910
+ const { feedMarkers, userFeedMarkers } = queryPayload;
5911
+ persistUnreadCountInfo({
5912
+ feedMarkers,
5913
+ userFeedMarkers,
5914
+ });
5915
+ client.log('channel/prepareUnreadCountInfo', rawPayload.channels);
5916
+ };
5917
+
5918
+ const getCachedMarker$2 = (entityId) => {
5919
+ var _a;
5920
+ const key = {
5921
+ entityId,
5922
+ userId: getActiveUser()._id,
5923
+ };
5924
+ return (_a = pullFromCache([
5925
+ 'channelMarker',
5926
+ 'get',
5927
+ getResolver('channelMarker')(key),
5928
+ ])) === null || _a === void 0 ? void 0 : _a.data;
5929
+ };
5930
+ const getUnreadInfoCached$1 = (channelId) => {
5931
+ var _a;
5932
+ return (_a = pullFromCache(['channelUnreadInfo', 'get', channelId])) === null || _a === void 0 ? void 0 : _a.data;
5933
+ };
5934
+ /**
5935
+ * The function use to get value of hasMentioned or isMentioned field.
5936
+ * function will get the value from marker params first, if there is no hasMentioned field, will look in to the cache.
5937
+ *
5938
+ * If consistent mode is enabled, the function will return the value from the channelUnreadCountInfo cache.
5939
+ * If not, the function will return the value from the channelMarker cache.
5940
+ * If not found in the both cache, use `false` as defaul value.
5941
+ */
5942
+ const getChannelIsMentioned = (channel, marker) => {
5943
+ var _a, _b, _c, _d;
5944
+ const client = getActiveClient();
5945
+ if (client.isUnreadCountEnabled && client.getMarkerSyncConsistentMode()) {
5946
+ return (_b = (_a = getUnreadInfoCached$1(channel.channelPublicId)) === null || _a === void 0 ? void 0 : _a.isMentioned) !== null && _b !== void 0 ? _b : false;
5947
+ }
5948
+ return (marker === null || marker === void 0 ? void 0 : marker.hasMentioned) !== undefined
5949
+ ? marker === null || marker === void 0 ? void 0 : marker.hasMentioned
5950
+ : (_d = (_c = getCachedMarker$2(channel.channelPublicId)) === null || _c === void 0 ? void 0 : _c.hasMentioned) !== null && _d !== void 0 ? _d : false;
5951
+ };
5952
+
5953
+ const getCachedMarker$1 = (entityId) => {
5954
+ var _a;
5955
+ const key = {
5956
+ entityId,
5957
+ userId: getActiveUser()._id,
5958
+ };
5959
+ return (_a = pullFromCache([
5960
+ 'channelMarker',
5961
+ 'get',
5962
+ getResolver('channelMarker')(key),
5963
+ ])) === null || _a === void 0 ? void 0 : _a.data;
5964
+ };
5965
+ const getUnreadInfoCached = (channelId) => {
5966
+ var _a;
5967
+ return (_a = pullFromCache(['channelUnreadInfo', 'get', channelId])) === null || _a === void 0 ? void 0 : _a.data;
5968
+ };
5969
+ /**
5970
+ * The function use to get value of unreadCount field.
5971
+ * function will get the value from marker params first, if there is no hasMentioned field, will look in to the cache.
5972
+ *
5973
+ * If consistent mode is enabled, the function will return the value from the channelUnreadCountInfo cache.
5974
+ * If not, the function will return the value from the channelMarker cache.
5975
+ * If not found in the both cache, use `0` as defaul value.
5976
+ */
5977
+ const getSubChannelsUnreadCount = (channel, marker) => {
5978
+ var _a, _b, _c, _d, _e;
5979
+ const client = getActiveClient();
5980
+ if (client.isUnreadCountEnabled && client.getMarkerSyncConsistentMode()) {
5981
+ // Marker service API uses channelInternalId as channelId
5982
+ return (_b = (_a = getUnreadInfoCached(channel.channelInternalId)) === null || _a === void 0 ? void 0 : _a.unreadCount) !== null && _b !== void 0 ? _b : 0;
5983
+ }
5984
+ if (marker === null || marker === void 0 ? void 0 : marker.isDeleted) {
5985
+ // NOTE: This is a temporary solution to handle the channel marker when the user is forced to
5986
+ // leave the channel because currently backend can't handle this, so every time a user is banned
5987
+ // from a channel or the channel is deleted the channel's unread count will reset to zero
5988
+ return 0;
5989
+ }
5990
+ return (_e = (_c = marker === null || marker === void 0 ? void 0 : marker.unreadCount) !== null && _c !== void 0 ? _c : (_d = getCachedMarker$1(channel.channelInternalId)) === null || _d === void 0 ? void 0 : _d.unreadCount) !== null && _e !== void 0 ? _e : 0;
5991
+ };
5992
+
5993
+ const getLegacyChannelUnread = (channelId) => {
5994
+ var _a;
5995
+ return (_a = pullFromCache(['channelUnread', 'get', channelId])) === null || _a === void 0 ? void 0 : _a.data;
5996
+ };
5997
+
5998
+ const constructChannelDynamicValue = (channel) => {
5999
+ const client = getActiveClient();
6000
+ const rest = __rest(channel, ["messageCount"]);
6001
+ return shallowClone(rest, {
6002
+ get unreadCount() {
6003
+ var _a, _b;
6004
+ return (_b = (_a = getLegacyChannelUnread(rest.channelId)) === null || _a === void 0 ? void 0 : _a.unreadCount) !== null && _b !== void 0 ? _b : 0;
6005
+ },
6006
+ get subChannelsUnreadCount() {
6007
+ return getSubChannelsUnreadCount(rest);
6008
+ },
6009
+ get isMentioned() {
6010
+ var _a, _b;
6011
+ if (client.useLegacyUnreadCount)
6012
+ return (_b = (_a = getLegacyChannelUnread(rest.channelId)) === null || _a === void 0 ? void 0 : _a.isMentioned) !== null && _b !== void 0 ? _b : false;
6013
+ return getChannelIsMentioned(rest);
6014
+ },
6015
+ });
6016
+ };
6017
+
4901
6018
  const ANALYTIC_CACHE_KEY = ['analytic', 'normal-priority'];
4902
6019
  const HIGH_PRIORITY_ANALYTIC_CACHE_KEY = ['analytic', 'high-priority'];
4903
6020
 
@@ -5197,20 +6314,6 @@ var AnalyticsEngine$1 = {
5197
6314
  },
5198
6315
  };
5199
6316
 
5200
- const userLinkedObject = (user) => {
5201
- return Object.assign(Object.assign({}, user), { get avatar() {
5202
- var _a;
5203
- if (!user.avatarFileId)
5204
- return undefined;
5205
- const avatar = (_a = pullFromCache([
5206
- 'file',
5207
- 'get',
5208
- `${user.avatarFileId}`,
5209
- ])) === null || _a === void 0 ? void 0 : _a.data;
5210
- return avatar;
5211
- } });
5212
- };
5213
-
5214
6317
  class StoryComputedValue {
5215
6318
  constructor(targetId, lastStoryExpiresAt, lastStorySeenExpiresAt) {
5216
6319
  this._syncingStoriesCount = 0;
@@ -5642,7 +6745,7 @@ const postLinkedObject = (post) => {
5642
6745
  } });
5643
6746
  };
5644
6747
 
5645
- const getCachedMarker$2 = (message) => {
6748
+ const getCachedMarker = (message) => {
5646
6749
  var _a, _b;
5647
6750
  const key = {
5648
6751
  creatorId: 'creatorPrivateId' in message ? message.creatorPrivateId : message.creatorId,
@@ -5660,7 +6763,7 @@ const getMessageReadCount = (message, marker) => {
5660
6763
  // Look in the marker param first
5661
6764
  return (_a = marker !== null && marker !== void 0 ? marker :
5662
6765
  // If the marker param is not set, look in the cache
5663
- getCachedMarker$2(message)) !== null && _a !== void 0 ? _a : { readCount: 0, deliveredCount: 0 };
6766
+ getCachedMarker(message)) !== null && _a !== void 0 ? _a : { readCount: 0, deliveredCount: 0 };
5664
6767
  }; // and if not found in cache use default value `0`
5665
6768
 
5666
6769
  /**
@@ -5903,31 +7006,6 @@ const markAsReadBySegment = async ({ subChannelId, readToSegment, }) => {
5903
7006
  }
5904
7007
  };
5905
7008
 
5906
- const reCalculateChannelUnreadInfo = (channelId) => {
5907
- var _a;
5908
- const cacheKeyChannelUnread = ['channelUnreadInfo', 'get', channelId];
5909
- const cacheChannelUnreadInfo = (_a = pullFromCache(cacheKeyChannelUnread)) === null || _a === void 0 ? void 0 : _a.data;
5910
- const cacheKeySubChannelUnread = ['subChannelUnreadInfo', 'get'];
5911
- const cachedSubChannelUnreadInfo = queryCache(cacheKeySubChannelUnread);
5912
- let channelUnreads = 0;
5913
- let isMentioned = false;
5914
- if (cachedSubChannelUnreadInfo && (cachedSubChannelUnreadInfo === null || cachedSubChannelUnreadInfo === void 0 ? void 0 : cachedSubChannelUnreadInfo.length) > 0) {
5915
- const subChannelUnreadsInfo = cachedSubChannelUnreadInfo === null || cachedSubChannelUnreadInfo === void 0 ? void 0 : cachedSubChannelUnreadInfo.filter(({ data }) => {
5916
- return data.channelId === channelId && !data.isDeleted;
5917
- });
5918
- channelUnreads = subChannelUnreadsInfo
5919
- .map(({ data }) => data.unreadCount)
5920
- .reduce((acc, cur) => acc + cur, 0);
5921
- isMentioned = subChannelUnreadsInfo.some(({ data }) => data.isMentioned);
5922
- }
5923
- const channelUnreadInfo = Object.assign(Object.assign({}, (cacheChannelUnreadInfo !== null && cacheChannelUnreadInfo !== void 0 ? cacheChannelUnreadInfo : {
5924
- channelId,
5925
- createdAt: new Date().toISOString(),
5926
- })), { updatedAt: new Date().toISOString(), unreadCount: channelUnreads, isMentioned });
5927
- pushToCache(cacheKeyChannelUnread, channelUnreadInfo);
5928
- return channelUnreadInfo;
5929
- };
5930
-
5931
7009
  class LegacyMessageReadReceiptSyncEngine {
5932
7010
  constructor() {
5933
7011
  this.isActive = true;
@@ -6131,1403 +7209,1442 @@ class LegacyMessageReadReceiptSyncEngine {
6131
7209
  }
6132
7210
  removeJobFromQueue(item) {
6133
7211
  const index = this.jobQueue.indexOf(item);
6134
- if (index > -1) {
6135
- this.jobQueue.splice(index, 1);
6136
- }
6137
- }
6138
- }
6139
- let instance$3 = null;
6140
- var LegacyReadReceiptSyncEngine = {
6141
- getInstance: () => {
6142
- if (!instance$3)
6143
- instance$3 = new LegacyMessageReadReceiptSyncEngine();
6144
- return instance$3;
6145
- },
6146
- };
6147
-
6148
- const markReadMessage = (message) => {
6149
- const client = getActiveClient();
6150
- if (client.useLegacyUnreadCount) {
6151
- const markReadReceiptEngine = ReadReceiptSyncEngine.getInstance();
6152
- markReadReceiptEngine.markRead(message.channelId, message.channelSegment);
6153
- }
6154
- else {
6155
- const markReadReceiptEngine = LegacyReadReceiptSyncEngine.getInstance();
6156
- markReadReceiptEngine.markRead(message.subChannelId, message.channelSegment);
6157
- }
6158
- };
6159
-
6160
- const messageLinkedObject = (message) => {
6161
- const rest = __rest(message, ["creatorPrivateId"]);
6162
- return Object.assign(Object.assign({}, rest), { get readCount() {
6163
- return getMessageReadCount(message).readCount;
6164
- },
6165
- get deliveredCount() {
6166
- return getMessageReadCount(message).deliveredCount;
6167
- },
6168
- get creator() {
6169
- var _a;
6170
- return (_a = pullFromCache(['user', 'get', message.creatorId])) === null || _a === void 0 ? void 0 : _a.data;
6171
- }, markRead: () => markReadMessage(message) });
6172
- };
6173
-
6174
- const reactorLinkedObject = (reactor) => {
6175
- return Object.assign(Object.assign({}, reactor), { get user() {
6176
- var _a;
6177
- const user = (_a = pullFromCache(['user', 'get', reactor.userId])) === null || _a === void 0 ? void 0 : _a.data;
6178
- if (!user)
6179
- return undefined;
6180
- return userLinkedObject(user);
6181
- } });
6182
- };
6183
-
6184
- /**
6185
- * ```js
6186
- * import { ChannelRepository } from '@amityco/ts-sdk'
6187
- * const success = await ChannelRepository.markAsRead('channelId')
6188
- * ```
6189
- * Updating all {@link Amity.SubChannel} in specify {@link Amity.Channel} as read
6190
- *
6191
- * @param channelId the ID of to specify {@link Amity.Channel}
6192
- * @returns A success boolean if the {@link Amity.Channel} was mark read
6193
- *
6194
- * @category Channel API
6195
- * @async
6196
- */
6197
- const markAsRead = async (channelId) => {
6198
- const client = getActiveClient();
6199
- client.log('channel/markAsRead', channelId);
6200
- const { data } = await client.http.put(`/api/v1/markers/channels/${channelId}/mark-read`);
6201
- const { userMarkers, userEntityMarkers: userEntityMarkersPayload, userFeedMarkers: userFeedMarkersPayload } = data, rest = __rest(data, ["userMarkers", "userEntityMarkers", "userFeedMarkers"]);
6202
- const cachedAt = client.cache && Date.now();
6203
- const channelMarkers = convertChannelMarkerResponse(userEntityMarkersPayload);
6204
- const subChannelMarkers = convertSubChannelMarkerResponse(userFeedMarkersPayload);
6205
- if (client.cache)
6206
- ingestInCache(Object.assign({ userMarkers, userEntityMarkers: channelMarkers, userFeedMarkers: subChannelMarkers }, rest), { cachedAt });
6207
- fireEvent('local.channelMarker.updated', {
6208
- userEntityMarkers: channelMarkers,
6209
- });
6210
- fireEvent('local.subChannelMarker.updated', {
6211
- userFeedMarkers: subChannelMarkers,
6212
- });
6213
- return true;
6214
- };
6215
-
6216
- /**
6217
- * ```js
6218
- * import { shallowClone } from '~/utils/shallowClone'
6219
- * const newObj = shallowClone(obj)
6220
- * ```
6221
- *
6222
- * Clone an object with same prototype and properties
6223
- *
6224
- * @param obj the object to clone
6225
- * @returns new object with same prototype and properties
6226
- *
6227
- * @category utility
6228
- * @private
6229
- */
6230
- function shallowClone(source, target) {
6231
- return Object.create(Object.getPrototypeOf(source), Object.assign(Object.assign({}, Object.getOwnPropertyDescriptors(source)), Object.getOwnPropertyDescriptors(target)));
6232
- }
7212
+ if (index > -1) {
7213
+ this.jobQueue.splice(index, 1);
7214
+ }
7215
+ }
7216
+ }
7217
+ let instance$3 = null;
7218
+ var LegacyReadReceiptSyncEngine = {
7219
+ getInstance: () => {
7220
+ if (!instance$3)
7221
+ instance$3 = new LegacyMessageReadReceiptSyncEngine();
7222
+ return instance$3;
7223
+ },
7224
+ };
6233
7225
 
6234
- const channelLinkedObject = (channel) => {
6235
- return shallowClone(channel, {
6236
- markAsRead: () => markAsRead(channel.channelInternalId),
6237
- });
7226
+ const markReadMessage = (message) => {
7227
+ const client = getActiveClient();
7228
+ if (client.useLegacyUnreadCount) {
7229
+ const markReadReceiptEngine = ReadReceiptSyncEngine.getInstance();
7230
+ markReadReceiptEngine.markRead(message.channelId, message.channelSegment);
7231
+ }
7232
+ else {
7233
+ const markReadReceiptEngine = LegacyReadReceiptSyncEngine.getInstance();
7234
+ markReadReceiptEngine.markRead(message.subChannelId, message.channelSegment);
7235
+ }
6238
7236
  };
6239
7237
 
6240
- const adLinkedObject = (ad) => {
6241
- const analyticsEngineInstance = AnalyticsEngine$1.getInstance();
6242
- const { image9_16: image916, image1_1: image11 } = ad, restAds = __rest(ad, ["image9_16", "image1_1"]);
6243
- return Object.assign(Object.assign({}, restAds), { analytics: {
6244
- markAsSeen: (placement) => {
6245
- analyticsEngineInstance.markAdAsViewed(ad, placement);
6246
- },
6247
- markLinkAsClicked: (placement) => {
6248
- analyticsEngineInstance.markAdAsClicked(ad, placement);
6249
- },
6250
- }, get advertiser() {
6251
- var _a, _b;
6252
- const advertiserData = (_a = pullFromCache([
6253
- 'advertiser',
6254
- 'get',
6255
- ad.advertiserId,
6256
- ])) === null || _a === void 0 ? void 0 : _a.data;
6257
- if (!advertiserData)
6258
- return;
6259
- const avatarFile = (_b = pullFromCache([
6260
- 'file',
6261
- 'get',
6262
- advertiserData.avatarFileId,
6263
- ])) === null || _b === void 0 ? void 0 : _b.data;
6264
- return Object.assign(Object.assign({}, advertiserData), { avatar: avatarFile });
7238
+ const messageLinkedObject = (message) => {
7239
+ const rest = __rest(message, ["creatorPrivateId"]);
7240
+ return Object.assign(Object.assign({}, rest), { get readCount() {
7241
+ return getMessageReadCount(message).readCount;
6265
7242
  },
6266
- get image1_1() {
6267
- const cacheData = pullFromCache(['file', 'get', image11]);
6268
- if (!cacheData)
6269
- return undefined;
6270
- return cacheData.data || undefined;
7243
+ get deliveredCount() {
7244
+ return getMessageReadCount(message).deliveredCount;
6271
7245
  },
6272
- get image9_16() {
6273
- const cacheData = pullFromCache(['file', 'get', image916]);
6274
- if (!cacheData)
6275
- return undefined;
6276
- return cacheData.data || undefined;
6277
- } });
7246
+ get creator() {
7247
+ var _a;
7248
+ return (_a = pullFromCache(['user', 'get', message.creatorId])) === null || _a === void 0 ? void 0 : _a.data;
7249
+ }, markRead: () => markReadMessage(message) });
6278
7250
  };
6279
7251
 
6280
- const pinnedPostLinkedObject = (pinnedPost) => {
6281
- var _a;
6282
- const postCached = pullFromCache(['post', 'get', pinnedPost.referenceId]);
6283
- const pinnedBy = (_a = queryCache(['user', 'get']).find(cache => {
6284
- var _a;
6285
- return ((_a = cache.data) === null || _a === void 0 ? void 0 : _a.userInternalId) === pinnedPost.pinnedBy;
6286
- })) === null || _a === void 0 ? void 0 : _a.data;
6287
- return Object.assign(Object.assign({}, pinnedPost), { pinnedBy,
6288
- get post() {
6289
- if (!(postCached === null || postCached === void 0 ? void 0 : postCached.data))
6290
- return;
6291
- return postLinkedObject(postCached.data);
6292
- },
6293
- get target() {
6294
- const pinTarget = pullFromCache([
6295
- 'pinTarget',
6296
- 'get',
6297
- postCached === null || postCached === void 0 ? void 0 : postCached.data.targetId,
6298
- ]);
6299
- if (!(pinTarget === null || pinTarget === void 0 ? void 0 : pinTarget.data))
6300
- return;
6301
- return pinTarget === null || pinTarget === void 0 ? void 0 : pinTarget.data;
7252
+ const reactorLinkedObject = (reactor) => {
7253
+ return Object.assign(Object.assign({}, reactor), { get user() {
7254
+ var _a;
7255
+ const user = (_a = pullFromCache(['user', 'get', reactor.userId])) === null || _a === void 0 ? void 0 : _a.data;
7256
+ if (!user)
7257
+ return undefined;
7258
+ return userLinkedObject(user);
6302
7259
  } });
6303
7260
  };
6304
7261
 
6305
- const notificationTrayLinkedObject = (noti) => {
6306
- return Object.assign(Object.assign({}, noti), { isSeen: noti.lastSeenAt > noti.lastOccurredAt, isRecent: new Date(noti.lastOccurredAt).getTime() >= Date.now() - WEEK, users: noti.actors
6307
- .map(({ publicId }) => pullFromCache(['user', 'get', publicId]))
6308
- .filter(isNonNullable)
6309
- .map(({ data }) => data)
6310
- .map(user => userLinkedObject(user)) });
6311
- };
6312
-
6313
- /* begin_public_function
6314
- id: invitation.createInvitations
6315
- */
6316
- /**
6317
- * ```js
6318
- * import { createInvitations } from '@amityco/ts-sdk'
6319
- * const created = await createInvitations({
6320
- * type: string,
6321
- * targetType: string,
6322
- * targetId: string,
6323
- * userIds: string[]
6324
- * }))
6325
- * ```
6326
- *
6327
- * Creates an {@link Amity.Invitation}
6328
- *
6329
- * @param bundle The data necessary to create a new {@link Amity.Invitation}
6330
- * @returns The newly created {@link Amity.Invitation}
6331
- *
6332
- * @category Invitation API
6333
- * @async
6334
- */
6335
- const createInvitations = async (bundle) => {
6336
- const client = getActiveClient();
6337
- client.log('invitation/createInvitations', bundle);
6338
- const { data } = await client.http.post('/api/v1/invitations', bundle);
6339
- const cachedAt = client.cache && Date.now();
6340
- if (client.cache)
6341
- ingestInCache(data, { cachedAt });
6342
- fireEvent('local.invitation.created', data);
6343
- return {
6344
- data: data.invitations,
6345
- cachedAt,
6346
- };
6347
- };
6348
- /* end_public_function */
6349
-
6350
- /* begin_public_function
6351
- id: invitation.accept
6352
- */
6353
- /**
6354
- * ```js
6355
- * import { acceptInvitation } from '@amityco/ts-sdk'
6356
- * const isAccepted = await acceptInvitation(invitationId)
6357
- * ```
6358
- *
6359
- * Accepts a {@link Amity.Invitation} object
6360
- *
6361
- * @param invitationId the {@link Amity.Invitation} to accept
6362
- * @returns A success boolean if the {@link Amity.Invitation} was accepted
6363
- *
6364
- * @category Invitation API
6365
- * @async
6366
- */
6367
- const acceptInvitation = async (invitationId) => {
6368
- var _a;
6369
- const client = getActiveClient();
6370
- client.log('invitation/acceptInvitation', invitationId);
6371
- const { data } = await client.http.post(`/api/v1/invitations/${invitationId}/accept`);
6372
- const invitation = (_a = pullFromCache([
6373
- 'invitation',
6374
- 'get',
6375
- invitationId,
6376
- ])) === null || _a === void 0 ? void 0 : _a.data;
6377
- if (invitation) {
6378
- upsertInCache(['invitation', 'get', invitationId], { status: "approved" /* InvitationStatusEnum.Approved */ });
6379
- fireEvent('local.invitation.updated', { invitations: [invitation] });
6380
- }
6381
- return data.success;
6382
- };
6383
- /* end_public_function */
6384
-
6385
- /* begin_public_function
6386
- id: invitation.reject
6387
- */
6388
- /**
6389
- * ```js
6390
- * import { rejectInvitation } from '@amityco/ts-sdk'
6391
- * const isRejected = await rejectInvitation(invitationId)
6392
- * ```
6393
- *
6394
- * Rejects a {@link Amity.Invitation} object
6395
- *
6396
- * @param invitationId the {@link Amity.Invitation} to reject
6397
- * @returns A success boolean if the {@link Amity.Invitation} was rejected
6398
- *
6399
- * @category Invitation API
6400
- * @async
6401
- */
6402
- const rejectInvitation = async (invitationId) => {
6403
- var _a;
6404
- const client = getActiveClient();
6405
- client.log('invitation/rejectInvitation', invitationId);
6406
- const { data } = await client.http.post(`/api/v1/invitations/${invitationId}/reject`);
6407
- const invitation = (_a = pullFromCache([
6408
- 'invitation',
6409
- 'get',
6410
- invitationId,
6411
- ])) === null || _a === void 0 ? void 0 : _a.data;
6412
- if (invitation) {
6413
- upsertInCache(['invitation', 'get', invitationId], { status: "rejected" /* InvitationStatusEnum.Rejected */ });
6414
- fireEvent('local.invitation.updated', { invitations: [invitation] });
6415
- }
6416
- return data.success;
6417
- };
6418
- /* end_public_function */
6419
-
6420
- /* begin_public_function
6421
- id: invitation.cancel
6422
- */
6423
7262
  /**
6424
7263
  * ```js
6425
- * import { cancelInvitation } from '@amityco/ts-sdk'
6426
- * const isCanceled = await cancelInvitation(invitationId)
7264
+ * import { ChannelRepository } from '@amityco/ts-sdk'
7265
+ * const success = await ChannelRepository.markAsRead('channelId')
6427
7266
  * ```
7267
+ * Updating all {@link Amity.SubChannel} in specify {@link Amity.Channel} as read
6428
7268
  *
6429
- * Cancels a {@link Amity.Invitation} object
6430
- *
6431
- * @param invitationId the {@link Amity.Invitation} to cancel
6432
- * @returns A success boolean if the {@link Amity.Invitation} was canceled
7269
+ * @param channelId the ID of to specify {@link Amity.Channel}
7270
+ * @returns A success boolean if the {@link Amity.Channel} was mark read
6433
7271
  *
6434
- * @category Invitation API
7272
+ * @category Channel API
6435
7273
  * @async
6436
- */
6437
- const cancelInvitation = async (invitationId) => {
6438
- var _a;
6439
- const client = getActiveClient();
6440
- client.log('invitation/cancelInvitation', invitationId);
6441
- const { data } = await client.http.delete(`/api/v1/invitations/${invitationId}`);
6442
- const invitation = (_a = pullFromCache([
6443
- 'invitation',
6444
- 'get',
6445
- invitationId,
6446
- ])) === null || _a === void 0 ? void 0 : _a.data;
6447
- if (invitation) {
6448
- dropFromCache(['invitation', 'get', invitationId]);
6449
- fireEvent('local.invitation.deleted', { invitations: [invitation] });
6450
- }
6451
- return data.success;
6452
- };
6453
- /* end_public_function */
6454
-
6455
- const communityLinkedObject = (community) => {
6456
- return Object.assign(Object.assign({}, community), { createInvitations: async (userIds) => {
6457
- await createInvitations({
6458
- type: "communityMemberInvite" /* InvitationTypeEnum.CommunityMemberInvite */,
6459
- targetType: 'community',
6460
- targetId: community.communityId,
6461
- userIds,
6462
- });
6463
- } });
7274
+ */
7275
+ const markAsRead = async (channelId) => {
7276
+ const client = getActiveClient();
7277
+ client.log('channel/markAsRead', channelId);
7278
+ const { data } = await client.http.put(`/api/v1/markers/channels/${channelId}/mark-read`);
7279
+ const { userMarkers, userEntityMarkers: userEntityMarkersPayload, userFeedMarkers: userFeedMarkersPayload } = data, rest = __rest(data, ["userMarkers", "userEntityMarkers", "userFeedMarkers"]);
7280
+ const cachedAt = client.cache && Date.now();
7281
+ const channelMarkers = convertChannelMarkerResponse(userEntityMarkersPayload);
7282
+ const subChannelMarkers = convertSubChannelMarkerResponse(userFeedMarkersPayload);
7283
+ if (client.cache)
7284
+ ingestInCache(Object.assign({ userMarkers, userEntityMarkers: channelMarkers, userFeedMarkers: subChannelMarkers }, rest), { cachedAt });
7285
+ fireEvent('local.channelMarker.updated', {
7286
+ userEntityMarkers: channelMarkers,
7287
+ });
7288
+ fireEvent('local.subChannelMarker.updated', {
7289
+ userFeedMarkers: subChannelMarkers,
7290
+ });
7291
+ return true;
6464
7292
  };
6465
7293
 
6466
- const invitationLinkedObject = (invitation) => {
6467
- return Object.assign(Object.assign({}, invitation), { accept: async () => {
6468
- await acceptInvitation(invitation._id);
6469
- }, reject: async () => {
6470
- await rejectInvitation(invitation._id);
6471
- }, cancel: async () => {
6472
- await cancelInvitation(invitation._id);
6473
- } });
7294
+ const channelLinkedObject = (channel) => {
7295
+ return shallowClone(channel, {
7296
+ markAsRead: () => markAsRead(channel.channelInternalId),
7297
+ });
6474
7298
  };
6475
7299
 
6476
- const LinkedObject = {
6477
- ad: adLinkedObject,
6478
- comment: commentLinkedObject,
6479
- post: postLinkedObject,
6480
- user: userLinkedObject,
6481
- category: categoryLinkedObject,
6482
- stream: streamLinkedObject,
6483
- story: storyLinkedObject,
6484
- storyTarget: storyTargetLinkedObject,
6485
- message: messageLinkedObject,
6486
- reactor: reactorLinkedObject,
6487
- channel: channelLinkedObject,
6488
- pinnedPost: pinnedPostLinkedObject,
6489
- notificationTray: notificationTrayLinkedObject,
6490
- community: communityLinkedObject,
6491
- invitation: invitationLinkedObject,
7300
+ const adLinkedObject = (ad) => {
7301
+ const analyticsEngineInstance = AnalyticsEngine$1.getInstance();
7302
+ const { image9_16: image916, image1_1: image11 } = ad, restAds = __rest(ad, ["image9_16", "image1_1"]);
7303
+ return Object.assign(Object.assign({}, restAds), { analytics: {
7304
+ markAsSeen: (placement) => {
7305
+ analyticsEngineInstance.markAdAsViewed(ad, placement);
7306
+ },
7307
+ markLinkAsClicked: (placement) => {
7308
+ analyticsEngineInstance.markAdAsClicked(ad, placement);
7309
+ },
7310
+ }, get advertiser() {
7311
+ var _a, _b;
7312
+ const advertiserData = (_a = pullFromCache([
7313
+ 'advertiser',
7314
+ 'get',
7315
+ ad.advertiserId,
7316
+ ])) === null || _a === void 0 ? void 0 : _a.data;
7317
+ if (!advertiserData)
7318
+ return;
7319
+ const avatarFile = (_b = pullFromCache([
7320
+ 'file',
7321
+ 'get',
7322
+ advertiserData.avatarFileId,
7323
+ ])) === null || _b === void 0 ? void 0 : _b.data;
7324
+ return Object.assign(Object.assign({}, advertiserData), { avatar: avatarFile });
7325
+ },
7326
+ get image1_1() {
7327
+ const cacheData = pullFromCache(['file', 'get', image11]);
7328
+ if (!cacheData)
7329
+ return undefined;
7330
+ return cacheData.data || undefined;
7331
+ },
7332
+ get image9_16() {
7333
+ const cacheData = pullFromCache(['file', 'get', image916]);
7334
+ if (!cacheData)
7335
+ return undefined;
7336
+ return cacheData.data || undefined;
7337
+ } });
6492
7338
  };
6493
7339
 
6494
- const getChannelMessagePreviewWithUser = (channel) => {
7340
+ const pinnedPostLinkedObject = (pinnedPost) => {
6495
7341
  var _a;
6496
- const messagePreview = channel.messagePreviewId
6497
- ? getChannelMessagePreview(channel.channelId)
6498
- : null;
6499
- const internalUser = (_a = pullFromCache([
6500
- 'user',
6501
- 'get',
6502
- messagePreview === null || messagePreview === void 0 ? void 0 : messagePreview.creatorId,
6503
- ])) === null || _a === void 0 ? void 0 : _a.data;
6504
- const messagePreviewWithUser = messagePreview
6505
- ? Object.assign(Object.assign({}, messagePreview), { user: internalUser ? LinkedObject.user(internalUser) : undefined }) : null;
6506
- return Object.assign(Object.assign({}, channel), { messagePreview: messagePreviewWithUser });
6507
- };
6508
-
6509
- const updateChannelMessagePreviewCache = (rawPayload) => {
6510
- var _a, _b;
6511
- const withMessageFeedInfo = (messagePreview) => {
7342
+ const postCached = pullFromCache(['post', 'get', pinnedPost.referenceId]);
7343
+ const pinnedBy = (_a = queryCache(['user', 'get']).find(cache => {
6512
7344
  var _a;
6513
- const messageFeedInfo = (_a = rawPayload.messageFeedsInfo) === null || _a === void 0 ? void 0 : _a.find(messageFeed => {
6514
- return messageFeed.messageFeedId === messagePreview.messageFeedId;
6515
- });
6516
- const { channelPublicId: channelId, messageFeedId: subChannelId, data, dataType, isDeleted, segment, creatorPublicId: creatorId, createdAt, updatedAt, } = messagePreview;
6517
- return {
6518
- channelId,
6519
- subChannelId,
6520
- data,
6521
- dataType,
6522
- isDeleted,
6523
- segment,
6524
- creatorId,
6525
- createdAt,
6526
- updatedAt,
6527
- subChannelName: messageFeedInfo === null || messageFeedInfo === void 0 ? void 0 : messageFeedInfo.name,
6528
- messagePreviewId: messageFeedInfo === null || messageFeedInfo === void 0 ? void 0 : messageFeedInfo.messagePreviewId,
6529
- subChannelUpdatedAt: messageFeedInfo === null || messageFeedInfo === void 0 ? void 0 : messageFeedInfo.updatedAt,
6530
- };
6531
- };
6532
- const newData = {
6533
- messagePreviewChannel: (_b = (_a = rawPayload.messagePreviews) === null || _a === void 0 ? void 0 : _a.map(messagePreview => withMessageFeedInfo(messagePreview))) !== null && _b !== void 0 ? _b : [],
6534
- };
6535
- ingestInCache(newData);
7345
+ return ((_a = cache.data) === null || _a === void 0 ? void 0 : _a.userInternalId) === pinnedPost.pinnedBy;
7346
+ })) === null || _a === void 0 ? void 0 : _a.data;
7347
+ return Object.assign(Object.assign({}, pinnedPost), { pinnedBy,
7348
+ get post() {
7349
+ if (!(postCached === null || postCached === void 0 ? void 0 : postCached.data))
7350
+ return;
7351
+ return postLinkedObject(postCached.data);
7352
+ },
7353
+ get target() {
7354
+ const pinTarget = pullFromCache([
7355
+ 'pinTarget',
7356
+ 'get',
7357
+ postCached === null || postCached === void 0 ? void 0 : postCached.data.targetId,
7358
+ ]);
7359
+ if (!(pinTarget === null || pinTarget === void 0 ? void 0 : pinTarget.data))
7360
+ return;
7361
+ return pinTarget === null || pinTarget === void 0 ? void 0 : pinTarget.data;
7362
+ } });
6536
7363
  };
6537
7364
 
6538
- const getSubChannelMessagePreview = (subChannelId) => {
6539
- var _a, _b;
6540
- return ((_b = (_a = pullFromCache(['messagePreviewSubChannel', 'get', subChannelId])) === null || _a === void 0 ? void 0 : _a.data) !== null && _b !== void 0 ? _b : null);
7365
+ const notificationTrayLinkedObject = (noti) => {
7366
+ return Object.assign(Object.assign({}, noti), { isSeen: noti.lastSeenAt > noti.lastOccurredAt, isRecent: new Date(noti.lastOccurredAt).getTime() >= Date.now() - WEEK, users: noti.actors
7367
+ .map(({ publicId }) => pullFromCache(['user', 'get', publicId]))
7368
+ .filter(isNonNullable)
7369
+ .map(({ data }) => data)
7370
+ .map(user => userLinkedObject(user)) });
6541
7371
  };
6542
7372
 
6543
- const getSubChannelMessagePreviewWithUser = (subChannel) => {
6544
- var _a;
6545
- const messagePreview = subChannel.messagePreviewId
6546
- ? getSubChannelMessagePreview(subChannel.subChannelId)
6547
- : null;
6548
- const messagePreviewWithUser = messagePreview
6549
- ? Object.assign(Object.assign({}, messagePreview), { user: (_a = pullFromCache(['user', 'get', messagePreview === null || messagePreview === void 0 ? void 0 : messagePreview.creatorId])) === null || _a === void 0 ? void 0 : _a.data }) : null;
6550
- return Object.assign(Object.assign({}, subChannel), { messagePreview: messagePreviewWithUser });
6551
- };
7373
+ /*
7374
+ * verifies membership status
7375
+ */
7376
+ function isMember(membership) {
7377
+ return membership !== 'none';
7378
+ }
7379
+ /*
7380
+ * checks if currently logged in user is part of the community
7381
+ */
7382
+ function isCurrentUserPartOfCommunity(c, m) {
7383
+ const { userId } = getActiveUser();
7384
+ return c.communityId === m.communityId && m.userId === userId;
7385
+ }
7386
+ /*
7387
+ * For mqtt events server will not send user specific data as it's broadcasted
7388
+ * to multiple users and it also does not include communityUser
7389
+ *
7390
+ * Client SDK needs to check for the existing isJoined field in cache data before calculating.
7391
+ * Althought this can be calculated, it's not scalable.
7392
+ */
7393
+ function updateMembershipStatus(communities, communityUsers) {
7394
+ return communities.map(c => {
7395
+ const cachedCommunity = pullFromCache([
7396
+ 'community',
7397
+ 'get',
7398
+ c.communityId,
7399
+ ]);
7400
+ if ((cachedCommunity === null || cachedCommunity === void 0 ? void 0 : cachedCommunity.data) && (cachedCommunity === null || cachedCommunity === void 0 ? void 0 : cachedCommunity.data.hasOwnProperty('isJoined'))) {
7401
+ return Object.assign(Object.assign({}, cachedCommunity.data), c);
7402
+ }
7403
+ const isJoined = communityUsers.some(m => isCurrentUserPartOfCommunity(c, m) && isMember(m.communityMembership));
7404
+ return Object.assign(Object.assign({}, c), { isJoined });
7405
+ });
7406
+ }
6552
7407
 
6553
- const updateSubChannelMessagePreviewCache = (rawPayload) => {
6554
- var _a, _b;
6555
- const withMessageFeedInfo = (messagePreview) => {
6556
- var _a;
6557
- const messageFeedInfo = (_a = rawPayload.messageFeeds) === null || _a === void 0 ? void 0 : _a.find(messageFeed => {
6558
- return messageFeed.messageFeedId === messagePreview.messageFeedId;
6559
- });
6560
- const { channelPublicId: channelId, messageFeedId: subChannelId, messageId: messagePreviewId, creatorPublicId: creatorId, data, dataType, isDeleted, segment, createdAt, updatedAt, } = messagePreview;
6561
- return {
6562
- messagePreviewId,
6563
- channelId,
6564
- subChannelId,
6565
- data,
6566
- dataType,
6567
- isDeleted,
6568
- segment,
6569
- creatorId,
6570
- createdAt,
6571
- updatedAt,
6572
- subChannelName: messageFeedInfo === null || messageFeedInfo === void 0 ? void 0 : messageFeedInfo.name,
6573
- subChannelUpdatedAt: messageFeedInfo === null || messageFeedInfo === void 0 ? void 0 : messageFeedInfo.updatedAt,
6574
- };
6575
- };
6576
- const newData = {
6577
- messagePreviewSubChannel: (_b = (_a = rawPayload.messages) === null || _a === void 0 ? void 0 : _a.map(messagePreview => withMessageFeedInfo(messagePreview))) !== null && _b !== void 0 ? _b : [],
6578
- };
6579
- ingestInCache(newData);
7408
+ const getMatchPostSetting = (value) => {
7409
+ var _a;
7410
+ return (_a = Object.keys(CommunityPostSettingMaps).find(key => value.needApprovalOnPostCreation ===
7411
+ CommunityPostSettingMaps[key].needApprovalOnPostCreation &&
7412
+ value.onlyAdminCanPost === CommunityPostSettingMaps[key].onlyAdminCanPost)) !== null && _a !== void 0 ? _a : DefaultCommunityPostSetting;
7413
+ };
7414
+ function addPostSetting({ communities }) {
7415
+ return communities.map((_a) => {
7416
+ var { needApprovalOnPostCreation, onlyAdminCanPost } = _a, restCommunityPayload = __rest(_a, ["needApprovalOnPostCreation", "onlyAdminCanPost"]);
7417
+ return (Object.assign({ postSetting: getMatchPostSetting({
7418
+ needApprovalOnPostCreation,
7419
+ onlyAdminCanPost,
7420
+ }) }, restCommunityPayload));
7421
+ });
7422
+ }
7423
+ const prepareCommunityPayload = (rawPayload) => {
7424
+ const communitiesWithPostSetting = addPostSetting({ communities: rawPayload.communities });
7425
+ // Convert users to internal format
7426
+ const internalUsers = rawPayload.users.map(convertRawUserToInternalUser);
7427
+ // map users with community
7428
+ const mappedCommunityUsers = rawPayload.communityUsers.map(communityUser => {
7429
+ const user = internalUsers.find(user => user.userId === communityUser.userId);
7430
+ return Object.assign(Object.assign({}, communityUser), { user });
7431
+ });
7432
+ const communityWithMembershipStatus = updateMembershipStatus(communitiesWithPostSetting, mappedCommunityUsers);
7433
+ return Object.assign(Object.assign({}, rawPayload), { users: rawPayload.users.map(convertRawUserToInternalUser), communities: communityWithMembershipStatus, communityUsers: mappedCommunityUsers });
7434
+ };
7435
+ const prepareCommunityJoinRequestPayload = (rawPayload) => {
7436
+ const mappedJoinRequests = rawPayload.joinRequests.map(joinRequest => {
7437
+ return Object.assign(Object.assign({}, joinRequest), { joinRequestId: joinRequest._id });
7438
+ });
7439
+ const users = rawPayload.users.map(convertRawUserToInternalUser);
7440
+ return Object.assign(Object.assign({}, rawPayload), { joinRequests: mappedJoinRequests, users });
7441
+ };
7442
+ const prepareCommunityMembershipPayload = (rawPayload) => {
7443
+ const communitiesWithPostSetting = addPostSetting({ communities: rawPayload.communities });
7444
+ // map users with community
7445
+ const mappedCommunityUsers = rawPayload.communityUsers.map(communityUser => {
7446
+ const user = rawPayload.users.find(user => user.userId === communityUser.userId);
7447
+ return Object.assign(Object.assign({}, communityUser), { user });
7448
+ });
7449
+ const communityWithMembershipStatus = updateMembershipStatus(communitiesWithPostSetting, mappedCommunityUsers);
7450
+ return Object.assign(Object.assign({}, rawPayload), { communities: communityWithMembershipStatus, communityUsers: mappedCommunityUsers });
7451
+ };
7452
+ const prepareCommunityRequest = (params) => {
7453
+ const { postSetting = undefined, storySetting } = params, restParam = __rest(params, ["postSetting", "storySetting"]);
7454
+ return Object.assign(Object.assign(Object.assign({}, restParam), (postSetting ? CommunityPostSettingMaps[postSetting] : undefined)), {
7455
+ // Convert story setting to the actual value. (Allow by default)
7456
+ allowCommentInStory: typeof (storySetting === null || storySetting === void 0 ? void 0 : storySetting.enableComment) === 'boolean' ? storySetting.enableComment : true });
7457
+ };
7458
+ const prepareSemanticSearchCommunityPayload = (_a) => {
7459
+ var communityPayload = __rest(_a, ["searchResult"]);
7460
+ const processedCommunityPayload = prepareCommunityPayload(communityPayload);
7461
+ return Object.assign({}, processedCommunityPayload);
6580
7462
  };
6581
7463
 
6582
- function updateSubChannelCache(subChannelId, subChannel, params) {
6583
- pushToCache(['subChannel', 'get', subChannelId],
6584
- // eslint-disable-next-line prefer-object-spread
6585
- shallowClone(subChannel, params));
6586
- }
6587
-
7464
+ /* begin_public_function
7465
+ id: joinRequest.approve
7466
+ */
6588
7467
  /**
6589
7468
  * ```js
6590
- * import { isInTombstone } from '@amityco/ts-sdk'
6591
- * const user = isInTombstone(["message", "messageId"])
7469
+ * import { joinRequest } from '@amityco/ts-sdk'
7470
+ * const isAccepted = await joinRequest.approve()
6592
7471
  * ```
6593
7472
  *
6594
- * Checks if the {@link Amity.TombstoneCacheOptions} exists
6595
- * in cache and it's not expired means it's in tombstone
6596
- * and we throw an Error
7473
+ * Accepts a {@link Amity.JoinRequest} object
6597
7474
  *
6598
- * @param model the model to check
6599
- * @param modelId the object id to check
6600
- * @returns the matching cache entry, or undefined.
7475
+ * @param joinRequest the {@link Amity.JoinRequest} to accept
7476
+ * @returns A success boolean if the {@link Amity.JoinRequest} was accepted
6601
7477
  *
6602
- * @category Cache API
7478
+ * @category Join Request API
7479
+ * @async
6603
7480
  */
6604
- const isInTombstone = (model, modelId) => {
6605
- const { log, cache } = getActiveClient();
6606
- const key = [model, CACHE_KEY_TOMBSTONE, modelId];
6607
- if (!cache)
6608
- return;
6609
- log('cache/api/isInTombstone', key);
6610
- const isInTombstone = pullFromCache(key);
6611
- const { lifeSpan } = queryOptions('cache_then_server', CACHE_LIFESPAN_TOMBSTONE);
6612
- if (isInTombstone && isFresh(isInTombstone.data, lifeSpan)) {
6613
- throw new ASCApiError('Item not found!', 400400 /* Amity.ServerError.ITEM_NOT_FOUND */, "error" /* Amity.ErrorLevel.ERROR */);
7481
+ const approveJoinRequest = async (joinRequest) => {
7482
+ var _a;
7483
+ const client = getActiveClient();
7484
+ client.log('joinRequest/approveJoinRequest', joinRequest.joinRequestId);
7485
+ const { data } = await client.http.post(`/api/v4/communities/${joinRequest.targetId}/join/approve`, {
7486
+ userId: joinRequest.requestorInternalId,
7487
+ });
7488
+ const joinRequestCache = (_a = pullFromCache([
7489
+ 'joinRequest',
7490
+ 'get',
7491
+ joinRequest.joinRequestId,
7492
+ ])) === null || _a === void 0 ? void 0 : _a.data;
7493
+ if (joinRequestCache) {
7494
+ upsertInCache(['joinRequest', 'get', joinRequest.joinRequestId], {
7495
+ status: "approved" /* JoinRequestStatusEnum.Approved */,
7496
+ });
7497
+ fireEvent('local.joinRequest.updated', [joinRequestCache]);
6614
7498
  }
6615
- };
7499
+ return data.success;
7500
+ };
7501
+ /* end_public_function */
6616
7502
 
7503
+ /* begin_public_function
7504
+ id: joinRequest.cancel
7505
+ */
6617
7506
  /**
6618
7507
  * ```js
6619
- * import { getMessageMarkers } from '@amityco/ts-sdk'
6620
- * const messageMarkers = await getMessageMarkers(['sch1', 'sch2'])
7508
+ * import { joinRequest } from '@amityco/ts-sdk'
7509
+ * const isCanceled = await joinRequest.cancel()
6621
7510
  * ```
6622
7511
  *
6623
- * Fetches a list of {@link Amity.MessageMarker} by messageIds
7512
+ * Cancels a {@link Amity.JoinRequest} object
6624
7513
  *
6625
- * @param messageIds the feed IDs of the {@link Amity.RawMessage} marker to fetch
6626
- * @returns A list of {@link Amity.MessageMarker} by messageIds
7514
+ * @param joinRequest the {@link Amity.JoinRequest} to cancel
7515
+ * @returns A success boolean if the {@link Amity.JoinRequest} was canceled
6627
7516
  *
6628
- * @category Channel API
7517
+ * @category Join Request API
6629
7518
  * @async
6630
- * @private
6631
7519
  */
6632
- const getMessageMarkers = async (messageIds) => {
7520
+ const cancelJoinRequest = async (joinRequest) => {
7521
+ var _a;
6633
7522
  const client = getActiveClient();
6634
- client.log('channel/getMessageMarkers', messageIds);
6635
- const { data: queryPayload } = await client.http.get(`/api/v1/markers/messages`, {
6636
- params: {
6637
- messageIds,
6638
- },
6639
- });
6640
- const { contentMarkers, feedMarkers, userMarkers } = queryPayload;
6641
- const cachedAt = client.cache && Date.now();
6642
- if (client.cache)
6643
- ingestInCache({ contentMarkers, feedMarkers, userMarkers }, { cachedAt });
6644
- fireEvent('local.feedMarker.fetched', { feedMarkers });
6645
- fireEvent('local.messageMarker.fetched', { contentMarkers });
6646
- fireEvent('local.userMarker.fetched', { userMarkers });
6647
- return { data: contentMarkers, cachedAt };
6648
- };
6649
-
6650
- const persistUnreadCountInfo = (payload) => {
6651
- const { feedMarkers, userFeedMarkers } = payload;
6652
- // calculate sub channel unread info and channel unread info
6653
- if (feedMarkers.length > 0 && userFeedMarkers.length > 0) {
6654
- const channelIds = [];
6655
- const feedMarkerMap = new Map(feedMarkers.map(fm => [fm.feedId, fm]));
6656
- userFeedMarkers.forEach(userFeedMarker => {
6657
- const feedMarker = feedMarkerMap.get(userFeedMarker.feedId);
6658
- if (!feedMarker)
6659
- return;
6660
- if (feedMarker.feedId === userFeedMarker.feedId) {
6661
- const unreadCount = feedMarker.lastSegment - userFeedMarker.readToSegment;
6662
- const subChannelUnreadInfo = {
6663
- subChannelId: feedMarker.feedId,
6664
- channelId: feedMarker.entityId,
6665
- readToSegment: userFeedMarker.readToSegment,
6666
- lastSegment: feedMarker.lastSegment,
6667
- lastMentionSegment: userFeedMarker.lastMentionSegment,
6668
- unreadCount: Math.max(0, unreadCount),
6669
- isMentioned: userFeedMarker.isMentioned,
6670
- isDeleted: feedMarker.isDeleted,
6671
- createdAt: userFeedMarker.createdAt,
6672
- updatedAt: userFeedMarker.updatedAt,
6673
- };
6674
- // update sub channel unread info in cache
6675
- ingestInCache({ subChannelUnreadInfo: [subChannelUnreadInfo] });
6676
- if (!channelIds.includes(feedMarker.entityId)) {
6677
- channelIds.push(feedMarker.entityId);
6678
- }
6679
- }
6680
- });
6681
- // re-calculate channel unread info in cache
6682
- channelIds.forEach(channelId => {
6683
- reCalculateChannelUnreadInfo(channelId);
6684
- });
7523
+ client.log('joinRequest/cancelJoinRequest', joinRequest.joinRequestId);
7524
+ const { data } = await client.http.delete(`/api/v4/communities/${joinRequest.targetId}/join`);
7525
+ const joinRequestCache = (_a = pullFromCache([
7526
+ 'joinRequest',
7527
+ 'get',
7528
+ joinRequest.joinRequestId,
7529
+ ])) === null || _a === void 0 ? void 0 : _a.data;
7530
+ if (joinRequestCache) {
7531
+ dropFromCache(['joinRequest', 'get', joinRequest.joinRequestId]);
7532
+ fireEvent('local.joinRequest.deleted', [joinRequestCache]);
6685
7533
  }
6686
- };
7534
+ return data.success;
7535
+ };
7536
+ /* end_public_function */
6687
7537
 
7538
+ /* begin_public_function
7539
+ id: joinRequest.reject
7540
+ */
6688
7541
  /**
6689
7542
  * ```js
6690
- * import { getSubChannelMarkers } from '@amityco/ts-sdk'
6691
- * const subChannelMarkers = await getSubChannelMarkers(['sch1', 'sch2'])
7543
+ * import { joinRequest } from '@amityco/ts-sdk'
7544
+ * const isRejected = await joinRequest.reject()
6692
7545
  * ```
6693
7546
  *
6694
- * Fetches a paginable list of {@link Amity.SubChannelMarker} objects
7547
+ * Rejects a {@link Amity.JoinRequest} object
6695
7548
  *
6696
- * @param messageFeedIds the feed IDs of the {@link Amity.RawSubChannel} marker to fetch
6697
- * @param page
6698
- * @returns A page of {@link Amity.SubChannelMarker} objects
7549
+ * @param joinRequest the {@link Amity.JoinRequest} to reject
7550
+ * @returns A success boolean if the {@link Amity.JoinRequest} was rejected
6699
7551
  *
6700
- * @category Channel API
7552
+ * @category Join Request API
6701
7553
  * @async
6702
- * @private
6703
7554
  */
6704
- const getSubChannelMarkers = async (messageFeedIds, page = { limit: 100 }) => {
7555
+ const rejectJoinRequest = async (joinRequest) => {
7556
+ var _a;
6705
7557
  const client = getActiveClient();
6706
- client.log('channel/getSubChannelMarkers', messageFeedIds, page);
6707
- const { data: queryPayload } = await client.http.get(`/api/v1/markers/message-feeds`, {
6708
- params: {
6709
- messageFeedIds,
6710
- options: {
6711
- token: toToken(page, 'skiplimit'),
6712
- },
6713
- },
7558
+ client.log('joinRequest/rejectJoinRequest', joinRequest.joinRequestId);
7559
+ const { data } = await client.http.post(`/api/v4/communities/${joinRequest.targetId}/join/reject`, {
7560
+ userId: joinRequest.requestorInternalId,
6714
7561
  });
6715
- const { paging } = queryPayload, payload = __rest(queryPayload, ["paging"]);
6716
- const { userEntityMarkers: userEntityMarkersPayload, userFeedMarkers: userFeedMarkersPayload, userMarkers, feedMarkers: feedMarkersPayload, } = payload;
6717
- // if consistent mode is enabled, persist the unread count info to the cache
6718
- if (client.isUnreadCountEnabled && client.getMarkerSyncConsistentMode()) {
6719
- persistUnreadCountInfo({
6720
- feedMarkers: feedMarkersPayload,
6721
- userFeedMarkers: userFeedMarkersPayload,
7562
+ const joinRequestCache = (_a = pullFromCache([
7563
+ 'joinRequest',
7564
+ 'get',
7565
+ joinRequest.joinRequestId,
7566
+ ])) === null || _a === void 0 ? void 0 : _a.data;
7567
+ if (joinRequestCache) {
7568
+ upsertInCache(['joinRequest', 'get', joinRequest.joinRequestId], {
7569
+ status: "rejected" /* JoinRequestStatusEnum.Rejected */,
6722
7570
  });
7571
+ fireEvent('local.joinRequest.updated', [joinRequestCache]);
6723
7572
  }
6724
- const userEntityMarkers = convertChannelMarkerResponse(userEntityMarkersPayload);
6725
- const userFeedMarkers = convertSubChannelMarkerResponse(userFeedMarkersPayload);
6726
- const cachedAt = client.cache && Date.now();
6727
- if (client.cache)
6728
- ingestInCache({ userEntityMarkers, userFeedMarkers, userMarkers }, { cachedAt });
6729
- fireEvent('local.channelMarker.fetched', { userEntityMarkers });
6730
- fireEvent('local.subChannelMarker.fetched', { userFeedMarkers });
6731
- fireEvent('local.userMarker.fetched', { userMarkers });
6732
- const nextPage = toPage(paging.next);
6733
- const prevPage = toPage(paging.previous);
6734
- return { data: userFeedMarkers, cachedAt, prevPage, nextPage };
6735
- };
7573
+ return data.success;
7574
+ };
7575
+ /* end_public_function */
6736
7576
 
6737
- const getUserMarker = async () => {
6738
- const client = getActiveClient();
6739
- client.log('channel/getUserMarker');
6740
- const { data: payload } = await client.http.get(`/api/v1/markers/userMarker`);
6741
- const { userMarkers } = payload;
6742
- const cachedAt = client.cache && Date.now();
6743
- if (client.cache)
6744
- ingestInCache({ userMarkers }, { cachedAt });
6745
- fireEvent('local.userMarker.fetched', { userMarkers });
6746
- const latestUserMarker = userMarkers.reduce((maxUserMarker, userMarker) => {
6747
- if (maxUserMarker == null ||
6748
- new Date(maxUserMarker.lastSyncAt).getTime() < new Date(userMarker.lastSyncAt).getTime()) {
6749
- return userMarker;
6750
- }
6751
- return maxUserMarker;
6752
- }, undefined);
6753
- return { data: latestUserMarker, cachedAt };
7577
+ const joinRequestLinkedObject = (joinRequest) => {
7578
+ return Object.assign(Object.assign({}, joinRequest), { get user() {
7579
+ var _a;
7580
+ const user = (_a = pullFromCache([
7581
+ 'user',
7582
+ 'get',
7583
+ joinRequest.requestorPublicId,
7584
+ ])) === null || _a === void 0 ? void 0 : _a.data;
7585
+ if (!user)
7586
+ return undefined;
7587
+ return userLinkedObject(user);
7588
+ }, cancel: async () => {
7589
+ await cancelJoinRequest(joinRequest);
7590
+ }, approve: async () => {
7591
+ await approveJoinRequest(joinRequest);
7592
+ }, reject: async () => {
7593
+ await rejectJoinRequest(joinRequest);
7594
+ } });
6754
7595
  };
6755
7596
 
6756
- /** @hidden */
6757
- /*
6758
- * @param message payload from http request without myReactions
6759
- * add myReactions to http response if the event was a reaction event
7597
+ /* begin_public_function
7598
+ id: community.getMyJoinRequest
7599
+ */
7600
+ /**
7601
+ * ```js
7602
+ * import { community } from '@amityco/ts-sdk'
7603
+ * const isJoined = await community.getMyJoinRequest('foobar')
7604
+ * ```
7605
+ *
7606
+ * Joins a {@link Amity.Community} object
7607
+ *
7608
+ * @param communityId the {@link Amity.Community} to join
7609
+ * @returns A success boolean if the {@link Amity.Community} was joined
7610
+ *
7611
+ * @category Community API
7612
+ * @async
6760
7613
  */
6761
- const prepareMessagePayloadForCache = (payload, reactors, event) => {
7614
+ const getMyJoinRequest = async (communityId) => {
6762
7615
  const client = getActiveClient();
6763
- const cached = pullFromCache(['message', 'get', payload.messageId]);
6764
- // '[]' in cases where the new reaction is the first one
6765
- const myReactions = (cached === null || cached === void 0 ? void 0 : cached.data.myReactions) || [];
6766
- // add myReactions to the payload
6767
- Object.assign(payload, { myReactions });
6768
- // check if there are any updates to the reactions
6769
- const latestReaction = reactors[0];
6770
- const isLatestReactionMine = latestReaction && latestReaction.userId === client.userId;
6771
- if (!isLatestReactionMine) {
6772
- return;
6773
- }
6774
- // new reaction added
6775
- if (event === 'message.reactionAdded' && !myReactions.includes(latestReaction.reactionName)) {
6776
- Object.assign(payload, {
6777
- myReactions: [...myReactions, latestReaction.reactionName],
6778
- });
6779
- }
6780
- // existing reaction removed
6781
- if (event === 'message.reactionRemoved' && myReactions.includes(latestReaction.reactionName)) {
6782
- Object.assign(payload, {
6783
- myReactions: myReactions.filter(x => x !== latestReaction.reactionName),
6784
- });
6785
- }
6786
- };
7616
+ client.log('community/myJoinRequest', communityId);
7617
+ const { data: payload } = await client.http.get(`/api/v4/communities/${communityId}/join/me`);
7618
+ const data = prepareCommunityJoinRequestPayload(payload);
7619
+ const cachedAt = client.cache && Date.now();
7620
+ if (client.cache)
7621
+ ingestInCache(data, { cachedAt });
7622
+ return {
7623
+ data: data.joinRequests[0] ? joinRequestLinkedObject(data.joinRequests[0]) : undefined,
7624
+ cachedAt,
7625
+ };
7626
+ };
7627
+ /* end_public_function */
6787
7628
 
6788
- /*
6789
- * This is a simple utility that infers the value of isDeleted based on the
6790
- * value of includeDeleted
7629
+ /* begin_public_function
7630
+ id: community.join
7631
+ */
7632
+ /**
7633
+ * ```js
7634
+ * import { community } from '@amityco/ts-sdk'
7635
+ * const isJoined = await community.join('foobar')
7636
+ * ```
6791
7637
  *
6792
- * There are two important things to note here:
6793
- * 1. `includeDeleted` is purely client side query param and not recognized by
6794
- * the server
6795
- * 2. The only values we wish to expose with regards to `isDeleted` (the server
6796
- * param for queries) is false | undefined and want to disallow users to query
6797
- * for deleted entities
7638
+ * Joins a {@link Amity.Community} object
7639
+ *
7640
+ * @param communityId the {@link Amity.Community} to join
7641
+ * @returns A status join result
6798
7642
  *
6799
- * Although this is a very simple utility, it's only purpose is to keep things
6800
- * DRY
7643
+ * @category Community API
7644
+ * @async
6801
7645
  */
6802
- const inferIsDeleted = (includeDeleted) => includeDeleted === true ? undefined : false;
7646
+ const joinRequest = async (communityId) => {
7647
+ const client = getActiveClient();
7648
+ client.log('community/joinRequest', communityId);
7649
+ const { data: payload } = await client.http.post(`/api/v4/communities/${communityId}/join`);
7650
+ const data = prepareCommunityJoinRequestPayload(payload);
7651
+ const cachedAt = client.cache && Date.now();
7652
+ if (client.cache)
7653
+ ingestInCache(data, { cachedAt });
7654
+ fireEvent('local.community.join', data.joinRequests);
7655
+ const status = data.joinRequests[0].status === "approved" /* JoinRequestStatusEnum.Approved */
7656
+ ? "success" /* JoinResultStatusEnum.Success */
7657
+ : "pending" /* JoinResultStatusEnum.Pending */;
7658
+ return status === "success" /* JoinResultStatusEnum.Success */
7659
+ ? { status }
7660
+ : { status, request: joinRequestLinkedObject(data.joinRequests[0]) };
7661
+ };
7662
+ /* end_public_function */
6803
7663
 
6804
- function getSubChannelIsMentioned(channelId, subChannelId, marker) {
6805
- var _a, _b;
6806
- // Look for `unreadCount` in the marker param first
6807
- if (marker) {
6808
- return marker.hasMentioned;
7664
+ class PaginationController {
7665
+ constructor(queryParams) {
7666
+ const { http } = getActiveClient();
7667
+ this.queryParams = queryParams;
7668
+ this.http = http;
6809
7669
  }
6810
- const client = getActiveClient();
6811
- // If consistent mode is enabled, look in the SubChannelUnreadCountInfo cache
6812
- if (client.isUnreadCountEnabled && client.getMarkerSyncConsistentMode()) {
6813
- const cachedUnreadCount = (_a = pullFromCache([
6814
- 'subChannelUnreadInfo',
6815
- 'get',
6816
- subChannelId,
6817
- ])) === null || _a === void 0 ? void 0 : _a.data;
6818
- if (cachedUnreadCount) {
6819
- return cachedUnreadCount.isMentioned;
6820
- }
6821
- return false;
7670
+ loadFirstPage() {
7671
+ return this.onFetch("first" /* Amity.LiveCollectionPageDirection.FIRST */);
6822
7672
  }
6823
- const key = {
6824
- entityId: channelId,
6825
- feedId: subChannelId,
6826
- userId: getActiveUser()._id,
6827
- };
6828
- // If the marker param is not set, look in the cache
6829
- const cachedMarker = (_b = pullFromCache([
6830
- 'subChannelMarker',
6831
- 'get',
6832
- getResolver('subChannelMarker')(key),
6833
- ])) === null || _b === void 0 ? void 0 : _b.data;
6834
- if (cachedMarker) {
6835
- return cachedMarker.hasMentioned;
7673
+ loadNextPage() {
7674
+ return this.onFetch("next" /* Amity.LiveCollectionPageDirection.NEXT */);
6836
7675
  }
6837
- // and if not found in cache use default value `false`
6838
- return false;
6839
- }
6840
-
6841
- function getSubChannelUnreadCount(channelId, subChannelId, marker) {
6842
- var _a, _b;
6843
- // Look for `unreadCount` in the marker param first
6844
- if (marker) {
6845
- return marker.unreadCount;
7676
+ loadPreviousPage() {
7677
+ return this.onFetch("prev" /* Amity.LiveCollectionPageDirection.PREV */);
6846
7678
  }
6847
- const client = getActiveClient();
6848
- // If consistent mode is enabled, look in the SubChannelUnreadCountInfo cache
6849
- if (client.isUnreadCountEnabled && client.getMarkerSyncConsistentMode()) {
6850
- const cachedUnreadCount = (_a = pullFromCache([
6851
- 'subChannelUnreadInfo',
6852
- 'get',
6853
- subChannelId,
6854
- ])) === null || _a === void 0 ? void 0 : _a.data;
6855
- if (cachedUnreadCount) {
6856
- return cachedUnreadCount.isDeleted ? 0 : cachedUnreadCount.unreadCount;
7679
+ async onFetch(direction = "first" /* Amity.LiveCollectionPageDirection.FIRST */) {
7680
+ var _a, _b, _c, _d;
7681
+ if (direction === 'prev' && !this.previousToken)
7682
+ return;
7683
+ if (direction === 'next' && !this.nextToken)
7684
+ return;
7685
+ let token;
7686
+ if (direction === 'prev')
7687
+ token = this.previousToken;
7688
+ if (direction === 'next')
7689
+ token = this.nextToken;
7690
+ const queryResponse = await this.getRequest(this.queryParams, token);
7691
+ if (direction === 'first') {
7692
+ this.nextToken = (_a = queryResponse.paging) === null || _a === void 0 ? void 0 : _a.next;
7693
+ this.previousToken = (_b = queryResponse.paging) === null || _b === void 0 ? void 0 : _b.previous;
6857
7694
  }
6858
- return 0;
7695
+ if (direction === 'prev')
7696
+ this.previousToken = (_c = queryResponse.paging) === null || _c === void 0 ? void 0 : _c.previous;
7697
+ if (direction === 'next')
7698
+ this.nextToken = (_d = queryResponse.paging) === null || _d === void 0 ? void 0 : _d.next;
7699
+ return queryResponse;
6859
7700
  }
6860
- const key = {
6861
- entityId: channelId,
6862
- feedId: subChannelId,
6863
- userId: getActiveUser()._id,
6864
- };
6865
- // If the marker param is not set, look in the cache
6866
- const cachedMarker = (_b = pullFromCache([
6867
- 'subChannelMarker',
6868
- 'get',
6869
- getResolver('subChannelMarker')(key),
6870
- ])) === null || _b === void 0 ? void 0 : _b.data;
6871
- if (cachedMarker) {
6872
- return cachedMarker.unreadCount;
7701
+ getNextToken() {
7702
+ return this.nextToken;
7703
+ }
7704
+ getPrevToken() {
7705
+ return this.previousToken;
6873
7706
  }
6874
- // and if not found in cache use default value `0`
6875
- return 0;
6876
7707
  }
6877
7708
 
6878
- const MARKER_INCLUDED_SUB_CHANNEL_TYPE$1 = ['broadcast', 'conversation', 'community'];
6879
- const isUnreadCountSupport$2 = ({ channelType }) => MARKER_INCLUDED_SUB_CHANNEL_TYPE$1.includes(channelType);
6880
- function convertFromRaw$2(_a) {
6881
- var { channelId, channelPublicId, channelType, childCount, creatorId, creatorPublicId, lastMessageId, lastMessageTimestamp, messageFeedId, name } = _a, rest = __rest(_a, ["channelId", "channelPublicId", "channelType", "childCount", "creatorId", "creatorPublicId", "lastMessageId", "lastMessageTimestamp", "messageFeedId", "name"]);
6882
- return Object.assign(Object.assign({ get unreadCount() {
6883
- return getSubChannelUnreadCount(channelId, messageFeedId);
6884
- },
6885
- get hasMentioned() {
6886
- return getSubChannelIsMentioned(channelId, messageFeedId);
6887
- },
6888
- get isMentioned() {
6889
- return getSubChannelIsMentioned(channelId, messageFeedId);
6890
- } }, rest), { channelId: channelPublicId, creatorId: creatorPublicId, displayName: name, lastActivity: lastMessageTimestamp, latestMessageId: lastMessageId, messageCount: childCount, subChannelId: messageFeedId, isUnreadCountSupport: isUnreadCountSupport$2({ channelType }) });
7709
+ /**
7710
+ * TODO: handle cache receive cache option, and cache policy
7711
+ * TODO: check if querybyIds is supported
7712
+ */
7713
+ class JoinRequestsPaginationController extends PaginationController {
7714
+ async getRequest(queryParams, token) {
7715
+ const { limit = COLLECTION_DEFAULT_PAGINATION_LIMIT, communityId } = queryParams, params = __rest(queryParams, ["limit", "communityId"]);
7716
+ const options = token ? { token } : { limit };
7717
+ const { data: queryResponse } = await this.http.get(`/api/v4/communities/${communityId}/join`, {
7718
+ params: Object.assign(Object.assign({}, params), { options }),
7719
+ });
7720
+ return queryResponse;
7721
+ }
6891
7722
  }
6892
7723
 
6893
- const mergePayloadWithLocal = (payload) => {
6894
- var _a, _b, _c;
6895
- const localMessage = (_b = (_a = queryCache(['message', 'get'])) === null || _a === void 0 ? void 0 : _a.find(({ data }) => data.messageId === payload.messageId)) === null || _b === void 0 ? void 0 : _b.data;
6896
- if (localMessage) {
6897
- return Object.assign(Object.assign(Object.assign({}, localMessage), payload), {
6898
- // NOTE: referenceId is missing in the some payload event. If we have local message data with referenceId, use it instead.
6899
- referenceId: (_c = localMessage.referenceId) !== null && _c !== void 0 ? _c : payload.referenceId });
7724
+ class QueryStreamController {
7725
+ constructor(query, cacheKey) {
7726
+ this.query = query;
7727
+ this.cacheKey = cacheKey;
6900
7728
  }
6901
- return payload;
6902
- };
6903
- function convertFromRaw$1(message, reactors, event) {
6904
- var _a;
6905
- const mergeMessage = mergePayloadWithLocal(message);
6906
- const { channelPublicId, childCount, creatorPublicId, mentionedUsers, messageFeedId, myReactions, reactionCount, reactions, referenceId, segment, messageId, creatorId } = mergeMessage, rest = __rest(mergeMessage, ["channelPublicId", "childCount", "creatorPublicId", "mentionedUsers", "messageFeedId", "myReactions", "reactionCount", "reactions", "referenceId", "segment", "messageId", "creatorId"]);
6907
- let cache;
6908
- if (referenceId) {
6909
- cache = pullFromCache(['message', 'get', referenceId]);
7729
+ }
7730
+
7731
+ var EnumJoinRequestAction;
7732
+ (function (EnumJoinRequestAction) {
7733
+ EnumJoinRequestAction["OnLocalJoinRequestCreated"] = "OnLocalJoinRequestCreated";
7734
+ EnumJoinRequestAction["OnLocalJoinRequestUpdated"] = "OnLocalJoinRequestUpdated";
7735
+ EnumJoinRequestAction["OnLocalJoinRequestDeleted"] = "OnLocalJoinRequestDeleted";
7736
+ })(EnumJoinRequestAction || (EnumJoinRequestAction = {}));
7737
+
7738
+ class JoinRequestsQueryStreamController extends QueryStreamController {
7739
+ constructor(query, cacheKey, notifyChange, preparePayload) {
7740
+ super(query, cacheKey);
7741
+ this.notifyChange = notifyChange;
7742
+ this.preparePayload = preparePayload;
6910
7743
  }
6911
- if (!cache) {
6912
- cache = pullFromCache(['message', 'get', messageId]);
7744
+ async saveToMainDB(response) {
7745
+ const processedPayload = await this.preparePayload(response);
7746
+ const client = getActiveClient();
7747
+ const cachedAt = client.cache && Date.now();
7748
+ if (client.cache) {
7749
+ ingestInCache(processedPayload, { cachedAt });
7750
+ }
6913
7751
  }
6914
- const out = Object.assign(Object.assign({}, rest), { messageId, channelId: channelPublicId, channelSegment: segment, childrenNumber: childCount, creatorId: creatorPublicId, creatorPrivateId: message.creatorId, reactions: reactions !== null && reactions !== void 0 ? reactions : {},
6915
- /*
6916
- * Previously, myReactions were added only if it was part of the payload.
6917
- * So empty myReactions were not present. So I've edited the payload to add
6918
- * a default for those cases.
6919
- *
6920
- * Check git blame for previous iteration
6921
- */
6922
- myReactions: myReactions || ((_a = cache === null || cache === void 0 ? void 0 : cache.data.myReactions) !== null && _a !== void 0 ? _a : []), reactionsCount: reactionCount, subChannelId: messageFeedId, uniqueId: cache ? cache.data.uniqueId : messageId, referenceId, syncState: "synced" /* Amity.SyncState.Synced */ });
6923
- if (mentionedUsers) {
6924
- out.mentionees = mentionedUsers.map(mention => {
6925
- if (mention.type === 'channel') {
6926
- return mention;
7752
+ appendToQueryStream(response, direction, refresh = false) {
7753
+ var _a, _b;
7754
+ if (refresh) {
7755
+ pushToCache(this.cacheKey, {
7756
+ data: response.joinRequests.map(joinRequest => getResolver('joinRequest')({ joinRequestId: joinRequest._id })),
7757
+ });
7758
+ }
7759
+ else {
7760
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
7761
+ const joinRequests = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
7762
+ pushToCache(this.cacheKey, Object.assign(Object.assign({}, collection), { data: [
7763
+ ...new Set([
7764
+ ...joinRequests,
7765
+ ...response.joinRequests.map(joinRequest => getResolver('joinRequest')({ joinRequestId: joinRequest._id })),
7766
+ ]),
7767
+ ] }));
7768
+ }
7769
+ }
7770
+ reactor(action) {
7771
+ return (joinRequest) => {
7772
+ var _a;
7773
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
7774
+ if (!collection)
7775
+ return;
7776
+ if (action === EnumJoinRequestAction.OnLocalJoinRequestUpdated) {
7777
+ const isExist = collection.data.find(id => id === joinRequest[0].joinRequestId);
7778
+ if (!isExist)
7779
+ return;
6927
7780
  }
6928
- return { type: 'user', userIds: mention.userPublicIds };
6929
- });
7781
+ if (action === EnumJoinRequestAction.OnLocalJoinRequestCreated) {
7782
+ collection.data = [
7783
+ ...new Set([
7784
+ ...joinRequest.map(joinRequest => joinRequest.joinRequestId),
7785
+ ...collection.data,
7786
+ ]),
7787
+ ];
7788
+ }
7789
+ if (action === EnumJoinRequestAction.OnLocalJoinRequestDeleted) {
7790
+ collection.data = collection.data.filter(id => id !== joinRequest[0].joinRequestId);
7791
+ }
7792
+ pushToCache(this.cacheKey, collection);
7793
+ this.notifyChange({ origin: "event" /* Amity.LiveDataOrigin.EVENT */, loading: false });
7794
+ };
7795
+ }
7796
+ subscribeRTE(createSubscriber) {
7797
+ return createSubscriber.map(subscriber => subscriber.fn(this.reactor(subscriber.action)));
7798
+ }
7799
+ }
7800
+
7801
+ function isObject(value) {
7802
+ return typeof value === 'object' && value !== null;
7803
+ }
7804
+ /**
7805
+ * convert all object getter property to static value
7806
+ */
7807
+ const convertGetterPropsToStatic = (obj) => {
7808
+ if (!isObject(obj)) {
7809
+ return obj;
7810
+ }
7811
+ const entries = Object.entries(obj).map(([key, value]) => {
7812
+ const descriptor = Object.getOwnPropertyDescriptor(obj, key);
7813
+ if (typeof (descriptor === null || descriptor === void 0 ? void 0 : descriptor.get) === 'function') {
7814
+ return [key, descriptor.get.call(obj)];
7815
+ }
7816
+ return [key, value];
7817
+ });
7818
+ return Object.fromEntries(entries);
7819
+ };
7820
+ const removeFunctionProperties = (obj) => {
7821
+ if (!isObject(obj)) {
7822
+ return obj;
7823
+ }
7824
+ const entries = Object.entries(obj).map(([key, value]) => {
7825
+ if (typeof value === 'function') {
7826
+ return [key, undefined];
7827
+ }
7828
+ return [key, value];
7829
+ });
7830
+ return Object.fromEntries(entries);
7831
+ };
7832
+
7833
+ class PaginationNoPageController {
7834
+ constructor(queryParams) {
7835
+ const { http } = getActiveClient();
7836
+ this.queryParams = queryParams;
7837
+ this.http = http;
6930
7838
  }
6931
- if (reactors && reactors.length && event) {
6932
- // mqtt event
6933
- prepareMessagePayloadForCache(out, reactors, event);
7839
+ async onFetch() {
7840
+ const queryResponse = await this.getRequest(this.queryParams);
7841
+ return queryResponse;
6934
7842
  }
6935
- return out;
6936
- }
6937
- const preUpdateMessageCache = (rawPayload) => {
6938
- ingestInCache({
6939
- messages: rawPayload.messages.map(message => convertFromRaw$1(message, rawPayload.reactions)),
6940
- });
6941
- };
6942
- const DEBOUNCE_TIME = 2000;
6943
- const currentDebounceMap = {};
6944
- const prepareMessagePayload = async (payload, event) => {
6945
- const markerIds = payload.messages.map(({ messageId }) => messageId);
6946
- if (markerIds.length > 0) {
6947
- // since the get markers method requires a channel cache to function with the reducer.
6948
- preUpdateMessageCache(payload);
6949
- const markerIdsKey = markerIds.join('');
6950
- if (currentDebounceMap[markerIdsKey]) {
6951
- clearTimeout(currentDebounceMap[markerIdsKey]);
6952
- }
6953
- currentDebounceMap[markerIdsKey] = setTimeout(() => {
6954
- try {
6955
- getMessageMarkers(markerIds);
7843
+ }
7844
+
7845
+ class LiveCollectionController {
7846
+ constructor(paginationController, queryStreamId, cacheKey, callback) {
7847
+ this.paginationController = paginationController;
7848
+ this.queryStreamId = queryStreamId;
7849
+ this.cacheKey = cacheKey;
7850
+ this.callback = callback;
7851
+ }
7852
+ async refresh() {
7853
+ try {
7854
+ let result;
7855
+ if (this.paginationController instanceof PaginationNoPageController) {
7856
+ result = await this.paginationController.onFetch();
6956
7857
  }
6957
- catch (_error) {
6958
- // do nothing
7858
+ else {
7859
+ result = await this.paginationController.loadFirstPage();
6959
7860
  }
6960
- }, DEBOUNCE_TIME);
7861
+ if (!result)
7862
+ return;
7863
+ await this.persistModel(result);
7864
+ this.persistQueryStream({
7865
+ response: result,
7866
+ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */,
7867
+ refresh: true,
7868
+ });
7869
+ this.notifyChange({ origin: "server" /* Amity.LiveDataOrigin.SERVER */, loading: false });
7870
+ }
7871
+ catch (e) {
7872
+ this.notifyChange({ origin: "server" /* Amity.LiveDataOrigin.SERVER */, loading: false, error: e });
7873
+ }
6961
7874
  }
6962
- const { messageFeeds } = payload, restPayload = __rest(payload, ["messageFeeds"]);
6963
- // upsert messageFeeds to subchannel cache because messageFeeds from event payload not include messagePreviewId
6964
- if (messageFeeds && messageFeeds.length > 0) {
6965
- messageFeeds === null || messageFeeds === void 0 ? void 0 : messageFeeds.forEach(messageFeed => {
6966
- var _a, _b;
6967
- const subChannelCache = (_b = (_a = pullFromCache(['subChannel', 'get', messageFeed.messageFeedId])) === null || _a === void 0 ? void 0 : _a.data) !== null && _b !== void 0 ? _b : {};
6968
- // exclude getter properties from existing subChannel cache, update only other properties to existing subChannel cache
6969
- const _c = convertFromRaw$2(messageFeed), restSubChannel = __rest(_c, ["unreadCount", "isMentioned"]);
6970
- updateSubChannelCache(messageFeed.messageFeedId, subChannelCache, restSubChannel);
6971
- });
7875
+ loadPage({ initial = false, direction = "next" /* Amity.LiveCollectionPageDirection.NEXT */, }) {
7876
+ this.setup();
7877
+ this.notifyChange({ origin: "local" /* Amity.LiveDataOrigin.LOCAL */, loading: true });
7878
+ if (initial) {
7879
+ this.refresh();
7880
+ }
7881
+ else if (direction === "prev" /* Amity.LiveCollectionPageDirection.PREV */) {
7882
+ this.loadPrevPage();
7883
+ }
7884
+ else if (direction === "next" /* Amity.LiveCollectionPageDirection.NEXT */) {
7885
+ this.loadNextPage();
7886
+ }
6972
7887
  }
6973
- return Object.assign(Object.assign({}, restPayload), { messages: payload.messages.map(m => convertFromRaw$1(m, payload.reactions, event)) });
6974
- };
6975
- function convertParams(_a) {
6976
- var { subChannelId, mentionees, dataType, data } = _a, rest = __rest(_a, ["subChannelId", "mentionees", "dataType", "data"]);
6977
- if (dataType === MessageContentType.IMAGE || dataType === MessageContentType.FILE) {
6978
- return Object.assign({ messageFeedId: subChannelId, mentionedUsers: mentionees, dataType, data: Object.assign({ caption: '' }, data) }, rest);
7888
+ async loadNextPage() {
7889
+ try {
7890
+ if (this.paginationController instanceof PaginationNoPageController)
7891
+ return;
7892
+ const result = await this.paginationController.loadNextPage();
7893
+ if (!result)
7894
+ return;
7895
+ await this.persistModel(result);
7896
+ this.persistQueryStream({
7897
+ response: result,
7898
+ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */,
7899
+ });
7900
+ this.notifyChange({ origin: "server" /* Amity.LiveDataOrigin.SERVER */, loading: false });
7901
+ }
7902
+ catch (e) {
7903
+ this.notifyChange({ origin: "server" /* Amity.LiveDataOrigin.SERVER */, loading: false, error: e });
7904
+ }
6979
7905
  }
6980
- return Object.assign({ messageFeedId: subChannelId, mentionedUsers: mentionees, dataType, data }, rest);
6981
- }
6982
- function convertQueryParams$1(_a) {
6983
- var { sortBy, subChannelId, includingTags, excludingTags, includeDeleted, aroundMessageId, limit, type } = _a, rest = __rest(_a, ["sortBy", "subChannelId", "includingTags", "excludingTags", "includeDeleted", "aroundMessageId", "limit", "type"]);
6984
- const out = Object.assign(Object.assign({}, rest), { messageFeedId: subChannelId, isDeleted: inferIsDeleted(includeDeleted), options: {
6985
- sortBy,
6986
- limit: limit || COLLECTION_DEFAULT_PAGINATION_LIMIT,
6987
- around: aroundMessageId,
6988
- } });
6989
- if (includingTags) {
6990
- out.includeTags = includingTags;
7906
+ async loadPrevPage() {
7907
+ try {
7908
+ if (this.paginationController instanceof PaginationNoPageController)
7909
+ return;
7910
+ const result = await this.paginationController.loadPreviousPage();
7911
+ if (!result)
7912
+ return;
7913
+ await this.persistModel(result);
7914
+ this.persistQueryStream({
7915
+ response: result,
7916
+ direction: "prev" /* Amity.LiveCollectionPageDirection.PREV */,
7917
+ });
7918
+ this.notifyChange({ origin: "server" /* Amity.LiveDataOrigin.SERVER */, loading: false });
7919
+ }
7920
+ catch (e) {
7921
+ this.notifyChange({ origin: "server" /* Amity.LiveDataOrigin.SERVER */, loading: false, error: e });
7922
+ }
6991
7923
  }
6992
- if (type) {
6993
- out.dataType = type;
7924
+ shouldNotify(data) {
7925
+ const newData = data.map(convertGetterPropsToStatic).map(removeFunctionProperties);
7926
+ if (isEqual(this.snapshot, newData))
7927
+ return false;
7928
+ this.snapshot = newData;
7929
+ return true;
6994
7930
  }
6995
- if (excludingTags) {
6996
- out.excludeTags = excludingTags;
7931
+ getCacheKey() {
7932
+ return this.cacheKey;
6997
7933
  }
6998
- return out;
6999
7934
  }
7000
7935
 
7001
- const MARKER_INCLUDED_SUB_CHANNEL_TYPE = ['broadcast', 'conversation', 'community'];
7002
7936
  /**
7003
- * Filter sub channel by type. Only conversation, community and broadcast type are included.
7937
+ * ```js
7938
+ * import { onJoinRequestCreated } from '@amityco/ts-sdk'
7939
+ * const dispose = onJoinRequestCreated(data => {
7940
+ * // ...
7941
+ * })
7942
+ * ```
7943
+ *
7944
+ * Fired when an {@link Amity.CommunityJoinRequestPayload} has been created
7945
+ *
7946
+ * @param callback The function to call when the event was fired
7947
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
7948
+ *
7949
+ * @category JoinRequest Events
7004
7950
  */
7005
- const isUnreadCountSupport$1 = ({ channelType }) => MARKER_INCLUDED_SUB_CHANNEL_TYPE.includes(channelType);
7006
- const preUpdateSubChannelCache = (rawPayload) => {
7007
- ingestInCache({
7008
- messageFeeds: rawPayload.messageFeeds.map(messageFeed => convertFromRaw$2(messageFeed)),
7009
- });
7010
- };
7011
- const prepareSubChannelPayload = async (rawPayload) => {
7012
- const markerIds = rawPayload.messageFeeds
7013
- .filter(isUnreadCountSupport$1)
7014
- .map(({ messageFeedId }) => messageFeedId);
7015
- if (markerIds.length > 0) {
7016
- // since the get markers method requires a channel cache to function with the reducer.
7017
- preUpdateSubChannelCache(rawPayload);
7018
- try {
7019
- await getSubChannelMarkers(markerIds);
7020
- }
7021
- catch (e) {
7022
- // empty block (from the spec, allow marker fetch to fail without having to do anything)
7951
+ const onJoinRequestCreated = (callback) => {
7952
+ const client = getActiveClient();
7953
+ const disposers = [
7954
+ createEventSubscriber(client, 'onJoinRequestCreated', 'local.joinRequest.created', payload => callback(payload)),
7955
+ ];
7956
+ return () => {
7957
+ disposers.forEach(fn => fn());
7958
+ };
7959
+ };
7960
+
7961
+ /**
7962
+ * ```js
7963
+ * import { onJoinRequestUpdated } from '@amityco/ts-sdk'
7964
+ * const dispose = onJoinRequestUpdated(data => {
7965
+ * // ...
7966
+ * })
7967
+ * ```
7968
+ *
7969
+ * Fired when an {@link Amity.CommunityJoinRequestPayload} has been created
7970
+ *
7971
+ * @param callback The function to call when the event was fired
7972
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
7973
+ *
7974
+ * @category JoinRequest Events
7975
+ */
7976
+ const onJoinRequestUpdated = (callback) => {
7977
+ const client = getActiveClient();
7978
+ const disposers = [
7979
+ createEventSubscriber(client, 'onJoinRequestUpdated', 'local.joinRequest.updated', payload => callback(payload)),
7980
+ ];
7981
+ return () => {
7982
+ disposers.forEach(fn => fn());
7983
+ };
7984
+ };
7985
+
7986
+ /**
7987
+ * ```js
7988
+ * import { onJoinRequestDeleted } from '@amityco/ts-sdk'
7989
+ * const dispose = onJoinRequestDeleted(data => {
7990
+ * // ...
7991
+ * })
7992
+ * ```
7993
+ *
7994
+ * Fired when an {@link Amity.CommunityJoinRequestPayload} has been created
7995
+ *
7996
+ * @param callback The function to call when the event was fired
7997
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
7998
+ *
7999
+ * @category JoinRequest Events
8000
+ */
8001
+ const onJoinRequestDeleted = (callback) => {
8002
+ const client = getActiveClient();
8003
+ const disposers = [
8004
+ createEventSubscriber(client, 'onJoinRequestDeleted', 'local.joinRequest.deleted', payload => callback(payload)),
8005
+ ];
8006
+ return () => {
8007
+ disposers.forEach(fn => fn());
8008
+ };
8009
+ };
8010
+
8011
+ class JoinRequestsLiveCollectionController extends LiveCollectionController {
8012
+ constructor(query, callback) {
8013
+ const queryStreamId = hash__default["default"](query);
8014
+ const cacheKey = ['joinRequest', 'collection', queryStreamId];
8015
+ const paginationController = new JoinRequestsPaginationController(query);
8016
+ super(paginationController, queryStreamId, cacheKey, callback);
8017
+ this.query = query;
8018
+ this.queryStreamController = new JoinRequestsQueryStreamController(this.query, this.cacheKey, this.notifyChange.bind(this), prepareCommunityJoinRequestPayload);
8019
+ this.callback = callback.bind(this);
8020
+ this.loadPage({ initial: true });
8021
+ }
8022
+ setup() {
8023
+ var _a;
8024
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
8025
+ if (!collection) {
8026
+ pushToCache(this.cacheKey, {
8027
+ data: [],
8028
+ params: this.query,
8029
+ });
7023
8030
  }
7024
8031
  }
7025
- updateSubChannelMessagePreviewCache(rawPayload);
7026
- // attach marker to sub channel
7027
- const messageFeeds = rawPayload.messageFeeds.map(convertFromRaw$2);
7028
- const messages = rawPayload.messages.map(m => convertFromRaw$1(m));
7029
- return Object.assign(Object.assign({}, rawPayload), { messageFeeds,
7030
- messages });
7031
- };
7032
- function convertQueryParams(_a) {
7033
- var { excludeDefaultSubChannel } = _a, rest = __rest(_a, ["excludeDefaultSubChannel"]);
7034
- const out = Object.assign({}, rest);
7035
- if (excludeDefaultSubChannel !== undefined) {
7036
- out.excludeDefaultMessageFeed = excludeDefaultSubChannel;
8032
+ async persistModel(queryPayload) {
8033
+ await this.queryStreamController.saveToMainDB(queryPayload);
8034
+ }
8035
+ persistQueryStream({ response, direction, refresh, }) {
8036
+ const joinRequestResponse = response;
8037
+ this.queryStreamController.appendToQueryStream(joinRequestResponse, direction, refresh);
8038
+ }
8039
+ startSubscription() {
8040
+ return this.queryStreamController.subscribeRTE([
8041
+ { fn: onJoinRequestCreated, action: EnumJoinRequestAction.OnLocalJoinRequestCreated },
8042
+ { fn: onJoinRequestUpdated, action: EnumJoinRequestAction.OnLocalJoinRequestUpdated },
8043
+ { fn: onJoinRequestDeleted, action: EnumJoinRequestAction.OnLocalJoinRequestDeleted },
8044
+ ]);
8045
+ }
8046
+ notifyChange({ origin, loading, error }) {
8047
+ var _a;
8048
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
8049
+ if (!collection)
8050
+ return;
8051
+ const data = this.applyFilter(collection.data
8052
+ .map(id => pullFromCache(['joinRequest', 'get', id]))
8053
+ .filter(isNonNullable)
8054
+ .map(({ data }) => data)
8055
+ .map(joinRequestLinkedObject));
8056
+ if (!this.shouldNotify(data) && origin === 'event')
8057
+ return;
8058
+ this.callback({
8059
+ onNextPage: () => this.loadPage({ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */ }),
8060
+ data,
8061
+ hasNextPage: !!this.paginationController.getNextToken(),
8062
+ loading,
8063
+ error,
8064
+ });
8065
+ }
8066
+ applyFilter(data) {
8067
+ let joinRequest = data;
8068
+ if (this.query.status) {
8069
+ joinRequest = joinRequest.filter(joinRequest => joinRequest.status === this.query.status);
8070
+ }
8071
+ const sortFn = (() => {
8072
+ switch (this.query.sortBy) {
8073
+ case 'firstCreated':
8074
+ return sortByFirstCreated;
8075
+ case 'lastCreated':
8076
+ return sortByLastCreated;
8077
+ default:
8078
+ return sortByLastCreated;
8079
+ }
8080
+ })();
8081
+ joinRequest = joinRequest.sort(sortFn);
8082
+ return joinRequest;
7037
8083
  }
7038
- return out;
7039
8084
  }
7040
8085
 
7041
8086
  /**
7042
- * ```js
7043
- * import { getSubChannel } from '@amityco/ts-sdk'
7044
- * const subChannel = await getSubChannel('foobar')
7045
- * ```
8087
+ * Get Join Requests
7046
8088
  *
7047
- * Fetches a {@link Amity.SubChannel} object
8089
+ * @param params the query parameters
8090
+ * @param callback the callback to be called when the join request are updated
8091
+ * @returns joinRequests
7048
8092
  *
7049
- * @param subChannelId the ID of the {@link Amity.SubChannel} to fetch
7050
- * @returns the associated {@link Amity.SubChannel} object
8093
+ * @category joinRequest Live Collection
7051
8094
  *
7052
- * @category Channel API
7053
- * @async
7054
8095
  */
7055
- const getSubChannel$1 = async (subChannelId) => {
7056
- const client = getActiveClient();
7057
- client.log('channel/getSubChannel', subChannelId);
7058
- isInTombstone('subChannel', subChannelId);
7059
- try {
7060
- const response = await client.http.get(`/api/v5/message-feeds/${encodeURIComponent(subChannelId)}`);
7061
- const data = await prepareSubChannelPayload(response.data);
7062
- const cachedAt = client.cache && Date.now();
7063
- if (client.cache)
7064
- ingestInCache(data, { cachedAt });
7065
- fireEvent('local.message-feed.fetched', data);
7066
- return {
7067
- data: data.messageFeeds[0],
7068
- cachedAt,
7069
- };
7070
- }
7071
- catch (error) {
7072
- if (checkIfShouldGoesToTombstone(error === null || error === void 0 ? void 0 : error.code)) {
7073
- pushToTombstone('subChannel', subChannelId);
7074
- }
7075
- throw error;
8096
+ const getJoinRequests = (params, callback, config) => {
8097
+ const { log, cache } = getActiveClient();
8098
+ if (!cache) {
8099
+ console.log(ENABLE_CACHE_MESSAGE);
7076
8100
  }
7077
- };
8101
+ const timestamp = Date.now();
8102
+ log(`getJoinRequests: (tmpid: ${timestamp}) > listen`);
8103
+ const joinRequestLiveCollection = new JoinRequestsLiveCollectionController(params, callback);
8104
+ const disposers = joinRequestLiveCollection.startSubscription();
8105
+ const cacheKey = joinRequestLiveCollection.getCacheKey();
8106
+ disposers.push(() => {
8107
+ dropFromCache(cacheKey);
8108
+ });
8109
+ return () => {
8110
+ log(`getJoinRequests (tmpid: ${timestamp}) > dispose`);
8111
+ disposers.forEach(fn => fn());
8112
+ };
8113
+ };
8114
+
8115
+ const convertRawInvitationToInternalInvitation = (rawInvitation) => {
8116
+ return Object.assign(Object.assign({}, rawInvitation), { createdById: rawInvitation.createdBy });
8117
+ };
8118
+
8119
+ const prepareInvitationPayload = (rawPayload) => {
8120
+ return Object.assign(Object.assign({}, rawPayload), { invitations: rawPayload.invitations.map(convertRawInvitationToInternalInvitation), users: rawPayload.users.map(convertRawUserToInternalUser) });
8121
+ };
8122
+
8123
+ /* begin_public_function
8124
+ id: invitation.createInvitations
8125
+ */
7078
8126
  /**
7079
8127
  * ```js
7080
- * import { getSubChannel } from '@amityco/ts-sdk'
7081
- * const subChannel = getSubChannel.locally('foobar')
8128
+ * import { createInvitations } from '@amityco/ts-sdk'
8129
+ * const created = await createInvitations({
8130
+ * type: string,
8131
+ * targetType: string,
8132
+ * targetId: string,
8133
+ * userIds: string[]
8134
+ * }))
7082
8135
  * ```
7083
8136
  *
7084
- * Fetches a {@link Amity.SubChannel} object from cache
8137
+ * Creates an {@link Amity.Invitation}
7085
8138
  *
7086
- * @param subChannelId the ID of the {@link Amity.SubChannel} to fetch
7087
- * @returns the associated {@link Amity.SubChannel} object
8139
+ * @param bundle The data necessary to create a new {@link Amity.Invitation}
8140
+ * @returns The newly created {@link Amity.Invitation}
7088
8141
  *
7089
- * @category Channel API
8142
+ * @category Invitation API
8143
+ * @async
7090
8144
  */
7091
- getSubChannel$1.locally = (subChannelId) => {
8145
+ const createInvitations = async (bundle) => {
7092
8146
  const client = getActiveClient();
7093
- client.log('channel/getSubChannel.locally', subChannelId);
7094
- if (!client.cache)
7095
- return;
7096
- const cached = pullFromCache(['subChannel', 'get', subChannelId]);
7097
- if (!cached)
7098
- return;
8147
+ client.log('invitation/createInvitations', bundle);
8148
+ const { data: payload } = await client.http.post('/api/v1/invitations', bundle);
8149
+ const data = prepareInvitationPayload(payload);
8150
+ const cachedAt = client.cache && Date.now();
8151
+ if (client.cache)
8152
+ ingestInCache(data, { cachedAt });
8153
+ fireEvent('local.invitation.created', data.invitations);
7099
8154
  return {
7100
- data: cached.data,
7101
- cachedAt: cached.cachedAt,
8155
+ data: data.invitations,
8156
+ cachedAt,
7102
8157
  };
7103
- };
7104
-
7105
- const convertDateStringToTimestamp = (dateString) => {
7106
- return new Date(dateString).getTime();
7107
- };
7108
-
7109
- const getMessagePreviewSetting$1 = async () => {
7110
- const client = getActiveClient();
7111
- return client.getMessagePreviewSetting(false);
7112
- };
7113
- const getSubChannelCache = async (subChannelId) => {
7114
- var _a;
7115
- let subChannelCache = (_a = pullFromCache(['subChannel', 'get', subChannelId])) === null || _a === void 0 ? void 0 : _a.data;
7116
- if (!subChannelCache) {
7117
- subChannelCache = (await getSubChannel$1(subChannelId)).data;
7118
- }
7119
- return subChannelCache;
7120
- };
7121
- const isLastestMessageOnSubchannel = (message) => {
7122
- var _a;
7123
- const cache = (_a = pullFromCache([
7124
- 'messagePreviewSubChannel',
7125
- 'get',
7126
- message.subChannelId,
7127
- ])) === null || _a === void 0 ? void 0 : _a.data;
7128
- // The message payload from optimistic created event has no segment, so we check createdAt instead.
7129
- return (!cache ||
7130
- cache.segment <= message.channelSegment ||
7131
- convertDateStringToTimestamp(cache.createdAt) <= convertDateStringToTimestamp(message.createdAt));
7132
- };
7133
- const isLastestMessageOnChannel = (message) => {
7134
- var _a;
7135
- const cache = (_a = pullFromCache([
7136
- 'messagePreviewChannel',
7137
- 'get',
7138
- message.channelId,
7139
- ])) === null || _a === void 0 ? void 0 : _a.data;
7140
- return (!cache ||
7141
- convertDateStringToTimestamp(cache.createdAt) <= convertDateStringToTimestamp(message.createdAt));
7142
- };
7143
- const handleMessageCreatedOnSubChannel = async (message) => {
7144
- const messagePreviewSetting = await getMessagePreviewSetting$1();
7145
- const { channelId, messageId: messagePreviewId, creatorId, createdAt, updatedAt, data, dataType, subChannelId, channelSegment: segment, isDeleted, } = message;
7146
- // 1. get subChannel from cache, if not exist fetch from server
7147
- const subChannelCache = await getSubChannelCache(subChannelId);
7148
- // 2. if messagePreviewSetting is NO_MESSAGE_PREVEIW, update only lastActiviy in subChannel cache
7149
- if (messagePreviewSetting === "no-message-preview" /* Amity.MessagePreviewSetting.NO_MESSAGE_PREVIEW */) {
7150
- // 2.1 if the message is the latest message, update lastActivity to be createdAt in subChannel cache
7151
- if (convertDateStringToTimestamp(subChannelCache.lastActivity) <
7152
- convertDateStringToTimestamp(createdAt))
7153
- updateSubChannelCache(message.subChannelId, subChannelCache, {
7154
- lastActivity: createdAt,
7155
- });
7156
- return;
7157
- }
7158
- // 3. if messagePreviewSetting is `NOT` NO_MESSAGE_PREVEIW, update messagePreviewSubChannel and subChannel cache
7159
- // 3.1 check if the message is the latest message, if not ignore the message.
7160
- if (!isLastestMessageOnSubchannel(message))
7161
- return;
7162
- // 3.2 if the message is the latest message, update messagePreviewSubChannel and subChannel cache
7163
- pushToCache(['messagePreviewSubChannel', 'get', message.subChannelId], {
7164
- channelId,
7165
- creatorId,
7166
- messagePreviewId,
7167
- createdAt,
7168
- updatedAt,
7169
- subChannelId,
7170
- data,
7171
- dataType,
7172
- segment,
7173
- isDeleted,
7174
- subChannelUpdatedAt: subChannelCache === null || subChannelCache === void 0 ? void 0 : subChannelCache.updatedAt,
7175
- subChannelName: subChannelCache === null || subChannelCache === void 0 ? void 0 : subChannelCache.displayName,
7176
- });
7177
- updateSubChannelCache(message.subChannelId, subChannelCache, {
7178
- lastActivity: createdAt,
7179
- messagePreviewId,
7180
- });
7181
8158
  };
7182
- const handleMessageUpdatedOnSubChannel = async (message) => {
7183
- var _a;
7184
- const { channelId, messageId: messagePreviewId, creatorId, createdAt, updatedAt, data, dataType, subChannelId, channelSegment: segment, isDeleted, } = message;
7185
- const messagePreviewSubChannelCache = (_a = pullFromCache([
7186
- 'messagePreviewSubChannel',
7187
- 'get',
7188
- message.subChannelId,
7189
- ])) === null || _a === void 0 ? void 0 : _a.data;
7190
- // if messagePreviewSubChannel is not exist, ignore the message.
7191
- if (messagePreviewSubChannelCache &&
7192
- messagePreviewSubChannelCache.messagePreviewId === message.messageId) {
7193
- const subChannelCache = await getSubChannelCache(subChannelId);
7194
- pushToCache(['messagePreviewSubChannel', 'get', message.subChannelId], {
7195
- channelId,
7196
- creatorId,
7197
- messagePreviewId,
7198
- createdAt,
7199
- updatedAt,
7200
- subChannelId,
7201
- data,
7202
- dataType,
7203
- segment,
7204
- isDeleted,
7205
- subChannelUpdatedAt: subChannelCache.updatedAt,
7206
- subChannelName: messagePreviewSubChannelCache.subChannelName,
7207
- });
7208
- }
7209
- };
7210
- const handleMessageCreated = async (message) => {
7211
- const { channelId, messageId: messagePreviewId, creatorId, createdAt, updatedAt, data, dataType, subChannelId, channelSegment: segment, isDeleted, } = message;
7212
- if (isLastestMessageOnChannel(message)) {
7213
- const subChannelCache = await getSubChannelCache(subChannelId);
7214
- pushToCache(['messagePreviewChannel', 'get', message.channelId], {
7215
- channelId,
7216
- creatorId,
7217
- messagePreviewId,
7218
- createdAt,
7219
- updatedAt,
7220
- subChannelId,
7221
- data,
7222
- dataType,
7223
- segment,
7224
- isDeleted,
7225
- subChannelUpdatedAt: subChannelCache === null || subChannelCache === void 0 ? void 0 : subChannelCache.updatedAt,
7226
- subChannelName: subChannelCache === null || subChannelCache === void 0 ? void 0 : subChannelCache.displayName,
7227
- });
7228
- }
7229
- };
7230
- const handleMessageUpdated = async (message) => {
7231
- /**
7232
- * Channel Case
7233
- */
8159
+ /* end_public_function */
8160
+
8161
+ /* begin_public_function
8162
+ id: invitation.accept
8163
+ */
8164
+ /**
8165
+ * ```js
8166
+ * import { acceptInvitation } from '@amityco/ts-sdk'
8167
+ * const isAccepted = await acceptInvitation(invitationId)
8168
+ * ```
8169
+ *
8170
+ * Accepts a {@link Amity.Invitation} object
8171
+ *
8172
+ * @param invitationId the {@link Amity.Invitation} to accept
8173
+ * @returns A success boolean if the {@link Amity.Invitation} was accepted
8174
+ *
8175
+ * @category Invitation API
8176
+ * @async
8177
+ */
8178
+ const acceptInvitation = async (invitationId) => {
7234
8179
  var _a;
7235
- const { channelId, messageId: messagePreviewId, creatorId, createdAt, updatedAt, data, dataType, subChannelId, channelSegment: segment, isDeleted, } = message;
7236
- const messagePreviewChannelCache = (_a = pullFromCache([
7237
- 'messagePreviewChannel',
8180
+ const client = getActiveClient();
8181
+ client.log('invitation/acceptInvitation', invitationId);
8182
+ const { data } = await client.http.post(`/api/v1/invitations/${invitationId}/accept`);
8183
+ const invitation = (_a = pullFromCache([
8184
+ 'invitation',
7238
8185
  'get',
7239
- message.channelId,
8186
+ invitationId,
7240
8187
  ])) === null || _a === void 0 ? void 0 : _a.data;
7241
- if (messagePreviewChannelCache &&
7242
- messagePreviewChannelCache.messagePreviewId === message.messageId) {
7243
- const subChannelCache = await getSubChannelCache(subChannelId);
7244
- pushToCache(['messagePreviewChannel', 'get', message.channelId], {
7245
- channelId,
7246
- creatorId,
7247
- messagePreviewId,
7248
- createdAt,
7249
- updatedAt,
7250
- subChannelId,
7251
- data,
7252
- dataType,
7253
- segment,
7254
- isDeleted,
7255
- subChannelUpdatedAt: subChannelCache.updatedAt,
7256
- subChannelName: messagePreviewChannelCache.subChannelName,
7257
- });
8188
+ if (invitation) {
8189
+ upsertInCache(['invitation', 'get', invitationId], { status: "approved" /* InvitationStatusEnum.Approved */ });
8190
+ fireEvent('local.invitation.updated', [invitation]);
7258
8191
  }
8192
+ return data.success;
7259
8193
  };
7260
- const handleSubChannelUpdated = async (subChannel) => {
7261
- var _a, _b, _c, _d;
7262
- const { channelId, subChannelId } = subChannel;
7263
- /** Channel Case */
7264
- const messagePreviewChannelCache = (_a = pullFromCache([
7265
- 'messagePreviewChannel',
8194
+ /* end_public_function */
8195
+
8196
+ /* begin_public_function
8197
+ id: invitation.reject
8198
+ */
8199
+ /**
8200
+ * ```js
8201
+ * import { rejectInvitation } from '@amityco/ts-sdk'
8202
+ * const isRejected = await rejectInvitation(invitationId)
8203
+ * ```
8204
+ *
8205
+ * Rejects a {@link Amity.Invitation} object
8206
+ *
8207
+ * @param invitationId the {@link Amity.Invitation} to reject
8208
+ * @returns A success boolean if the {@link Amity.Invitation} was rejected
8209
+ *
8210
+ * @category Invitation API
8211
+ * @async
8212
+ */
8213
+ const rejectInvitation = async (invitationId) => {
8214
+ var _a;
8215
+ const client = getActiveClient();
8216
+ client.log('invitation/rejectInvitation', invitationId);
8217
+ const { data } = await client.http.post(`/api/v1/invitations/${invitationId}/reject`);
8218
+ const invitation = (_a = pullFromCache([
8219
+ 'invitation',
7266
8220
  'get',
7267
- channelId,
8221
+ invitationId,
7268
8222
  ])) === null || _a === void 0 ? void 0 : _a.data;
7269
- if ((messagePreviewChannelCache === null || messagePreviewChannelCache === void 0 ? void 0 : messagePreviewChannelCache.subChannelId) === subChannelId) {
7270
- const subChannelCache = (_b = pullFromCache([
7271
- 'subChannel',
7272
- 'get',
7273
- subChannelId,
7274
- ])) === null || _b === void 0 ? void 0 : _b.data;
7275
- pushToCache(['messagePreviewChannel', 'get', channelId], Object.assign(Object.assign({}, messagePreviewChannelCache), { subChannelName: subChannelCache === null || subChannelCache === void 0 ? void 0 : subChannelCache.displayName, subChannelUpdatedAt: subChannelCache === null || subChannelCache === void 0 ? void 0 : subChannelCache.updatedAt }));
7276
- }
7277
- /** SubChannel Case */
7278
- const messagePreviewSubChannelCache = (_c = pullFromCache([
7279
- 'messagePreviewSubChannel',
7280
- 'get',
7281
- subChannelId,
7282
- ])) === null || _c === void 0 ? void 0 : _c.data;
7283
- if (messagePreviewSubChannelCache &&
7284
- new Date(messagePreviewSubChannelCache.updatedAt).valueOf() >
7285
- new Date(subChannel.updatedAt).valueOf()) {
7286
- const subChannelCache = (_d = pullFromCache([
7287
- 'subChannel',
7288
- 'get',
7289
- subChannelId,
7290
- ])) === null || _d === void 0 ? void 0 : _d.data;
7291
- pushToCache(['messagePreviewSubChannel', 'get', subChannelId], Object.assign(Object.assign({}, messagePreviewSubChannelCache), { subChannelName: subChannelCache === null || subChannelCache === void 0 ? void 0 : subChannelCache.displayName, subChannelUpdatedAt: subChannelCache === null || subChannelCache === void 0 ? void 0 : subChannelCache.updatedAt }));
8223
+ if (invitation) {
8224
+ upsertInCache(['invitation', 'get', invitationId], { status: "rejected" /* InvitationStatusEnum.Rejected */ });
8225
+ fireEvent('local.invitation.updated', [invitation]);
7292
8226
  }
7293
- };
7294
-
7295
- function convertRawUserToInternalUser(rawUser) {
7296
- return Object.assign(Object.assign({}, rawUser), { isGlobalBanned: (rawUser === null || rawUser === void 0 ? void 0 : rawUser.isGlobalBan) || false });
7297
- }
8227
+ return data.success;
8228
+ };
8229
+ /* end_public_function */
7298
8230
 
7299
- const MARKER_INCLUDED_CHANNEL_TYPE = ['broadcast', 'conversation', 'community'];
7300
- const isUnreadCountSupport = ({ type }) => MARKER_INCLUDED_CHANNEL_TYPE.includes(type);
7301
- function convertFromRaw(channel, options = { isMessagePreviewUpdated: true }) {
8231
+ /* begin_public_function
8232
+ id: invitation.cancel
8233
+ */
8234
+ /**
8235
+ * ```js
8236
+ * import { cancelInvitation } from '@amityco/ts-sdk'
8237
+ * const isCanceled = await cancelInvitation(invitationId)
8238
+ * ```
8239
+ *
8240
+ * Cancels a {@link Amity.Invitation} object
8241
+ *
8242
+ * @param invitationId the {@link Amity.Invitation} to cancel
8243
+ * @returns A success boolean if the {@link Amity.Invitation} was canceled
8244
+ *
8245
+ * @category Invitation API
8246
+ * @async
8247
+ */
8248
+ const cancelInvitation = async (invitationId) => {
7302
8249
  var _a;
7303
- let { messagePreviewId } = channel;
7304
- const messagePreviewChannelCache = (_a = pullFromCache([
7305
- 'messagePreviewChannel',
8250
+ const client = getActiveClient();
8251
+ client.log('invitation/cancelInvitation', invitationId);
8252
+ const { data } = await client.http.delete(`/api/v1/invitations/${invitationId}`);
8253
+ const invitation = (_a = pullFromCache([
8254
+ 'invitation',
7306
8255
  'get',
7307
- channel.channelId,
8256
+ invitationId,
7308
8257
  ])) === null || _a === void 0 ? void 0 : _a.data;
7309
- if ((messagePreviewChannelCache === null || messagePreviewChannelCache === void 0 ? void 0 : messagePreviewChannelCache.messagePreviewId) && !options.isMessagePreviewUpdated) {
7310
- messagePreviewId = messagePreviewChannelCache.messagePreviewId;
7311
- }
7312
- return Object.assign(Object.assign({}, channel), { defaultSubChannelId: channel.channelInternalId, isUnreadCountSupport: isUnreadCountSupport(channel), messagePreviewId });
7313
- }
7314
- const preUpdateChannelCache = (rawPayload, options = { isMessagePreviewUpdated: true }) => {
7315
- ingestInCache({
7316
- channels: rawPayload.channels.map(channel => convertFromRaw(channel, { isMessagePreviewUpdated: options.isMessagePreviewUpdated })),
7317
- });
7318
- };
7319
- const updateChannelUnread = ({ currentUserId, channels, channelUsers, }) => {
7320
- for (let i = 0; i < channels.length; i += 1) {
7321
- const cacheKey = ['channelUnread', 'get', channels[i].channelId];
7322
- const channelUser = channelUsers.find(channelUser => channelUser.channelId === channels[i].channelId && channelUser.userId === currentUserId);
7323
- let unreadCount = 0;
7324
- let readToSegment = null;
7325
- let lastMentionedSegment = null;
7326
- let isMentioned = false;
7327
- if (channelUser) {
7328
- readToSegment = channelUser.readToSegment;
7329
- lastMentionedSegment = channelUser.lastMentionedSegment;
7330
- unreadCount = Math.max(channels[i].messageCount - readToSegment, 0);
7331
- isMentioned = lastMentionedSegment > readToSegment;
7332
- }
7333
- const cacheChannelUnread = {
7334
- channelId: channels[i].channelId,
7335
- lastSegment: channels[i].messageCount,
7336
- readToSegment,
7337
- lastMentionedSegment,
7338
- unreadCount,
7339
- isMentioned,
7340
- isDeleted: channels[i].isDeleted || false,
7341
- };
7342
- pushToCache(cacheKey, cacheChannelUnread);
8258
+ if (invitation) {
8259
+ dropFromCache(['invitation', 'get', invitationId]);
8260
+ fireEvent('local.invitation.deleted', [invitation]);
7343
8261
  }
8262
+ return data.success;
7344
8263
  };
7345
- const prepareChannelPayload = async (rawPayload, options = { isMessagePreviewUpdated: true }) => {
8264
+ /* end_public_function */
8265
+
8266
+ const prepareMyInvitationsPayload = (rawPayload) => {
8267
+ return Object.assign(Object.assign({}, rawPayload), { users: rawPayload.users.map(convertRawUserToInternalUser), invitations: rawPayload.invitations.map(convertRawInvitationToInternalInvitation) });
8268
+ };
8269
+
8270
+ const invitationLinkedObject = (invitation) => {
8271
+ return Object.assign(Object.assign({}, invitation), { get user() {
8272
+ const cacheData = pullFromCache(['user', 'get', invitation.invitedUserPublicId]);
8273
+ if (cacheData === null || cacheData === void 0 ? void 0 : cacheData.data)
8274
+ return userLinkedObject(cacheData.data);
8275
+ return undefined;
8276
+ },
8277
+ get createdBy() {
8278
+ const cacheData = pullFromCache(['user', 'get', invitation.inviterUserPublicId]);
8279
+ if (cacheData === null || cacheData === void 0 ? void 0 : cacheData.data)
8280
+ return userLinkedObject(cacheData.data);
8281
+ return undefined;
8282
+ },
8283
+ get target() {
8284
+ if (invitation.targetType === 'community') {
8285
+ const cacheData = pullFromCache([
8286
+ 'community',
8287
+ 'get',
8288
+ invitation.targetId,
8289
+ ]);
8290
+ if (cacheData === null || cacheData === void 0 ? void 0 : cacheData.data)
8291
+ return cacheData.data;
8292
+ return undefined;
8293
+ }
8294
+ return undefined;
8295
+ }, accept: async () => {
8296
+ await acceptInvitation(invitation._id);
8297
+ }, reject: async () => {
8298
+ await rejectInvitation(invitation._id);
8299
+ }, cancel: async () => {
8300
+ await cancelInvitation(invitation._id);
8301
+ } });
8302
+ };
8303
+
8304
+ /* begin_public_function
8305
+ id: invitation.get
8306
+ */
8307
+ /**
8308
+ * ```js
8309
+ * import { getInvitation } from '@amityco/ts-sdk'
8310
+ * const { invitation } = await getInvitation(targetType, targetId)
8311
+ * ```
8312
+ *
8313
+ * Get a {@link Amity.Invitation} object
8314
+ *
8315
+ * @param targetType The type of the target of the {@link Amity.Invitation}
8316
+ * @param targetId The ID of the target of the {@link Amity.Invitation}
8317
+ * @returns A {@link Amity.Invitation} object
8318
+ *
8319
+ * @category Invitation API
8320
+ * @async
8321
+ */
8322
+ const getInvitation = async (targetType, targetId) => {
7346
8323
  const client = getActiveClient();
7347
- const networkPreviewSetting = await client.getMessagePreviewSetting(false);
7348
- if (options.isMessagePreviewUpdated &&
7349
- networkPreviewSetting !== "no-message-preview" /* Amity.MessagePreviewSetting.NO_MESSAGE_PREVIEW */ &&
7350
- rawPayload.messagePreviews &&
7351
- rawPayload.messagePreviews.length > 0) {
7352
- updateChannelMessagePreviewCache(rawPayload);
8324
+ client.log('invitation/getInvitation', targetType, targetId);
8325
+ const { data: payload } = await client.http.get(`/api/v1/invitations/me`, { params: { targetType, targetId } });
8326
+ const data = prepareMyInvitationsPayload(payload);
8327
+ const cachedAt = client.cache && Date.now();
8328
+ if (client.cache)
8329
+ ingestInCache(data, { cachedAt });
8330
+ return {
8331
+ data: data.invitations[0] ? invitationLinkedObject(data.invitations[0]) : undefined,
8332
+ cachedAt,
8333
+ };
8334
+ };
8335
+ /* end_public_function */
8336
+
8337
+ var InvitationActionsEnum;
8338
+ (function (InvitationActionsEnum) {
8339
+ InvitationActionsEnum["OnLocalInvitationCreated"] = "onLocalInvitationCreated";
8340
+ InvitationActionsEnum["OnLocalInvitationUpdated"] = "onLocalInvitationUpdated";
8341
+ InvitationActionsEnum["OnLocalInvitationDeleted"] = "onLocalInvitationDeleted";
8342
+ })(InvitationActionsEnum || (InvitationActionsEnum = {}));
8343
+
8344
+ class InvitationsPaginationController extends PaginationController {
8345
+ async getRequest(queryParams, token) {
8346
+ const { limit = COLLECTION_DEFAULT_PAGINATION_LIMIT } = queryParams, params = __rest(queryParams, ["limit"]);
8347
+ const options = token ? { token } : { limit };
8348
+ const { data } = await this.http.get('/api/v1/invitations', { params: Object.assign(Object.assign({}, params), { options }) });
8349
+ return data;
7353
8350
  }
7354
- if (client.useLegacyUnreadCount) {
7355
- updateChannelUnread({
7356
- channels: rawPayload.channels,
7357
- channelUsers: rawPayload.channelUsers,
7358
- currentUserId: client.userId,
7359
- });
8351
+ }
8352
+
8353
+ class InvitationsQueryStreamController extends QueryStreamController {
8354
+ constructor(query, cacheKey, notifyChange, preparePayload) {
8355
+ super(query, cacheKey);
8356
+ this.notifyChange = notifyChange;
8357
+ this.preparePayload = preparePayload;
7360
8358
  }
7361
- else {
7362
- const markerIds = rawPayload.channels
7363
- // filter channel by type. Only conversation, community and broadcast type are included.
7364
- .filter(isUnreadCountSupport)
7365
- .map(({ channelInternalId }) => channelInternalId);
7366
- if (markerIds.length > 0) {
7367
- // since the get markers method requires a channel cache to function with the reducer.
7368
- preUpdateChannelCache(rawPayload, {
7369
- isMessagePreviewUpdated: options.isMessagePreviewUpdated,
8359
+ async saveToMainDB(response) {
8360
+ const processedPayload = await this.preparePayload(response);
8361
+ const client = getActiveClient();
8362
+ const cachedAt = client.cache && Date.now();
8363
+ if (client.cache) {
8364
+ ingestInCache(processedPayload, { cachedAt });
8365
+ }
8366
+ }
8367
+ appendToQueryStream(response, direction, refresh = false) {
8368
+ var _a, _b;
8369
+ if (refresh) {
8370
+ pushToCache(this.cacheKey, {
8371
+ data: response.invitations.map(getResolver('invitation')),
7370
8372
  });
7371
- try {
7372
- await getChannelMarkers(markerIds);
8373
+ }
8374
+ else {
8375
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
8376
+ const invitations = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
8377
+ pushToCache(this.cacheKey, Object.assign(Object.assign({}, collection), { data: [
8378
+ ...new Set([...invitations, ...response.invitations.map(getResolver('invitation'))]),
8379
+ ] }));
8380
+ }
8381
+ }
8382
+ reactor(action) {
8383
+ return (invitations) => {
8384
+ var _a;
8385
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
8386
+ if (!collection)
8387
+ return;
8388
+ if (action === InvitationActionsEnum.OnLocalInvitationUpdated) {
8389
+ const isExist = collection.data.find(id => id === invitations[0].invitationId);
8390
+ if (!isExist)
8391
+ return;
7373
8392
  }
7374
- catch (e) {
7375
- // empty block (from the spec, allow marker fetch to fail without having to do anything)
8393
+ if (action === InvitationActionsEnum.OnLocalInvitationCreated) {
8394
+ collection.data = [
8395
+ ...new Set([
8396
+ ...invitations.map(invitation => invitation.invitationId),
8397
+ ...collection.data,
8398
+ ]),
8399
+ ];
7376
8400
  }
7377
- }
8401
+ if (action === InvitationActionsEnum.OnLocalInvitationDeleted) {
8402
+ collection.data = collection.data.filter(id => id !== invitations[0].invitationId);
8403
+ }
8404
+ pushToCache(this.cacheKey, collection);
8405
+ this.notifyChange({ origin: "event" /* Amity.LiveDataOrigin.EVENT */, loading: false });
8406
+ };
7378
8407
  }
7379
- // convert raw channel to internal channel
7380
- const channels = rawPayload.channels.map(payload => convertFromRaw(payload, { isMessagePreviewUpdated: options.isMessagePreviewUpdated }));
7381
- // convert raw channel user to membership (add user object)
7382
- const channelUsers = rawPayload.channelUsers.map(channelUser => {
7383
- return convertRawMembershipToMembership(channelUser);
7384
- });
7385
- const users = rawPayload.users.map(convertRawUserToInternalUser);
7386
- const restRawPayload = __rest(rawPayload, ["messageFeedsInfo", "messagePreviews"]);
7387
- return Object.assign(Object.assign({}, restRawPayload), { users,
7388
- channels,
7389
- channelUsers });
7390
- };
8408
+ subscribeRTE(createSubscriber) {
8409
+ return createSubscriber.map(subscriber => subscriber.fn(this.reactor(subscriber.action)));
8410
+ }
8411
+ }
7391
8412
 
7392
8413
  /**
7393
8414
  * ```js
7394
- * import { getSubChannelMarkers } from '@amityco/ts-sdk'
7395
- * const subChannelMarkers = await getSubChannelMarkers(['sch1', 'sch2'])
8415
+ * import { onLocalInvitationCreated } from '@amityco/ts-sdk'
8416
+ * const dispose = onLocalInvitationCreated(data => {
8417
+ * // ...
8418
+ * })
7396
8419
  * ```
7397
8420
  *
7398
- * Fetches a paginable list of {@link Amity.SubChannelMarker} objects
8421
+ * Fired when an {@link Amity.InvitationPayload} has been created
7399
8422
  *
7400
- * @param messageFeedIds the feed IDs of the {@link Amity.RawSubChannel} marker to fetch
7401
- * @param page
7402
- * @returns A page of {@link Amity.SubChannelMarker} objects
8423
+ * @param callback The function to call when the event was fired
8424
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
7403
8425
  *
7404
- * @category Channel API
7405
- * @async
7406
- * @private
8426
+ * @category Invitation Events
7407
8427
  */
7408
- const getUserMessageFeedMakers = async (channelIds) => {
7409
- const client = getActiveClient();
7410
- client.log('channel/getUserMessageFeedMakers', channelIds);
7411
- const { data } = await client.http.get(`/api/v1/markers/user-message-feed`, {
7412
- params: {
7413
- channelIds,
7414
- },
7415
- });
7416
- fireEvent('local.userMessageFeedMarker.fetched', { userMessageFeedMarker: data });
7417
- return data;
7418
- };
7419
-
7420
- const prepareUnreadCountInfo = async (rawPayload) => {
8428
+ const onLocalInvitationCreated = (callback) => {
7421
8429
  const client = getActiveClient();
7422
- // if consistent mode is enabled, persist the unread count info to the cache
7423
- // Marker service API uses channelInternalId as channelId
7424
- const queryPayload = await getUserMessageFeedMakers(rawPayload.channels.map(({ channelInternalId }) => channelInternalId));
7425
- const { feedMarkers, userFeedMarkers } = queryPayload;
7426
- persistUnreadCountInfo({
7427
- feedMarkers,
7428
- userFeedMarkers,
7429
- });
7430
- client.log('channel/prepareUnreadCountInfo', rawPayload.channels);
8430
+ const disposers = [
8431
+ createEventSubscriber(client, 'onLocalInvitationCreated', 'local.invitation.created', payload => callback(payload)),
8432
+ ];
8433
+ return () => {
8434
+ disposers.forEach(fn => fn());
8435
+ };
7431
8436
  };
7432
8437
 
7433
- const getCachedMarker$1 = (entityId) => {
7434
- var _a;
7435
- const key = {
7436
- entityId,
7437
- userId: getActiveUser()._id,
7438
- };
7439
- return (_a = pullFromCache([
7440
- 'channelMarker',
7441
- 'get',
7442
- getResolver('channelMarker')(key),
7443
- ])) === null || _a === void 0 ? void 0 : _a.data;
7444
- };
7445
- const getUnreadInfoCached$1 = (channelId) => {
7446
- var _a;
7447
- return (_a = pullFromCache(['channelUnreadInfo', 'get', channelId])) === null || _a === void 0 ? void 0 : _a.data;
7448
- };
7449
8438
  /**
7450
- * The function use to get value of hasMentioned or isMentioned field.
7451
- * function will get the value from marker params first, if there is no hasMentioned field, will look in to the cache.
8439
+ * ```js
8440
+ * import { onLocalInvitationUpdated } from '@amityco/ts-sdk'
8441
+ * const dispose = onLocalInvitationUpdated(data => {
8442
+ * // ...
8443
+ * })
8444
+ * ```
7452
8445
  *
7453
- * If consistent mode is enabled, the function will return the value from the channelUnreadCountInfo cache.
7454
- * If not, the function will return the value from the channelMarker cache.
7455
- * If not found in the both cache, use `false` as defaul value.
8446
+ * Fired when an {@link Amity.InvitationPayload} has been updated
8447
+ *
8448
+ * @param callback The function to call when the event was fired
8449
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
8450
+ *
8451
+ * @category Invitation Events
7456
8452
  */
7457
- const getChannelIsMentioned = (channel, marker) => {
7458
- var _a, _b, _c, _d;
8453
+ const onLocalInvitationUpdated = (callback) => {
7459
8454
  const client = getActiveClient();
7460
- if (client.isUnreadCountEnabled && client.getMarkerSyncConsistentMode()) {
7461
- return (_b = (_a = getUnreadInfoCached$1(channel.channelPublicId)) === null || _a === void 0 ? void 0 : _a.isMentioned) !== null && _b !== void 0 ? _b : false;
7462
- }
7463
- return (marker === null || marker === void 0 ? void 0 : marker.hasMentioned) !== undefined
7464
- ? marker === null || marker === void 0 ? void 0 : marker.hasMentioned
7465
- : (_d = (_c = getCachedMarker$1(channel.channelPublicId)) === null || _c === void 0 ? void 0 : _c.hasMentioned) !== null && _d !== void 0 ? _d : false;
8455
+ const disposers = [
8456
+ createEventSubscriber(client, 'onLocalInvitationUpdated', 'local.invitation.updated', payload => callback(payload)),
8457
+ ];
8458
+ return () => {
8459
+ disposers.forEach(fn => fn());
8460
+ };
7466
8461
  };
7467
8462
 
7468
- const getCachedMarker = (entityId) => {
7469
- var _a;
7470
- const key = {
7471
- entityId,
7472
- userId: getActiveUser()._id,
7473
- };
7474
- return (_a = pullFromCache([
7475
- 'channelMarker',
7476
- 'get',
7477
- getResolver('channelMarker')(key),
7478
- ])) === null || _a === void 0 ? void 0 : _a.data;
7479
- };
7480
- const getUnreadInfoCached = (channelId) => {
7481
- var _a;
7482
- return (_a = pullFromCache(['channelUnreadInfo', 'get', channelId])) === null || _a === void 0 ? void 0 : _a.data;
7483
- };
7484
8463
  /**
7485
- * The function use to get value of unreadCount field.
7486
- * function will get the value from marker params first, if there is no hasMentioned field, will look in to the cache.
8464
+ * ```js
8465
+ * import { onLocalInvitationDeleted } from '@amityco/ts-sdk'
8466
+ * const dispose = onLocalInvitationDeleted(data => {
8467
+ * // ...
8468
+ * })
8469
+ * ```
7487
8470
  *
7488
- * If consistent mode is enabled, the function will return the value from the channelUnreadCountInfo cache.
7489
- * If not, the function will return the value from the channelMarker cache.
7490
- * If not found in the both cache, use `0` as defaul value.
8471
+ * Fired when an {@link Amity.InvitationPayload} has been deleted
8472
+ *
8473
+ * @param callback The function to call when the event was fired
8474
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
8475
+ *
8476
+ * @category Invitation Events
7491
8477
  */
7492
- const getSubChannelsUnreadCount = (channel, marker) => {
7493
- var _a, _b, _c, _d, _e;
8478
+ const onLocalInvitationDeleted = (callback) => {
7494
8479
  const client = getActiveClient();
7495
- if (client.isUnreadCountEnabled && client.getMarkerSyncConsistentMode()) {
7496
- // Marker service API uses channelInternalId as channelId
7497
- return (_b = (_a = getUnreadInfoCached(channel.channelInternalId)) === null || _a === void 0 ? void 0 : _a.unreadCount) !== null && _b !== void 0 ? _b : 0;
8480
+ const disposers = [
8481
+ createEventSubscriber(client, 'onLocalInvitationDeleted', 'local.invitation.deleted', payload => callback(payload)),
8482
+ ];
8483
+ return () => {
8484
+ disposers.forEach(fn => fn());
8485
+ };
8486
+ };
8487
+
8488
+ class InvitationsLiveCollectionController extends LiveCollectionController {
8489
+ constructor(query, callback) {
8490
+ const queryStreamId = hash__default["default"](query);
8491
+ const cacheKey = ['invitation', 'collection', queryStreamId];
8492
+ const paginationController = new InvitationsPaginationController(query);
8493
+ super(paginationController, queryStreamId, cacheKey, callback);
8494
+ this.query = query;
8495
+ this.queryStreamController = new InvitationsQueryStreamController(this.query, this.cacheKey, this.notifyChange.bind(this), prepareInvitationPayload);
8496
+ this.callback = callback.bind(this);
8497
+ this.loadPage({ initial: true });
7498
8498
  }
7499
- if (marker === null || marker === void 0 ? void 0 : marker.isDeleted) {
7500
- // NOTE: This is a temporary solution to handle the channel marker when the user is forced to
7501
- // leave the channel because currently backend can't handle this, so every time a user is banned
7502
- // from a channel or the channel is deleted the channel's unread count will reset to zero
7503
- return 0;
8499
+ setup() {
8500
+ var _a;
8501
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
8502
+ if (!collection) {
8503
+ pushToCache(this.cacheKey, {
8504
+ data: [],
8505
+ params: this.query,
8506
+ });
8507
+ }
8508
+ }
8509
+ async persistModel(queryPayload) {
8510
+ await this.queryStreamController.saveToMainDB(queryPayload);
8511
+ }
8512
+ persistQueryStream({ response, direction, refresh, }) {
8513
+ this.queryStreamController.appendToQueryStream(response, direction, refresh);
8514
+ }
8515
+ startSubscription() {
8516
+ return this.queryStreamController.subscribeRTE([
8517
+ {
8518
+ fn: onLocalInvitationCreated,
8519
+ action: InvitationActionsEnum.OnLocalInvitationCreated,
8520
+ },
8521
+ {
8522
+ fn: onLocalInvitationUpdated,
8523
+ action: InvitationActionsEnum.OnLocalInvitationUpdated,
8524
+ },
8525
+ {
8526
+ fn: onLocalInvitationDeleted,
8527
+ action: InvitationActionsEnum.OnLocalInvitationDeleted,
8528
+ },
8529
+ ]);
8530
+ }
8531
+ notifyChange({ origin, loading, error }) {
8532
+ var _a, _b;
8533
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
8534
+ if (!collection)
8535
+ return;
8536
+ const data = this.applyFilter((_b = collection.data
8537
+ .map(id => pullFromCache(['invitation', 'get', id]))
8538
+ .filter(isNonNullable)
8539
+ .map(({ data }) => invitationLinkedObject(data))) !== null && _b !== void 0 ? _b : []);
8540
+ if (!this.shouldNotify(data) && origin === 'event')
8541
+ return;
8542
+ this.callback({
8543
+ onNextPage: () => this.loadPage({ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */ }),
8544
+ data,
8545
+ hasNextPage: !!this.paginationController.getNextToken(),
8546
+ loading,
8547
+ error,
8548
+ });
8549
+ }
8550
+ applyFilter(data) {
8551
+ let invitations = data;
8552
+ if (this.query.targetId) {
8553
+ invitations = invitations.filter(invitation => invitation.targetId === this.query.targetId);
8554
+ }
8555
+ if (this.query.statuses) {
8556
+ invitations = invitations.filter(invitation => { var _a; return (_a = this.query.statuses) === null || _a === void 0 ? void 0 : _a.includes(invitation.status); });
8557
+ }
8558
+ if (this.query.targetType) {
8559
+ invitations = invitations.filter(invitation => invitation.targetType === this.query.targetType);
8560
+ }
8561
+ if (this.query.type) {
8562
+ invitations = invitations.filter(invitation => invitation.type === this.query.type);
8563
+ }
8564
+ const sortFn = (() => {
8565
+ switch (this.query.sortBy) {
8566
+ case 'firstCreated':
8567
+ return sortByFirstCreated;
8568
+ case 'lastCreated':
8569
+ return sortByLastCreated;
8570
+ default:
8571
+ return sortByLastCreated;
8572
+ }
8573
+ })();
8574
+ invitations = invitations.sort(sortFn);
8575
+ return invitations;
8576
+ }
8577
+ }
8578
+
8579
+ /**
8580
+ * Get invitations
8581
+ *
8582
+ * @param params the query parameters
8583
+ * @param callback the callback to be called when the invitations are updated
8584
+ * @returns invitations
8585
+ *
8586
+ * @category Invitation Live Collection
8587
+ *
8588
+ */
8589
+ const getInvitations = (params, callback, config) => {
8590
+ const { log, cache } = getActiveClient();
8591
+ if (!cache) {
8592
+ console.log(ENABLE_CACHE_MESSAGE);
7504
8593
  }
7505
- return (_e = (_c = marker === null || marker === void 0 ? void 0 : marker.unreadCount) !== null && _c !== void 0 ? _c : (_d = getCachedMarker(channel.channelInternalId)) === null || _d === void 0 ? void 0 : _d.unreadCount) !== null && _e !== void 0 ? _e : 0;
8594
+ const timestamp = Date.now();
8595
+ log(`getInvitations: (tmpid: ${timestamp}) > listen`);
8596
+ const invitationsLiveCollection = new InvitationsLiveCollectionController(params, callback);
8597
+ const disposers = invitationsLiveCollection.startSubscription();
8598
+ const cacheKey = invitationsLiveCollection.getCacheKey();
8599
+ disposers.push(() => {
8600
+ dropFromCache(cacheKey);
8601
+ });
8602
+ return () => {
8603
+ log(`getInvitations (tmpid: ${timestamp}) > dispose`);
8604
+ disposers.forEach(fn => fn());
8605
+ };
7506
8606
  };
7507
8607
 
7508
- const getLegacyChannelUnread = (channelId) => {
7509
- var _a;
7510
- return (_a = pullFromCache(['channelUnread', 'get', channelId])) === null || _a === void 0 ? void 0 : _a.data;
8608
+ const communityLinkedObject = (community) => {
8609
+ return Object.assign(Object.assign({}, community), { createInvitations: async (userIds) => {
8610
+ await createInvitations({
8611
+ type: "communityMemberInvite" /* InvitationTypeEnum.CommunityMemberInvite */,
8612
+ targetType: 'community',
8613
+ targetId: community.communityId,
8614
+ userIds,
8615
+ });
8616
+ }, getMemberInvitations: (params, callback) => {
8617
+ return getInvitations(Object.assign(Object.assign({}, params), { targetId: community.communityId, targetType: 'community', type: "communityMemberInvite" /* InvitationTypeEnum.CommunityMemberInvite */ }), callback);
8618
+ }, getInvitation: async () => {
8619
+ const { data } = await getInvitation('community', community.communityId);
8620
+ return data;
8621
+ }, join: async () => {
8622
+ return joinRequest(community.communityId);
8623
+ }, getJoinRequests: (params, callback) => {
8624
+ return getJoinRequests(Object.assign(Object.assign({}, params), { communityId: community.communityId }), callback);
8625
+ }, getMyJoinRequest: async () => {
8626
+ const { data } = await getMyJoinRequest(community.communityId);
8627
+ return data;
8628
+ } });
7511
8629
  };
7512
8630
 
7513
- const constructChannelDynamicValue = (channel) => {
7514
- const client = getActiveClient();
7515
- const rest = __rest(channel, ["messageCount"]);
7516
- return shallowClone(rest, {
7517
- get unreadCount() {
7518
- var _a, _b;
7519
- return (_b = (_a = getLegacyChannelUnread(rest.channelId)) === null || _a === void 0 ? void 0 : _a.unreadCount) !== null && _b !== void 0 ? _b : 0;
7520
- },
7521
- get subChannelsUnreadCount() {
7522
- return getSubChannelsUnreadCount(rest);
7523
- },
7524
- get isMentioned() {
7525
- var _a, _b;
7526
- if (client.useLegacyUnreadCount)
7527
- return (_b = (_a = getLegacyChannelUnread(rest.channelId)) === null || _a === void 0 ? void 0 : _a.isMentioned) !== null && _b !== void 0 ? _b : false;
7528
- return getChannelIsMentioned(rest);
7529
- },
7530
- });
8631
+ const LinkedObject = {
8632
+ ad: adLinkedObject,
8633
+ comment: commentLinkedObject,
8634
+ post: postLinkedObject,
8635
+ user: userLinkedObject,
8636
+ category: categoryLinkedObject,
8637
+ stream: streamLinkedObject,
8638
+ story: storyLinkedObject,
8639
+ storyTarget: storyTargetLinkedObject,
8640
+ message: messageLinkedObject,
8641
+ reactor: reactorLinkedObject,
8642
+ channel: channelLinkedObject,
8643
+ pinnedPost: pinnedPostLinkedObject,
8644
+ notificationTray: notificationTrayLinkedObject,
8645
+ community: communityLinkedObject,
8646
+ invitation: invitationLinkedObject,
8647
+ joinRequest: joinRequestLinkedObject,
7531
8648
  };
7532
8649
 
7533
8650
  const constructChannelObject = (channel) => {
@@ -10249,38 +11366,6 @@ const onMessageMarked = (callback) => {
10249
11366
  return createEventSubscriber(client, 'messageMarker/onMessageMarked', 'marker.marked-message', filter);
10250
11367
  };
10251
11368
 
10252
- function isObject(value) {
10253
- return typeof value === 'object' && value !== null;
10254
- }
10255
- /**
10256
- * convert all object getter property to static value
10257
- */
10258
- const convertGetterPropsToStatic = (obj) => {
10259
- if (!isObject(obj)) {
10260
- return obj;
10261
- }
10262
- const entries = Object.entries(obj).map(([key, value]) => {
10263
- const descriptor = Object.getOwnPropertyDescriptor(obj, key);
10264
- if (typeof (descriptor === null || descriptor === void 0 ? void 0 : descriptor.get) === 'function') {
10265
- return [key, descriptor.get.call(obj)];
10266
- }
10267
- return [key, value];
10268
- });
10269
- return Object.fromEntries(entries);
10270
- };
10271
- const removeFunctionProperties = (obj) => {
10272
- if (!isObject(obj)) {
10273
- return obj;
10274
- }
10275
- const entries = Object.entries(obj).map(([key, value]) => {
10276
- if (typeof value === 'function') {
10277
- return [key, undefined];
10278
- }
10279
- return [key, value];
10280
- });
10281
- return Object.fromEntries(entries);
10282
- };
10283
-
10284
11369
  /**
10285
11370
  *
10286
11371
  * ```js
@@ -10894,51 +11979,6 @@ const onLocalFollowRequestAccepted = (callback) => createLocalFollowEventSubscri
10894
11979
 
10895
11980
  const onLocalFollowRequestDeclined = (callback) => createLocalFollowEventSubscriber('local.follow.requestDeclined', callback);
10896
11981
 
10897
- class PaginationController {
10898
- constructor(queryParams) {
10899
- const { http } = getActiveClient();
10900
- this.queryParams = queryParams;
10901
- this.http = http;
10902
- }
10903
- loadFirstPage() {
10904
- return this.onFetch("first" /* Amity.LiveCollectionPageDirection.FIRST */);
10905
- }
10906
- loadNextPage() {
10907
- return this.onFetch("next" /* Amity.LiveCollectionPageDirection.NEXT */);
10908
- }
10909
- loadPreviousPage() {
10910
- return this.onFetch("prev" /* Amity.LiveCollectionPageDirection.PREV */);
10911
- }
10912
- async onFetch(direction = "first" /* Amity.LiveCollectionPageDirection.FIRST */) {
10913
- var _a, _b, _c, _d;
10914
- if (direction === 'prev' && !this.previousToken)
10915
- return;
10916
- if (direction === 'next' && !this.nextToken)
10917
- return;
10918
- let token;
10919
- if (direction === 'prev')
10920
- token = this.previousToken;
10921
- if (direction === 'next')
10922
- token = this.nextToken;
10923
- const queryResponse = await this.getRequest(this.queryParams, token);
10924
- if (direction === 'first') {
10925
- this.nextToken = (_a = queryResponse.paging) === null || _a === void 0 ? void 0 : _a.next;
10926
- this.previousToken = (_b = queryResponse.paging) === null || _b === void 0 ? void 0 : _b.previous;
10927
- }
10928
- if (direction === 'prev')
10929
- this.previousToken = (_c = queryResponse.paging) === null || _c === void 0 ? void 0 : _c.previous;
10930
- if (direction === 'next')
10931
- this.nextToken = (_d = queryResponse.paging) === null || _d === void 0 ? void 0 : _d.next;
10932
- return queryResponse;
10933
- }
10934
- getNextToken() {
10935
- return this.nextToken;
10936
- }
10937
- getPrevToken() {
10938
- return this.previousToken;
10939
- }
10940
- }
10941
-
10942
11982
  class FollowerPaginationController extends PaginationController {
10943
11983
  async getRequest(queryParams, token) {
10944
11984
  const { limit = COLLECTION_DEFAULT_PAGINATION_LIMIT, userId } = queryParams, params = __rest(queryParams, ["limit", "userId"]);
@@ -10952,13 +11992,6 @@ class FollowerPaginationController extends PaginationController {
10952
11992
  }
10953
11993
  }
10954
11994
 
10955
- class QueryStreamController {
10956
- constructor(query, cacheKey) {
10957
- this.query = query;
10958
- this.cacheKey = cacheKey;
10959
- }
10960
- }
10961
-
10962
11995
  var EnumFollowActions;
10963
11996
  (function (EnumFollowActions) {
10964
11997
  EnumFollowActions["OnRequested"] = "onRequested";
@@ -11009,123 +12042,20 @@ class FollowerQueryStreamController extends QueryStreamController {
11009
12042
  case EnumFollowActions.OnCanceled:
11010
12043
  case EnumFollowActions.OnUnfollowed:
11011
12044
  case EnumFollowActions.OnDeleted:
11012
- collection.data = collection.data.filter(p => p !== getResolver('follow')(followStatus));
11013
- break;
11014
- case EnumFollowActions.OnRequested:
11015
- case EnumFollowActions.OnAccepted:
11016
- case EnumFollowActions.OnFollowed:
11017
- collection.data = [...new Set([getResolver('follow')(followStatus), ...collection.data])];
11018
- break;
11019
- }
11020
- pushToCache(this.cacheKey, collection);
11021
- this.notifyChange({ origin: "event" /* Amity.LiveDataOrigin.EVENT */, loading: false });
11022
- };
11023
- }
11024
- subscribeRTE(createSubscriber) {
11025
- return createSubscriber.map(subscriber => subscriber.fn(this.reactor(subscriber.action)));
11026
- }
11027
- }
11028
-
11029
- class PaginationNoPageController {
11030
- constructor(queryParams) {
11031
- const { http } = getActiveClient();
11032
- this.queryParams = queryParams;
11033
- this.http = http;
11034
- }
11035
- async onFetch() {
11036
- const queryResponse = await this.getRequest(this.queryParams);
11037
- return queryResponse;
11038
- }
11039
- }
11040
-
11041
- class LiveCollectionController {
11042
- constructor(paginationController, queryStreamId, cacheKey, callback) {
11043
- this.paginationController = paginationController;
11044
- this.queryStreamId = queryStreamId;
11045
- this.cacheKey = cacheKey;
11046
- this.callback = callback;
11047
- }
11048
- async refresh() {
11049
- try {
11050
- let result;
11051
- if (this.paginationController instanceof PaginationNoPageController) {
11052
- result = await this.paginationController.onFetch();
11053
- }
11054
- else {
11055
- result = await this.paginationController.loadFirstPage();
11056
- }
11057
- if (!result)
11058
- return;
11059
- await this.persistModel(result);
11060
- this.persistQueryStream({
11061
- response: result,
11062
- direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */,
11063
- refresh: true,
11064
- });
11065
- this.notifyChange({ origin: "server" /* Amity.LiveDataOrigin.SERVER */, loading: false });
11066
- }
11067
- catch (e) {
11068
- this.notifyChange({ origin: "server" /* Amity.LiveDataOrigin.SERVER */, loading: false, error: e });
11069
- }
11070
- }
11071
- loadPage({ initial = false, direction = "next" /* Amity.LiveCollectionPageDirection.NEXT */, }) {
11072
- this.setup();
11073
- this.notifyChange({ origin: "local" /* Amity.LiveDataOrigin.LOCAL */, loading: true });
11074
- if (initial) {
11075
- this.refresh();
11076
- }
11077
- else if (direction === "prev" /* Amity.LiveCollectionPageDirection.PREV */) {
11078
- this.loadPrevPage();
11079
- }
11080
- else if (direction === "next" /* Amity.LiveCollectionPageDirection.NEXT */) {
11081
- this.loadNextPage();
11082
- }
11083
- }
11084
- async loadNextPage() {
11085
- try {
11086
- if (this.paginationController instanceof PaginationNoPageController)
11087
- return;
11088
- const result = await this.paginationController.loadNextPage();
11089
- if (!result)
11090
- return;
11091
- await this.persistModel(result);
11092
- this.persistQueryStream({
11093
- response: result,
11094
- direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */,
11095
- });
11096
- this.notifyChange({ origin: "server" /* Amity.LiveDataOrigin.SERVER */, loading: false });
11097
- }
11098
- catch (e) {
11099
- this.notifyChange({ origin: "server" /* Amity.LiveDataOrigin.SERVER */, loading: false, error: e });
11100
- }
11101
- }
11102
- async loadPrevPage() {
11103
- try {
11104
- if (this.paginationController instanceof PaginationNoPageController)
11105
- return;
11106
- const result = await this.paginationController.loadPreviousPage();
11107
- if (!result)
11108
- return;
11109
- await this.persistModel(result);
11110
- this.persistQueryStream({
11111
- response: result,
11112
- direction: "prev" /* Amity.LiveCollectionPageDirection.PREV */,
11113
- });
11114
- this.notifyChange({ origin: "server" /* Amity.LiveDataOrigin.SERVER */, loading: false });
11115
- }
11116
- catch (e) {
11117
- this.notifyChange({ origin: "server" /* Amity.LiveDataOrigin.SERVER */, loading: false, error: e });
11118
- }
11119
- }
11120
- shouldNotify(data) {
11121
- const newData = data.map(convertGetterPropsToStatic).map(removeFunctionProperties);
11122
- if (isEqual(this.snapshot, newData))
11123
- return false;
11124
- this.snapshot = newData;
11125
- return true;
12045
+ collection.data = collection.data.filter(p => p !== getResolver('follow')(followStatus));
12046
+ break;
12047
+ case EnumFollowActions.OnRequested:
12048
+ case EnumFollowActions.OnAccepted:
12049
+ case EnumFollowActions.OnFollowed:
12050
+ collection.data = [...new Set([getResolver('follow')(followStatus), ...collection.data])];
12051
+ break;
12052
+ }
12053
+ pushToCache(this.cacheKey, collection);
12054
+ this.notifyChange({ origin: "event" /* Amity.LiveDataOrigin.EVENT */, loading: false });
12055
+ };
11126
12056
  }
11127
- getCacheKey() {
11128
- return this.cacheKey;
12057
+ subscribeRTE(createSubscriber) {
12058
+ return createSubscriber.map(subscriber => subscriber.fn(this.reactor(subscriber.action)));
11129
12059
  }
11130
12060
  }
11131
12061
 
@@ -13271,41 +14201,6 @@ getComment$2.locally = (commentId) => {
13271
14201
  };
13272
14202
  };
13273
14203
 
13274
- /*
13275
- * verifies membership status
13276
- */
13277
- function isMember(membership) {
13278
- return membership !== 'none';
13279
- }
13280
- /*
13281
- * checks if currently logged in user is part of the community
13282
- */
13283
- function isCurrentUserPartOfCommunity(c, m) {
13284
- const { userId } = getActiveUser();
13285
- return c.communityId === m.communityId && m.userId === userId;
13286
- }
13287
- /*
13288
- * For mqtt events server will not send user specific data as it's broadcasted
13289
- * to multiple users and it also does not include communityUser
13290
- *
13291
- * Client SDK needs to check for the existing isJoined field in cache data before calculating.
13292
- * Althought this can be calculated, it's not scalable.
13293
- */
13294
- function updateMembershipStatus(communities, communityUsers) {
13295
- return communities.map(c => {
13296
- const cachedCommunity = pullFromCache([
13297
- 'community',
13298
- 'get',
13299
- c.communityId,
13300
- ]);
13301
- if ((cachedCommunity === null || cachedCommunity === void 0 ? void 0 : cachedCommunity.data) && (cachedCommunity === null || cachedCommunity === void 0 ? void 0 : cachedCommunity.data.hasOwnProperty('isJoined'))) {
13302
- return Object.assign(Object.assign({}, cachedCommunity.data), c);
13303
- }
13304
- const isJoined = communityUsers.some(m => isCurrentUserPartOfCommunity(c, m) && isMember(m.communityMembership));
13305
- return Object.assign(Object.assign({}, c), { isJoined });
13306
- });
13307
- }
13308
-
13309
14204
  const getMyReactionsInCache = (payload, eventPrefix) => {
13310
14205
  var _a, _b;
13311
14206
  let id;
@@ -13620,53 +14515,6 @@ removeReaction.optimistically = (referenceType, referenceId, reactionName) => {
13620
14515
  return !((_d = reaction === null || reaction === void 0 ? void 0 : reaction.myReactions) === null || _d === void 0 ? void 0 : _d.includes(reactionName));
13621
14516
  };
13622
14517
 
13623
- const getMatchPostSetting = (value) => {
13624
- var _a;
13625
- return (_a = Object.keys(CommunityPostSettingMaps).find(key => value.needApprovalOnPostCreation ===
13626
- CommunityPostSettingMaps[key].needApprovalOnPostCreation &&
13627
- value.onlyAdminCanPost === CommunityPostSettingMaps[key].onlyAdminCanPost)) !== null && _a !== void 0 ? _a : DefaultCommunityPostSetting;
13628
- };
13629
- function addPostSetting({ communities }) {
13630
- return communities.map((_a) => {
13631
- var { needApprovalOnPostCreation, onlyAdminCanPost } = _a, restCommunityPayload = __rest(_a, ["needApprovalOnPostCreation", "onlyAdminCanPost"]);
13632
- return (Object.assign({ postSetting: getMatchPostSetting({
13633
- needApprovalOnPostCreation,
13634
- onlyAdminCanPost,
13635
- }) }, restCommunityPayload));
13636
- });
13637
- }
13638
- const prepareCommunityPayload = (rawPayload) => {
13639
- const communitiesWithPostSetting = addPostSetting({ communities: rawPayload.communities });
13640
- // map users with community
13641
- const mappedCommunityUsers = rawPayload.communityUsers.map(communityUser => {
13642
- const user = rawPayload.users.find(user => user.userId === communityUser.userId);
13643
- return Object.assign(Object.assign({}, communityUser), { user });
13644
- });
13645
- const communityWithMembershipStatus = updateMembershipStatus(communitiesWithPostSetting, mappedCommunityUsers);
13646
- return Object.assign(Object.assign({}, rawPayload), { communities: communityWithMembershipStatus, communityUsers: mappedCommunityUsers });
13647
- };
13648
- const prepareCommunityMembershipPayload = (rawPayload) => {
13649
- const communitiesWithPostSetting = addPostSetting({ communities: rawPayload.communities });
13650
- // map users with community
13651
- const mappedCommunityUsers = rawPayload.communityUsers.map(communityUser => {
13652
- const user = rawPayload.users.find(user => user.userId === communityUser.userId);
13653
- return Object.assign(Object.assign({}, communityUser), { user });
13654
- });
13655
- const communityWithMembershipStatus = updateMembershipStatus(communitiesWithPostSetting, mappedCommunityUsers);
13656
- return Object.assign(Object.assign({}, rawPayload), { communities: communityWithMembershipStatus, communityUsers: mappedCommunityUsers });
13657
- };
13658
- const prepareCommunityRequest = (params) => {
13659
- const { postSetting = undefined, storySetting } = params, restParam = __rest(params, ["postSetting", "storySetting"]);
13660
- return Object.assign(Object.assign(Object.assign({}, restParam), (postSetting ? CommunityPostSettingMaps[postSetting] : undefined)), {
13661
- // Convert story setting to the actual value. (Allow by default)
13662
- allowCommentInStory: typeof (storySetting === null || storySetting === void 0 ? void 0 : storySetting.enableComment) === 'boolean' ? storySetting.enableComment : true });
13663
- };
13664
- const prepareSemanticSearchCommunityPayload = (_a) => {
13665
- var communityPayload = __rest(_a, ["searchResult"]);
13666
- const processedCommunityPayload = prepareCommunityPayload(communityPayload);
13667
- return Object.assign({}, processedCommunityPayload);
13668
- };
13669
-
13670
14518
  const preparePostPayload = (payload) => {
13671
14519
  const { posts: postsData } = payload, postPayload = __rest(payload, ["posts"]);
13672
14520
  // Unpack community payload by mapping payload field to postSetting value.
@@ -18727,12 +19575,15 @@ const saveCommunityUsers = (communities, communityUsers) => {
18727
19575
  * @category Community API
18728
19576
  * @async
18729
19577
  */
18730
- const getCommunities$1 = async (communityIds) => {
19578
+ const getCommunities$1 = async (communityIds, includeDiscoverablePrivateCommunity) => {
18731
19579
  const client = getActiveClient();
18732
19580
  client.log('community/getCommunities', communityIds);
18733
19581
  // API-FIX: endpoint should not be /list, parameters should be querystring.
18734
19582
  const { data: payload } = await client.http.get(`/api/v3/communities/list`, {
18735
- params: { communityIds },
19583
+ params: {
19584
+ communityIds,
19585
+ includeDiscoverablePrivateCommunity: includeDiscoverablePrivateCommunity !== null && includeDiscoverablePrivateCommunity !== void 0 ? includeDiscoverablePrivateCommunity : true,
19586
+ },
18736
19587
  });
18737
19588
  const data = prepareCommunityPayload(payload);
18738
19589
  const cachedAt = client.cache && Date.now();
@@ -18819,7 +19670,7 @@ const createCommunity = async (bundle) => {
18819
19670
  /**
18820
19671
  * ```js
18821
19672
  * import { updateCommunity } from '@amityco/ts-sdk'
18822
- * const updated = await updateCommunity(communityId, { displayName: 'foobar' })
19673
+ * const updated = await updateCommunity(communityId, { displayName: 'foobar', isDiscoverable: true, requiresJoinApproval: false })
18823
19674
  * ```
18824
19675
  *
18825
19676
  * Updates an {@link Amity.Community}
@@ -18864,11 +19715,16 @@ const updateCommunity = async (communityId, patch) => {
18864
19715
  * @category Community API
18865
19716
  * @async
18866
19717
  */
18867
- const getCommunity$1 = async (communityId) => {
19718
+ const getCommunity$1 = async (communityId, type, includeDiscoverablePrivateCommunity) => {
18868
19719
  const client = getActiveClient();
18869
19720
  client.log('community/getCommunity', communityId);
18870
19721
  // API-FIX: endpoint should not be /list, parameters should be querystring.
18871
- const { data: payload } = await client.http.get(`/api/v3/communities/${communityId}`);
19722
+ const { data: payload } = await client.http.get(`/api/v3/communities/${communityId}`, {
19723
+ params: {
19724
+ type: 'communityJoinRequest',
19725
+ includeDiscoverablePrivateCommunity: includeDiscoverablePrivateCommunity !== null && includeDiscoverablePrivateCommunity !== void 0 ? includeDiscoverablePrivateCommunity : true,
19726
+ },
19727
+ });
18872
19728
  const data = prepareCommunityPayload(payload);
18873
19729
  const cachedAt = client.cache && Date.now();
18874
19730
  if (client.cache) {
@@ -18903,7 +19759,7 @@ getCommunity$1.locally = (communityId) => {
18903
19759
  if (!cached)
18904
19760
  return;
18905
19761
  return {
18906
- data: cached.data,
19762
+ data: LinkedObject.community(cached.data),
18907
19763
  cachedAt: cached.cachedAt,
18908
19764
  };
18909
19765
  };
@@ -18943,6 +19799,9 @@ const deleteCommunity = async (communityId) => {
18943
19799
  };
18944
19800
  /* end_public_function */
18945
19801
 
19802
+ /**
19803
+ * @deprecated This function will to be deprecated and use the new community.join().
19804
+ */
18946
19805
  /* begin_public_function
18947
19806
  id: community.join
18948
19807
  */
@@ -19083,10 +19942,11 @@ const onCommunityDeleted = (callback) => createCommunityEventSubscriber('communi
19083
19942
  */
19084
19943
  class CommunitiesPaginationController$1 extends PaginationController {
19085
19944
  async getRequest(queryParams, token) {
19945
+ var _a;
19086
19946
  const { limit = COLLECTION_DEFAULT_PAGINATION_LIMIT } = queryParams, params = __rest(queryParams, ["limit"]);
19087
19947
  const options = token ? { token } : { limit };
19088
19948
  const { data: queryResponse } = await this.http.get(`/api/v3/communities`, {
19089
- params: Object.assign(Object.assign({}, params), { isDeleted: inferIsDeleted(params.includeDeleted), keyword: params.displayName, filter: params.membership, options }),
19949
+ params: Object.assign(Object.assign({}, params), { isDeleted: inferIsDeleted(params.includeDeleted), keyword: params.displayName, filter: params.membership, includeDiscoverablePrivateCommunity: (_a = params.includeDiscoverablePrivateCommunity) !== null && _a !== void 0 ? _a : true, options }),
19090
19950
  });
19091
19951
  return queryResponse;
19092
19952
  }
@@ -20533,7 +21393,7 @@ class TrendingCommunityLiveCollectionController extends LiveCollectionController
20533
21393
  const data = (_b = collection.data
20534
21394
  .map(id => pullFromCache(['community', 'get', id]))
20535
21395
  .filter(isNonNullable)
20536
- .map(({ data }) => data)) !== null && _b !== void 0 ? _b : [];
21396
+ .map(({ data }) => communityLinkedObject(data))) !== null && _b !== void 0 ? _b : [];
20537
21397
  if (!this.shouldNotify(data) && origin === 'event')
20538
21398
  return;
20539
21399
  this.callback({
@@ -20695,7 +21555,7 @@ class RecommendedCommunityLiveCollectionController extends LiveCollectionControl
20695
21555
  const data = (_b = collection.data
20696
21556
  .map(id => pullFromCache(['community', 'get', id]))
20697
21557
  .filter(isNonNullable)
20698
- .map(({ data }) => data)) !== null && _b !== void 0 ? _b : [];
21558
+ .map(({ data }) => communityLinkedObject(data))) !== null && _b !== void 0 ? _b : [];
20699
21559
  if (!this.shouldNotify(data) && origin === 'event')
20700
21560
  return;
20701
21561
  this.callback({
@@ -23345,7 +24205,8 @@ class PinnedPostQueryStreamController extends QueryStreamController {
23345
24205
  const client = getActiveClient();
23346
24206
  const cachedAt = client.cache && Date.now();
23347
24207
  if (client.cache) {
23348
- ingestInCache(response, { cachedAt });
24208
+ const processedPayload = Object.assign(Object.assign({}, response), { users: response.users ? response.users.map(convertRawUserToInternalUser) : [] });
24209
+ ingestInCache(processedPayload, { cachedAt });
23349
24210
  }
23350
24211
  }
23351
24212
  appendToQueryStream(response, direction, refresh = false) {
@@ -23474,7 +24335,8 @@ class GlobalPinnedPostQueryStreamController extends QueryStreamController {
23474
24335
  const client = getActiveClient();
23475
24336
  const cachedAt = client.cache && Date.now();
23476
24337
  if (client.cache) {
23477
- ingestInCache(response, { cachedAt });
24338
+ const processedPayload = Object.assign(Object.assign({}, response), { users: response.users.map(convertRawUserToInternalUser) });
24339
+ ingestInCache(processedPayload, { cachedAt });
23478
24340
  }
23479
24341
  }
23480
24342
  appendToQueryStream(response, direction, refresh = false) {
@@ -26628,34 +27490,204 @@ var index$1 = /*#__PURE__*/Object.freeze({
26628
27490
  onNotificationTraySeenUpdated: onNotificationTraySeenUpdated
26629
27491
  });
26630
27492
 
27493
+ class MyInvitationsPaginationController extends PaginationController {
27494
+ async getRequest(queryParams, token) {
27495
+ const { limit = COLLECTION_DEFAULT_PAGINATION_LIMIT } = queryParams, params = __rest(queryParams, ["limit"]);
27496
+ const options = token ? { token } : { limit };
27497
+ const { data } = await this.http.get('/api/v1/invitations/me', { params: Object.assign(Object.assign({}, params), { options }) });
27498
+ await getCommunities$1(data.invitations.map(invitation => invitation.targetId));
27499
+ return data;
27500
+ }
27501
+ }
27502
+
27503
+ class MyInvitationsQueryStreamController extends QueryStreamController {
27504
+ constructor(query, cacheKey, notifyChange, preparePayload) {
27505
+ super(query, cacheKey);
27506
+ this.notifyChange = notifyChange;
27507
+ this.preparePayload = preparePayload;
27508
+ }
27509
+ async saveToMainDB(response) {
27510
+ const processedPayload = await this.preparePayload(response);
27511
+ const client = getActiveClient();
27512
+ const cachedAt = client.cache && Date.now();
27513
+ if (client.cache) {
27514
+ ingestInCache(processedPayload, { cachedAt });
27515
+ }
27516
+ }
27517
+ appendToQueryStream(response, direction, refresh = false) {
27518
+ var _a, _b;
27519
+ if (refresh) {
27520
+ pushToCache(this.cacheKey, {
27521
+ data: response.invitations.map(getResolver('invitation')),
27522
+ });
27523
+ }
27524
+ else {
27525
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
27526
+ const invitations = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
27527
+ pushToCache(this.cacheKey, Object.assign(Object.assign({}, collection), { data: [
27528
+ ...new Set([...invitations, ...response.invitations.map(getResolver('invitation'))]),
27529
+ ] }));
27530
+ }
27531
+ }
27532
+ reactor(action) {
27533
+ return (invitations) => {
27534
+ var _a;
27535
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
27536
+ if (!collection)
27537
+ return;
27538
+ if (action === InvitationActionsEnum.OnLocalInvitationUpdated) {
27539
+ const isExist = collection.data.find(id => id === invitations[0].invitationId);
27540
+ if (!isExist)
27541
+ return;
27542
+ }
27543
+ if (action === InvitationActionsEnum.OnLocalInvitationCreated) {
27544
+ const client = getActiveClient();
27545
+ const myInvitations = invitations.filter(invitation => invitation.invitedUserId === client.userId);
27546
+ collection.data = [
27547
+ ...new Set([
27548
+ ...myInvitations.map(invitation => invitation.invitationId),
27549
+ ...collection.data,
27550
+ ]),
27551
+ ];
27552
+ }
27553
+ if (action === InvitationActionsEnum.OnLocalInvitationDeleted) {
27554
+ collection.data = collection.data.filter(id => id !== invitations[0].invitationId);
27555
+ }
27556
+ pushToCache(this.cacheKey, collection);
27557
+ this.notifyChange({ origin: "event" /* Amity.LiveDataOrigin.EVENT */, loading: false });
27558
+ };
27559
+ }
27560
+ subscribeRTE(createSubscriber) {
27561
+ return createSubscriber.map(subscriber => subscriber.fn(this.reactor(subscriber.action)));
27562
+ }
27563
+ }
27564
+
27565
+ class MyInvitationsLiveCollectionController extends LiveCollectionController {
27566
+ constructor(query, callback) {
27567
+ const queryStreamId = hash__default["default"](query);
27568
+ const cacheKey = ['invitation', 'collection', queryStreamId];
27569
+ const paginationController = new MyInvitationsPaginationController(query);
27570
+ super(paginationController, queryStreamId, cacheKey, callback);
27571
+ this.query = query;
27572
+ this.queryStreamController = new MyInvitationsQueryStreamController(this.query, this.cacheKey, this.notifyChange.bind(this), prepareMyInvitationsPayload);
27573
+ this.callback = callback.bind(this);
27574
+ this.loadPage({ initial: true });
27575
+ }
27576
+ setup() {
27577
+ var _a;
27578
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
27579
+ if (!collection) {
27580
+ pushToCache(this.cacheKey, {
27581
+ data: [],
27582
+ params: this.query,
27583
+ });
27584
+ }
27585
+ }
27586
+ async persistModel(queryPayload) {
27587
+ await this.queryStreamController.saveToMainDB(queryPayload);
27588
+ }
27589
+ persistQueryStream({ response, direction, refresh, }) {
27590
+ this.queryStreamController.appendToQueryStream(response, direction, refresh);
27591
+ }
27592
+ startSubscription() {
27593
+ return this.queryStreamController.subscribeRTE([
27594
+ {
27595
+ fn: onLocalInvitationCreated,
27596
+ action: InvitationActionsEnum.OnLocalInvitationCreated,
27597
+ },
27598
+ {
27599
+ fn: onLocalInvitationUpdated,
27600
+ action: InvitationActionsEnum.OnLocalInvitationUpdated,
27601
+ },
27602
+ {
27603
+ fn: onLocalInvitationDeleted,
27604
+ action: InvitationActionsEnum.OnLocalInvitationDeleted,
27605
+ },
27606
+ ]);
27607
+ }
27608
+ notifyChange({ origin, loading, error }) {
27609
+ var _a, _b;
27610
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
27611
+ if (!collection)
27612
+ return;
27613
+ const data = this.applyFilter((_b = collection.data
27614
+ .map(id => pullFromCache(['invitation', 'get', id]))
27615
+ .filter(isNonNullable)
27616
+ .map(({ data }) => invitationLinkedObject(data))) !== null && _b !== void 0 ? _b : []);
27617
+ if (!this.shouldNotify(data) && origin === 'event')
27618
+ return;
27619
+ this.callback({
27620
+ onNextPage: () => this.loadPage({ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */ }),
27621
+ data,
27622
+ hasNextPage: !!this.paginationController.getNextToken(),
27623
+ loading,
27624
+ error,
27625
+ });
27626
+ }
27627
+ applyFilter(data) {
27628
+ let invitations = data;
27629
+ if (this.query.targetId) {
27630
+ invitations = invitations.filter(invitation => invitation.targetId === this.query.targetId);
27631
+ }
27632
+ if (this.query.statuses) {
27633
+ invitations = invitations.filter(invitation => { var _a; return (_a = this.query.statuses) === null || _a === void 0 ? void 0 : _a.includes(invitation.status); });
27634
+ }
27635
+ if (this.query.targetType) {
27636
+ invitations = invitations.filter(invitation => invitation.targetType === this.query.targetType);
27637
+ }
27638
+ if (this.query.type) {
27639
+ invitations = invitations.filter(invitation => invitation.type === this.query.type);
27640
+ }
27641
+ const sortFn = (() => {
27642
+ switch (this.query.sortBy) {
27643
+ case 'firstCreated':
27644
+ return sortByFirstCreated;
27645
+ case 'lastCreated':
27646
+ return sortByLastCreated;
27647
+ default:
27648
+ return sortByLastCreated;
27649
+ }
27650
+ })();
27651
+ invitations = invitations.sort(sortFn);
27652
+ return invitations;
27653
+ }
27654
+ }
27655
+
26631
27656
  /**
26632
- * ```js
26633
- * import { onLocalInvitationCreated } from '@amityco/ts-sdk'
26634
- * const dispose = onLocalInvitationCreated(data => {
26635
- * // ...
26636
- * })
26637
- * ```
27657
+ * Get my community invitations
26638
27658
  *
26639
- * Fired when an {@link Amity.InvitationPayload} has been created
27659
+ * @param params the query parameters
27660
+ * @param callback the callback to be called when the invitations are fetched
27661
+ * @returns invitations
26640
27662
  *
26641
- * @param callback The function to call when the event was fired
26642
- * @returns an {@link Amity.Unsubscriber} function to stop listening
27663
+ * @category My Community Invitations Live Collection
26643
27664
  *
26644
- * @category Invitation Events
26645
27665
  */
26646
- const onLocalInvitationCreated = (callback) => {
26647
- const client = getActiveClient();
26648
- const disposers = [
26649
- createEventSubscriber(client, 'onLocalInvitationCreated', 'local.invitation.created', payload => callback(payload)),
26650
- ];
27666
+ const getMyCommunityInvitations = (params, callback, config) => {
27667
+ const { log, cache } = getActiveClient();
27668
+ if (!cache) {
27669
+ console.log(ENABLE_CACHE_MESSAGE);
27670
+ }
27671
+ const timestamp = Date.now();
27672
+ log(`getMyCommunityInvitations: (tmpid: ${timestamp}) > listen`);
27673
+ const invitationsLiveCollection = new MyInvitationsLiveCollectionController(Object.assign(Object.assign({}, params), { targetType: 'community', statuses: ["pending" /* InvitationStatusEnum.Pending */] }), callback);
27674
+ const disposers = invitationsLiveCollection.startSubscription();
27675
+ const cacheKey = invitationsLiveCollection.getCacheKey();
27676
+ disposers.push(() => {
27677
+ dropFromCache(cacheKey);
27678
+ });
26651
27679
  return () => {
27680
+ log(`getInvitations (tmpid: ${timestamp}) > dispose`);
26652
27681
  disposers.forEach(fn => fn());
26653
27682
  };
26654
27683
  };
26655
27684
 
26656
27685
  var index = /*#__PURE__*/Object.freeze({
26657
27686
  __proto__: null,
26658
- onLocalInvitationCreated: onLocalInvitationCreated
27687
+ onLocalInvitationCreated: onLocalInvitationCreated,
27688
+ onLocalInvitationUpdated: onLocalInvitationUpdated,
27689
+ onLocalInvitationDeleted: onLocalInvitationDeleted,
27690
+ getMyCommunityInvitations: getMyCommunityInvitations
26659
27691
  });
26660
27692
 
26661
27693
  exports.API_REGIONS = API_REGIONS;