@amityco/ts-sdk 7.4.1-b7aa4210.0 → 7.4.1-c116567e.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 (207) hide show
  1. package/dist/@types/core/events.d.ts +3 -0
  2. package/dist/@types/core/events.d.ts.map +1 -1
  3. package/dist/@types/core/model.d.ts +3 -1
  4. package/dist/@types/core/model.d.ts.map +1 -1
  5. package/dist/@types/core/payload.d.ts +11 -4
  6. package/dist/@types/core/payload.d.ts.map +1 -1
  7. package/dist/@types/domains/client.d.ts +10 -0
  8. package/dist/@types/domains/client.d.ts.map +1 -1
  9. package/dist/@types/domains/community.d.ts +10 -1
  10. package/dist/@types/domains/community.d.ts.map +1 -1
  11. package/dist/@types/domains/invitation.d.ts +72 -0
  12. package/dist/@types/domains/invitation.d.ts.map +1 -0
  13. package/dist/@types/index.d.ts +2 -0
  14. package/dist/@types/index.d.ts.map +1 -1
  15. package/dist/communityRepository/api/createCommunity.d.ts +2 -2
  16. package/dist/communityRepository/api/createCommunity.d.ts.map +1 -1
  17. package/dist/communityRepository/api/getCommunities.d.ts +1 -1
  18. package/dist/communityRepository/api/getCommunities.d.ts.map +1 -1
  19. package/dist/communityRepository/api/getCommunity.d.ts.map +1 -1
  20. package/dist/communityRepository/api/getRecommendedCommunities.d.ts +3 -1
  21. package/dist/communityRepository/api/getRecommendedCommunities.d.ts.map +1 -1
  22. package/dist/communityRepository/api/getTrendingCommunities.d.ts +3 -1
  23. package/dist/communityRepository/api/getTrendingCommunities.d.ts.map +1 -1
  24. package/dist/communityRepository/api/queryCommunities.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/communityMembership/events/onCommunityJoined.d.ts +1 -1
  28. package/dist/communityRepository/communityMembership/events/onCommunityJoined.d.ts.map +1 -1
  29. package/dist/communityRepository/communityMembership/events/onCommunityLeft.d.ts +1 -1
  30. package/dist/communityRepository/communityMembership/events/onCommunityLeft.d.ts.map +1 -1
  31. package/dist/communityRepository/communityMembership/events/onCommunityUserAdded.d.ts +1 -1
  32. package/dist/communityRepository/communityMembership/events/onCommunityUserAdded.d.ts.map +1 -1
  33. package/dist/communityRepository/communityMembership/events/onCommunityUserBanned.d.ts +1 -1
  34. package/dist/communityRepository/communityMembership/events/onCommunityUserBanned.d.ts.map +1 -1
  35. package/dist/communityRepository/communityMembership/events/onCommunityUserChanged.d.ts +1 -1
  36. package/dist/communityRepository/communityMembership/events/onCommunityUserChanged.d.ts.map +1 -1
  37. package/dist/communityRepository/communityMembership/events/onCommunityUserRemoved.d.ts +1 -1
  38. package/dist/communityRepository/communityMembership/events/onCommunityUserRemoved.d.ts.map +1 -1
  39. package/dist/communityRepository/communityMembership/events/onCommunityUserRoleAdded.d.ts +1 -1
  40. package/dist/communityRepository/communityMembership/events/onCommunityUserRoleAdded.d.ts.map +1 -1
  41. package/dist/communityRepository/communityMembership/events/onCommunityUserRoleRemoved.d.ts +1 -1
  42. package/dist/communityRepository/communityMembership/events/onCommunityUserRoleRemoved.d.ts.map +1 -1
  43. package/dist/communityRepository/communityMembership/events/onCommunityUserUnbanned.d.ts +1 -1
  44. package/dist/communityRepository/communityMembership/events/onCommunityUserUnbanned.d.ts.map +1 -1
  45. package/dist/communityRepository/communityMembership/events/onLocalCommunityJoined.d.ts +1 -1
  46. package/dist/communityRepository/communityMembership/events/onLocalCommunityJoined.d.ts.map +1 -1
  47. package/dist/communityRepository/communityMembership/events/onLocalCommunityLeft.d.ts +1 -1
  48. package/dist/communityRepository/communityMembership/events/onLocalCommunityLeft.d.ts.map +1 -1
  49. package/dist/communityRepository/communityMembership/events/onLocalCommunityUserAdded.d.ts +1 -1
  50. package/dist/communityRepository/communityMembership/events/onLocalCommunityUserAdded.d.ts.map +1 -1
  51. package/dist/communityRepository/communityMembership/events/onLocalCommunityUserRemoved.d.ts +1 -1
  52. package/dist/communityRepository/communityMembership/events/onLocalCommunityUserRemoved.d.ts.map +1 -1
  53. package/dist/communityRepository/communityMembership/events/onUserDeleted.d.ts +1 -1
  54. package/dist/communityRepository/communityMembership/events/onUserDeleted.d.ts.map +1 -1
  55. package/dist/communityRepository/communityMembership/events/utils.d.ts +2 -2
  56. package/dist/communityRepository/communityMembership/events/utils.d.ts.map +1 -1
  57. package/dist/communityRepository/communityMembership/observers/getMembers/CommunityMembersQueryStreamController.d.ts +2 -2
  58. package/dist/communityRepository/communityMembership/observers/getMembers/CommunityMembersQueryStreamController.d.ts.map +1 -1
  59. package/dist/communityRepository/communityMembership/observers/searchMembers/SearchCommunityMembersQueryStreamController.d.ts +2 -2
  60. package/dist/communityRepository/communityMembership/observers/searchMembers/SearchCommunityMembersQueryStreamController.d.ts.map +1 -1
  61. package/dist/communityRepository/communityModeration/events/onLocalCommunityRoleAdded.d.ts +1 -1
  62. package/dist/communityRepository/communityModeration/events/onLocalCommunityRoleAdded.d.ts.map +1 -1
  63. package/dist/communityRepository/communityModeration/events/onLocalCommunityRoleRemoved.d.ts +1 -1
  64. package/dist/communityRepository/communityModeration/events/onLocalCommunityRoleRemoved.d.ts.map +1 -1
  65. package/dist/communityRepository/events/onCommunityCreated.d.ts +1 -1
  66. package/dist/communityRepository/events/onCommunityCreated.d.ts.map +1 -1
  67. package/dist/communityRepository/events/onCommunityDeleted.d.ts +1 -1
  68. package/dist/communityRepository/events/onCommunityDeleted.d.ts.map +1 -1
  69. package/dist/communityRepository/events/onCommunityUpdated.d.ts +1 -1
  70. package/dist/communityRepository/events/onCommunityUpdated.d.ts.map +1 -1
  71. package/dist/communityRepository/events/utils.d.ts +1 -1
  72. package/dist/communityRepository/events/utils.d.ts.map +1 -1
  73. package/dist/communityRepository/observers/getCommunities/CommunitiesQueryStreamController.d.ts +2 -2
  74. package/dist/communityRepository/observers/getCommunities/CommunitiesQueryStreamController.d.ts.map +1 -1
  75. package/dist/communityRepository/observers/getRecommendedCommunities/RecommendedCommunitiesQueryStreamController.d.ts +2 -2
  76. package/dist/communityRepository/observers/getRecommendedCommunities/RecommendedCommunitiesQueryStreamController.d.ts.map +1 -1
  77. package/dist/communityRepository/observers/getTrendingCommunities/TrendingCommunitiesQueryStreamController.d.ts +2 -2
  78. package/dist/communityRepository/observers/getTrendingCommunities/TrendingCommunitiesQueryStreamController.d.ts.map +1 -1
  79. package/dist/communityRepository/observers/searchCommunities/SearchCommunitiesQueryStreamController.d.ts +2 -2
  80. package/dist/communityRepository/observers/searchCommunities/SearchCommunitiesQueryStreamController.d.ts.map +1 -1
  81. package/dist/communityRepository/observers/semanticSearch/SemanticSearchCommunityQueryStreamController.d.ts +2 -2
  82. package/dist/communityRepository/observers/semanticSearch/SemanticSearchCommunityQueryStreamController.d.ts.map +1 -1
  83. package/dist/communityRepository/utils/communityWithMembership.d.ts +1 -1
  84. package/dist/communityRepository/utils/communityWithMembership.d.ts.map +1 -1
  85. package/dist/communityRepository/utils/payload.d.ts +1 -1
  86. package/dist/communityRepository/utils/payload.d.ts.map +1 -1
  87. package/dist/core/events.d.ts +3 -3
  88. package/dist/core/events.d.ts.map +1 -1
  89. package/dist/core/model/idResolvers.d.ts.map +1 -1
  90. package/dist/core/model/index.d.ts.map +1 -1
  91. package/dist/index.cjs.js +2935 -2421
  92. package/dist/index.d.ts +1 -0
  93. package/dist/index.d.ts.map +1 -1
  94. package/dist/index.esm.js +2283 -1770
  95. package/dist/index.umd.js +4 -4
  96. package/dist/invitationRepository/events/index.d.ts +4 -0
  97. package/dist/invitationRepository/events/index.d.ts.map +1 -0
  98. package/dist/invitationRepository/events/onLocalInvitationCreated.d.ts +17 -0
  99. package/dist/invitationRepository/events/onLocalInvitationCreated.d.ts.map +1 -0
  100. package/dist/invitationRepository/events/onLocalInvitationDeleted.d.ts +17 -0
  101. package/dist/invitationRepository/events/onLocalInvitationDeleted.d.ts.map +1 -0
  102. package/dist/invitationRepository/events/onLocalInvitationUpdated.d.ts +17 -0
  103. package/dist/invitationRepository/events/onLocalInvitationUpdated.d.ts.map +1 -0
  104. package/dist/invitationRepository/index.d.ts +2 -0
  105. package/dist/invitationRepository/index.d.ts.map +1 -0
  106. package/dist/invitationRepository/internalApi/acceptInvitation.d.ts +16 -0
  107. package/dist/invitationRepository/internalApi/acceptInvitation.d.ts.map +1 -0
  108. package/dist/invitationRepository/internalApi/cancelInvitation.d.ts +16 -0
  109. package/dist/invitationRepository/internalApi/cancelInvitation.d.ts.map +1 -0
  110. package/dist/invitationRepository/internalApi/createInvitations.d.ts +21 -0
  111. package/dist/invitationRepository/internalApi/createInvitations.d.ts.map +1 -0
  112. package/dist/invitationRepository/internalApi/index.d.ts +5 -0
  113. package/dist/invitationRepository/internalApi/index.d.ts.map +1 -0
  114. package/dist/invitationRepository/internalApi/rejectInvitation.d.ts +16 -0
  115. package/dist/invitationRepository/internalApi/rejectInvitation.d.ts.map +1 -0
  116. package/dist/invitationRepository/observers/getInvitations/InvitationsLiveCollectionController.d.ts +14 -0
  117. package/dist/invitationRepository/observers/getInvitations/InvitationsLiveCollectionController.d.ts.map +1 -0
  118. package/dist/invitationRepository/observers/getInvitations/InvitationsPaginationController.d.ts +5 -0
  119. package/dist/invitationRepository/observers/getInvitations/InvitationsPaginationController.d.ts.map +1 -0
  120. package/dist/invitationRepository/observers/getInvitations/InvitationsQueryStreamController.d.ts +15 -0
  121. package/dist/invitationRepository/observers/getInvitations/InvitationsQueryStreamController.d.ts.map +1 -0
  122. package/dist/invitationRepository/observers/getInvitations/enums.d.ts +6 -0
  123. package/dist/invitationRepository/observers/getInvitations/enums.d.ts.map +1 -0
  124. package/dist/invitationRepository/observers/getInvitations.d.ts +12 -0
  125. package/dist/invitationRepository/observers/getInvitations.d.ts.map +1 -0
  126. package/dist/invitationRepository/utils/index.d.ts +2 -0
  127. package/dist/invitationRepository/utils/index.d.ts.map +1 -0
  128. package/dist/invitationRepository/utils/prepareInvitationPayload.d.ts +2 -0
  129. package/dist/invitationRepository/utils/prepareInvitationPayload.d.ts.map +1 -0
  130. package/dist/utils/linkedObject/communityLinkedObject.d.ts +2 -0
  131. package/dist/utils/linkedObject/communityLinkedObject.d.ts.map +1 -0
  132. package/dist/utils/linkedObject/index.d.ts +2 -0
  133. package/dist/utils/linkedObject/index.d.ts.map +1 -1
  134. package/dist/utils/linkedObject/invitationLinkedObject.d.ts +2 -0
  135. package/dist/utils/linkedObject/invitationLinkedObject.d.ts.map +1 -0
  136. package/dist/utils/tests/dummy/post.d.ts +3 -3
  137. package/package.json +1 -1
  138. package/src/@types/core/events.ts +4 -0
  139. package/src/@types/core/model.ts +5 -1
  140. package/src/@types/core/payload.ts +13 -4
  141. package/src/@types/domains/client.ts +12 -0
  142. package/src/@types/domains/community.ts +18 -1
  143. package/src/@types/domains/invitation.ts +92 -0
  144. package/src/@types/index.ts +2 -0
  145. package/src/communityRepository/api/createCommunity.ts +5 -2
  146. package/src/communityRepository/api/getCommunities.ts +7 -2
  147. package/src/communityRepository/api/getCommunity.ts +4 -1
  148. package/src/communityRepository/api/getRecommendedCommunities.ts +11 -4
  149. package/src/communityRepository/api/getTrendingCommunities.ts +11 -4
  150. package/src/communityRepository/api/queryCommunities.ts +6 -1
  151. package/src/communityRepository/api/updateCommunity.ts +13 -3
  152. package/src/communityRepository/communityMembership/events/onCommunityJoined.ts +1 -1
  153. package/src/communityRepository/communityMembership/events/onCommunityLeft.ts +1 -1
  154. package/src/communityRepository/communityMembership/events/onCommunityUserAdded.ts +1 -1
  155. package/src/communityRepository/communityMembership/events/onCommunityUserBanned.ts +1 -1
  156. package/src/communityRepository/communityMembership/events/onCommunityUserChanged.ts +1 -1
  157. package/src/communityRepository/communityMembership/events/onCommunityUserRemoved.ts +1 -1
  158. package/src/communityRepository/communityMembership/events/onCommunityUserRoleAdded.ts +1 -1
  159. package/src/communityRepository/communityMembership/events/onCommunityUserRoleRemoved.ts +1 -1
  160. package/src/communityRepository/communityMembership/events/onCommunityUserUnbanned.ts +1 -1
  161. package/src/communityRepository/communityMembership/events/onLocalCommunityJoined.ts +1 -1
  162. package/src/communityRepository/communityMembership/events/onLocalCommunityLeft.ts +1 -1
  163. package/src/communityRepository/communityMembership/events/onLocalCommunityUserAdded.ts +1 -1
  164. package/src/communityRepository/communityMembership/events/onLocalCommunityUserRemoved.ts +1 -1
  165. package/src/communityRepository/communityMembership/events/onUserDeleted.ts +3 -1
  166. package/src/communityRepository/communityMembership/events/utils.ts +2 -2
  167. package/src/communityRepository/communityMembership/observers/getMembers/CommunityMembersQueryStreamController.ts +8 -2
  168. package/src/communityRepository/communityMembership/observers/searchMembers/SearchCommunityMembersQueryStreamController.ts +8 -2
  169. package/src/communityRepository/communityModeration/events/onLocalCommunityRoleAdded.ts +1 -1
  170. package/src/communityRepository/communityModeration/events/onLocalCommunityRoleRemoved.ts +1 -1
  171. package/src/communityRepository/events/onCommunityCreated.ts +1 -1
  172. package/src/communityRepository/events/onCommunityDeleted.ts +1 -1
  173. package/src/communityRepository/events/onCommunityUpdated.ts +1 -1
  174. package/src/communityRepository/events/utils.ts +1 -1
  175. package/src/communityRepository/observers/getCommunities/CommunitiesQueryStreamController.ts +2 -2
  176. package/src/communityRepository/observers/getRecommendedCommunities/RecommendedCommunitiesQueryStreamController.ts +2 -2
  177. package/src/communityRepository/observers/getTrendingCommunities/TrendingCommunitiesQueryStreamController.ts +2 -2
  178. package/src/communityRepository/observers/searchCommunities/SearchCommunitiesQueryStreamController.ts +2 -2
  179. package/src/communityRepository/observers/semanticSearch/SemanticSearchCommunityQueryStreamController.ts +2 -2
  180. package/src/communityRepository/utils/communityWithMembership.ts +8 -4
  181. package/src/communityRepository/utils/payload.ts +1 -1
  182. package/src/core/liveCollection/PaginationController.ts +1 -1
  183. package/src/core/liveCollection/PaginationNoPageController.ts +1 -1
  184. package/src/core/model/idResolvers.ts +2 -0
  185. package/src/core/model/index.ts +2 -0
  186. package/src/index.ts +2 -0
  187. package/src/invitationRepository/events/index.ts +3 -0
  188. package/src/invitationRepository/events/onLocalInvitationCreated.ts +33 -0
  189. package/src/invitationRepository/events/onLocalInvitationDeleted.ts +33 -0
  190. package/src/invitationRepository/events/onLocalInvitationUpdated.ts +33 -0
  191. package/src/invitationRepository/index.ts +1 -0
  192. package/src/invitationRepository/internalApi/acceptInvitation.ts +45 -0
  193. package/src/invitationRepository/internalApi/cancelInvitation.ts +44 -0
  194. package/src/invitationRepository/internalApi/createInvitations.ts +52 -0
  195. package/src/invitationRepository/internalApi/index.ts +4 -0
  196. package/src/invitationRepository/internalApi/rejectInvitation.ts +45 -0
  197. package/src/invitationRepository/observers/getInvitations/InvitationsLiveCollectionController.ts +148 -0
  198. package/src/invitationRepository/observers/getInvitations/InvitationsPaginationController.ts +19 -0
  199. package/src/invitationRepository/observers/getInvitations/InvitationsQueryStreamController.ts +97 -0
  200. package/src/invitationRepository/observers/getInvitations/enums.ts +5 -0
  201. package/src/invitationRepository/observers/getInvitations.ts +44 -0
  202. package/src/invitationRepository/utils/index.ts +1 -0
  203. package/src/invitationRepository/utils/prepareInvitationPayload.ts +11 -0
  204. package/src/messagePreview/utils/getChannelMessagePreviewWithUser.ts +3 -3
  205. package/src/utils/linkedObject/communityLinkedObject.ts +29 -0
  206. package/src/utils/linkedObject/index.ts +4 -0
  207. package/src/utils/linkedObject/invitationLinkedObject.ts +44 -0
package/dist/index.esm.js CHANGED
@@ -8,6 +8,12 @@ import uuid$1 from 'react-native-uuid';
8
8
  import hash from 'object-hash';
9
9
  import Hls from 'hls.js';
10
10
 
11
+ var MembershipAcceptanceTypeEnum;
12
+ (function (MembershipAcceptanceTypeEnum) {
13
+ MembershipAcceptanceTypeEnum["AUTOMATIC"] = "automatic";
14
+ MembershipAcceptanceTypeEnum["INVITATION"] = "invitation";
15
+ })(MembershipAcceptanceTypeEnum || (MembershipAcceptanceTypeEnum = {}));
16
+
11
17
  const FileType = Object.freeze({
12
18
  FILE: 'file',
13
19
  IMAGE: 'image',
@@ -97,6 +103,24 @@ const PostContentType = Object.freeze({
97
103
  POLL: 'poll',
98
104
  });
99
105
 
106
+ var InvitationTypeEnum;
107
+ (function (InvitationTypeEnum) {
108
+ InvitationTypeEnum["CommunityMemberInvite"] = "communityMemberInvite";
109
+ InvitationTypeEnum["LivestreamInvite"] = "livestreamInvite";
110
+ })(InvitationTypeEnum || (InvitationTypeEnum = {}));
111
+ var InvitationStatusEnum;
112
+ (function (InvitationStatusEnum) {
113
+ InvitationStatusEnum["Pending"] = "pending";
114
+ InvitationStatusEnum["Approved"] = "approved";
115
+ InvitationStatusEnum["Rejected"] = "rejected";
116
+ InvitationStatusEnum["Cancelled"] = "cancelled";
117
+ })(InvitationStatusEnum || (InvitationStatusEnum = {}));
118
+ var InvitationSortByEnum;
119
+ (function (InvitationSortByEnum) {
120
+ InvitationSortByEnum["FirstCreated"] = "firstCreated";
121
+ InvitationSortByEnum["LastCreated"] = "lastCreated";
122
+ })(InvitationSortByEnum || (InvitationSortByEnum = {}));
123
+
100
124
  function getVersion() {
101
125
  try {
102
126
  // the string ''v7.4.0-esm'' should be replaced by actual value by @rollup/plugin-replace
@@ -543,6 +567,7 @@ const idResolvers = {
543
567
  pinTarget: ({ targetId }) => targetId,
544
568
  notificationTrayItem: ({ _id }) => _id,
545
569
  notificationTraySeen: ({ userId }) => userId,
570
+ invitation: ({ _id }) => _id,
546
571
  };
547
572
  /**
548
573
  * Retrieve the id resolver matching a domain name
@@ -595,6 +620,7 @@ const PAYLOAD2MODEL = {
595
620
  pinTargets: 'pinTarget',
596
621
  pins: 'pin',
597
622
  notificationTrayItems: 'notificationTrayItem',
623
+ invitations: 'invitation',
598
624
  };
599
625
  /** hidden */
600
626
  const isOutdated = (prevData, nextData) => {
@@ -20969,305 +20995,6 @@ const getChannelMessagePreview = (channelId) => {
20969
20995
  return ((_b = (_a = pullFromCache(['messagePreviewChannel', 'get', channelId])) === null || _a === void 0 ? void 0 : _a.data) !== null && _b !== void 0 ? _b : null);
20970
20996
  };
20971
20997
 
20972
- const ANALYTIC_CACHE_KEY = ['analytic', 'normal-priority'];
20973
- const HIGH_PRIORITY_ANALYTIC_CACHE_KEY = ['analytic', 'high-priority'];
20974
-
20975
- const syncEvent = async (events) => {
20976
- const client = getActiveClient();
20977
- const params = {
20978
- activities: events,
20979
- };
20980
- await client.http.post('/api/v1/analytics/activities', params);
20981
- };
20982
-
20983
- class AnalyticsEventSyncer {
20984
- constructor() {
20985
- this._timer = undefined;
20986
- this._high_priority_timer = undefined;
20987
- }
20988
- start() {
20989
- this.syncCapturedEvent();
20990
- this._timer = setInterval(() => {
20991
- this.syncCapturedEvent();
20992
- }, 1 * MINUTE);
20993
- this._high_priority_timer = setInterval(() => {
20994
- this.syncHighPriorityCapturedEvent();
20995
- }, 10 * SECOND$1);
20996
- }
20997
- stop() {
20998
- if (this._timer) {
20999
- clearInterval(this._timer);
21000
- this._timer = undefined;
21001
- }
21002
- if (this._high_priority_timer) {
21003
- clearInterval(this._high_priority_timer);
21004
- this._high_priority_timer = undefined;
21005
- }
21006
- }
21007
- async syncCapturedEvent() {
21008
- try {
21009
- // Must query only objects that have same userId with current logged-in user.
21010
- // Query captured event with maximum of 1000
21011
- // Order by latest first
21012
- // e.g., If there are 2000 events we will query 1000-2000 first
21013
- const cache = pullFromCache(ANALYTIC_CACHE_KEY);
21014
- if (!(cache === null || cache === void 0 ? void 0 : cache.data))
21015
- return;
21016
- if (cache.data.event.length === 0)
21017
- return;
21018
- const capturedEvents = cache.data.event;
21019
- await syncEvent(capturedEvents);
21020
- dropFromCache(ANALYTIC_CACHE_KEY);
21021
- }
21022
- catch (error) {
21023
- // stop and destroy all events
21024
- this.stop();
21025
- dropFromCache(ANALYTIC_CACHE_KEY);
21026
- }
21027
- }
21028
- async syncHighPriorityCapturedEvent() {
21029
- try {
21030
- // Must query only objects that have same userId with current logged-in user.
21031
- // Query captured event with maximum of 1000
21032
- // Order by latest first
21033
- // e.g., If there are 2000 events we will query 1000-2000 first
21034
- const cache = pullFromCache(HIGH_PRIORITY_ANALYTIC_CACHE_KEY);
21035
- if (!(cache === null || cache === void 0 ? void 0 : cache.data))
21036
- return;
21037
- if (cache.data.event.length === 0)
21038
- return;
21039
- const capturedEvents = cache.data.event;
21040
- await syncEvent(capturedEvents);
21041
- dropFromCache(HIGH_PRIORITY_ANALYTIC_CACHE_KEY);
21042
- }
21043
- catch (error) {
21044
- // stop and destroy all events
21045
- this.stop();
21046
- dropFromCache(HIGH_PRIORITY_ANALYTIC_CACHE_KEY);
21047
- }
21048
- }
21049
- }
21050
-
21051
- class AnalyticsEventCapturer {
21052
- constructor() {
21053
- this._expireTime = 5 * MINUTE;
21054
- this._poolLimit = 1000;
21055
- this._recentViewed = {};
21056
- this._recentHighPriorityViewed = {};
21057
- // Story
21058
- this._throttleStoryTimer = undefined;
21059
- this._bufferNewSeenStoryReferenceIds = [];
21060
- }
21061
- isAbleToEnqueue({ uniqueId, expireTime, isHighPriority = false, }) {
21062
- const now = new Date();
21063
- // Get the recent view date (if any)
21064
- const recentViewedDate = isHighPriority
21065
- ? this._recentHighPriorityViewed[uniqueId]
21066
- : this._recentViewed[uniqueId];
21067
- // If this is the first view, always allow it
21068
- if (!recentViewedDate) {
21069
- return true;
21070
- }
21071
- const timeDiff = now.getTime() - recentViewedDate.getTime();
21072
- if (timeDiff < expireTime) {
21073
- // just recently view this post, ignore the event.
21074
- return false;
21075
- }
21076
- return true;
21077
- }
21078
- markAs({ uniqueId, contentId, contentType, activityType, metadata, }) {
21079
- if (!this.isAbleToEnqueue({ uniqueId, expireTime: this._expireTime }))
21080
- return;
21081
- const now = new Date();
21082
- const currentData = { event: [] };
21083
- const cache = pullFromCache(ANALYTIC_CACHE_KEY);
21084
- if (cache === null || cache === void 0 ? void 0 : cache.data) {
21085
- currentData.event = cache.data.event;
21086
- }
21087
- // If the pool is full (Max 1000 items), remove the oldest data
21088
- if (currentData.event.length >= this._poolLimit) {
21089
- // Remove oldest data
21090
- currentData.event.shift();
21091
- }
21092
- const analyticItem = {
21093
- contentId,
21094
- contentType,
21095
- activityType,
21096
- timestamp: now.toISOString(),
21097
- };
21098
- if (metadata) {
21099
- analyticItem.metadata = metadata;
21100
- }
21101
- currentData.event.push(analyticItem);
21102
- upsertInCache(ANALYTIC_CACHE_KEY, currentData);
21103
- this._recentViewed[uniqueId] = now;
21104
- }
21105
- markPostAsViewed(postId) {
21106
- this.markAs({
21107
- uniqueId: postId,
21108
- contentId: postId,
21109
- contentType: "post" /* Amity.AnalyticEventContentType.Post */,
21110
- activityType: "view" /* Amity.AnalyticEventActivityType.View */,
21111
- });
21112
- }
21113
- markStory(story, activityType) {
21114
- if (!story.expiresAt)
21115
- return;
21116
- const now = new Date();
21117
- const expireTime = new Date(story.expiresAt);
21118
- if (!this.isAbleToEnqueue({
21119
- uniqueId: story.storyId,
21120
- expireTime: expireTime.getTime(),
21121
- isHighPriority: true,
21122
- }))
21123
- return;
21124
- const currentData = { event: [] };
21125
- const cache = pullFromCache(HIGH_PRIORITY_ANALYTIC_CACHE_KEY);
21126
- if (cache === null || cache === void 0 ? void 0 : cache.data) {
21127
- currentData.event = cache.data.event;
21128
- }
21129
- // If the pool is full (Max 1000 items), remove the oldest data
21130
- if (currentData.event.length >= this._poolLimit) {
21131
- // Remove oldest data
21132
- currentData.event.shift();
21133
- }
21134
- currentData.event.push({
21135
- contentId: story.storyId,
21136
- contentType: "story" /* Amity.AnalyticEventContentType.Story */,
21137
- activityType,
21138
- timestamp: now.toISOString(),
21139
- });
21140
- upsertInCache(HIGH_PRIORITY_ANALYTIC_CACHE_KEY, currentData);
21141
- this._recentHighPriorityViewed[story.storyId] = now;
21142
- // Fire internal event if the activity type is not click
21143
- if (activityType === "linkClicked" /* Amity.AnalyticEventActivityType.Click */)
21144
- return;
21145
- // Mark story as SEEN
21146
- pushToCache(["story-seen" /* STORY_KEY_CACHE.IS_SEEN */, 'get', story.storyId], new Date().toISOString());
21147
- // Update the latest timestamp for LocalStoryLastSeen
21148
- const currentLastSeen = pullFromCache([
21149
- "story-last-seen" /* STORY_KEY_CACHE.LAST_SEEN */,
21150
- story.targetId,
21151
- ]);
21152
- if (currentLastSeen === null || currentLastSeen === void 0 ? void 0 : currentLastSeen.data) {
21153
- if (new Date(currentLastSeen.data).getTime() < new Date(story.expiresAt).getTime()) {
21154
- pushToCache(["story-last-seen" /* STORY_KEY_CACHE.LAST_SEEN */, story.targetId], story.expiresAt);
21155
- }
21156
- }
21157
- else {
21158
- pushToCache(["story-last-seen" /* STORY_KEY_CACHE.LAST_SEEN */, story.targetId], story.expiresAt);
21159
- }
21160
- this._bufferNewSeenStoryReferenceIds.push(story.referenceId);
21161
- if (this._throttleStoryTimer)
21162
- return;
21163
- this._throttleStoryTimer = setTimeout(() => {
21164
- clearTimeout(this._throttleStoryTimer);
21165
- fireEvent('local.story.reload', { referenceIds: this._bufferNewSeenStoryReferenceIds });
21166
- this._bufferNewSeenStoryReferenceIds = [];
21167
- }, 300);
21168
- }
21169
- resetAllBuckets() {
21170
- this._recentViewed = {};
21171
- this._recentHighPriorityViewed = {};
21172
- dropFromCache(ANALYTIC_CACHE_KEY);
21173
- dropFromCache(HIGH_PRIORITY_ANALYTIC_CACHE_KEY);
21174
- }
21175
- markStoryAsViewed(story) {
21176
- this.markStory(story, "view" /* Amity.AnalyticEventActivityType.View */);
21177
- }
21178
- markStoryAsClicked(story) {
21179
- this.markStory(story, "linkClicked" /* Amity.AnalyticEventActivityType.Click */);
21180
- }
21181
- markAdAsViewed(ad, placement) {
21182
- const metadata = {
21183
- placement,
21184
- };
21185
- const activityType = "view" /* Amity.AnalyticEventActivityType.View */;
21186
- this.markAs({
21187
- uniqueId: `${ad.adId}.${activityType}.${placement}`,
21188
- contentId: ad.adId,
21189
- contentType: "ad" /* Amity.AnalyticEventContentType.Ad */,
21190
- activityType,
21191
- metadata,
21192
- });
21193
- }
21194
- markAdAsClicked(ad, placement) {
21195
- const metadata = {
21196
- placement,
21197
- };
21198
- const activityType = "linkClicked" /* Amity.AnalyticEventActivityType.Click */;
21199
- this.markAs({
21200
- uniqueId: `${ad.adId}.${activityType}.${placement}`,
21201
- contentId: ad.adId,
21202
- contentType: "ad" /* Amity.AnalyticEventContentType.Ad */,
21203
- activityType,
21204
- metadata,
21205
- });
21206
- }
21207
- }
21208
-
21209
- class AnalyticsEngine {
21210
- constructor() {
21211
- this._client = getActiveClient();
21212
- this._eventCapturer = new AnalyticsEventCapturer();
21213
- this._eventSyncer = new AnalyticsEventSyncer();
21214
- }
21215
- markPostAsViewed(postId) {
21216
- if (this._client.sessionState === "established" /* Amity.SessionStates.ESTABLISHED */ ||
21217
- this._client.sessionState === "tokenExpired" /* Amity.SessionStates.TOKEN_EXPIRED */ // For case token_expired, we assume token is expired and gonna re-connect soon
21218
- ) {
21219
- this._eventCapturer.markPostAsViewed(postId);
21220
- }
21221
- }
21222
- markStoryAsViewed(story) {
21223
- if (this._client.sessionState === "established" /* Amity.SessionStates.ESTABLISHED */ ||
21224
- this._client.sessionState === "tokenExpired" /* Amity.SessionStates.TOKEN_EXPIRED */ // For case token_expired, we assume token is expired and gonna re-connect soon
21225
- ) {
21226
- this._eventCapturer.markStoryAsViewed(story);
21227
- }
21228
- }
21229
- markAdAsViewed(ad, placement) {
21230
- if (this._client.sessionState === "established" /* Amity.SessionStates.ESTABLISHED */ ||
21231
- this._client.sessionState === "tokenExpired" /* Amity.SessionStates.TOKEN_EXPIRED */) {
21232
- this._eventCapturer.markAdAsViewed(ad, placement);
21233
- }
21234
- }
21235
- markAdAsClicked(ad, placement) {
21236
- if (this._client.sessionState === "established" /* Amity.SessionStates.ESTABLISHED */ ||
21237
- this._client.sessionState === "tokenExpired" /* Amity.SessionStates.TOKEN_EXPIRED */) {
21238
- this._eventCapturer.markAdAsClicked(ad, placement);
21239
- }
21240
- }
21241
- markStoryAsClicked(story) {
21242
- if (this._client.sessionState === "established" /* Amity.SessionStates.ESTABLISHED */ ||
21243
- this._client.sessionState === "tokenExpired" /* Amity.SessionStates.TOKEN_EXPIRED */) {
21244
- this._eventCapturer.markStoryAsClicked(story);
21245
- }
21246
- }
21247
- established() {
21248
- this._eventSyncer.start();
21249
- }
21250
- handleTokenExpired() {
21251
- this._stopAndDestroy();
21252
- }
21253
- destroy() {
21254
- this._stopAndDestroy();
21255
- }
21256
- _stopAndDestroy() {
21257
- this._eventSyncer.stop();
21258
- this._eventCapturer.resetAllBuckets();
21259
- }
21260
- }
21261
- let instance$5;
21262
- var AnalyticsEngine$1 = {
21263
- getInstance: () => {
21264
- if (!instance$5) {
21265
- instance$5 = new AnalyticsEngine();
21266
- }
21267
- return instance$5;
21268
- },
21269
- };
21270
-
21271
20998
  const userLinkedObject = (user) => {
21272
20999
  return Object.assign(Object.assign({}, user), { get avatar() {
21273
21000
  var _a;
@@ -21282,140 +21009,1521 @@ const userLinkedObject = (user) => {
21282
21009
  } });
21283
21010
  };
21284
21011
 
21285
- class StoryComputedValue {
21286
- constructor(targetId, lastStoryExpiresAt, lastStorySeenExpiresAt) {
21287
- this._syncingStoriesCount = 0;
21288
- this._errorStoriesCount = 0;
21289
- this._targetId = targetId;
21290
- this._lastStoryExpiresAt = lastStoryExpiresAt;
21291
- this._lastStorySeenExpiresAt = lastStorySeenExpiresAt;
21292
- this.cacheStoryExpireTime = pullFromCache([
21293
- "story-expire" /* STORY_KEY_CACHE.EXPIRE */,
21294
- this._targetId,
21295
- ]);
21296
- this.cacheStoreSeenTime = pullFromCache([
21297
- "story-last-seen" /* STORY_KEY_CACHE.LAST_SEEN */,
21298
- this._targetId,
21299
- ]);
21300
- this.getTotalStoryByStatus();
21301
- }
21302
- get lastStoryExpiresAt() {
21303
- return this._lastStoryExpiresAt ? new Date(this._lastStoryExpiresAt).getTime() : 0;
21304
- }
21305
- get lastStorySeenExpiresAt() {
21306
- return this._lastStorySeenExpiresAt ? new Date(this._lastStorySeenExpiresAt).getTime() : 0;
21307
- }
21308
- get localLastStoryExpires() {
21309
- var _a, _b;
21310
- return ((_a = this.cacheStoryExpireTime) === null || _a === void 0 ? void 0 : _a.data)
21311
- ? new Date((_b = this.cacheStoryExpireTime) === null || _b === void 0 ? void 0 : _b.data).getTime()
21312
- : 0;
21313
- }
21314
- get localLastStorySeenExpiresAt() {
21315
- var _a, _b;
21316
- return ((_a = this.cacheStoreSeenTime) === null || _a === void 0 ? void 0 : _a.data) ? new Date((_b = this.cacheStoreSeenTime) === null || _b === void 0 ? void 0 : _b.data).getTime() : 0;
21317
- }
21318
- get isContainUnSyncedStory() {
21319
- const currentSyncingState = pullFromCache([
21320
- "story-sync-state" /* STORY_KEY_CACHE.SYNC_STATE */,
21321
- this._targetId,
21322
- ]);
21323
- if (!(currentSyncingState === null || currentSyncingState === void 0 ? void 0 : currentSyncingState.data))
21324
- return false;
21325
- return ["syncing" /* Amity.SyncState.Syncing */, "error" /* Amity.SyncState.Error */].includes(currentSyncingState.data);
21326
- }
21327
- getLocalLastSortingDate() {
21328
- if (this.isContainUnSyncedStory) {
21329
- return this.localLastStoryExpires;
21330
- }
21331
- return this.lastStoryExpiresAt;
21332
- }
21333
- getHasUnseenFlag() {
21334
- const now = new Date().getTime();
21335
- const highestSeen = Math.max(this.lastStorySeenExpiresAt, this.localLastStorySeenExpiresAt);
21336
- pullFromCache([
21337
- "story-sync-state" /* STORY_KEY_CACHE.SYNC_STATE */,
21338
- this._targetId,
21339
- ]);
21340
- if (this.isContainUnSyncedStory) {
21341
- return this.localLastStoryExpires > now && this.localLastStoryExpires > highestSeen;
21342
- }
21343
- return this.lastStoryExpiresAt > now && this.lastStoryExpiresAt > highestSeen;
21344
- }
21345
- getTotalStoryByStatus() {
21346
- const stories = queryCache(["story" /* STORY_KEY_CACHE.STORY */, 'get']);
21347
- if (!stories) {
21348
- this._errorStoriesCount = 0;
21349
- this._syncingStoriesCount = 0;
21350
- return;
21351
- }
21352
- const groupByType = stories.reduce((acc, story) => {
21353
- const { data: { targetId, syncState, isDeleted }, } = story;
21354
- if (targetId === this._targetId && !isDeleted) {
21355
- acc[syncState] += 1;
21356
- }
21357
- return acc;
21358
- }, {
21359
- syncing: 0,
21360
- error: 0,
21361
- synced: 0,
21012
+ const getChannelMessagePreviewWithUser = (channel) => {
21013
+ var _a;
21014
+ const messagePreview = channel.messagePreviewId
21015
+ ? getChannelMessagePreview(channel.channelId)
21016
+ : null;
21017
+ const internalUser = (_a = pullFromCache([
21018
+ 'user',
21019
+ 'get',
21020
+ messagePreview === null || messagePreview === void 0 ? void 0 : messagePreview.creatorId,
21021
+ ])) === null || _a === void 0 ? void 0 : _a.data;
21022
+ const messagePreviewWithUser = messagePreview
21023
+ ? Object.assign(Object.assign({}, messagePreview), { user: internalUser ? userLinkedObject(internalUser) : undefined }) : null;
21024
+ return Object.assign(Object.assign({}, channel), { messagePreview: messagePreviewWithUser });
21025
+ };
21026
+
21027
+ const updateChannelMessagePreviewCache = (rawPayload) => {
21028
+ var _a, _b;
21029
+ const withMessageFeedInfo = (messagePreview) => {
21030
+ var _a;
21031
+ const messageFeedInfo = (_a = rawPayload.messageFeedsInfo) === null || _a === void 0 ? void 0 : _a.find(messageFeed => {
21032
+ return messageFeed.messageFeedId === messagePreview.messageFeedId;
21362
21033
  });
21363
- this._errorStoriesCount = groupByType.error;
21364
- this._syncingStoriesCount = groupByType.syncing;
21365
- }
21366
- get syncingStoriesCount() {
21367
- return this._syncingStoriesCount;
21368
- }
21369
- get failedStoriesCount() {
21370
- return this._errorStoriesCount;
21371
- }
21372
- }
21034
+ const { channelPublicId: channelId, messageFeedId: subChannelId, data, dataType, isDeleted, segment, creatorPublicId: creatorId, createdAt, updatedAt, } = messagePreview;
21035
+ return {
21036
+ channelId,
21037
+ subChannelId,
21038
+ data,
21039
+ dataType,
21040
+ isDeleted,
21041
+ segment,
21042
+ creatorId,
21043
+ createdAt,
21044
+ updatedAt,
21045
+ subChannelName: messageFeedInfo === null || messageFeedInfo === void 0 ? void 0 : messageFeedInfo.name,
21046
+ messagePreviewId: messageFeedInfo === null || messageFeedInfo === void 0 ? void 0 : messageFeedInfo.messagePreviewId,
21047
+ subChannelUpdatedAt: messageFeedInfo === null || messageFeedInfo === void 0 ? void 0 : messageFeedInfo.updatedAt,
21048
+ };
21049
+ };
21050
+ const newData = {
21051
+ messagePreviewChannel: (_b = (_a = rawPayload.messagePreviews) === null || _a === void 0 ? void 0 : _a.map(messagePreview => withMessageFeedInfo(messagePreview))) !== null && _b !== void 0 ? _b : [],
21052
+ };
21053
+ ingestInCache(newData);
21054
+ };
21373
21055
 
21374
- const storyTargetLinkedObject = (storyTarget) => {
21375
- const { targetType, targetId, lastStoryExpiresAt, lastStorySeenExpiresAt, targetUpdatedAt, localFilter, } = storyTarget;
21376
- const computedValue = new StoryComputedValue(targetId, lastStoryExpiresAt, lastStorySeenExpiresAt);
21377
- return {
21378
- targetType,
21379
- targetId,
21380
- lastStoryExpiresAt,
21381
- updatedAt: targetUpdatedAt,
21382
- // Additional data
21383
- hasUnseen: computedValue.getHasUnseenFlag(),
21384
- syncingStoriesCount: computedValue.syncingStoriesCount,
21385
- failedStoriesCount: computedValue.failedStoriesCount,
21386
- localFilter,
21387
- localLastExpires: computedValue.localLastStoryExpires,
21388
- localLastSeen: computedValue.localLastStorySeenExpiresAt,
21389
- localSortingDate: computedValue.getLocalLastSortingDate(),
21056
+ const getSubChannelMessagePreview = (subChannelId) => {
21057
+ var _a, _b;
21058
+ return ((_b = (_a = pullFromCache(['messagePreviewSubChannel', 'get', subChannelId])) === null || _a === void 0 ? void 0 : _a.data) !== null && _b !== void 0 ? _b : null);
21059
+ };
21060
+
21061
+ const getSubChannelMessagePreviewWithUser = (subChannel) => {
21062
+ var _a;
21063
+ const messagePreview = subChannel.messagePreviewId
21064
+ ? getSubChannelMessagePreview(subChannel.subChannelId)
21065
+ : null;
21066
+ const messagePreviewWithUser = messagePreview
21067
+ ? 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;
21068
+ return Object.assign(Object.assign({}, subChannel), { messagePreview: messagePreviewWithUser });
21069
+ };
21070
+
21071
+ const updateSubChannelMessagePreviewCache = (rawPayload) => {
21072
+ var _a, _b;
21073
+ const withMessageFeedInfo = (messagePreview) => {
21074
+ var _a;
21075
+ const messageFeedInfo = (_a = rawPayload.messageFeeds) === null || _a === void 0 ? void 0 : _a.find(messageFeed => {
21076
+ return messageFeed.messageFeedId === messagePreview.messageFeedId;
21077
+ });
21078
+ const { channelPublicId: channelId, messageFeedId: subChannelId, messageId: messagePreviewId, creatorPublicId: creatorId, data, dataType, isDeleted, segment, createdAt, updatedAt, } = messagePreview;
21079
+ return {
21080
+ messagePreviewId,
21081
+ channelId,
21082
+ subChannelId,
21083
+ data,
21084
+ dataType,
21085
+ isDeleted,
21086
+ segment,
21087
+ creatorId,
21088
+ createdAt,
21089
+ updatedAt,
21090
+ subChannelName: messageFeedInfo === null || messageFeedInfo === void 0 ? void 0 : messageFeedInfo.name,
21091
+ subChannelUpdatedAt: messageFeedInfo === null || messageFeedInfo === void 0 ? void 0 : messageFeedInfo.updatedAt,
21092
+ };
21093
+ };
21094
+ const newData = {
21095
+ messagePreviewSubChannel: (_b = (_a = rawPayload.messages) === null || _a === void 0 ? void 0 : _a.map(messagePreview => withMessageFeedInfo(messagePreview))) !== null && _b !== void 0 ? _b : [],
21390
21096
  };
21097
+ ingestInCache(newData);
21391
21098
  };
21392
21099
 
21393
- const storyLinkedObject = (story) => {
21394
- const analyticsEngineInstance = AnalyticsEngine$1.getInstance();
21395
- const storyTargetCache = pullFromCache([
21396
- "storyTarget" /* STORY_KEY_CACHE.STORY_TARGET */,
21397
- 'get',
21398
- story.targetId,
21399
- ]);
21400
- const communityCacheData = pullFromCache(['community', 'get', story.targetId]);
21401
- return Object.assign(Object.assign({}, story), { analytics: {
21402
- markAsSeen: () => {
21403
- if (!story.expiresAt)
21404
- return;
21405
- if (story.syncState !== "synced" /* Amity.SyncState.Synced */)
21406
- return;
21407
- analyticsEngineInstance.markStoryAsViewed(story);
21408
- },
21409
- markLinkAsClicked: () => {
21410
- if (!story.expiresAt)
21411
- return;
21412
- if (story.syncState !== "synced" /* Amity.SyncState.Synced */)
21413
- return;
21414
- analyticsEngineInstance.markStoryAsClicked(story);
21415
- },
21416
- }, get videoData() {
21417
- var _a, _b;
21418
- const cache = pullFromCache([
21100
+ /**
21101
+ * ```js
21102
+ * import { shallowClone } from '~/utils/shallowClone'
21103
+ * const newObj = shallowClone(obj)
21104
+ * ```
21105
+ *
21106
+ * Clone an object with same prototype and properties
21107
+ *
21108
+ * @param obj the object to clone
21109
+ * @returns new object with same prototype and properties
21110
+ *
21111
+ * @category utility
21112
+ * @private
21113
+ */
21114
+ function shallowClone(source, target) {
21115
+ return Object.create(Object.getPrototypeOf(source), Object.assign(Object.assign({}, Object.getOwnPropertyDescriptors(source)), Object.getOwnPropertyDescriptors(target)));
21116
+ }
21117
+
21118
+ function updateSubChannelCache(subChannelId, subChannel, params) {
21119
+ pushToCache(['subChannel', 'get', subChannelId],
21120
+ // eslint-disable-next-line prefer-object-spread
21121
+ shallowClone(subChannel, params));
21122
+ }
21123
+
21124
+ /**
21125
+ * ```js
21126
+ * import { isInTombstone } from '@amityco/ts-sdk'
21127
+ * const user = isInTombstone(["message", "messageId"])
21128
+ * ```
21129
+ *
21130
+ * Checks if the {@link Amity.TombstoneCacheOptions} exists
21131
+ * in cache and it's not expired means it's in tombstone
21132
+ * and we throw an Error
21133
+ *
21134
+ * @param model the model to check
21135
+ * @param modelId the object id to check
21136
+ * @returns the matching cache entry, or undefined.
21137
+ *
21138
+ * @category Cache API
21139
+ */
21140
+ const isInTombstone = (model, modelId) => {
21141
+ const { log, cache } = getActiveClient();
21142
+ const key = [model, CACHE_KEY_TOMBSTONE, modelId];
21143
+ if (!cache)
21144
+ return;
21145
+ log('cache/api/isInTombstone', key);
21146
+ const isInTombstone = pullFromCache(key);
21147
+ const { lifeSpan } = queryOptions('cache_then_server', CACHE_LIFESPAN_TOMBSTONE);
21148
+ if (isInTombstone && isFresh(isInTombstone.data, lifeSpan)) {
21149
+ throw new ASCApiError('Item not found!', 400400 /* Amity.ServerError.ITEM_NOT_FOUND */, "error" /* Amity.ErrorLevel.ERROR */);
21150
+ }
21151
+ };
21152
+
21153
+ /**
21154
+ * ```js
21155
+ * import { getMessageMarkers } from '@amityco/ts-sdk'
21156
+ * const messageMarkers = await getMessageMarkers(['sch1', 'sch2'])
21157
+ * ```
21158
+ *
21159
+ * Fetches a list of {@link Amity.MessageMarker} by messageIds
21160
+ *
21161
+ * @param messageIds the feed IDs of the {@link Amity.RawMessage} marker to fetch
21162
+ * @returns A list of {@link Amity.MessageMarker} by messageIds
21163
+ *
21164
+ * @category Channel API
21165
+ * @async
21166
+ * @private
21167
+ */
21168
+ const getMessageMarkers = async (messageIds) => {
21169
+ const client = getActiveClient();
21170
+ client.log('channel/getMessageMarkers', messageIds);
21171
+ const { data: queryPayload } = await client.http.get(`/api/v1/markers/messages`, {
21172
+ params: {
21173
+ messageIds,
21174
+ },
21175
+ });
21176
+ const { contentMarkers, feedMarkers, userMarkers } = queryPayload;
21177
+ const cachedAt = client.cache && Date.now();
21178
+ if (client.cache)
21179
+ ingestInCache({ contentMarkers, feedMarkers, userMarkers }, { cachedAt });
21180
+ fireEvent('local.feedMarker.fetched', { feedMarkers });
21181
+ fireEvent('local.messageMarker.fetched', { contentMarkers });
21182
+ fireEvent('local.userMarker.fetched', { userMarkers });
21183
+ return { data: contentMarkers, cachedAt };
21184
+ };
21185
+
21186
+ const reCalculateChannelUnreadInfo = (channelId) => {
21187
+ var _a;
21188
+ const cacheKeyChannelUnread = ['channelUnreadInfo', 'get', channelId];
21189
+ const cacheChannelUnreadInfo = (_a = pullFromCache(cacheKeyChannelUnread)) === null || _a === void 0 ? void 0 : _a.data;
21190
+ const cacheKeySubChannelUnread = ['subChannelUnreadInfo', 'get'];
21191
+ const cachedSubChannelUnreadInfo = queryCache(cacheKeySubChannelUnread);
21192
+ let channelUnreads = 0;
21193
+ let isMentioned = false;
21194
+ if (cachedSubChannelUnreadInfo && (cachedSubChannelUnreadInfo === null || cachedSubChannelUnreadInfo === void 0 ? void 0 : cachedSubChannelUnreadInfo.length) > 0) {
21195
+ const subChannelUnreadsInfo = cachedSubChannelUnreadInfo === null || cachedSubChannelUnreadInfo === void 0 ? void 0 : cachedSubChannelUnreadInfo.filter(({ data }) => {
21196
+ return data.channelId === channelId && !data.isDeleted;
21197
+ });
21198
+ channelUnreads = subChannelUnreadsInfo
21199
+ .map(({ data }) => data.unreadCount)
21200
+ .reduce((acc, cur) => acc + cur, 0);
21201
+ isMentioned = subChannelUnreadsInfo.some(({ data }) => data.isMentioned);
21202
+ }
21203
+ const channelUnreadInfo = Object.assign(Object.assign({}, (cacheChannelUnreadInfo !== null && cacheChannelUnreadInfo !== void 0 ? cacheChannelUnreadInfo : {
21204
+ channelId,
21205
+ createdAt: new Date().toISOString(),
21206
+ })), { updatedAt: new Date().toISOString(), unreadCount: channelUnreads, isMentioned });
21207
+ pushToCache(cacheKeyChannelUnread, channelUnreadInfo);
21208
+ return channelUnreadInfo;
21209
+ };
21210
+
21211
+ const persistUnreadCountInfo = (payload) => {
21212
+ const { feedMarkers, userFeedMarkers } = payload;
21213
+ // calculate sub channel unread info and channel unread info
21214
+ if (feedMarkers.length > 0 && userFeedMarkers.length > 0) {
21215
+ const channelIds = [];
21216
+ const feedMarkerMap = new Map(feedMarkers.map(fm => [fm.feedId, fm]));
21217
+ userFeedMarkers.forEach(userFeedMarker => {
21218
+ const feedMarker = feedMarkerMap.get(userFeedMarker.feedId);
21219
+ if (!feedMarker)
21220
+ return;
21221
+ if (feedMarker.feedId === userFeedMarker.feedId) {
21222
+ const unreadCount = feedMarker.lastSegment - userFeedMarker.readToSegment;
21223
+ const subChannelUnreadInfo = {
21224
+ subChannelId: feedMarker.feedId,
21225
+ channelId: feedMarker.entityId,
21226
+ readToSegment: userFeedMarker.readToSegment,
21227
+ lastSegment: feedMarker.lastSegment,
21228
+ lastMentionSegment: userFeedMarker.lastMentionSegment,
21229
+ unreadCount: Math.max(0, unreadCount),
21230
+ isMentioned: userFeedMarker.isMentioned,
21231
+ isDeleted: feedMarker.isDeleted,
21232
+ createdAt: userFeedMarker.createdAt,
21233
+ updatedAt: userFeedMarker.updatedAt,
21234
+ };
21235
+ // update sub channel unread info in cache
21236
+ ingestInCache({ subChannelUnreadInfo: [subChannelUnreadInfo] });
21237
+ if (!channelIds.includes(feedMarker.entityId)) {
21238
+ channelIds.push(feedMarker.entityId);
21239
+ }
21240
+ }
21241
+ });
21242
+ // re-calculate channel unread info in cache
21243
+ channelIds.forEach(channelId => {
21244
+ reCalculateChannelUnreadInfo(channelId);
21245
+ });
21246
+ }
21247
+ };
21248
+
21249
+ /**
21250
+ * ```js
21251
+ * import { getSubChannelMarkers } from '@amityco/ts-sdk'
21252
+ * const subChannelMarkers = await getSubChannelMarkers(['sch1', 'sch2'])
21253
+ * ```
21254
+ *
21255
+ * Fetches a paginable list of {@link Amity.SubChannelMarker} objects
21256
+ *
21257
+ * @param messageFeedIds the feed IDs of the {@link Amity.RawSubChannel} marker to fetch
21258
+ * @param page
21259
+ * @returns A page of {@link Amity.SubChannelMarker} objects
21260
+ *
21261
+ * @category Channel API
21262
+ * @async
21263
+ * @private
21264
+ */
21265
+ const getSubChannelMarkers = async (messageFeedIds, page = { limit: 100 }) => {
21266
+ const client = getActiveClient();
21267
+ client.log('channel/getSubChannelMarkers', messageFeedIds, page);
21268
+ const { data: queryPayload } = await client.http.get(`/api/v1/markers/message-feeds`, {
21269
+ params: {
21270
+ messageFeedIds,
21271
+ options: {
21272
+ token: toToken(page, 'skiplimit'),
21273
+ },
21274
+ },
21275
+ });
21276
+ const { paging } = queryPayload, payload = __rest(queryPayload, ["paging"]);
21277
+ const { userEntityMarkers: userEntityMarkersPayload, userFeedMarkers: userFeedMarkersPayload, userMarkers, feedMarkers: feedMarkersPayload, } = payload;
21278
+ // if consistent mode is enabled, persist the unread count info to the cache
21279
+ if (client.isUnreadCountEnabled && client.getMarkerSyncConsistentMode()) {
21280
+ persistUnreadCountInfo({
21281
+ feedMarkers: feedMarkersPayload,
21282
+ userFeedMarkers: userFeedMarkersPayload,
21283
+ });
21284
+ }
21285
+ const userEntityMarkers = convertChannelMarkerResponse(userEntityMarkersPayload);
21286
+ const userFeedMarkers = convertSubChannelMarkerResponse(userFeedMarkersPayload);
21287
+ const cachedAt = client.cache && Date.now();
21288
+ if (client.cache)
21289
+ ingestInCache({ userEntityMarkers, userFeedMarkers, userMarkers }, { cachedAt });
21290
+ fireEvent('local.channelMarker.fetched', { userEntityMarkers });
21291
+ fireEvent('local.subChannelMarker.fetched', { userFeedMarkers });
21292
+ fireEvent('local.userMarker.fetched', { userMarkers });
21293
+ const nextPage = toPage(paging.next);
21294
+ const prevPage = toPage(paging.previous);
21295
+ return { data: userFeedMarkers, cachedAt, prevPage, nextPage };
21296
+ };
21297
+
21298
+ const getUserMarker = async () => {
21299
+ const client = getActiveClient();
21300
+ client.log('channel/getUserMarker');
21301
+ const { data: payload } = await client.http.get(`/api/v1/markers/userMarker`);
21302
+ const { userMarkers } = payload;
21303
+ const cachedAt = client.cache && Date.now();
21304
+ if (client.cache)
21305
+ ingestInCache({ userMarkers }, { cachedAt });
21306
+ fireEvent('local.userMarker.fetched', { userMarkers });
21307
+ const latestUserMarker = userMarkers.reduce((maxUserMarker, userMarker) => {
21308
+ if (maxUserMarker == null ||
21309
+ new Date(maxUserMarker.lastSyncAt).getTime() < new Date(userMarker.lastSyncAt).getTime()) {
21310
+ return userMarker;
21311
+ }
21312
+ return maxUserMarker;
21313
+ }, undefined);
21314
+ return { data: latestUserMarker, cachedAt };
21315
+ };
21316
+
21317
+ /** @hidden */
21318
+ /*
21319
+ * @param message payload from http request without myReactions
21320
+ * add myReactions to http response if the event was a reaction event
21321
+ */
21322
+ const prepareMessagePayloadForCache = (payload, reactors, event) => {
21323
+ const client = getActiveClient();
21324
+ const cached = pullFromCache(['message', 'get', payload.messageId]);
21325
+ // '[]' in cases where the new reaction is the first one
21326
+ const myReactions = (cached === null || cached === void 0 ? void 0 : cached.data.myReactions) || [];
21327
+ // add myReactions to the payload
21328
+ Object.assign(payload, { myReactions });
21329
+ // check if there are any updates to the reactions
21330
+ const latestReaction = reactors[0];
21331
+ const isLatestReactionMine = latestReaction && latestReaction.userId === client.userId;
21332
+ if (!isLatestReactionMine) {
21333
+ return;
21334
+ }
21335
+ // new reaction added
21336
+ if (event === 'message.reactionAdded' && !myReactions.includes(latestReaction.reactionName)) {
21337
+ Object.assign(payload, {
21338
+ myReactions: [...myReactions, latestReaction.reactionName],
21339
+ });
21340
+ }
21341
+ // existing reaction removed
21342
+ if (event === 'message.reactionRemoved' && myReactions.includes(latestReaction.reactionName)) {
21343
+ Object.assign(payload, {
21344
+ myReactions: myReactions.filter(x => x !== latestReaction.reactionName),
21345
+ });
21346
+ }
21347
+ };
21348
+
21349
+ /*
21350
+ * This is a simple utility that infers the value of isDeleted based on the
21351
+ * value of includeDeleted
21352
+ *
21353
+ * There are two important things to note here:
21354
+ * 1. `includeDeleted` is purely client side query param and not recognized by
21355
+ * the server
21356
+ * 2. The only values we wish to expose with regards to `isDeleted` (the server
21357
+ * param for queries) is false | undefined and want to disallow users to query
21358
+ * for deleted entities
21359
+ *
21360
+ * Although this is a very simple utility, it's only purpose is to keep things
21361
+ * DRY
21362
+ */
21363
+ const inferIsDeleted = (includeDeleted) => includeDeleted === true ? undefined : false;
21364
+
21365
+ function getSubChannelIsMentioned(channelId, subChannelId, marker) {
21366
+ var _a, _b;
21367
+ // Look for `unreadCount` in the marker param first
21368
+ if (marker) {
21369
+ return marker.hasMentioned;
21370
+ }
21371
+ const client = getActiveClient();
21372
+ // If consistent mode is enabled, look in the SubChannelUnreadCountInfo cache
21373
+ if (client.isUnreadCountEnabled && client.getMarkerSyncConsistentMode()) {
21374
+ const cachedUnreadCount = (_a = pullFromCache([
21375
+ 'subChannelUnreadInfo',
21376
+ 'get',
21377
+ subChannelId,
21378
+ ])) === null || _a === void 0 ? void 0 : _a.data;
21379
+ if (cachedUnreadCount) {
21380
+ return cachedUnreadCount.isMentioned;
21381
+ }
21382
+ return false;
21383
+ }
21384
+ const key = {
21385
+ entityId: channelId,
21386
+ feedId: subChannelId,
21387
+ userId: getActiveUser()._id,
21388
+ };
21389
+ // If the marker param is not set, look in the cache
21390
+ const cachedMarker = (_b = pullFromCache([
21391
+ 'subChannelMarker',
21392
+ 'get',
21393
+ getResolver('subChannelMarker')(key),
21394
+ ])) === null || _b === void 0 ? void 0 : _b.data;
21395
+ if (cachedMarker) {
21396
+ return cachedMarker.hasMentioned;
21397
+ }
21398
+ // and if not found in cache use default value `false`
21399
+ return false;
21400
+ }
21401
+
21402
+ function getSubChannelUnreadCount(channelId, subChannelId, marker) {
21403
+ var _a, _b;
21404
+ // Look for `unreadCount` in the marker param first
21405
+ if (marker) {
21406
+ return marker.unreadCount;
21407
+ }
21408
+ const client = getActiveClient();
21409
+ // If consistent mode is enabled, look in the SubChannelUnreadCountInfo cache
21410
+ if (client.isUnreadCountEnabled && client.getMarkerSyncConsistentMode()) {
21411
+ const cachedUnreadCount = (_a = pullFromCache([
21412
+ 'subChannelUnreadInfo',
21413
+ 'get',
21414
+ subChannelId,
21415
+ ])) === null || _a === void 0 ? void 0 : _a.data;
21416
+ if (cachedUnreadCount) {
21417
+ return cachedUnreadCount.isDeleted ? 0 : cachedUnreadCount.unreadCount;
21418
+ }
21419
+ return 0;
21420
+ }
21421
+ const key = {
21422
+ entityId: channelId,
21423
+ feedId: subChannelId,
21424
+ userId: getActiveUser()._id,
21425
+ };
21426
+ // If the marker param is not set, look in the cache
21427
+ const cachedMarker = (_b = pullFromCache([
21428
+ 'subChannelMarker',
21429
+ 'get',
21430
+ getResolver('subChannelMarker')(key),
21431
+ ])) === null || _b === void 0 ? void 0 : _b.data;
21432
+ if (cachedMarker) {
21433
+ return cachedMarker.unreadCount;
21434
+ }
21435
+ // and if not found in cache use default value `0`
21436
+ return 0;
21437
+ }
21438
+
21439
+ const MARKER_INCLUDED_SUB_CHANNEL_TYPE$1 = ['broadcast', 'conversation', 'community'];
21440
+ const isUnreadCountSupport$2 = ({ channelType }) => MARKER_INCLUDED_SUB_CHANNEL_TYPE$1.includes(channelType);
21441
+ function convertFromRaw$2(_a) {
21442
+ 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"]);
21443
+ return Object.assign(Object.assign({ get unreadCount() {
21444
+ return getSubChannelUnreadCount(channelId, messageFeedId);
21445
+ },
21446
+ get hasMentioned() {
21447
+ return getSubChannelIsMentioned(channelId, messageFeedId);
21448
+ },
21449
+ get isMentioned() {
21450
+ return getSubChannelIsMentioned(channelId, messageFeedId);
21451
+ } }, rest), { channelId: channelPublicId, creatorId: creatorPublicId, displayName: name, lastActivity: lastMessageTimestamp, latestMessageId: lastMessageId, messageCount: childCount, subChannelId: messageFeedId, isUnreadCountSupport: isUnreadCountSupport$2({ channelType }) });
21452
+ }
21453
+
21454
+ const mergePayloadWithLocal = (payload) => {
21455
+ var _a, _b, _c;
21456
+ 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;
21457
+ if (localMessage) {
21458
+ return Object.assign(Object.assign(Object.assign({}, localMessage), payload), {
21459
+ // NOTE: referenceId is missing in the some payload event. If we have local message data with referenceId, use it instead.
21460
+ referenceId: (_c = localMessage.referenceId) !== null && _c !== void 0 ? _c : payload.referenceId });
21461
+ }
21462
+ return payload;
21463
+ };
21464
+ function convertFromRaw$1(message, reactors, event) {
21465
+ var _a;
21466
+ const mergeMessage = mergePayloadWithLocal(message);
21467
+ 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"]);
21468
+ let cache;
21469
+ if (referenceId) {
21470
+ cache = pullFromCache(['message', 'get', referenceId]);
21471
+ }
21472
+ if (!cache) {
21473
+ cache = pullFromCache(['message', 'get', messageId]);
21474
+ }
21475
+ 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 : {},
21476
+ /*
21477
+ * Previously, myReactions were added only if it was part of the payload.
21478
+ * So empty myReactions were not present. So I've edited the payload to add
21479
+ * a default for those cases.
21480
+ *
21481
+ * Check git blame for previous iteration
21482
+ */
21483
+ 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 */ });
21484
+ if (mentionedUsers) {
21485
+ out.mentionees = mentionedUsers.map(mention => {
21486
+ if (mention.type === 'channel') {
21487
+ return mention;
21488
+ }
21489
+ return { type: 'user', userIds: mention.userPublicIds };
21490
+ });
21491
+ }
21492
+ if (reactors && reactors.length && event) {
21493
+ // mqtt event
21494
+ prepareMessagePayloadForCache(out, reactors, event);
21495
+ }
21496
+ return out;
21497
+ }
21498
+ const preUpdateMessageCache = (rawPayload) => {
21499
+ ingestInCache({
21500
+ messages: rawPayload.messages.map(message => convertFromRaw$1(message, rawPayload.reactions)),
21501
+ });
21502
+ };
21503
+ const DEBOUNCE_TIME = 2000;
21504
+ const currentDebounceMap = {};
21505
+ const prepareMessagePayload = async (payload, event) => {
21506
+ const markerIds = payload.messages.map(({ messageId }) => messageId);
21507
+ if (markerIds.length > 0) {
21508
+ // since the get markers method requires a channel cache to function with the reducer.
21509
+ preUpdateMessageCache(payload);
21510
+ const markerIdsKey = markerIds.join('');
21511
+ if (currentDebounceMap[markerIdsKey]) {
21512
+ clearTimeout(currentDebounceMap[markerIdsKey]);
21513
+ }
21514
+ currentDebounceMap[markerIdsKey] = setTimeout(() => {
21515
+ try {
21516
+ getMessageMarkers(markerIds);
21517
+ }
21518
+ catch (_error) {
21519
+ // do nothing
21520
+ }
21521
+ }, DEBOUNCE_TIME);
21522
+ }
21523
+ const { messageFeeds } = payload, restPayload = __rest(payload, ["messageFeeds"]);
21524
+ // upsert messageFeeds to subchannel cache because messageFeeds from event payload not include messagePreviewId
21525
+ if (messageFeeds && messageFeeds.length > 0) {
21526
+ messageFeeds === null || messageFeeds === void 0 ? void 0 : messageFeeds.forEach(messageFeed => {
21527
+ var _a, _b;
21528
+ const subChannelCache = (_b = (_a = pullFromCache(['subChannel', 'get', messageFeed.messageFeedId])) === null || _a === void 0 ? void 0 : _a.data) !== null && _b !== void 0 ? _b : {};
21529
+ // exclude getter properties from existing subChannel cache, update only other properties to existing subChannel cache
21530
+ const _c = convertFromRaw$2(messageFeed), restSubChannel = __rest(_c, ["unreadCount", "isMentioned"]);
21531
+ updateSubChannelCache(messageFeed.messageFeedId, subChannelCache, restSubChannel);
21532
+ });
21533
+ }
21534
+ return Object.assign(Object.assign({}, restPayload), { messages: payload.messages.map(m => convertFromRaw$1(m, payload.reactions, event)) });
21535
+ };
21536
+ function convertParams(_a) {
21537
+ var { subChannelId, mentionees, dataType, data } = _a, rest = __rest(_a, ["subChannelId", "mentionees", "dataType", "data"]);
21538
+ if (dataType === MessageContentType.IMAGE || dataType === MessageContentType.FILE) {
21539
+ return Object.assign({ messageFeedId: subChannelId, mentionedUsers: mentionees, dataType, data: Object.assign({ caption: '' }, data) }, rest);
21540
+ }
21541
+ return Object.assign({ messageFeedId: subChannelId, mentionedUsers: mentionees, dataType, data }, rest);
21542
+ }
21543
+ function convertQueryParams$1(_a) {
21544
+ var { sortBy, subChannelId, includingTags, excludingTags, includeDeleted, aroundMessageId, limit, type } = _a, rest = __rest(_a, ["sortBy", "subChannelId", "includingTags", "excludingTags", "includeDeleted", "aroundMessageId", "limit", "type"]);
21545
+ const out = Object.assign(Object.assign({}, rest), { messageFeedId: subChannelId, isDeleted: inferIsDeleted(includeDeleted), options: {
21546
+ sortBy,
21547
+ limit: limit || COLLECTION_DEFAULT_PAGINATION_LIMIT,
21548
+ around: aroundMessageId,
21549
+ } });
21550
+ if (includingTags) {
21551
+ out.includeTags = includingTags;
21552
+ }
21553
+ if (type) {
21554
+ out.dataType = type;
21555
+ }
21556
+ if (excludingTags) {
21557
+ out.excludeTags = excludingTags;
21558
+ }
21559
+ return out;
21560
+ }
21561
+
21562
+ const MARKER_INCLUDED_SUB_CHANNEL_TYPE = ['broadcast', 'conversation', 'community'];
21563
+ /**
21564
+ * Filter sub channel by type. Only conversation, community and broadcast type are included.
21565
+ */
21566
+ const isUnreadCountSupport$1 = ({ channelType }) => MARKER_INCLUDED_SUB_CHANNEL_TYPE.includes(channelType);
21567
+ const preUpdateSubChannelCache = (rawPayload) => {
21568
+ ingestInCache({
21569
+ messageFeeds: rawPayload.messageFeeds.map(messageFeed => convertFromRaw$2(messageFeed)),
21570
+ });
21571
+ };
21572
+ const prepareSubChannelPayload = async (rawPayload) => {
21573
+ const markerIds = rawPayload.messageFeeds
21574
+ .filter(isUnreadCountSupport$1)
21575
+ .map(({ messageFeedId }) => messageFeedId);
21576
+ if (markerIds.length > 0) {
21577
+ // since the get markers method requires a channel cache to function with the reducer.
21578
+ preUpdateSubChannelCache(rawPayload);
21579
+ try {
21580
+ await getSubChannelMarkers(markerIds);
21581
+ }
21582
+ catch (e) {
21583
+ // empty block (from the spec, allow marker fetch to fail without having to do anything)
21584
+ }
21585
+ }
21586
+ updateSubChannelMessagePreviewCache(rawPayload);
21587
+ // attach marker to sub channel
21588
+ const messageFeeds = rawPayload.messageFeeds.map(convertFromRaw$2);
21589
+ const messages = rawPayload.messages.map(m => convertFromRaw$1(m));
21590
+ return Object.assign(Object.assign({}, rawPayload), { messageFeeds,
21591
+ messages });
21592
+ };
21593
+ function convertQueryParams(_a) {
21594
+ var { excludeDefaultSubChannel } = _a, rest = __rest(_a, ["excludeDefaultSubChannel"]);
21595
+ const out = Object.assign({}, rest);
21596
+ if (excludeDefaultSubChannel !== undefined) {
21597
+ out.excludeDefaultMessageFeed = excludeDefaultSubChannel;
21598
+ }
21599
+ return out;
21600
+ }
21601
+
21602
+ /**
21603
+ * ```js
21604
+ * import { getSubChannel } from '@amityco/ts-sdk'
21605
+ * const subChannel = await getSubChannel('foobar')
21606
+ * ```
21607
+ *
21608
+ * Fetches a {@link Amity.SubChannel} object
21609
+ *
21610
+ * @param subChannelId the ID of the {@link Amity.SubChannel} to fetch
21611
+ * @returns the associated {@link Amity.SubChannel} object
21612
+ *
21613
+ * @category Channel API
21614
+ * @async
21615
+ */
21616
+ const getSubChannel$1 = async (subChannelId) => {
21617
+ const client = getActiveClient();
21618
+ client.log('channel/getSubChannel', subChannelId);
21619
+ isInTombstone('subChannel', subChannelId);
21620
+ try {
21621
+ const response = await client.http.get(`/api/v5/message-feeds/${encodeURIComponent(subChannelId)}`);
21622
+ const data = await prepareSubChannelPayload(response.data);
21623
+ const cachedAt = client.cache && Date.now();
21624
+ if (client.cache)
21625
+ ingestInCache(data, { cachedAt });
21626
+ fireEvent('local.message-feed.fetched', data);
21627
+ return {
21628
+ data: data.messageFeeds[0],
21629
+ cachedAt,
21630
+ };
21631
+ }
21632
+ catch (error) {
21633
+ if (checkIfShouldGoesToTombstone(error === null || error === void 0 ? void 0 : error.code)) {
21634
+ pushToTombstone('subChannel', subChannelId);
21635
+ }
21636
+ throw error;
21637
+ }
21638
+ };
21639
+ /**
21640
+ * ```js
21641
+ * import { getSubChannel } from '@amityco/ts-sdk'
21642
+ * const subChannel = getSubChannel.locally('foobar')
21643
+ * ```
21644
+ *
21645
+ * Fetches a {@link Amity.SubChannel} object from cache
21646
+ *
21647
+ * @param subChannelId the ID of the {@link Amity.SubChannel} to fetch
21648
+ * @returns the associated {@link Amity.SubChannel} object
21649
+ *
21650
+ * @category Channel API
21651
+ */
21652
+ getSubChannel$1.locally = (subChannelId) => {
21653
+ const client = getActiveClient();
21654
+ client.log('channel/getSubChannel.locally', subChannelId);
21655
+ if (!client.cache)
21656
+ return;
21657
+ const cached = pullFromCache(['subChannel', 'get', subChannelId]);
21658
+ if (!cached)
21659
+ return;
21660
+ return {
21661
+ data: cached.data,
21662
+ cachedAt: cached.cachedAt,
21663
+ };
21664
+ };
21665
+
21666
+ const convertDateStringToTimestamp = (dateString) => {
21667
+ return new Date(dateString).getTime();
21668
+ };
21669
+
21670
+ const getMessagePreviewSetting$1 = async () => {
21671
+ const client = getActiveClient();
21672
+ return client.getMessagePreviewSetting(false);
21673
+ };
21674
+ const getSubChannelCache = async (subChannelId) => {
21675
+ var _a;
21676
+ let subChannelCache = (_a = pullFromCache(['subChannel', 'get', subChannelId])) === null || _a === void 0 ? void 0 : _a.data;
21677
+ if (!subChannelCache) {
21678
+ subChannelCache = (await getSubChannel$1(subChannelId)).data;
21679
+ }
21680
+ return subChannelCache;
21681
+ };
21682
+ const isLastestMessageOnSubchannel = (message) => {
21683
+ var _a;
21684
+ const cache = (_a = pullFromCache([
21685
+ 'messagePreviewSubChannel',
21686
+ 'get',
21687
+ message.subChannelId,
21688
+ ])) === null || _a === void 0 ? void 0 : _a.data;
21689
+ // The message payload from optimistic created event has no segment, so we check createdAt instead.
21690
+ return (!cache ||
21691
+ cache.segment <= message.channelSegment ||
21692
+ convertDateStringToTimestamp(cache.createdAt) <= convertDateStringToTimestamp(message.createdAt));
21693
+ };
21694
+ const isLastestMessageOnChannel = (message) => {
21695
+ var _a;
21696
+ const cache = (_a = pullFromCache([
21697
+ 'messagePreviewChannel',
21698
+ 'get',
21699
+ message.channelId,
21700
+ ])) === null || _a === void 0 ? void 0 : _a.data;
21701
+ return (!cache ||
21702
+ convertDateStringToTimestamp(cache.createdAt) <= convertDateStringToTimestamp(message.createdAt));
21703
+ };
21704
+ const handleMessageCreatedOnSubChannel = async (message) => {
21705
+ const messagePreviewSetting = await getMessagePreviewSetting$1();
21706
+ const { channelId, messageId: messagePreviewId, creatorId, createdAt, updatedAt, data, dataType, subChannelId, channelSegment: segment, isDeleted, } = message;
21707
+ // 1. get subChannel from cache, if not exist fetch from server
21708
+ const subChannelCache = await getSubChannelCache(subChannelId);
21709
+ // 2. if messagePreviewSetting is NO_MESSAGE_PREVEIW, update only lastActiviy in subChannel cache
21710
+ if (messagePreviewSetting === "no-message-preview" /* Amity.MessagePreviewSetting.NO_MESSAGE_PREVIEW */) {
21711
+ // 2.1 if the message is the latest message, update lastActivity to be createdAt in subChannel cache
21712
+ if (convertDateStringToTimestamp(subChannelCache.lastActivity) <
21713
+ convertDateStringToTimestamp(createdAt))
21714
+ updateSubChannelCache(message.subChannelId, subChannelCache, {
21715
+ lastActivity: createdAt,
21716
+ });
21717
+ return;
21718
+ }
21719
+ // 3. if messagePreviewSetting is `NOT` NO_MESSAGE_PREVEIW, update messagePreviewSubChannel and subChannel cache
21720
+ // 3.1 check if the message is the latest message, if not ignore the message.
21721
+ if (!isLastestMessageOnSubchannel(message))
21722
+ return;
21723
+ // 3.2 if the message is the latest message, update messagePreviewSubChannel and subChannel cache
21724
+ pushToCache(['messagePreviewSubChannel', 'get', message.subChannelId], {
21725
+ channelId,
21726
+ creatorId,
21727
+ messagePreviewId,
21728
+ createdAt,
21729
+ updatedAt,
21730
+ subChannelId,
21731
+ data,
21732
+ dataType,
21733
+ segment,
21734
+ isDeleted,
21735
+ subChannelUpdatedAt: subChannelCache === null || subChannelCache === void 0 ? void 0 : subChannelCache.updatedAt,
21736
+ subChannelName: subChannelCache === null || subChannelCache === void 0 ? void 0 : subChannelCache.displayName,
21737
+ });
21738
+ updateSubChannelCache(message.subChannelId, subChannelCache, {
21739
+ lastActivity: createdAt,
21740
+ messagePreviewId,
21741
+ });
21742
+ };
21743
+ const handleMessageUpdatedOnSubChannel = async (message) => {
21744
+ var _a;
21745
+ const { channelId, messageId: messagePreviewId, creatorId, createdAt, updatedAt, data, dataType, subChannelId, channelSegment: segment, isDeleted, } = message;
21746
+ const messagePreviewSubChannelCache = (_a = pullFromCache([
21747
+ 'messagePreviewSubChannel',
21748
+ 'get',
21749
+ message.subChannelId,
21750
+ ])) === null || _a === void 0 ? void 0 : _a.data;
21751
+ // if messagePreviewSubChannel is not exist, ignore the message.
21752
+ if (messagePreviewSubChannelCache &&
21753
+ messagePreviewSubChannelCache.messagePreviewId === message.messageId) {
21754
+ const subChannelCache = await getSubChannelCache(subChannelId);
21755
+ pushToCache(['messagePreviewSubChannel', 'get', message.subChannelId], {
21756
+ channelId,
21757
+ creatorId,
21758
+ messagePreviewId,
21759
+ createdAt,
21760
+ updatedAt,
21761
+ subChannelId,
21762
+ data,
21763
+ dataType,
21764
+ segment,
21765
+ isDeleted,
21766
+ subChannelUpdatedAt: subChannelCache.updatedAt,
21767
+ subChannelName: messagePreviewSubChannelCache.subChannelName,
21768
+ });
21769
+ }
21770
+ };
21771
+ const handleMessageCreated = async (message) => {
21772
+ const { channelId, messageId: messagePreviewId, creatorId, createdAt, updatedAt, data, dataType, subChannelId, channelSegment: segment, isDeleted, } = message;
21773
+ if (isLastestMessageOnChannel(message)) {
21774
+ const subChannelCache = await getSubChannelCache(subChannelId);
21775
+ pushToCache(['messagePreviewChannel', 'get', message.channelId], {
21776
+ channelId,
21777
+ creatorId,
21778
+ messagePreviewId,
21779
+ createdAt,
21780
+ updatedAt,
21781
+ subChannelId,
21782
+ data,
21783
+ dataType,
21784
+ segment,
21785
+ isDeleted,
21786
+ subChannelUpdatedAt: subChannelCache === null || subChannelCache === void 0 ? void 0 : subChannelCache.updatedAt,
21787
+ subChannelName: subChannelCache === null || subChannelCache === void 0 ? void 0 : subChannelCache.displayName,
21788
+ });
21789
+ }
21790
+ };
21791
+ const handleMessageUpdated = async (message) => {
21792
+ /**
21793
+ * Channel Case
21794
+ */
21795
+ var _a;
21796
+ const { channelId, messageId: messagePreviewId, creatorId, createdAt, updatedAt, data, dataType, subChannelId, channelSegment: segment, isDeleted, } = message;
21797
+ const messagePreviewChannelCache = (_a = pullFromCache([
21798
+ 'messagePreviewChannel',
21799
+ 'get',
21800
+ message.channelId,
21801
+ ])) === null || _a === void 0 ? void 0 : _a.data;
21802
+ if (messagePreviewChannelCache &&
21803
+ messagePreviewChannelCache.messagePreviewId === message.messageId) {
21804
+ const subChannelCache = await getSubChannelCache(subChannelId);
21805
+ pushToCache(['messagePreviewChannel', 'get', message.channelId], {
21806
+ channelId,
21807
+ creatorId,
21808
+ messagePreviewId,
21809
+ createdAt,
21810
+ updatedAt,
21811
+ subChannelId,
21812
+ data,
21813
+ dataType,
21814
+ segment,
21815
+ isDeleted,
21816
+ subChannelUpdatedAt: subChannelCache.updatedAt,
21817
+ subChannelName: messagePreviewChannelCache.subChannelName,
21818
+ });
21819
+ }
21820
+ };
21821
+ const handleSubChannelUpdated = async (subChannel) => {
21822
+ var _a, _b, _c, _d;
21823
+ const { channelId, subChannelId } = subChannel;
21824
+ /** Channel Case */
21825
+ const messagePreviewChannelCache = (_a = pullFromCache([
21826
+ 'messagePreviewChannel',
21827
+ 'get',
21828
+ channelId,
21829
+ ])) === null || _a === void 0 ? void 0 : _a.data;
21830
+ if ((messagePreviewChannelCache === null || messagePreviewChannelCache === void 0 ? void 0 : messagePreviewChannelCache.subChannelId) === subChannelId) {
21831
+ const subChannelCache = (_b = pullFromCache([
21832
+ 'subChannel',
21833
+ 'get',
21834
+ subChannelId,
21835
+ ])) === null || _b === void 0 ? void 0 : _b.data;
21836
+ 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 }));
21837
+ }
21838
+ /** SubChannel Case */
21839
+ const messagePreviewSubChannelCache = (_c = pullFromCache([
21840
+ 'messagePreviewSubChannel',
21841
+ 'get',
21842
+ subChannelId,
21843
+ ])) === null || _c === void 0 ? void 0 : _c.data;
21844
+ if (messagePreviewSubChannelCache &&
21845
+ new Date(messagePreviewSubChannelCache.updatedAt).valueOf() >
21846
+ new Date(subChannel.updatedAt).valueOf()) {
21847
+ const subChannelCache = (_d = pullFromCache([
21848
+ 'subChannel',
21849
+ 'get',
21850
+ subChannelId,
21851
+ ])) === null || _d === void 0 ? void 0 : _d.data;
21852
+ 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 }));
21853
+ }
21854
+ };
21855
+
21856
+ function convertRawUserToInternalUser(rawUser) {
21857
+ return Object.assign(Object.assign({}, rawUser), { isGlobalBanned: (rawUser === null || rawUser === void 0 ? void 0 : rawUser.isGlobalBan) || false });
21858
+ }
21859
+
21860
+ const MARKER_INCLUDED_CHANNEL_TYPE = ['broadcast', 'conversation', 'community'];
21861
+ const isUnreadCountSupport = ({ type }) => MARKER_INCLUDED_CHANNEL_TYPE.includes(type);
21862
+ function convertFromRaw(channel, options = { isMessagePreviewUpdated: true }) {
21863
+ var _a;
21864
+ let { messagePreviewId } = channel;
21865
+ const messagePreviewChannelCache = (_a = pullFromCache([
21866
+ 'messagePreviewChannel',
21867
+ 'get',
21868
+ channel.channelId,
21869
+ ])) === null || _a === void 0 ? void 0 : _a.data;
21870
+ if ((messagePreviewChannelCache === null || messagePreviewChannelCache === void 0 ? void 0 : messagePreviewChannelCache.messagePreviewId) && !options.isMessagePreviewUpdated) {
21871
+ messagePreviewId = messagePreviewChannelCache.messagePreviewId;
21872
+ }
21873
+ return Object.assign(Object.assign({}, channel), { defaultSubChannelId: channel.channelInternalId, isUnreadCountSupport: isUnreadCountSupport(channel), messagePreviewId });
21874
+ }
21875
+ const preUpdateChannelCache = (rawPayload, options = { isMessagePreviewUpdated: true }) => {
21876
+ ingestInCache({
21877
+ channels: rawPayload.channels.map(channel => convertFromRaw(channel, { isMessagePreviewUpdated: options.isMessagePreviewUpdated })),
21878
+ });
21879
+ };
21880
+ const updateChannelUnread = ({ currentUserId, channels, channelUsers, }) => {
21881
+ for (let i = 0; i < channels.length; i += 1) {
21882
+ const cacheKey = ['channelUnread', 'get', channels[i].channelId];
21883
+ const channelUser = channelUsers.find(channelUser => channelUser.channelId === channels[i].channelId && channelUser.userId === currentUserId);
21884
+ let unreadCount = 0;
21885
+ let readToSegment = null;
21886
+ let lastMentionedSegment = null;
21887
+ let isMentioned = false;
21888
+ if (channelUser) {
21889
+ readToSegment = channelUser.readToSegment;
21890
+ lastMentionedSegment = channelUser.lastMentionedSegment;
21891
+ unreadCount = Math.max(channels[i].messageCount - readToSegment, 0);
21892
+ isMentioned = lastMentionedSegment > readToSegment;
21893
+ }
21894
+ const cacheChannelUnread = {
21895
+ channelId: channels[i].channelId,
21896
+ lastSegment: channels[i].messageCount,
21897
+ readToSegment,
21898
+ lastMentionedSegment,
21899
+ unreadCount,
21900
+ isMentioned,
21901
+ isDeleted: channels[i].isDeleted || false,
21902
+ };
21903
+ pushToCache(cacheKey, cacheChannelUnread);
21904
+ }
21905
+ };
21906
+ const prepareChannelPayload = async (rawPayload, options = { isMessagePreviewUpdated: true }) => {
21907
+ const client = getActiveClient();
21908
+ const networkPreviewSetting = await client.getMessagePreviewSetting(false);
21909
+ if (options.isMessagePreviewUpdated &&
21910
+ networkPreviewSetting !== "no-message-preview" /* Amity.MessagePreviewSetting.NO_MESSAGE_PREVIEW */ &&
21911
+ rawPayload.messagePreviews &&
21912
+ rawPayload.messagePreviews.length > 0) {
21913
+ updateChannelMessagePreviewCache(rawPayload);
21914
+ }
21915
+ if (client.useLegacyUnreadCount) {
21916
+ updateChannelUnread({
21917
+ channels: rawPayload.channels,
21918
+ channelUsers: rawPayload.channelUsers,
21919
+ currentUserId: client.userId,
21920
+ });
21921
+ }
21922
+ else {
21923
+ const markerIds = rawPayload.channels
21924
+ // filter channel by type. Only conversation, community and broadcast type are included.
21925
+ .filter(isUnreadCountSupport)
21926
+ .map(({ channelInternalId }) => channelInternalId);
21927
+ if (markerIds.length > 0) {
21928
+ // since the get markers method requires a channel cache to function with the reducer.
21929
+ preUpdateChannelCache(rawPayload, {
21930
+ isMessagePreviewUpdated: options.isMessagePreviewUpdated,
21931
+ });
21932
+ try {
21933
+ await getChannelMarkers(markerIds);
21934
+ }
21935
+ catch (e) {
21936
+ // empty block (from the spec, allow marker fetch to fail without having to do anything)
21937
+ }
21938
+ }
21939
+ }
21940
+ // convert raw channel to internal channel
21941
+ const channels = rawPayload.channels.map(payload => convertFromRaw(payload, { isMessagePreviewUpdated: options.isMessagePreviewUpdated }));
21942
+ // convert raw channel user to membership (add user object)
21943
+ const channelUsers = rawPayload.channelUsers.map(channelUser => {
21944
+ return convertRawMembershipToMembership(channelUser);
21945
+ });
21946
+ const users = rawPayload.users.map(convertRawUserToInternalUser);
21947
+ const restRawPayload = __rest(rawPayload, ["messageFeedsInfo", "messagePreviews"]);
21948
+ return Object.assign(Object.assign({}, restRawPayload), { users,
21949
+ channels,
21950
+ channelUsers });
21951
+ };
21952
+
21953
+ /**
21954
+ * ```js
21955
+ * import { getSubChannelMarkers } from '@amityco/ts-sdk'
21956
+ * const subChannelMarkers = await getSubChannelMarkers(['sch1', 'sch2'])
21957
+ * ```
21958
+ *
21959
+ * Fetches a paginable list of {@link Amity.SubChannelMarker} objects
21960
+ *
21961
+ * @param messageFeedIds the feed IDs of the {@link Amity.RawSubChannel} marker to fetch
21962
+ * @param page
21963
+ * @returns A page of {@link Amity.SubChannelMarker} objects
21964
+ *
21965
+ * @category Channel API
21966
+ * @async
21967
+ * @private
21968
+ */
21969
+ const getUserMessageFeedMakers = async (channelIds) => {
21970
+ const client = getActiveClient();
21971
+ client.log('channel/getUserMessageFeedMakers', channelIds);
21972
+ const { data } = await client.http.get(`/api/v1/markers/user-message-feed`, {
21973
+ params: {
21974
+ channelIds,
21975
+ },
21976
+ });
21977
+ fireEvent('local.userMessageFeedMarker.fetched', { userMessageFeedMarker: data });
21978
+ return data;
21979
+ };
21980
+
21981
+ const prepareUnreadCountInfo = async (rawPayload) => {
21982
+ const client = getActiveClient();
21983
+ // if consistent mode is enabled, persist the unread count info to the cache
21984
+ // Marker service API uses channelInternalId as channelId
21985
+ const queryPayload = await getUserMessageFeedMakers(rawPayload.channels.map(({ channelInternalId }) => channelInternalId));
21986
+ const { feedMarkers, userFeedMarkers } = queryPayload;
21987
+ persistUnreadCountInfo({
21988
+ feedMarkers,
21989
+ userFeedMarkers,
21990
+ });
21991
+ client.log('channel/prepareUnreadCountInfo', rawPayload.channels);
21992
+ };
21993
+
21994
+ const getCachedMarker$2 = (entityId) => {
21995
+ var _a;
21996
+ const key = {
21997
+ entityId,
21998
+ userId: getActiveUser()._id,
21999
+ };
22000
+ return (_a = pullFromCache([
22001
+ 'channelMarker',
22002
+ 'get',
22003
+ getResolver('channelMarker')(key),
22004
+ ])) === null || _a === void 0 ? void 0 : _a.data;
22005
+ };
22006
+ const getUnreadInfoCached$1 = (channelId) => {
22007
+ var _a;
22008
+ return (_a = pullFromCache(['channelUnreadInfo', 'get', channelId])) === null || _a === void 0 ? void 0 : _a.data;
22009
+ };
22010
+ /**
22011
+ * The function use to get value of hasMentioned or isMentioned field.
22012
+ * function will get the value from marker params first, if there is no hasMentioned field, will look in to the cache.
22013
+ *
22014
+ * If consistent mode is enabled, the function will return the value from the channelUnreadCountInfo cache.
22015
+ * If not, the function will return the value from the channelMarker cache.
22016
+ * If not found in the both cache, use `false` as defaul value.
22017
+ */
22018
+ const getChannelIsMentioned = (channel, marker) => {
22019
+ var _a, _b, _c, _d;
22020
+ const client = getActiveClient();
22021
+ if (client.isUnreadCountEnabled && client.getMarkerSyncConsistentMode()) {
22022
+ return (_b = (_a = getUnreadInfoCached$1(channel.channelPublicId)) === null || _a === void 0 ? void 0 : _a.isMentioned) !== null && _b !== void 0 ? _b : false;
22023
+ }
22024
+ return (marker === null || marker === void 0 ? void 0 : marker.hasMentioned) !== undefined
22025
+ ? marker === null || marker === void 0 ? void 0 : marker.hasMentioned
22026
+ : (_d = (_c = getCachedMarker$2(channel.channelPublicId)) === null || _c === void 0 ? void 0 : _c.hasMentioned) !== null && _d !== void 0 ? _d : false;
22027
+ };
22028
+
22029
+ const getCachedMarker$1 = (entityId) => {
22030
+ var _a;
22031
+ const key = {
22032
+ entityId,
22033
+ userId: getActiveUser()._id,
22034
+ };
22035
+ return (_a = pullFromCache([
22036
+ 'channelMarker',
22037
+ 'get',
22038
+ getResolver('channelMarker')(key),
22039
+ ])) === null || _a === void 0 ? void 0 : _a.data;
22040
+ };
22041
+ const getUnreadInfoCached = (channelId) => {
22042
+ var _a;
22043
+ return (_a = pullFromCache(['channelUnreadInfo', 'get', channelId])) === null || _a === void 0 ? void 0 : _a.data;
22044
+ };
22045
+ /**
22046
+ * The function use to get value of unreadCount field.
22047
+ * function will get the value from marker params first, if there is no hasMentioned field, will look in to the cache.
22048
+ *
22049
+ * If consistent mode is enabled, the function will return the value from the channelUnreadCountInfo cache.
22050
+ * If not, the function will return the value from the channelMarker cache.
22051
+ * If not found in the both cache, use `0` as defaul value.
22052
+ */
22053
+ const getSubChannelsUnreadCount = (channel, marker) => {
22054
+ var _a, _b, _c, _d, _e;
22055
+ const client = getActiveClient();
22056
+ if (client.isUnreadCountEnabled && client.getMarkerSyncConsistentMode()) {
22057
+ // Marker service API uses channelInternalId as channelId
22058
+ return (_b = (_a = getUnreadInfoCached(channel.channelInternalId)) === null || _a === void 0 ? void 0 : _a.unreadCount) !== null && _b !== void 0 ? _b : 0;
22059
+ }
22060
+ if (marker === null || marker === void 0 ? void 0 : marker.isDeleted) {
22061
+ // NOTE: This is a temporary solution to handle the channel marker when the user is forced to
22062
+ // leave the channel because currently backend can't handle this, so every time a user is banned
22063
+ // from a channel or the channel is deleted the channel's unread count will reset to zero
22064
+ return 0;
22065
+ }
22066
+ 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;
22067
+ };
22068
+
22069
+ const getLegacyChannelUnread = (channelId) => {
22070
+ var _a;
22071
+ return (_a = pullFromCache(['channelUnread', 'get', channelId])) === null || _a === void 0 ? void 0 : _a.data;
22072
+ };
22073
+
22074
+ const constructChannelDynamicValue = (channel) => {
22075
+ const client = getActiveClient();
22076
+ const rest = __rest(channel, ["messageCount"]);
22077
+ return shallowClone(rest, {
22078
+ get unreadCount() {
22079
+ var _a, _b;
22080
+ return (_b = (_a = getLegacyChannelUnread(rest.channelId)) === null || _a === void 0 ? void 0 : _a.unreadCount) !== null && _b !== void 0 ? _b : 0;
22081
+ },
22082
+ get subChannelsUnreadCount() {
22083
+ return getSubChannelsUnreadCount(rest);
22084
+ },
22085
+ get isMentioned() {
22086
+ var _a, _b;
22087
+ if (client.useLegacyUnreadCount)
22088
+ return (_b = (_a = getLegacyChannelUnread(rest.channelId)) === null || _a === void 0 ? void 0 : _a.isMentioned) !== null && _b !== void 0 ? _b : false;
22089
+ return getChannelIsMentioned(rest);
22090
+ },
22091
+ });
22092
+ };
22093
+
22094
+ const ANALYTIC_CACHE_KEY = ['analytic', 'normal-priority'];
22095
+ const HIGH_PRIORITY_ANALYTIC_CACHE_KEY = ['analytic', 'high-priority'];
22096
+
22097
+ const syncEvent = async (events) => {
22098
+ const client = getActiveClient();
22099
+ const params = {
22100
+ activities: events,
22101
+ };
22102
+ await client.http.post('/api/v1/analytics/activities', params);
22103
+ };
22104
+
22105
+ class AnalyticsEventSyncer {
22106
+ constructor() {
22107
+ this._timer = undefined;
22108
+ this._high_priority_timer = undefined;
22109
+ }
22110
+ start() {
22111
+ this.syncCapturedEvent();
22112
+ this._timer = setInterval(() => {
22113
+ this.syncCapturedEvent();
22114
+ }, 1 * MINUTE);
22115
+ this._high_priority_timer = setInterval(() => {
22116
+ this.syncHighPriorityCapturedEvent();
22117
+ }, 10 * SECOND$1);
22118
+ }
22119
+ stop() {
22120
+ if (this._timer) {
22121
+ clearInterval(this._timer);
22122
+ this._timer = undefined;
22123
+ }
22124
+ if (this._high_priority_timer) {
22125
+ clearInterval(this._high_priority_timer);
22126
+ this._high_priority_timer = undefined;
22127
+ }
22128
+ }
22129
+ async syncCapturedEvent() {
22130
+ try {
22131
+ // Must query only objects that have same userId with current logged-in user.
22132
+ // Query captured event with maximum of 1000
22133
+ // Order by latest first
22134
+ // e.g., If there are 2000 events we will query 1000-2000 first
22135
+ const cache = pullFromCache(ANALYTIC_CACHE_KEY);
22136
+ if (!(cache === null || cache === void 0 ? void 0 : cache.data))
22137
+ return;
22138
+ if (cache.data.event.length === 0)
22139
+ return;
22140
+ const capturedEvents = cache.data.event;
22141
+ await syncEvent(capturedEvents);
22142
+ dropFromCache(ANALYTIC_CACHE_KEY);
22143
+ }
22144
+ catch (error) {
22145
+ // stop and destroy all events
22146
+ this.stop();
22147
+ dropFromCache(ANALYTIC_CACHE_KEY);
22148
+ }
22149
+ }
22150
+ async syncHighPriorityCapturedEvent() {
22151
+ try {
22152
+ // Must query only objects that have same userId with current logged-in user.
22153
+ // Query captured event with maximum of 1000
22154
+ // Order by latest first
22155
+ // e.g., If there are 2000 events we will query 1000-2000 first
22156
+ const cache = pullFromCache(HIGH_PRIORITY_ANALYTIC_CACHE_KEY);
22157
+ if (!(cache === null || cache === void 0 ? void 0 : cache.data))
22158
+ return;
22159
+ if (cache.data.event.length === 0)
22160
+ return;
22161
+ const capturedEvents = cache.data.event;
22162
+ await syncEvent(capturedEvents);
22163
+ dropFromCache(HIGH_PRIORITY_ANALYTIC_CACHE_KEY);
22164
+ }
22165
+ catch (error) {
22166
+ // stop and destroy all events
22167
+ this.stop();
22168
+ dropFromCache(HIGH_PRIORITY_ANALYTIC_CACHE_KEY);
22169
+ }
22170
+ }
22171
+ }
22172
+
22173
+ class AnalyticsEventCapturer {
22174
+ constructor() {
22175
+ this._expireTime = 5 * MINUTE;
22176
+ this._poolLimit = 1000;
22177
+ this._recentViewed = {};
22178
+ this._recentHighPriorityViewed = {};
22179
+ // Story
22180
+ this._throttleStoryTimer = undefined;
22181
+ this._bufferNewSeenStoryReferenceIds = [];
22182
+ }
22183
+ isAbleToEnqueue({ uniqueId, expireTime, isHighPriority = false, }) {
22184
+ const now = new Date();
22185
+ // Get the recent view date (if any)
22186
+ const recentViewedDate = isHighPriority
22187
+ ? this._recentHighPriorityViewed[uniqueId]
22188
+ : this._recentViewed[uniqueId];
22189
+ // If this is the first view, always allow it
22190
+ if (!recentViewedDate) {
22191
+ return true;
22192
+ }
22193
+ const timeDiff = now.getTime() - recentViewedDate.getTime();
22194
+ if (timeDiff < expireTime) {
22195
+ // just recently view this post, ignore the event.
22196
+ return false;
22197
+ }
22198
+ return true;
22199
+ }
22200
+ markAs({ uniqueId, contentId, contentType, activityType, metadata, }) {
22201
+ if (!this.isAbleToEnqueue({ uniqueId, expireTime: this._expireTime }))
22202
+ return;
22203
+ const now = new Date();
22204
+ const currentData = { event: [] };
22205
+ const cache = pullFromCache(ANALYTIC_CACHE_KEY);
22206
+ if (cache === null || cache === void 0 ? void 0 : cache.data) {
22207
+ currentData.event = cache.data.event;
22208
+ }
22209
+ // If the pool is full (Max 1000 items), remove the oldest data
22210
+ if (currentData.event.length >= this._poolLimit) {
22211
+ // Remove oldest data
22212
+ currentData.event.shift();
22213
+ }
22214
+ const analyticItem = {
22215
+ contentId,
22216
+ contentType,
22217
+ activityType,
22218
+ timestamp: now.toISOString(),
22219
+ };
22220
+ if (metadata) {
22221
+ analyticItem.metadata = metadata;
22222
+ }
22223
+ currentData.event.push(analyticItem);
22224
+ upsertInCache(ANALYTIC_CACHE_KEY, currentData);
22225
+ this._recentViewed[uniqueId] = now;
22226
+ }
22227
+ markPostAsViewed(postId) {
22228
+ this.markAs({
22229
+ uniqueId: postId,
22230
+ contentId: postId,
22231
+ contentType: "post" /* Amity.AnalyticEventContentType.Post */,
22232
+ activityType: "view" /* Amity.AnalyticEventActivityType.View */,
22233
+ });
22234
+ }
22235
+ markStory(story, activityType) {
22236
+ if (!story.expiresAt)
22237
+ return;
22238
+ const now = new Date();
22239
+ const expireTime = new Date(story.expiresAt);
22240
+ if (!this.isAbleToEnqueue({
22241
+ uniqueId: story.storyId,
22242
+ expireTime: expireTime.getTime(),
22243
+ isHighPriority: true,
22244
+ }))
22245
+ return;
22246
+ const currentData = { event: [] };
22247
+ const cache = pullFromCache(HIGH_PRIORITY_ANALYTIC_CACHE_KEY);
22248
+ if (cache === null || cache === void 0 ? void 0 : cache.data) {
22249
+ currentData.event = cache.data.event;
22250
+ }
22251
+ // If the pool is full (Max 1000 items), remove the oldest data
22252
+ if (currentData.event.length >= this._poolLimit) {
22253
+ // Remove oldest data
22254
+ currentData.event.shift();
22255
+ }
22256
+ currentData.event.push({
22257
+ contentId: story.storyId,
22258
+ contentType: "story" /* Amity.AnalyticEventContentType.Story */,
22259
+ activityType,
22260
+ timestamp: now.toISOString(),
22261
+ });
22262
+ upsertInCache(HIGH_PRIORITY_ANALYTIC_CACHE_KEY, currentData);
22263
+ this._recentHighPriorityViewed[story.storyId] = now;
22264
+ // Fire internal event if the activity type is not click
22265
+ if (activityType === "linkClicked" /* Amity.AnalyticEventActivityType.Click */)
22266
+ return;
22267
+ // Mark story as SEEN
22268
+ pushToCache(["story-seen" /* STORY_KEY_CACHE.IS_SEEN */, 'get', story.storyId], new Date().toISOString());
22269
+ // Update the latest timestamp for LocalStoryLastSeen
22270
+ const currentLastSeen = pullFromCache([
22271
+ "story-last-seen" /* STORY_KEY_CACHE.LAST_SEEN */,
22272
+ story.targetId,
22273
+ ]);
22274
+ if (currentLastSeen === null || currentLastSeen === void 0 ? void 0 : currentLastSeen.data) {
22275
+ if (new Date(currentLastSeen.data).getTime() < new Date(story.expiresAt).getTime()) {
22276
+ pushToCache(["story-last-seen" /* STORY_KEY_CACHE.LAST_SEEN */, story.targetId], story.expiresAt);
22277
+ }
22278
+ }
22279
+ else {
22280
+ pushToCache(["story-last-seen" /* STORY_KEY_CACHE.LAST_SEEN */, story.targetId], story.expiresAt);
22281
+ }
22282
+ this._bufferNewSeenStoryReferenceIds.push(story.referenceId);
22283
+ if (this._throttleStoryTimer)
22284
+ return;
22285
+ this._throttleStoryTimer = setTimeout(() => {
22286
+ clearTimeout(this._throttleStoryTimer);
22287
+ fireEvent('local.story.reload', { referenceIds: this._bufferNewSeenStoryReferenceIds });
22288
+ this._bufferNewSeenStoryReferenceIds = [];
22289
+ }, 300);
22290
+ }
22291
+ resetAllBuckets() {
22292
+ this._recentViewed = {};
22293
+ this._recentHighPriorityViewed = {};
22294
+ dropFromCache(ANALYTIC_CACHE_KEY);
22295
+ dropFromCache(HIGH_PRIORITY_ANALYTIC_CACHE_KEY);
22296
+ }
22297
+ markStoryAsViewed(story) {
22298
+ this.markStory(story, "view" /* Amity.AnalyticEventActivityType.View */);
22299
+ }
22300
+ markStoryAsClicked(story) {
22301
+ this.markStory(story, "linkClicked" /* Amity.AnalyticEventActivityType.Click */);
22302
+ }
22303
+ markAdAsViewed(ad, placement) {
22304
+ const metadata = {
22305
+ placement,
22306
+ };
22307
+ const activityType = "view" /* Amity.AnalyticEventActivityType.View */;
22308
+ this.markAs({
22309
+ uniqueId: `${ad.adId}.${activityType}.${placement}`,
22310
+ contentId: ad.adId,
22311
+ contentType: "ad" /* Amity.AnalyticEventContentType.Ad */,
22312
+ activityType,
22313
+ metadata,
22314
+ });
22315
+ }
22316
+ markAdAsClicked(ad, placement) {
22317
+ const metadata = {
22318
+ placement,
22319
+ };
22320
+ const activityType = "linkClicked" /* Amity.AnalyticEventActivityType.Click */;
22321
+ this.markAs({
22322
+ uniqueId: `${ad.adId}.${activityType}.${placement}`,
22323
+ contentId: ad.adId,
22324
+ contentType: "ad" /* Amity.AnalyticEventContentType.Ad */,
22325
+ activityType,
22326
+ metadata,
22327
+ });
22328
+ }
22329
+ }
22330
+
22331
+ class AnalyticsEngine {
22332
+ constructor() {
22333
+ this._client = getActiveClient();
22334
+ this._eventCapturer = new AnalyticsEventCapturer();
22335
+ this._eventSyncer = new AnalyticsEventSyncer();
22336
+ }
22337
+ markPostAsViewed(postId) {
22338
+ if (this._client.sessionState === "established" /* Amity.SessionStates.ESTABLISHED */ ||
22339
+ this._client.sessionState === "tokenExpired" /* Amity.SessionStates.TOKEN_EXPIRED */ // For case token_expired, we assume token is expired and gonna re-connect soon
22340
+ ) {
22341
+ this._eventCapturer.markPostAsViewed(postId);
22342
+ }
22343
+ }
22344
+ markStoryAsViewed(story) {
22345
+ if (this._client.sessionState === "established" /* Amity.SessionStates.ESTABLISHED */ ||
22346
+ this._client.sessionState === "tokenExpired" /* Amity.SessionStates.TOKEN_EXPIRED */ // For case token_expired, we assume token is expired and gonna re-connect soon
22347
+ ) {
22348
+ this._eventCapturer.markStoryAsViewed(story);
22349
+ }
22350
+ }
22351
+ markAdAsViewed(ad, placement) {
22352
+ if (this._client.sessionState === "established" /* Amity.SessionStates.ESTABLISHED */ ||
22353
+ this._client.sessionState === "tokenExpired" /* Amity.SessionStates.TOKEN_EXPIRED */) {
22354
+ this._eventCapturer.markAdAsViewed(ad, placement);
22355
+ }
22356
+ }
22357
+ markAdAsClicked(ad, placement) {
22358
+ if (this._client.sessionState === "established" /* Amity.SessionStates.ESTABLISHED */ ||
22359
+ this._client.sessionState === "tokenExpired" /* Amity.SessionStates.TOKEN_EXPIRED */) {
22360
+ this._eventCapturer.markAdAsClicked(ad, placement);
22361
+ }
22362
+ }
22363
+ markStoryAsClicked(story) {
22364
+ if (this._client.sessionState === "established" /* Amity.SessionStates.ESTABLISHED */ ||
22365
+ this._client.sessionState === "tokenExpired" /* Amity.SessionStates.TOKEN_EXPIRED */) {
22366
+ this._eventCapturer.markStoryAsClicked(story);
22367
+ }
22368
+ }
22369
+ established() {
22370
+ this._eventSyncer.start();
22371
+ }
22372
+ handleTokenExpired() {
22373
+ this._stopAndDestroy();
22374
+ }
22375
+ destroy() {
22376
+ this._stopAndDestroy();
22377
+ }
22378
+ _stopAndDestroy() {
22379
+ this._eventSyncer.stop();
22380
+ this._eventCapturer.resetAllBuckets();
22381
+ }
22382
+ }
22383
+ let instance$5;
22384
+ var AnalyticsEngine$1 = {
22385
+ getInstance: () => {
22386
+ if (!instance$5) {
22387
+ instance$5 = new AnalyticsEngine();
22388
+ }
22389
+ return instance$5;
22390
+ },
22391
+ };
22392
+
22393
+ class StoryComputedValue {
22394
+ constructor(targetId, lastStoryExpiresAt, lastStorySeenExpiresAt) {
22395
+ this._syncingStoriesCount = 0;
22396
+ this._errorStoriesCount = 0;
22397
+ this._targetId = targetId;
22398
+ this._lastStoryExpiresAt = lastStoryExpiresAt;
22399
+ this._lastStorySeenExpiresAt = lastStorySeenExpiresAt;
22400
+ this.cacheStoryExpireTime = pullFromCache([
22401
+ "story-expire" /* STORY_KEY_CACHE.EXPIRE */,
22402
+ this._targetId,
22403
+ ]);
22404
+ this.cacheStoreSeenTime = pullFromCache([
22405
+ "story-last-seen" /* STORY_KEY_CACHE.LAST_SEEN */,
22406
+ this._targetId,
22407
+ ]);
22408
+ this.getTotalStoryByStatus();
22409
+ }
22410
+ get lastStoryExpiresAt() {
22411
+ return this._lastStoryExpiresAt ? new Date(this._lastStoryExpiresAt).getTime() : 0;
22412
+ }
22413
+ get lastStorySeenExpiresAt() {
22414
+ return this._lastStorySeenExpiresAt ? new Date(this._lastStorySeenExpiresAt).getTime() : 0;
22415
+ }
22416
+ get localLastStoryExpires() {
22417
+ var _a, _b;
22418
+ return ((_a = this.cacheStoryExpireTime) === null || _a === void 0 ? void 0 : _a.data)
22419
+ ? new Date((_b = this.cacheStoryExpireTime) === null || _b === void 0 ? void 0 : _b.data).getTime()
22420
+ : 0;
22421
+ }
22422
+ get localLastStorySeenExpiresAt() {
22423
+ var _a, _b;
22424
+ return ((_a = this.cacheStoreSeenTime) === null || _a === void 0 ? void 0 : _a.data) ? new Date((_b = this.cacheStoreSeenTime) === null || _b === void 0 ? void 0 : _b.data).getTime() : 0;
22425
+ }
22426
+ get isContainUnSyncedStory() {
22427
+ const currentSyncingState = pullFromCache([
22428
+ "story-sync-state" /* STORY_KEY_CACHE.SYNC_STATE */,
22429
+ this._targetId,
22430
+ ]);
22431
+ if (!(currentSyncingState === null || currentSyncingState === void 0 ? void 0 : currentSyncingState.data))
22432
+ return false;
22433
+ return ["syncing" /* Amity.SyncState.Syncing */, "error" /* Amity.SyncState.Error */].includes(currentSyncingState.data);
22434
+ }
22435
+ getLocalLastSortingDate() {
22436
+ if (this.isContainUnSyncedStory) {
22437
+ return this.localLastStoryExpires;
22438
+ }
22439
+ return this.lastStoryExpiresAt;
22440
+ }
22441
+ getHasUnseenFlag() {
22442
+ const now = new Date().getTime();
22443
+ const highestSeen = Math.max(this.lastStorySeenExpiresAt, this.localLastStorySeenExpiresAt);
22444
+ pullFromCache([
22445
+ "story-sync-state" /* STORY_KEY_CACHE.SYNC_STATE */,
22446
+ this._targetId,
22447
+ ]);
22448
+ if (this.isContainUnSyncedStory) {
22449
+ return this.localLastStoryExpires > now && this.localLastStoryExpires > highestSeen;
22450
+ }
22451
+ return this.lastStoryExpiresAt > now && this.lastStoryExpiresAt > highestSeen;
22452
+ }
22453
+ getTotalStoryByStatus() {
22454
+ const stories = queryCache(["story" /* STORY_KEY_CACHE.STORY */, 'get']);
22455
+ if (!stories) {
22456
+ this._errorStoriesCount = 0;
22457
+ this._syncingStoriesCount = 0;
22458
+ return;
22459
+ }
22460
+ const groupByType = stories.reduce((acc, story) => {
22461
+ const { data: { targetId, syncState, isDeleted }, } = story;
22462
+ if (targetId === this._targetId && !isDeleted) {
22463
+ acc[syncState] += 1;
22464
+ }
22465
+ return acc;
22466
+ }, {
22467
+ syncing: 0,
22468
+ error: 0,
22469
+ synced: 0,
22470
+ });
22471
+ this._errorStoriesCount = groupByType.error;
22472
+ this._syncingStoriesCount = groupByType.syncing;
22473
+ }
22474
+ get syncingStoriesCount() {
22475
+ return this._syncingStoriesCount;
22476
+ }
22477
+ get failedStoriesCount() {
22478
+ return this._errorStoriesCount;
22479
+ }
22480
+ }
22481
+
22482
+ const storyTargetLinkedObject = (storyTarget) => {
22483
+ const { targetType, targetId, lastStoryExpiresAt, lastStorySeenExpiresAt, targetUpdatedAt, localFilter, } = storyTarget;
22484
+ const computedValue = new StoryComputedValue(targetId, lastStoryExpiresAt, lastStorySeenExpiresAt);
22485
+ return {
22486
+ targetType,
22487
+ targetId,
22488
+ lastStoryExpiresAt,
22489
+ updatedAt: targetUpdatedAt,
22490
+ // Additional data
22491
+ hasUnseen: computedValue.getHasUnseenFlag(),
22492
+ syncingStoriesCount: computedValue.syncingStoriesCount,
22493
+ failedStoriesCount: computedValue.failedStoriesCount,
22494
+ localFilter,
22495
+ localLastExpires: computedValue.localLastStoryExpires,
22496
+ localLastSeen: computedValue.localLastStorySeenExpiresAt,
22497
+ localSortingDate: computedValue.getLocalLastSortingDate(),
22498
+ };
22499
+ };
22500
+
22501
+ const storyLinkedObject = (story) => {
22502
+ const analyticsEngineInstance = AnalyticsEngine$1.getInstance();
22503
+ const storyTargetCache = pullFromCache([
22504
+ "storyTarget" /* STORY_KEY_CACHE.STORY_TARGET */,
22505
+ 'get',
22506
+ story.targetId,
22507
+ ]);
22508
+ const communityCacheData = pullFromCache(['community', 'get', story.targetId]);
22509
+ return Object.assign(Object.assign({}, story), { analytics: {
22510
+ markAsSeen: () => {
22511
+ if (!story.expiresAt)
22512
+ return;
22513
+ if (story.syncState !== "synced" /* Amity.SyncState.Synced */)
22514
+ return;
22515
+ analyticsEngineInstance.markStoryAsViewed(story);
22516
+ },
22517
+ markLinkAsClicked: () => {
22518
+ if (!story.expiresAt)
22519
+ return;
22520
+ if (story.syncState !== "synced" /* Amity.SyncState.Synced */)
22521
+ return;
22522
+ analyticsEngineInstance.markStoryAsClicked(story);
22523
+ },
22524
+ }, get videoData() {
22525
+ var _a, _b;
22526
+ const cache = pullFromCache([
21419
22527
  'file',
21420
22528
  'get',
21421
22529
  (_b = (_a = story.data) === null || _a === void 0 ? void 0 : _a.videoFileId) === null || _b === void 0 ? void 0 : _b.original,
@@ -21713,7 +22821,7 @@ const postLinkedObject = (post) => {
21713
22821
  } });
21714
22822
  };
21715
22823
 
21716
- const getCachedMarker$2 = (message) => {
22824
+ const getCachedMarker = (message) => {
21717
22825
  var _a, _b;
21718
22826
  const key = {
21719
22827
  creatorId: 'creatorPrivateId' in message ? message.creatorPrivateId : message.creatorId,
@@ -21731,7 +22839,7 @@ const getMessageReadCount = (message, marker) => {
21731
22839
  // Look in the marker param first
21732
22840
  return (_a = marker !== null && marker !== void 0 ? marker :
21733
22841
  // If the marker param is not set, look in the cache
21734
- getCachedMarker$2(message)) !== null && _a !== void 0 ? _a : { readCount: 0, deliveredCount: 0 };
22842
+ getCachedMarker(message)) !== null && _a !== void 0 ? _a : { readCount: 0, deliveredCount: 0 };
21735
22843
  }; // and if not found in cache use default value `0`
21736
22844
 
21737
22845
  /**
@@ -21974,31 +23082,6 @@ const markAsReadBySegment = async ({ subChannelId, readToSegment, }) => {
21974
23082
  }
21975
23083
  };
21976
23084
 
21977
- const reCalculateChannelUnreadInfo = (channelId) => {
21978
- var _a;
21979
- const cacheKeyChannelUnread = ['channelUnreadInfo', 'get', channelId];
21980
- const cacheChannelUnreadInfo = (_a = pullFromCache(cacheKeyChannelUnread)) === null || _a === void 0 ? void 0 : _a.data;
21981
- const cacheKeySubChannelUnread = ['subChannelUnreadInfo', 'get'];
21982
- const cachedSubChannelUnreadInfo = queryCache(cacheKeySubChannelUnread);
21983
- let channelUnreads = 0;
21984
- let isMentioned = false;
21985
- if (cachedSubChannelUnreadInfo && (cachedSubChannelUnreadInfo === null || cachedSubChannelUnreadInfo === void 0 ? void 0 : cachedSubChannelUnreadInfo.length) > 0) {
21986
- const subChannelUnreadsInfo = cachedSubChannelUnreadInfo === null || cachedSubChannelUnreadInfo === void 0 ? void 0 : cachedSubChannelUnreadInfo.filter(({ data }) => {
21987
- return data.channelId === channelId && !data.isDeleted;
21988
- });
21989
- channelUnreads = subChannelUnreadsInfo
21990
- .map(({ data }) => data.unreadCount)
21991
- .reduce((acc, cur) => acc + cur, 0);
21992
- isMentioned = subChannelUnreadsInfo.some(({ data }) => data.isMentioned);
21993
- }
21994
- const channelUnreadInfo = Object.assign(Object.assign({}, (cacheChannelUnreadInfo !== null && cacheChannelUnreadInfo !== void 0 ? cacheChannelUnreadInfo : {
21995
- channelId,
21996
- createdAt: new Date().toISOString(),
21997
- })), { updatedAt: new Date().toISOString(), unreadCount: channelUnreads, isMentioned });
21998
- pushToCache(cacheKeyChannelUnread, channelUnreadInfo);
21999
- return channelUnreadInfo;
22000
- };
22001
-
22002
23085
  class LegacyMessageReadReceiptSyncEngine {
22003
23086
  constructor() {
22004
23087
  this.isActive = true;
@@ -22242,1198 +23325,801 @@ const messageLinkedObject = (message) => {
22242
23325
  }, markRead: () => markReadMessage(message) });
22243
23326
  };
22244
23327
 
22245
- const reactorLinkedObject = (reactor) => {
22246
- return Object.assign(Object.assign({}, reactor), { get user() {
22247
- var _a;
22248
- const user = (_a = pullFromCache(['user', 'get', reactor.userId])) === null || _a === void 0 ? void 0 : _a.data;
22249
- if (!user)
22250
- return undefined;
22251
- return userLinkedObject(user);
22252
- } });
22253
- };
22254
-
22255
- /**
22256
- * ```js
22257
- * import { ChannelRepository } from '@amityco/ts-sdk'
22258
- * const success = await ChannelRepository.markAsRead('channelId')
22259
- * ```
22260
- * Updating all {@link Amity.SubChannel} in specify {@link Amity.Channel} as read
22261
- *
22262
- * @param channelId the ID of to specify {@link Amity.Channel}
22263
- * @returns A success boolean if the {@link Amity.Channel} was mark read
22264
- *
22265
- * @category Channel API
22266
- * @async
22267
- */
22268
- const markAsRead = async (channelId) => {
22269
- const client = getActiveClient();
22270
- client.log('channel/markAsRead', channelId);
22271
- const { data } = await client.http.put(`/api/v1/markers/channels/${channelId}/mark-read`);
22272
- const { userMarkers, userEntityMarkers: userEntityMarkersPayload, userFeedMarkers: userFeedMarkersPayload } = data, rest = __rest(data, ["userMarkers", "userEntityMarkers", "userFeedMarkers"]);
22273
- const cachedAt = client.cache && Date.now();
22274
- const channelMarkers = convertChannelMarkerResponse(userEntityMarkersPayload);
22275
- const subChannelMarkers = convertSubChannelMarkerResponse(userFeedMarkersPayload);
22276
- if (client.cache)
22277
- ingestInCache(Object.assign({ userMarkers, userEntityMarkers: channelMarkers, userFeedMarkers: subChannelMarkers }, rest), { cachedAt });
22278
- fireEvent('local.channelMarker.updated', {
22279
- userEntityMarkers: channelMarkers,
22280
- });
22281
- fireEvent('local.subChannelMarker.updated', {
22282
- userFeedMarkers: subChannelMarkers,
22283
- });
22284
- return true;
22285
- };
22286
-
22287
- /**
22288
- * ```js
22289
- * import { shallowClone } from '~/utils/shallowClone'
22290
- * const newObj = shallowClone(obj)
22291
- * ```
22292
- *
22293
- * Clone an object with same prototype and properties
22294
- *
22295
- * @param obj the object to clone
22296
- * @returns new object with same prototype and properties
22297
- *
22298
- * @category utility
22299
- * @private
22300
- */
22301
- function shallowClone(source, target) {
22302
- return Object.create(Object.getPrototypeOf(source), Object.assign(Object.assign({}, Object.getOwnPropertyDescriptors(source)), Object.getOwnPropertyDescriptors(target)));
22303
- }
22304
-
22305
- const channelLinkedObject = (channel) => {
22306
- return shallowClone(channel, {
22307
- markAsRead: () => markAsRead(channel.channelInternalId),
22308
- });
22309
- };
22310
-
22311
- const adLinkedObject = (ad) => {
22312
- const analyticsEngineInstance = AnalyticsEngine$1.getInstance();
22313
- const { image9_16: image916, image1_1: image11 } = ad, restAds = __rest(ad, ["image9_16", "image1_1"]);
22314
- return Object.assign(Object.assign({}, restAds), { analytics: {
22315
- markAsSeen: (placement) => {
22316
- analyticsEngineInstance.markAdAsViewed(ad, placement);
22317
- },
22318
- markLinkAsClicked: (placement) => {
22319
- analyticsEngineInstance.markAdAsClicked(ad, placement);
22320
- },
22321
- }, get advertiser() {
22322
- var _a, _b;
22323
- const advertiserData = (_a = pullFromCache([
22324
- 'advertiser',
22325
- 'get',
22326
- ad.advertiserId,
22327
- ])) === null || _a === void 0 ? void 0 : _a.data;
22328
- if (!advertiserData)
22329
- return;
22330
- const avatarFile = (_b = pullFromCache([
22331
- 'file',
22332
- 'get',
22333
- advertiserData.avatarFileId,
22334
- ])) === null || _b === void 0 ? void 0 : _b.data;
22335
- return Object.assign(Object.assign({}, advertiserData), { avatar: avatarFile });
22336
- },
22337
- get image1_1() {
22338
- const cacheData = pullFromCache(['file', 'get', image11]);
22339
- if (!cacheData)
22340
- return undefined;
22341
- return cacheData.data || undefined;
22342
- },
22343
- get image9_16() {
22344
- const cacheData = pullFromCache(['file', 'get', image916]);
22345
- if (!cacheData)
22346
- return undefined;
22347
- return cacheData.data || undefined;
22348
- } });
22349
- };
22350
-
22351
- const pinnedPostLinkedObject = (pinnedPost) => {
22352
- var _a;
22353
- const postCached = pullFromCache(['post', 'get', pinnedPost.referenceId]);
22354
- const pinnedBy = (_a = queryCache(['user', 'get']).find(cache => {
22355
- var _a;
22356
- return ((_a = cache.data) === null || _a === void 0 ? void 0 : _a.userInternalId) === pinnedPost.pinnedBy;
22357
- })) === null || _a === void 0 ? void 0 : _a.data;
22358
- return Object.assign(Object.assign({}, pinnedPost), { pinnedBy,
22359
- get post() {
22360
- if (!(postCached === null || postCached === void 0 ? void 0 : postCached.data))
22361
- return;
22362
- return postLinkedObject(postCached.data);
22363
- },
22364
- get target() {
22365
- const pinTarget = pullFromCache([
22366
- 'pinTarget',
22367
- 'get',
22368
- postCached === null || postCached === void 0 ? void 0 : postCached.data.targetId,
22369
- ]);
22370
- if (!(pinTarget === null || pinTarget === void 0 ? void 0 : pinTarget.data))
22371
- return;
22372
- return pinTarget === null || pinTarget === void 0 ? void 0 : pinTarget.data;
22373
- } });
22374
- };
22375
-
22376
- const notificationTrayLinkedObject = (noti) => {
22377
- return Object.assign(Object.assign({}, noti), { isSeen: noti.lastSeenAt > noti.lastOccurredAt, isRecent: new Date(noti.lastOccurredAt).getTime() >= Date.now() - WEEK, users: noti.actors
22378
- .map(({ publicId }) => pullFromCache(['user', 'get', publicId]))
22379
- .filter(isNonNullable)
22380
- .map(({ data }) => data)
22381
- .map(user => userLinkedObject(user)) });
22382
- };
22383
-
22384
- const LinkedObject = {
22385
- ad: adLinkedObject,
22386
- comment: commentLinkedObject,
22387
- post: postLinkedObject,
22388
- user: userLinkedObject,
22389
- category: categoryLinkedObject,
22390
- stream: streamLinkedObject,
22391
- story: storyLinkedObject,
22392
- storyTarget: storyTargetLinkedObject,
22393
- message: messageLinkedObject,
22394
- reactor: reactorLinkedObject,
22395
- channel: channelLinkedObject,
22396
- pinnedPost: pinnedPostLinkedObject,
22397
- notificationTray: notificationTrayLinkedObject,
22398
- };
22399
-
22400
- const getChannelMessagePreviewWithUser = (channel) => {
22401
- var _a;
22402
- const messagePreview = channel.messagePreviewId
22403
- ? getChannelMessagePreview(channel.channelId)
22404
- : null;
22405
- const internalUser = (_a = pullFromCache([
22406
- 'user',
22407
- 'get',
22408
- messagePreview === null || messagePreview === void 0 ? void 0 : messagePreview.creatorId,
22409
- ])) === null || _a === void 0 ? void 0 : _a.data;
22410
- const messagePreviewWithUser = messagePreview
22411
- ? Object.assign(Object.assign({}, messagePreview), { user: internalUser ? LinkedObject.user(internalUser) : undefined }) : null;
22412
- return Object.assign(Object.assign({}, channel), { messagePreview: messagePreviewWithUser });
22413
- };
22414
-
22415
- const updateChannelMessagePreviewCache = (rawPayload) => {
22416
- var _a, _b;
22417
- const withMessageFeedInfo = (messagePreview) => {
22418
- var _a;
22419
- const messageFeedInfo = (_a = rawPayload.messageFeedsInfo) === null || _a === void 0 ? void 0 : _a.find(messageFeed => {
22420
- return messageFeed.messageFeedId === messagePreview.messageFeedId;
22421
- });
22422
- const { channelPublicId: channelId, messageFeedId: subChannelId, data, dataType, isDeleted, segment, creatorPublicId: creatorId, createdAt, updatedAt, } = messagePreview;
22423
- return {
22424
- channelId,
22425
- subChannelId,
22426
- data,
22427
- dataType,
22428
- isDeleted,
22429
- segment,
22430
- creatorId,
22431
- createdAt,
22432
- updatedAt,
22433
- subChannelName: messageFeedInfo === null || messageFeedInfo === void 0 ? void 0 : messageFeedInfo.name,
22434
- messagePreviewId: messageFeedInfo === null || messageFeedInfo === void 0 ? void 0 : messageFeedInfo.messagePreviewId,
22435
- subChannelUpdatedAt: messageFeedInfo === null || messageFeedInfo === void 0 ? void 0 : messageFeedInfo.updatedAt,
22436
- };
22437
- };
22438
- const newData = {
22439
- messagePreviewChannel: (_b = (_a = rawPayload.messagePreviews) === null || _a === void 0 ? void 0 : _a.map(messagePreview => withMessageFeedInfo(messagePreview))) !== null && _b !== void 0 ? _b : [],
22440
- };
22441
- ingestInCache(newData);
22442
- };
22443
-
22444
- const getSubChannelMessagePreview = (subChannelId) => {
22445
- var _a, _b;
22446
- return ((_b = (_a = pullFromCache(['messagePreviewSubChannel', 'get', subChannelId])) === null || _a === void 0 ? void 0 : _a.data) !== null && _b !== void 0 ? _b : null);
22447
- };
22448
-
22449
- const getSubChannelMessagePreviewWithUser = (subChannel) => {
22450
- var _a;
22451
- const messagePreview = subChannel.messagePreviewId
22452
- ? getSubChannelMessagePreview(subChannel.subChannelId)
22453
- : null;
22454
- const messagePreviewWithUser = messagePreview
22455
- ? 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;
22456
- return Object.assign(Object.assign({}, subChannel), { messagePreview: messagePreviewWithUser });
22457
- };
22458
-
22459
- const updateSubChannelMessagePreviewCache = (rawPayload) => {
22460
- var _a, _b;
22461
- const withMessageFeedInfo = (messagePreview) => {
22462
- var _a;
22463
- const messageFeedInfo = (_a = rawPayload.messageFeeds) === null || _a === void 0 ? void 0 : _a.find(messageFeed => {
22464
- return messageFeed.messageFeedId === messagePreview.messageFeedId;
22465
- });
22466
- const { channelPublicId: channelId, messageFeedId: subChannelId, messageId: messagePreviewId, creatorPublicId: creatorId, data, dataType, isDeleted, segment, createdAt, updatedAt, } = messagePreview;
22467
- return {
22468
- messagePreviewId,
22469
- channelId,
22470
- subChannelId,
22471
- data,
22472
- dataType,
22473
- isDeleted,
22474
- segment,
22475
- creatorId,
22476
- createdAt,
22477
- updatedAt,
22478
- subChannelName: messageFeedInfo === null || messageFeedInfo === void 0 ? void 0 : messageFeedInfo.name,
22479
- subChannelUpdatedAt: messageFeedInfo === null || messageFeedInfo === void 0 ? void 0 : messageFeedInfo.updatedAt,
22480
- };
22481
- };
22482
- const newData = {
22483
- messagePreviewSubChannel: (_b = (_a = rawPayload.messages) === null || _a === void 0 ? void 0 : _a.map(messagePreview => withMessageFeedInfo(messagePreview))) !== null && _b !== void 0 ? _b : [],
22484
- };
22485
- ingestInCache(newData);
22486
- };
22487
-
22488
- function updateSubChannelCache(subChannelId, subChannel, params) {
22489
- pushToCache(['subChannel', 'get', subChannelId],
22490
- // eslint-disable-next-line prefer-object-spread
22491
- shallowClone(subChannel, params));
22492
- }
22493
-
22494
- /**
22495
- * ```js
22496
- * import { isInTombstone } from '@amityco/ts-sdk'
22497
- * const user = isInTombstone(["message", "messageId"])
22498
- * ```
22499
- *
22500
- * Checks if the {@link Amity.TombstoneCacheOptions} exists
22501
- * in cache and it's not expired means it's in tombstone
22502
- * and we throw an Error
22503
- *
22504
- * @param model the model to check
22505
- * @param modelId the object id to check
22506
- * @returns the matching cache entry, or undefined.
22507
- *
22508
- * @category Cache API
22509
- */
22510
- const isInTombstone = (model, modelId) => {
22511
- const { log, cache } = getActiveClient();
22512
- const key = [model, CACHE_KEY_TOMBSTONE, modelId];
22513
- if (!cache)
22514
- return;
22515
- log('cache/api/isInTombstone', key);
22516
- const isInTombstone = pullFromCache(key);
22517
- const { lifeSpan } = queryOptions('cache_then_server', CACHE_LIFESPAN_TOMBSTONE);
22518
- if (isInTombstone && isFresh(isInTombstone.data, lifeSpan)) {
22519
- throw new ASCApiError('Item not found!', 400400 /* Amity.ServerError.ITEM_NOT_FOUND */, "error" /* Amity.ErrorLevel.ERROR */);
22520
- }
22521
- };
22522
-
22523
- /**
22524
- * ```js
22525
- * import { getMessageMarkers } from '@amityco/ts-sdk'
22526
- * const messageMarkers = await getMessageMarkers(['sch1', 'sch2'])
22527
- * ```
22528
- *
22529
- * Fetches a list of {@link Amity.MessageMarker} by messageIds
22530
- *
22531
- * @param messageIds the feed IDs of the {@link Amity.RawMessage} marker to fetch
22532
- * @returns A list of {@link Amity.MessageMarker} by messageIds
22533
- *
22534
- * @category Channel API
22535
- * @async
22536
- * @private
22537
- */
22538
- const getMessageMarkers = async (messageIds) => {
22539
- const client = getActiveClient();
22540
- client.log('channel/getMessageMarkers', messageIds);
22541
- const { data: queryPayload } = await client.http.get(`/api/v1/markers/messages`, {
22542
- params: {
22543
- messageIds,
22544
- },
22545
- });
22546
- const { contentMarkers, feedMarkers, userMarkers } = queryPayload;
22547
- const cachedAt = client.cache && Date.now();
22548
- if (client.cache)
22549
- ingestInCache({ contentMarkers, feedMarkers, userMarkers }, { cachedAt });
22550
- fireEvent('local.feedMarker.fetched', { feedMarkers });
22551
- fireEvent('local.messageMarker.fetched', { contentMarkers });
22552
- fireEvent('local.userMarker.fetched', { userMarkers });
22553
- return { data: contentMarkers, cachedAt };
22554
- };
22555
-
22556
- const persistUnreadCountInfo = (payload) => {
22557
- const { feedMarkers, userFeedMarkers } = payload;
22558
- // calculate sub channel unread info and channel unread info
22559
- if (feedMarkers.length > 0 && userFeedMarkers.length > 0) {
22560
- const channelIds = [];
22561
- const feedMarkerMap = new Map(feedMarkers.map(fm => [fm.feedId, fm]));
22562
- userFeedMarkers.forEach(userFeedMarker => {
22563
- const feedMarker = feedMarkerMap.get(userFeedMarker.feedId);
22564
- if (!feedMarker)
22565
- return;
22566
- if (feedMarker.feedId === userFeedMarker.feedId) {
22567
- const unreadCount = feedMarker.lastSegment - userFeedMarker.readToSegment;
22568
- const subChannelUnreadInfo = {
22569
- subChannelId: feedMarker.feedId,
22570
- channelId: feedMarker.entityId,
22571
- readToSegment: userFeedMarker.readToSegment,
22572
- lastSegment: feedMarker.lastSegment,
22573
- lastMentionSegment: userFeedMarker.lastMentionSegment,
22574
- unreadCount: Math.max(0, unreadCount),
22575
- isMentioned: userFeedMarker.isMentioned,
22576
- isDeleted: feedMarker.isDeleted,
22577
- createdAt: userFeedMarker.createdAt,
22578
- updatedAt: userFeedMarker.updatedAt,
22579
- };
22580
- // update sub channel unread info in cache
22581
- ingestInCache({ subChannelUnreadInfo: [subChannelUnreadInfo] });
22582
- if (!channelIds.includes(feedMarker.entityId)) {
22583
- channelIds.push(feedMarker.entityId);
22584
- }
22585
- }
22586
- });
22587
- // re-calculate channel unread info in cache
22588
- channelIds.forEach(channelId => {
22589
- reCalculateChannelUnreadInfo(channelId);
22590
- });
22591
- }
23328
+ const reactorLinkedObject = (reactor) => {
23329
+ return Object.assign(Object.assign({}, reactor), { get user() {
23330
+ var _a;
23331
+ const user = (_a = pullFromCache(['user', 'get', reactor.userId])) === null || _a === void 0 ? void 0 : _a.data;
23332
+ if (!user)
23333
+ return undefined;
23334
+ return userLinkedObject(user);
23335
+ } });
22592
23336
  };
22593
23337
 
22594
23338
  /**
22595
23339
  * ```js
22596
- * import { getSubChannelMarkers } from '@amityco/ts-sdk'
22597
- * const subChannelMarkers = await getSubChannelMarkers(['sch1', 'sch2'])
23340
+ * import { ChannelRepository } from '@amityco/ts-sdk'
23341
+ * const success = await ChannelRepository.markAsRead('channelId')
22598
23342
  * ```
23343
+ * Updating all {@link Amity.SubChannel} in specify {@link Amity.Channel} as read
22599
23344
  *
22600
- * Fetches a paginable list of {@link Amity.SubChannelMarker} objects
22601
- *
22602
- * @param messageFeedIds the feed IDs of the {@link Amity.RawSubChannel} marker to fetch
22603
- * @param page
22604
- * @returns A page of {@link Amity.SubChannelMarker} objects
23345
+ * @param channelId the ID of to specify {@link Amity.Channel}
23346
+ * @returns A success boolean if the {@link Amity.Channel} was mark read
22605
23347
  *
22606
23348
  * @category Channel API
22607
23349
  * @async
22608
- * @private
22609
23350
  */
22610
- const getSubChannelMarkers = async (messageFeedIds, page = { limit: 100 }) => {
22611
- const client = getActiveClient();
22612
- client.log('channel/getSubChannelMarkers', messageFeedIds, page);
22613
- const { data: queryPayload } = await client.http.get(`/api/v1/markers/message-feeds`, {
22614
- params: {
22615
- messageFeedIds,
22616
- options: {
22617
- token: toToken(page, 'skiplimit'),
22618
- },
22619
- },
22620
- });
22621
- const { paging } = queryPayload, payload = __rest(queryPayload, ["paging"]);
22622
- const { userEntityMarkers: userEntityMarkersPayload, userFeedMarkers: userFeedMarkersPayload, userMarkers, feedMarkers: feedMarkersPayload, } = payload;
22623
- // if consistent mode is enabled, persist the unread count info to the cache
22624
- if (client.isUnreadCountEnabled && client.getMarkerSyncConsistentMode()) {
22625
- persistUnreadCountInfo({
22626
- feedMarkers: feedMarkersPayload,
22627
- userFeedMarkers: userFeedMarkersPayload,
22628
- });
22629
- }
22630
- const userEntityMarkers = convertChannelMarkerResponse(userEntityMarkersPayload);
22631
- const userFeedMarkers = convertSubChannelMarkerResponse(userFeedMarkersPayload);
22632
- const cachedAt = client.cache && Date.now();
22633
- if (client.cache)
22634
- ingestInCache({ userEntityMarkers, userFeedMarkers, userMarkers }, { cachedAt });
22635
- fireEvent('local.channelMarker.fetched', { userEntityMarkers });
22636
- fireEvent('local.subChannelMarker.fetched', { userFeedMarkers });
22637
- fireEvent('local.userMarker.fetched', { userMarkers });
22638
- const nextPage = toPage(paging.next);
22639
- const prevPage = toPage(paging.previous);
22640
- return { data: userFeedMarkers, cachedAt, prevPage, nextPage };
22641
- };
22642
-
22643
- const getUserMarker = async () => {
23351
+ const markAsRead = async (channelId) => {
22644
23352
  const client = getActiveClient();
22645
- client.log('channel/getUserMarker');
22646
- const { data: payload } = await client.http.get(`/api/v1/markers/userMarker`);
22647
- const { userMarkers } = payload;
23353
+ client.log('channel/markAsRead', channelId);
23354
+ const { data } = await client.http.put(`/api/v1/markers/channels/${channelId}/mark-read`);
23355
+ const { userMarkers, userEntityMarkers: userEntityMarkersPayload, userFeedMarkers: userFeedMarkersPayload } = data, rest = __rest(data, ["userMarkers", "userEntityMarkers", "userFeedMarkers"]);
22648
23356
  const cachedAt = client.cache && Date.now();
23357
+ const channelMarkers = convertChannelMarkerResponse(userEntityMarkersPayload);
23358
+ const subChannelMarkers = convertSubChannelMarkerResponse(userFeedMarkersPayload);
22649
23359
  if (client.cache)
22650
- ingestInCache({ userMarkers }, { cachedAt });
22651
- fireEvent('local.userMarker.fetched', { userMarkers });
22652
- const latestUserMarker = userMarkers.reduce((maxUserMarker, userMarker) => {
22653
- if (maxUserMarker == null ||
22654
- new Date(maxUserMarker.lastSyncAt).getTime() < new Date(userMarker.lastSyncAt).getTime()) {
22655
- return userMarker;
22656
- }
22657
- return maxUserMarker;
22658
- }, undefined);
22659
- return { data: latestUserMarker, cachedAt };
23360
+ ingestInCache(Object.assign({ userMarkers, userEntityMarkers: channelMarkers, userFeedMarkers: subChannelMarkers }, rest), { cachedAt });
23361
+ fireEvent('local.channelMarker.updated', {
23362
+ userEntityMarkers: channelMarkers,
23363
+ });
23364
+ fireEvent('local.subChannelMarker.updated', {
23365
+ userFeedMarkers: subChannelMarkers,
23366
+ });
23367
+ return true;
22660
23368
  };
22661
23369
 
22662
- /** @hidden */
22663
- /*
22664
- * @param message payload from http request without myReactions
22665
- * add myReactions to http response if the event was a reaction event
22666
- */
22667
- const prepareMessagePayloadForCache = (payload, reactors, event) => {
22668
- const client = getActiveClient();
22669
- const cached = pullFromCache(['message', 'get', payload.messageId]);
22670
- // '[]' in cases where the new reaction is the first one
22671
- const myReactions = (cached === null || cached === void 0 ? void 0 : cached.data.myReactions) || [];
22672
- // add myReactions to the payload
22673
- Object.assign(payload, { myReactions });
22674
- // check if there are any updates to the reactions
22675
- const latestReaction = reactors[0];
22676
- const isLatestReactionMine = latestReaction && latestReaction.userId === client.userId;
22677
- if (!isLatestReactionMine) {
22678
- return;
22679
- }
22680
- // new reaction added
22681
- if (event === 'message.reactionAdded' && !myReactions.includes(latestReaction.reactionName)) {
22682
- Object.assign(payload, {
22683
- myReactions: [...myReactions, latestReaction.reactionName],
22684
- });
22685
- }
22686
- // existing reaction removed
22687
- if (event === 'message.reactionRemoved' && myReactions.includes(latestReaction.reactionName)) {
22688
- Object.assign(payload, {
22689
- myReactions: myReactions.filter(x => x !== latestReaction.reactionName),
22690
- });
22691
- }
23370
+ const channelLinkedObject = (channel) => {
23371
+ return shallowClone(channel, {
23372
+ markAsRead: () => markAsRead(channel.channelInternalId),
23373
+ });
22692
23374
  };
22693
23375
 
22694
- /*
22695
- * This is a simple utility that infers the value of isDeleted based on the
22696
- * value of includeDeleted
22697
- *
22698
- * There are two important things to note here:
22699
- * 1. `includeDeleted` is purely client side query param and not recognized by
22700
- * the server
22701
- * 2. The only values we wish to expose with regards to `isDeleted` (the server
22702
- * param for queries) is false | undefined and want to disallow users to query
22703
- * for deleted entities
22704
- *
22705
- * Although this is a very simple utility, it's only purpose is to keep things
22706
- * DRY
22707
- */
22708
- const inferIsDeleted = (includeDeleted) => includeDeleted === true ? undefined : false;
22709
-
22710
- function getSubChannelIsMentioned(channelId, subChannelId, marker) {
22711
- var _a, _b;
22712
- // Look for `unreadCount` in the marker param first
22713
- if (marker) {
22714
- return marker.hasMentioned;
22715
- }
22716
- const client = getActiveClient();
22717
- // If consistent mode is enabled, look in the SubChannelUnreadCountInfo cache
22718
- if (client.isUnreadCountEnabled && client.getMarkerSyncConsistentMode()) {
22719
- const cachedUnreadCount = (_a = pullFromCache([
22720
- 'subChannelUnreadInfo',
22721
- 'get',
22722
- subChannelId,
22723
- ])) === null || _a === void 0 ? void 0 : _a.data;
22724
- if (cachedUnreadCount) {
22725
- return cachedUnreadCount.isMentioned;
22726
- }
22727
- return false;
22728
- }
22729
- const key = {
22730
- entityId: channelId,
22731
- feedId: subChannelId,
22732
- userId: getActiveUser()._id,
22733
- };
22734
- // If the marker param is not set, look in the cache
22735
- const cachedMarker = (_b = pullFromCache([
22736
- 'subChannelMarker',
22737
- 'get',
22738
- getResolver('subChannelMarker')(key),
22739
- ])) === null || _b === void 0 ? void 0 : _b.data;
22740
- if (cachedMarker) {
22741
- return cachedMarker.hasMentioned;
22742
- }
22743
- // and if not found in cache use default value `false`
22744
- return false;
22745
- }
22746
-
22747
- function getSubChannelUnreadCount(channelId, subChannelId, marker) {
22748
- var _a, _b;
22749
- // Look for `unreadCount` in the marker param first
22750
- if (marker) {
22751
- return marker.unreadCount;
22752
- }
22753
- const client = getActiveClient();
22754
- // If consistent mode is enabled, look in the SubChannelUnreadCountInfo cache
22755
- if (client.isUnreadCountEnabled && client.getMarkerSyncConsistentMode()) {
22756
- const cachedUnreadCount = (_a = pullFromCache([
22757
- 'subChannelUnreadInfo',
22758
- 'get',
22759
- subChannelId,
22760
- ])) === null || _a === void 0 ? void 0 : _a.data;
22761
- if (cachedUnreadCount) {
22762
- return cachedUnreadCount.isDeleted ? 0 : cachedUnreadCount.unreadCount;
22763
- }
22764
- return 0;
22765
- }
22766
- const key = {
22767
- entityId: channelId,
22768
- feedId: subChannelId,
22769
- userId: getActiveUser()._id,
22770
- };
22771
- // If the marker param is not set, look in the cache
22772
- const cachedMarker = (_b = pullFromCache([
22773
- 'subChannelMarker',
22774
- 'get',
22775
- getResolver('subChannelMarker')(key),
22776
- ])) === null || _b === void 0 ? void 0 : _b.data;
22777
- if (cachedMarker) {
22778
- return cachedMarker.unreadCount;
22779
- }
22780
- // and if not found in cache use default value `0`
22781
- return 0;
22782
- }
22783
-
22784
- const MARKER_INCLUDED_SUB_CHANNEL_TYPE$1 = ['broadcast', 'conversation', 'community'];
22785
- const isUnreadCountSupport$2 = ({ channelType }) => MARKER_INCLUDED_SUB_CHANNEL_TYPE$1.includes(channelType);
22786
- function convertFromRaw$2(_a) {
22787
- 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"]);
22788
- return Object.assign(Object.assign({ get unreadCount() {
22789
- return getSubChannelUnreadCount(channelId, messageFeedId);
23376
+ const adLinkedObject = (ad) => {
23377
+ const analyticsEngineInstance = AnalyticsEngine$1.getInstance();
23378
+ const { image9_16: image916, image1_1: image11 } = ad, restAds = __rest(ad, ["image9_16", "image1_1"]);
23379
+ return Object.assign(Object.assign({}, restAds), { analytics: {
23380
+ markAsSeen: (placement) => {
23381
+ analyticsEngineInstance.markAdAsViewed(ad, placement);
23382
+ },
23383
+ markLinkAsClicked: (placement) => {
23384
+ analyticsEngineInstance.markAdAsClicked(ad, placement);
23385
+ },
23386
+ }, get advertiser() {
23387
+ var _a, _b;
23388
+ const advertiserData = (_a = pullFromCache([
23389
+ 'advertiser',
23390
+ 'get',
23391
+ ad.advertiserId,
23392
+ ])) === null || _a === void 0 ? void 0 : _a.data;
23393
+ if (!advertiserData)
23394
+ return;
23395
+ const avatarFile = (_b = pullFromCache([
23396
+ 'file',
23397
+ 'get',
23398
+ advertiserData.avatarFileId,
23399
+ ])) === null || _b === void 0 ? void 0 : _b.data;
23400
+ return Object.assign(Object.assign({}, advertiserData), { avatar: avatarFile });
22790
23401
  },
22791
- get hasMentioned() {
22792
- return getSubChannelIsMentioned(channelId, messageFeedId);
23402
+ get image1_1() {
23403
+ const cacheData = pullFromCache(['file', 'get', image11]);
23404
+ if (!cacheData)
23405
+ return undefined;
23406
+ return cacheData.data || undefined;
22793
23407
  },
22794
- get isMentioned() {
22795
- return getSubChannelIsMentioned(channelId, messageFeedId);
22796
- } }, rest), { channelId: channelPublicId, creatorId: creatorPublicId, displayName: name, lastActivity: lastMessageTimestamp, latestMessageId: lastMessageId, messageCount: childCount, subChannelId: messageFeedId, isUnreadCountSupport: isUnreadCountSupport$2({ channelType }) });
22797
- }
23408
+ get image9_16() {
23409
+ const cacheData = pullFromCache(['file', 'get', image916]);
23410
+ if (!cacheData)
23411
+ return undefined;
23412
+ return cacheData.data || undefined;
23413
+ } });
23414
+ };
22798
23415
 
22799
- const mergePayloadWithLocal = (payload) => {
22800
- var _a, _b, _c;
22801
- 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;
22802
- if (localMessage) {
22803
- return Object.assign(Object.assign(Object.assign({}, localMessage), payload), {
22804
- // NOTE: referenceId is missing in the some payload event. If we have local message data with referenceId, use it instead.
22805
- referenceId: (_c = localMessage.referenceId) !== null && _c !== void 0 ? _c : payload.referenceId });
22806
- }
22807
- return payload;
22808
- };
22809
- function convertFromRaw$1(message, reactors, event) {
23416
+ const pinnedPostLinkedObject = (pinnedPost) => {
22810
23417
  var _a;
22811
- const mergeMessage = mergePayloadWithLocal(message);
22812
- 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"]);
22813
- let cache;
22814
- if (referenceId) {
22815
- cache = pullFromCache(['message', 'get', referenceId]);
22816
- }
22817
- if (!cache) {
22818
- cache = pullFromCache(['message', 'get', messageId]);
22819
- }
22820
- 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 : {},
22821
- /*
22822
- * Previously, myReactions were added only if it was part of the payload.
22823
- * So empty myReactions were not present. So I've edited the payload to add
22824
- * a default for those cases.
22825
- *
22826
- * Check git blame for previous iteration
22827
- */
22828
- 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 */ });
22829
- if (mentionedUsers) {
22830
- out.mentionees = mentionedUsers.map(mention => {
22831
- if (mention.type === 'channel') {
22832
- return mention;
22833
- }
22834
- return { type: 'user', userIds: mention.userPublicIds };
22835
- });
22836
- }
22837
- if (reactors && reactors.length && event) {
22838
- // mqtt event
22839
- prepareMessagePayloadForCache(out, reactors, event);
22840
- }
22841
- return out;
22842
- }
22843
- const preUpdateMessageCache = (rawPayload) => {
22844
- ingestInCache({
22845
- messages: rawPayload.messages.map(message => convertFromRaw$1(message, rawPayload.reactions)),
22846
- });
22847
- };
22848
- const DEBOUNCE_TIME = 2000;
22849
- const currentDebounceMap = {};
22850
- const prepareMessagePayload = async (payload, event) => {
22851
- const markerIds = payload.messages.map(({ messageId }) => messageId);
22852
- if (markerIds.length > 0) {
22853
- // since the get markers method requires a channel cache to function with the reducer.
22854
- preUpdateMessageCache(payload);
22855
- const markerIdsKey = markerIds.join('');
22856
- if (currentDebounceMap[markerIdsKey]) {
22857
- clearTimeout(currentDebounceMap[markerIdsKey]);
22858
- }
22859
- currentDebounceMap[markerIdsKey] = setTimeout(() => {
22860
- try {
22861
- getMessageMarkers(markerIds);
22862
- }
22863
- catch (_error) {
22864
- // do nothing
22865
- }
22866
- }, DEBOUNCE_TIME);
22867
- }
22868
- const { messageFeeds } = payload, restPayload = __rest(payload, ["messageFeeds"]);
22869
- // upsert messageFeeds to subchannel cache because messageFeeds from event payload not include messagePreviewId
22870
- if (messageFeeds && messageFeeds.length > 0) {
22871
- messageFeeds === null || messageFeeds === void 0 ? void 0 : messageFeeds.forEach(messageFeed => {
22872
- var _a, _b;
22873
- const subChannelCache = (_b = (_a = pullFromCache(['subChannel', 'get', messageFeed.messageFeedId])) === null || _a === void 0 ? void 0 : _a.data) !== null && _b !== void 0 ? _b : {};
22874
- // exclude getter properties from existing subChannel cache, update only other properties to existing subChannel cache
22875
- const _c = convertFromRaw$2(messageFeed), restSubChannel = __rest(_c, ["unreadCount", "isMentioned"]);
22876
- updateSubChannelCache(messageFeed.messageFeedId, subChannelCache, restSubChannel);
22877
- });
22878
- }
22879
- return Object.assign(Object.assign({}, restPayload), { messages: payload.messages.map(m => convertFromRaw$1(m, payload.reactions, event)) });
22880
- };
22881
- function convertParams(_a) {
22882
- var { subChannelId, mentionees, dataType, data } = _a, rest = __rest(_a, ["subChannelId", "mentionees", "dataType", "data"]);
22883
- if (dataType === MessageContentType.IMAGE || dataType === MessageContentType.FILE) {
22884
- return Object.assign({ messageFeedId: subChannelId, mentionedUsers: mentionees, dataType, data: Object.assign({ caption: '' }, data) }, rest);
22885
- }
22886
- return Object.assign({ messageFeedId: subChannelId, mentionedUsers: mentionees, dataType, data }, rest);
22887
- }
22888
- function convertQueryParams$1(_a) {
22889
- var { sortBy, subChannelId, includingTags, excludingTags, includeDeleted, aroundMessageId, limit, type } = _a, rest = __rest(_a, ["sortBy", "subChannelId", "includingTags", "excludingTags", "includeDeleted", "aroundMessageId", "limit", "type"]);
22890
- const out = Object.assign(Object.assign({}, rest), { messageFeedId: subChannelId, isDeleted: inferIsDeleted(includeDeleted), options: {
22891
- sortBy,
22892
- limit: limit || COLLECTION_DEFAULT_PAGINATION_LIMIT,
22893
- around: aroundMessageId,
23418
+ const postCached = pullFromCache(['post', 'get', pinnedPost.referenceId]);
23419
+ const pinnedBy = (_a = queryCache(['user', 'get']).find(cache => {
23420
+ var _a;
23421
+ return ((_a = cache.data) === null || _a === void 0 ? void 0 : _a.userInternalId) === pinnedPost.pinnedBy;
23422
+ })) === null || _a === void 0 ? void 0 : _a.data;
23423
+ return Object.assign(Object.assign({}, pinnedPost), { pinnedBy,
23424
+ get post() {
23425
+ if (!(postCached === null || postCached === void 0 ? void 0 : postCached.data))
23426
+ return;
23427
+ return postLinkedObject(postCached.data);
23428
+ },
23429
+ get target() {
23430
+ const pinTarget = pullFromCache([
23431
+ 'pinTarget',
23432
+ 'get',
23433
+ postCached === null || postCached === void 0 ? void 0 : postCached.data.targetId,
23434
+ ]);
23435
+ if (!(pinTarget === null || pinTarget === void 0 ? void 0 : pinTarget.data))
23436
+ return;
23437
+ return pinTarget === null || pinTarget === void 0 ? void 0 : pinTarget.data;
22894
23438
  } });
22895
- if (includingTags) {
22896
- out.includeTags = includingTags;
22897
- }
22898
- if (type) {
22899
- out.dataType = type;
22900
- }
22901
- if (excludingTags) {
22902
- out.excludeTags = excludingTags;
22903
- }
22904
- return out;
22905
- }
23439
+ };
22906
23440
 
22907
- const MARKER_INCLUDED_SUB_CHANNEL_TYPE = ['broadcast', 'conversation', 'community'];
23441
+ const notificationTrayLinkedObject = (noti) => {
23442
+ return Object.assign(Object.assign({}, noti), { isSeen: noti.lastSeenAt > noti.lastOccurredAt, isRecent: new Date(noti.lastOccurredAt).getTime() >= Date.now() - WEEK, users: noti.actors
23443
+ .map(({ publicId }) => pullFromCache(['user', 'get', publicId]))
23444
+ .filter(isNonNullable)
23445
+ .map(({ data }) => data)
23446
+ .map(user => userLinkedObject(user)) });
23447
+ };
23448
+
23449
+ const prepareInvitationPayload = (rawPayload) => {
23450
+ return {
23451
+ invitations: rawPayload.invitations.map(invitation => (Object.assign(Object.assign({}, invitation), { invitationId: invitation._id, createdById: invitation.createdBy }))),
23452
+ };
23453
+ };
23454
+
23455
+ /* begin_public_function
23456
+ id: invitation.createInvitations
23457
+ */
22908
23458
  /**
22909
- * Filter sub channel by type. Only conversation, community and broadcast type are included.
23459
+ * ```js
23460
+ * import { createInvitations } from '@amityco/ts-sdk'
23461
+ * const created = await createInvitations({
23462
+ * type: string,
23463
+ * targetType: string,
23464
+ * targetId: string,
23465
+ * userIds: string[]
23466
+ * }))
23467
+ * ```
23468
+ *
23469
+ * Creates an {@link Amity.Invitation}
23470
+ *
23471
+ * @param bundle The data necessary to create a new {@link Amity.Invitation}
23472
+ * @returns The newly created {@link Amity.Invitation}
23473
+ *
23474
+ * @category Invitation API
23475
+ * @async
22910
23476
  */
22911
- const isUnreadCountSupport$1 = ({ channelType }) => MARKER_INCLUDED_SUB_CHANNEL_TYPE.includes(channelType);
22912
- const preUpdateSubChannelCache = (rawPayload) => {
22913
- ingestInCache({
22914
- messageFeeds: rawPayload.messageFeeds.map(messageFeed => convertFromRaw$2(messageFeed)),
22915
- });
22916
- };
22917
- const prepareSubChannelPayload = async (rawPayload) => {
22918
- const markerIds = rawPayload.messageFeeds
22919
- .filter(isUnreadCountSupport$1)
22920
- .map(({ messageFeedId }) => messageFeedId);
22921
- if (markerIds.length > 0) {
22922
- // since the get markers method requires a channel cache to function with the reducer.
22923
- preUpdateSubChannelCache(rawPayload);
22924
- try {
22925
- await getSubChannelMarkers(markerIds);
22926
- }
22927
- catch (e) {
22928
- // empty block (from the spec, allow marker fetch to fail without having to do anything)
22929
- }
22930
- }
22931
- updateSubChannelMessagePreviewCache(rawPayload);
22932
- // attach marker to sub channel
22933
- const messageFeeds = rawPayload.messageFeeds.map(convertFromRaw$2);
22934
- const messages = rawPayload.messages.map(m => convertFromRaw$1(m));
22935
- return Object.assign(Object.assign({}, rawPayload), { messageFeeds,
22936
- messages });
23477
+ const createInvitations = async (bundle) => {
23478
+ const client = getActiveClient();
23479
+ client.log('invitation/createInvitations', bundle);
23480
+ const { data: payload } = await client.http.post('/api/v1/invitations', bundle);
23481
+ const data = prepareInvitationPayload(payload);
23482
+ const cachedAt = client.cache && Date.now();
23483
+ if (client.cache)
23484
+ ingestInCache(data, { cachedAt });
23485
+ fireEvent('local.invitation.created', data.invitations);
23486
+ return {
23487
+ data: data.invitations,
23488
+ cachedAt,
23489
+ };
22937
23490
  };
22938
- function convertQueryParams(_a) {
22939
- var { excludeDefaultSubChannel } = _a, rest = __rest(_a, ["excludeDefaultSubChannel"]);
22940
- const out = Object.assign({}, rest);
22941
- if (excludeDefaultSubChannel !== undefined) {
22942
- out.excludeDefaultMessageFeed = excludeDefaultSubChannel;
22943
- }
22944
- return out;
22945
- }
23491
+ /* end_public_function */
22946
23492
 
23493
+ /* begin_public_function
23494
+ id: invitation.accept
23495
+ */
22947
23496
  /**
22948
23497
  * ```js
22949
- * import { getSubChannel } from '@amityco/ts-sdk'
22950
- * const subChannel = await getSubChannel('foobar')
23498
+ * import { acceptInvitation } from '@amityco/ts-sdk'
23499
+ * const isAccepted = await acceptInvitation(invitationId)
22951
23500
  * ```
22952
23501
  *
22953
- * Fetches a {@link Amity.SubChannel} object
23502
+ * Accepts a {@link Amity.Invitation} object
22954
23503
  *
22955
- * @param subChannelId the ID of the {@link Amity.SubChannel} to fetch
22956
- * @returns the associated {@link Amity.SubChannel} object
23504
+ * @param invitationId the {@link Amity.Invitation} to accept
23505
+ * @returns A success boolean if the {@link Amity.Invitation} was accepted
22957
23506
  *
22958
- * @category Channel API
23507
+ * @category Invitation API
22959
23508
  * @async
22960
23509
  */
22961
- const getSubChannel$1 = async (subChannelId) => {
23510
+ const acceptInvitation = async (invitationId) => {
23511
+ var _a;
22962
23512
  const client = getActiveClient();
22963
- client.log('channel/getSubChannel', subChannelId);
22964
- isInTombstone('subChannel', subChannelId);
22965
- try {
22966
- const response = await client.http.get(`/api/v5/message-feeds/${encodeURIComponent(subChannelId)}`);
22967
- const data = await prepareSubChannelPayload(response.data);
22968
- const cachedAt = client.cache && Date.now();
22969
- if (client.cache)
22970
- ingestInCache(data, { cachedAt });
22971
- fireEvent('local.message-feed.fetched', data);
22972
- return {
22973
- data: data.messageFeeds[0],
22974
- cachedAt,
22975
- };
22976
- }
22977
- catch (error) {
22978
- if (checkIfShouldGoesToTombstone(error === null || error === void 0 ? void 0 : error.code)) {
22979
- pushToTombstone('subChannel', subChannelId);
22980
- }
22981
- throw error;
23513
+ client.log('invitation/acceptInvitation', invitationId);
23514
+ const { data } = await client.http.post(`/api/v1/invitations/${invitationId}/accept`);
23515
+ const invitation = (_a = pullFromCache([
23516
+ 'invitation',
23517
+ 'get',
23518
+ invitationId,
23519
+ ])) === null || _a === void 0 ? void 0 : _a.data;
23520
+ if (invitation) {
23521
+ upsertInCache(['invitation', 'get', invitationId], { status: "approved" /* InvitationStatusEnum.Approved */ });
23522
+ fireEvent('local.invitation.updated', [invitation]);
22982
23523
  }
23524
+ return data.success;
22983
23525
  };
23526
+ /* end_public_function */
23527
+
23528
+ /* begin_public_function
23529
+ id: invitation.reject
23530
+ */
22984
23531
  /**
22985
23532
  * ```js
22986
- * import { getSubChannel } from '@amityco/ts-sdk'
22987
- * const subChannel = getSubChannel.locally('foobar')
23533
+ * import { rejectInvitation } from '@amityco/ts-sdk'
23534
+ * const isRejected = await rejectInvitation(invitationId)
22988
23535
  * ```
22989
23536
  *
22990
- * Fetches a {@link Amity.SubChannel} object from cache
23537
+ * Rejects a {@link Amity.Invitation} object
22991
23538
  *
22992
- * @param subChannelId the ID of the {@link Amity.SubChannel} to fetch
22993
- * @returns the associated {@link Amity.SubChannel} object
23539
+ * @param invitationId the {@link Amity.Invitation} to reject
23540
+ * @returns A success boolean if the {@link Amity.Invitation} was rejected
22994
23541
  *
22995
- * @category Channel API
23542
+ * @category Invitation API
23543
+ * @async
22996
23544
  */
22997
- getSubChannel$1.locally = (subChannelId) => {
22998
- const client = getActiveClient();
22999
- client.log('channel/getSubChannel.locally', subChannelId);
23000
- if (!client.cache)
23001
- return;
23002
- const cached = pullFromCache(['subChannel', 'get', subChannelId]);
23003
- if (!cached)
23004
- return;
23005
- return {
23006
- data: cached.data,
23007
- cachedAt: cached.cachedAt,
23008
- };
23009
- };
23010
-
23011
- const convertDateStringToTimestamp = (dateString) => {
23012
- return new Date(dateString).getTime();
23013
- };
23014
-
23015
- const getMessagePreviewSetting$1 = async () => {
23016
- const client = getActiveClient();
23017
- return client.getMessagePreviewSetting(false);
23018
- };
23019
- const getSubChannelCache = async (subChannelId) => {
23020
- var _a;
23021
- let subChannelCache = (_a = pullFromCache(['subChannel', 'get', subChannelId])) === null || _a === void 0 ? void 0 : _a.data;
23022
- if (!subChannelCache) {
23023
- subChannelCache = (await getSubChannel$1(subChannelId)).data;
23024
- }
23025
- return subChannelCache;
23026
- };
23027
- const isLastestMessageOnSubchannel = (message) => {
23028
- var _a;
23029
- const cache = (_a = pullFromCache([
23030
- 'messagePreviewSubChannel',
23031
- 'get',
23032
- message.subChannelId,
23033
- ])) === null || _a === void 0 ? void 0 : _a.data;
23034
- // The message payload from optimistic created event has no segment, so we check createdAt instead.
23035
- return (!cache ||
23036
- cache.segment <= message.channelSegment ||
23037
- convertDateStringToTimestamp(cache.createdAt) <= convertDateStringToTimestamp(message.createdAt));
23038
- };
23039
- const isLastestMessageOnChannel = (message) => {
23545
+ const rejectInvitation = async (invitationId) => {
23040
23546
  var _a;
23041
- const cache = (_a = pullFromCache([
23042
- 'messagePreviewChannel',
23547
+ const client = getActiveClient();
23548
+ client.log('invitation/rejectInvitation', invitationId);
23549
+ const { data } = await client.http.post(`/api/v1/invitations/${invitationId}/reject`);
23550
+ const invitation = (_a = pullFromCache([
23551
+ 'invitation',
23043
23552
  'get',
23044
- message.channelId,
23553
+ invitationId,
23045
23554
  ])) === null || _a === void 0 ? void 0 : _a.data;
23046
- return (!cache ||
23047
- convertDateStringToTimestamp(cache.createdAt) <= convertDateStringToTimestamp(message.createdAt));
23048
- };
23049
- const handleMessageCreatedOnSubChannel = async (message) => {
23050
- const messagePreviewSetting = await getMessagePreviewSetting$1();
23051
- const { channelId, messageId: messagePreviewId, creatorId, createdAt, updatedAt, data, dataType, subChannelId, channelSegment: segment, isDeleted, } = message;
23052
- // 1. get subChannel from cache, if not exist fetch from server
23053
- const subChannelCache = await getSubChannelCache(subChannelId);
23054
- // 2. if messagePreviewSetting is NO_MESSAGE_PREVEIW, update only lastActiviy in subChannel cache
23055
- if (messagePreviewSetting === "no-message-preview" /* Amity.MessagePreviewSetting.NO_MESSAGE_PREVIEW */) {
23056
- // 2.1 if the message is the latest message, update lastActivity to be createdAt in subChannel cache
23057
- if (convertDateStringToTimestamp(subChannelCache.lastActivity) <
23058
- convertDateStringToTimestamp(createdAt))
23059
- updateSubChannelCache(message.subChannelId, subChannelCache, {
23060
- lastActivity: createdAt,
23061
- });
23062
- return;
23555
+ if (invitation) {
23556
+ upsertInCache(['invitation', 'get', invitationId], { status: "rejected" /* InvitationStatusEnum.Rejected */ });
23557
+ fireEvent('local.invitation.updated', [invitation]);
23063
23558
  }
23064
- // 3. if messagePreviewSetting is `NOT` NO_MESSAGE_PREVEIW, update messagePreviewSubChannel and subChannel cache
23065
- // 3.1 check if the message is the latest message, if not ignore the message.
23066
- if (!isLastestMessageOnSubchannel(message))
23067
- return;
23068
- // 3.2 if the message is the latest message, update messagePreviewSubChannel and subChannel cache
23069
- pushToCache(['messagePreviewSubChannel', 'get', message.subChannelId], {
23070
- channelId,
23071
- creatorId,
23072
- messagePreviewId,
23073
- createdAt,
23074
- updatedAt,
23075
- subChannelId,
23076
- data,
23077
- dataType,
23078
- segment,
23079
- isDeleted,
23080
- subChannelUpdatedAt: subChannelCache === null || subChannelCache === void 0 ? void 0 : subChannelCache.updatedAt,
23081
- subChannelName: subChannelCache === null || subChannelCache === void 0 ? void 0 : subChannelCache.displayName,
23082
- });
23083
- updateSubChannelCache(message.subChannelId, subChannelCache, {
23084
- lastActivity: createdAt,
23085
- messagePreviewId,
23086
- });
23559
+ return data.success;
23087
23560
  };
23088
- const handleMessageUpdatedOnSubChannel = async (message) => {
23561
+ /* end_public_function */
23562
+
23563
+ /* begin_public_function
23564
+ id: invitation.cancel
23565
+ */
23566
+ /**
23567
+ * ```js
23568
+ * import { cancelInvitation } from '@amityco/ts-sdk'
23569
+ * const isCanceled = await cancelInvitation(invitationId)
23570
+ * ```
23571
+ *
23572
+ * Cancels a {@link Amity.Invitation} object
23573
+ *
23574
+ * @param invitationId the {@link Amity.Invitation} to cancel
23575
+ * @returns A success boolean if the {@link Amity.Invitation} was canceled
23576
+ *
23577
+ * @category Invitation API
23578
+ * @async
23579
+ */
23580
+ const cancelInvitation = async (invitationId) => {
23089
23581
  var _a;
23090
- const { channelId, messageId: messagePreviewId, creatorId, createdAt, updatedAt, data, dataType, subChannelId, channelSegment: segment, isDeleted, } = message;
23091
- const messagePreviewSubChannelCache = (_a = pullFromCache([
23092
- 'messagePreviewSubChannel',
23582
+ const client = getActiveClient();
23583
+ client.log('invitation/cancelInvitation', invitationId);
23584
+ const { data } = await client.http.delete(`/api/v1/invitations/${invitationId}`);
23585
+ const invitation = (_a = pullFromCache([
23586
+ 'invitation',
23093
23587
  'get',
23094
- message.subChannelId,
23588
+ invitationId,
23095
23589
  ])) === null || _a === void 0 ? void 0 : _a.data;
23096
- // if messagePreviewSubChannel is not exist, ignore the message.
23097
- if (messagePreviewSubChannelCache &&
23098
- messagePreviewSubChannelCache.messagePreviewId === message.messageId) {
23099
- const subChannelCache = await getSubChannelCache(subChannelId);
23100
- pushToCache(['messagePreviewSubChannel', 'get', message.subChannelId], {
23101
- channelId,
23102
- creatorId,
23103
- messagePreviewId,
23104
- createdAt,
23105
- updatedAt,
23106
- subChannelId,
23107
- data,
23108
- dataType,
23109
- segment,
23110
- isDeleted,
23111
- subChannelUpdatedAt: subChannelCache.updatedAt,
23112
- subChannelName: messagePreviewSubChannelCache.subChannelName,
23113
- });
23590
+ if (invitation) {
23591
+ dropFromCache(['invitation', 'get', invitationId]);
23592
+ fireEvent('local.invitation.deleted', [invitation]);
23114
23593
  }
23594
+ return data.success;
23115
23595
  };
23116
- const handleMessageCreated = async (message) => {
23117
- const { channelId, messageId: messagePreviewId, creatorId, createdAt, updatedAt, data, dataType, subChannelId, channelSegment: segment, isDeleted, } = message;
23118
- if (isLastestMessageOnChannel(message)) {
23119
- const subChannelCache = await getSubChannelCache(subChannelId);
23120
- pushToCache(['messagePreviewChannel', 'get', message.channelId], {
23121
- channelId,
23122
- creatorId,
23123
- messagePreviewId,
23124
- createdAt,
23125
- updatedAt,
23126
- subChannelId,
23127
- data,
23128
- dataType,
23129
- segment,
23130
- isDeleted,
23131
- subChannelUpdatedAt: subChannelCache === null || subChannelCache === void 0 ? void 0 : subChannelCache.updatedAt,
23132
- subChannelName: subChannelCache === null || subChannelCache === void 0 ? void 0 : subChannelCache.displayName,
23133
- });
23596
+ /* end_public_function */
23597
+
23598
+ var InvitationActionsEnum;
23599
+ (function (InvitationActionsEnum) {
23600
+ InvitationActionsEnum["OnLocalInvitationCreated"] = "onLocalInvitationCreated";
23601
+ InvitationActionsEnum["OnLocalInvitationUpdated"] = "onLocalInvitationUpdated";
23602
+ InvitationActionsEnum["OnLocalInvitationDeleted"] = "onLocalInvitationDeleted";
23603
+ })(InvitationActionsEnum || (InvitationActionsEnum = {}));
23604
+
23605
+ const invitationLinkedObject = (invitation) => {
23606
+ return Object.assign(Object.assign({}, invitation), { get user() {
23607
+ const cacheData = pullFromCache(['user', 'get', invitation.userId]);
23608
+ if (cacheData === null || cacheData === void 0 ? void 0 : cacheData.data)
23609
+ return userLinkedObject(cacheData.data);
23610
+ return undefined;
23611
+ },
23612
+ get createdBy() {
23613
+ const cacheData = pullFromCache(['user', 'get', invitation.createdById]);
23614
+ if (cacheData === null || cacheData === void 0 ? void 0 : cacheData.data)
23615
+ return userLinkedObject(cacheData.data);
23616
+ return undefined;
23617
+ },
23618
+ get target() {
23619
+ if (invitation.targetType === 'community') {
23620
+ const cacheData = pullFromCache([
23621
+ 'community',
23622
+ 'get',
23623
+ invitation.targetId,
23624
+ ]);
23625
+ if (cacheData === null || cacheData === void 0 ? void 0 : cacheData.data)
23626
+ return cacheData.data;
23627
+ return undefined;
23628
+ }
23629
+ return undefined;
23630
+ }, accept: async () => {
23631
+ await acceptInvitation(invitation._id);
23632
+ }, reject: async () => {
23633
+ await rejectInvitation(invitation._id);
23634
+ }, cancel: async () => {
23635
+ await cancelInvitation(invitation._id);
23636
+ } });
23637
+ };
23638
+
23639
+ class PaginationController {
23640
+ constructor(queryParams) {
23641
+ const { http } = getActiveClient();
23642
+ this.queryParams = queryParams;
23643
+ this.http = http;
23134
23644
  }
23135
- };
23136
- const handleMessageUpdated = async (message) => {
23137
- /**
23138
- * Channel Case
23139
- */
23140
- var _a;
23141
- const { channelId, messageId: messagePreviewId, creatorId, createdAt, updatedAt, data, dataType, subChannelId, channelSegment: segment, isDeleted, } = message;
23142
- const messagePreviewChannelCache = (_a = pullFromCache([
23143
- 'messagePreviewChannel',
23144
- 'get',
23145
- message.channelId,
23146
- ])) === null || _a === void 0 ? void 0 : _a.data;
23147
- if (messagePreviewChannelCache &&
23148
- messagePreviewChannelCache.messagePreviewId === message.messageId) {
23149
- const subChannelCache = await getSubChannelCache(subChannelId);
23150
- pushToCache(['messagePreviewChannel', 'get', message.channelId], {
23151
- channelId,
23152
- creatorId,
23153
- messagePreviewId,
23154
- createdAt,
23155
- updatedAt,
23156
- subChannelId,
23157
- data,
23158
- dataType,
23159
- segment,
23160
- isDeleted,
23161
- subChannelUpdatedAt: subChannelCache.updatedAt,
23162
- subChannelName: messagePreviewChannelCache.subChannelName,
23163
- });
23645
+ loadFirstPage() {
23646
+ return this.onFetch("first" /* Amity.LiveCollectionPageDirection.FIRST */);
23164
23647
  }
23165
- };
23166
- const handleSubChannelUpdated = async (subChannel) => {
23167
- var _a, _b, _c, _d;
23168
- const { channelId, subChannelId } = subChannel;
23169
- /** Channel Case */
23170
- const messagePreviewChannelCache = (_a = pullFromCache([
23171
- 'messagePreviewChannel',
23172
- 'get',
23173
- channelId,
23174
- ])) === null || _a === void 0 ? void 0 : _a.data;
23175
- if ((messagePreviewChannelCache === null || messagePreviewChannelCache === void 0 ? void 0 : messagePreviewChannelCache.subChannelId) === subChannelId) {
23176
- const subChannelCache = (_b = pullFromCache([
23177
- 'subChannel',
23178
- 'get',
23179
- subChannelId,
23180
- ])) === null || _b === void 0 ? void 0 : _b.data;
23181
- 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 }));
23648
+ loadNextPage() {
23649
+ return this.onFetch("next" /* Amity.LiveCollectionPageDirection.NEXT */);
23182
23650
  }
23183
- /** SubChannel Case */
23184
- const messagePreviewSubChannelCache = (_c = pullFromCache([
23185
- 'messagePreviewSubChannel',
23186
- 'get',
23187
- subChannelId,
23188
- ])) === null || _c === void 0 ? void 0 : _c.data;
23189
- if (messagePreviewSubChannelCache &&
23190
- new Date(messagePreviewSubChannelCache.updatedAt).valueOf() >
23191
- new Date(subChannel.updatedAt).valueOf()) {
23192
- const subChannelCache = (_d = pullFromCache([
23193
- 'subChannel',
23194
- 'get',
23195
- subChannelId,
23196
- ])) === null || _d === void 0 ? void 0 : _d.data;
23197
- 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 }));
23651
+ loadPreviousPage() {
23652
+ return this.onFetch("prev" /* Amity.LiveCollectionPageDirection.PREV */);
23198
23653
  }
23199
- };
23654
+ async onFetch(direction = "first" /* Amity.LiveCollectionPageDirection.FIRST */) {
23655
+ var _a, _b, _c, _d;
23656
+ if (direction === 'prev' && !this.previousToken)
23657
+ return;
23658
+ if (direction === 'next' && !this.nextToken)
23659
+ return;
23660
+ let token;
23661
+ if (direction === 'prev')
23662
+ token = this.previousToken;
23663
+ if (direction === 'next')
23664
+ token = this.nextToken;
23665
+ const queryResponse = await this.getRequest(this.queryParams, token);
23666
+ if (direction === 'first') {
23667
+ this.nextToken = (_a = queryResponse.paging) === null || _a === void 0 ? void 0 : _a.next;
23668
+ this.previousToken = (_b = queryResponse.paging) === null || _b === void 0 ? void 0 : _b.previous;
23669
+ }
23670
+ if (direction === 'prev')
23671
+ this.previousToken = (_c = queryResponse.paging) === null || _c === void 0 ? void 0 : _c.previous;
23672
+ if (direction === 'next')
23673
+ this.nextToken = (_d = queryResponse.paging) === null || _d === void 0 ? void 0 : _d.next;
23674
+ return queryResponse;
23675
+ }
23676
+ getNextToken() {
23677
+ return this.nextToken;
23678
+ }
23679
+ getPrevToken() {
23680
+ return this.previousToken;
23681
+ }
23682
+ }
23200
23683
 
23201
- function convertRawUserToInternalUser(rawUser) {
23202
- return Object.assign(Object.assign({}, rawUser), { isGlobalBanned: (rawUser === null || rawUser === void 0 ? void 0 : rawUser.isGlobalBan) || false });
23684
+ class InvitationsPaginationController extends PaginationController {
23685
+ async getRequest(queryParams, token) {
23686
+ const { limit = COLLECTION_DEFAULT_PAGINATION_LIMIT } = queryParams, params = __rest(queryParams, ["limit"]);
23687
+ const options = token ? { token } : { limit };
23688
+ const { data } = await this.http.get(`/api/v1/invitations`, { params: Object.assign(Object.assign({}, params), { options }) });
23689
+ return data;
23690
+ }
23203
23691
  }
23204
23692
 
23205
- const MARKER_INCLUDED_CHANNEL_TYPE = ['broadcast', 'conversation', 'community'];
23206
- const isUnreadCountSupport = ({ type }) => MARKER_INCLUDED_CHANNEL_TYPE.includes(type);
23207
- function convertFromRaw(channel, options = { isMessagePreviewUpdated: true }) {
23208
- var _a;
23209
- let { messagePreviewId } = channel;
23210
- const messagePreviewChannelCache = (_a = pullFromCache([
23211
- 'messagePreviewChannel',
23212
- 'get',
23213
- channel.channelId,
23214
- ])) === null || _a === void 0 ? void 0 : _a.data;
23215
- if ((messagePreviewChannelCache === null || messagePreviewChannelCache === void 0 ? void 0 : messagePreviewChannelCache.messagePreviewId) && !options.isMessagePreviewUpdated) {
23216
- messagePreviewId = messagePreviewChannelCache.messagePreviewId;
23693
+ class QueryStreamController {
23694
+ constructor(query, cacheKey) {
23695
+ this.query = query;
23696
+ this.cacheKey = cacheKey;
23217
23697
  }
23218
- return Object.assign(Object.assign({}, channel), { defaultSubChannelId: channel.channelInternalId, isUnreadCountSupport: isUnreadCountSupport(channel), messagePreviewId });
23698
+ }
23699
+
23700
+ class InvitationsQueryStreamController extends QueryStreamController {
23701
+ constructor(query, cacheKey, notifyChange, preparePayload) {
23702
+ super(query, cacheKey);
23703
+ this.notifyChange = notifyChange;
23704
+ this.preparePayload = preparePayload;
23705
+ }
23706
+ async saveToMainDB(response) {
23707
+ const processedPayload = await this.preparePayload(response);
23708
+ const client = getActiveClient();
23709
+ const cachedAt = client.cache && Date.now();
23710
+ if (client.cache) {
23711
+ ingestInCache(processedPayload, { cachedAt });
23712
+ }
23713
+ }
23714
+ appendToQueryStream(response, direction, refresh = false) {
23715
+ var _a, _b;
23716
+ if (refresh) {
23717
+ pushToCache(this.cacheKey, {
23718
+ data: response.invitations.map(getResolver('invitation')),
23719
+ });
23720
+ }
23721
+ else {
23722
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
23723
+ const invitations = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
23724
+ pushToCache(this.cacheKey, Object.assign(Object.assign({}, collection), { data: [
23725
+ ...new Set([...invitations, ...response.invitations.map(getResolver('invitation'))]),
23726
+ ] }));
23727
+ }
23728
+ }
23729
+ reactor(action) {
23730
+ return (invitations) => {
23731
+ var _a;
23732
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
23733
+ if (!collection)
23734
+ return;
23735
+ if (action === InvitationActionsEnum.OnLocalInvitationUpdated) {
23736
+ const isExist = collection.data.find(id => id === invitations[0].invitationId);
23737
+ if (!isExist)
23738
+ return;
23739
+ }
23740
+ if (action === InvitationActionsEnum.OnLocalInvitationCreated) {
23741
+ collection.data = [
23742
+ ...new Set([
23743
+ ...invitations.map(invitation => invitation.invitationId),
23744
+ ...collection.data,
23745
+ ]),
23746
+ ];
23747
+ }
23748
+ if (action === InvitationActionsEnum.OnLocalInvitationDeleted) {
23749
+ collection.data = collection.data.filter(id => id !== invitations[0].invitationId);
23750
+ }
23751
+ pushToCache(this.cacheKey, collection);
23752
+ this.notifyChange({ origin: "event" /* Amity.LiveDataOrigin.EVENT */, loading: false });
23753
+ };
23754
+ }
23755
+ subscribeRTE(createSubscriber) {
23756
+ return createSubscriber.map(subscriber => subscriber.fn(this.reactor(subscriber.action)));
23757
+ }
23758
+ }
23759
+
23760
+ function isObject(value) {
23761
+ return typeof value === 'object' && value !== null;
23219
23762
  }
23220
- const preUpdateChannelCache = (rawPayload, options = { isMessagePreviewUpdated: true }) => {
23221
- ingestInCache({
23222
- channels: rawPayload.channels.map(channel => convertFromRaw(channel, { isMessagePreviewUpdated: options.isMessagePreviewUpdated })),
23763
+ /**
23764
+ * convert all object getter property to static value
23765
+ */
23766
+ const convertGetterPropsToStatic = (obj) => {
23767
+ if (!isObject(obj)) {
23768
+ return obj;
23769
+ }
23770
+ const entries = Object.entries(obj).map(([key, value]) => {
23771
+ const descriptor = Object.getOwnPropertyDescriptor(obj, key);
23772
+ if (typeof (descriptor === null || descriptor === void 0 ? void 0 : descriptor.get) === 'function') {
23773
+ return [key, descriptor.get.call(obj)];
23774
+ }
23775
+ return [key, value];
23223
23776
  });
23777
+ return Object.fromEntries(entries);
23224
23778
  };
23225
- const updateChannelUnread = ({ currentUserId, channels, channelUsers, }) => {
23226
- for (let i = 0; i < channels.length; i += 1) {
23227
- const cacheKey = ['channelUnread', 'get', channels[i].channelId];
23228
- const channelUser = channelUsers.find(channelUser => channelUser.channelId === channels[i].channelId && channelUser.userId === currentUserId);
23229
- let unreadCount = 0;
23230
- let readToSegment = null;
23231
- let lastMentionedSegment = null;
23232
- let isMentioned = false;
23233
- if (channelUser) {
23234
- readToSegment = channelUser.readToSegment;
23235
- lastMentionedSegment = channelUser.lastMentionedSegment;
23236
- unreadCount = Math.max(channels[i].messageCount - readToSegment, 0);
23237
- isMentioned = lastMentionedSegment > readToSegment;
23779
+ const removeFunctionProperties = (obj) => {
23780
+ if (!isObject(obj)) {
23781
+ return obj;
23782
+ }
23783
+ const entries = Object.entries(obj).map(([key, value]) => {
23784
+ if (typeof value === 'function') {
23785
+ return [key, undefined];
23238
23786
  }
23239
- const cacheChannelUnread = {
23240
- channelId: channels[i].channelId,
23241
- lastSegment: channels[i].messageCount,
23242
- readToSegment,
23243
- lastMentionedSegment,
23244
- unreadCount,
23245
- isMentioned,
23246
- isDeleted: channels[i].isDeleted || false,
23247
- };
23248
- pushToCache(cacheKey, cacheChannelUnread);
23787
+ return [key, value];
23788
+ });
23789
+ return Object.fromEntries(entries);
23790
+ };
23791
+
23792
+ class PaginationNoPageController {
23793
+ constructor(queryParams) {
23794
+ const { http } = getActiveClient();
23795
+ this.queryParams = queryParams;
23796
+ this.http = http;
23249
23797
  }
23250
- };
23251
- const prepareChannelPayload = async (rawPayload, options = { isMessagePreviewUpdated: true }) => {
23252
- const client = getActiveClient();
23253
- const networkPreviewSetting = await client.getMessagePreviewSetting(false);
23254
- if (options.isMessagePreviewUpdated &&
23255
- networkPreviewSetting !== "no-message-preview" /* Amity.MessagePreviewSetting.NO_MESSAGE_PREVIEW */ &&
23256
- rawPayload.messagePreviews &&
23257
- rawPayload.messagePreviews.length > 0) {
23258
- updateChannelMessagePreviewCache(rawPayload);
23798
+ async onFetch() {
23799
+ const queryResponse = await this.getRequest(this.queryParams);
23800
+ return queryResponse;
23259
23801
  }
23260
- if (client.useLegacyUnreadCount) {
23261
- updateChannelUnread({
23262
- channels: rawPayload.channels,
23263
- channelUsers: rawPayload.channelUsers,
23264
- currentUserId: client.userId,
23265
- });
23802
+ }
23803
+
23804
+ class LiveCollectionController {
23805
+ constructor(paginationController, queryStreamId, cacheKey, callback) {
23806
+ this.paginationController = paginationController;
23807
+ this.queryStreamId = queryStreamId;
23808
+ this.cacheKey = cacheKey;
23809
+ this.callback = callback;
23266
23810
  }
23267
- else {
23268
- const markerIds = rawPayload.channels
23269
- // filter channel by type. Only conversation, community and broadcast type are included.
23270
- .filter(isUnreadCountSupport)
23271
- .map(({ channelInternalId }) => channelInternalId);
23272
- if (markerIds.length > 0) {
23273
- // since the get markers method requires a channel cache to function with the reducer.
23274
- preUpdateChannelCache(rawPayload, {
23275
- isMessagePreviewUpdated: options.isMessagePreviewUpdated,
23276
- });
23277
- try {
23278
- await getChannelMarkers(markerIds);
23811
+ async refresh() {
23812
+ try {
23813
+ let result;
23814
+ if (this.paginationController instanceof PaginationNoPageController) {
23815
+ result = await this.paginationController.onFetch();
23279
23816
  }
23280
- catch (e) {
23281
- // empty block (from the spec, allow marker fetch to fail without having to do anything)
23817
+ else {
23818
+ result = await this.paginationController.loadFirstPage();
23282
23819
  }
23820
+ if (!result)
23821
+ return;
23822
+ await this.persistModel(result);
23823
+ this.persistQueryStream({
23824
+ response: result,
23825
+ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */,
23826
+ refresh: true,
23827
+ });
23828
+ this.notifyChange({ origin: "server" /* Amity.LiveDataOrigin.SERVER */, loading: false });
23829
+ }
23830
+ catch (e) {
23831
+ this.notifyChange({ origin: "server" /* Amity.LiveDataOrigin.SERVER */, loading: false, error: e });
23832
+ }
23833
+ }
23834
+ loadPage({ initial = false, direction = "next" /* Amity.LiveCollectionPageDirection.NEXT */, }) {
23835
+ this.setup();
23836
+ this.notifyChange({ origin: "local" /* Amity.LiveDataOrigin.LOCAL */, loading: true });
23837
+ if (initial) {
23838
+ this.refresh();
23839
+ }
23840
+ else if (direction === "prev" /* Amity.LiveCollectionPageDirection.PREV */) {
23841
+ this.loadPrevPage();
23842
+ }
23843
+ else if (direction === "next" /* Amity.LiveCollectionPageDirection.NEXT */) {
23844
+ this.loadNextPage();
23845
+ }
23846
+ }
23847
+ async loadNextPage() {
23848
+ try {
23849
+ if (this.paginationController instanceof PaginationNoPageController)
23850
+ return;
23851
+ const result = await this.paginationController.loadNextPage();
23852
+ if (!result)
23853
+ return;
23854
+ await this.persistModel(result);
23855
+ this.persistQueryStream({
23856
+ response: result,
23857
+ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */,
23858
+ });
23859
+ this.notifyChange({ origin: "server" /* Amity.LiveDataOrigin.SERVER */, loading: false });
23860
+ }
23861
+ catch (e) {
23862
+ this.notifyChange({ origin: "server" /* Amity.LiveDataOrigin.SERVER */, loading: false, error: e });
23863
+ }
23864
+ }
23865
+ async loadPrevPage() {
23866
+ try {
23867
+ if (this.paginationController instanceof PaginationNoPageController)
23868
+ return;
23869
+ const result = await this.paginationController.loadPreviousPage();
23870
+ if (!result)
23871
+ return;
23872
+ await this.persistModel(result);
23873
+ this.persistQueryStream({
23874
+ response: result,
23875
+ direction: "prev" /* Amity.LiveCollectionPageDirection.PREV */,
23876
+ });
23877
+ this.notifyChange({ origin: "server" /* Amity.LiveDataOrigin.SERVER */, loading: false });
23878
+ }
23879
+ catch (e) {
23880
+ this.notifyChange({ origin: "server" /* Amity.LiveDataOrigin.SERVER */, loading: false, error: e });
23283
23881
  }
23284
23882
  }
23285
- // convert raw channel to internal channel
23286
- const channels = rawPayload.channels.map(payload => convertFromRaw(payload, { isMessagePreviewUpdated: options.isMessagePreviewUpdated }));
23287
- // convert raw channel user to membership (add user object)
23288
- const channelUsers = rawPayload.channelUsers.map(channelUser => {
23289
- return convertRawMembershipToMembership(channelUser);
23290
- });
23291
- const users = rawPayload.users.map(convertRawUserToInternalUser);
23292
- const restRawPayload = __rest(rawPayload, ["messageFeedsInfo", "messagePreviews"]);
23293
- return Object.assign(Object.assign({}, restRawPayload), { users,
23294
- channels,
23295
- channelUsers });
23296
- };
23883
+ shouldNotify(data) {
23884
+ const newData = data.map(convertGetterPropsToStatic).map(removeFunctionProperties);
23885
+ if (isEqual(this.snapshot, newData))
23886
+ return false;
23887
+ this.snapshot = newData;
23888
+ return true;
23889
+ }
23890
+ getCacheKey() {
23891
+ return this.cacheKey;
23892
+ }
23893
+ }
23297
23894
 
23298
23895
  /**
23299
23896
  * ```js
23300
- * import { getSubChannelMarkers } from '@amityco/ts-sdk'
23301
- * const subChannelMarkers = await getSubChannelMarkers(['sch1', 'sch2'])
23897
+ * import { onLocalInvitationCreated } from '@amityco/ts-sdk'
23898
+ * const dispose = onLocalInvitationCreated(data => {
23899
+ * // ...
23900
+ * })
23302
23901
  * ```
23303
23902
  *
23304
- * Fetches a paginable list of {@link Amity.SubChannelMarker} objects
23903
+ * Fired when an {@link Amity.InvitationPayload} has been created
23305
23904
  *
23306
- * @param messageFeedIds the feed IDs of the {@link Amity.RawSubChannel} marker to fetch
23307
- * @param page
23308
- * @returns A page of {@link Amity.SubChannelMarker} objects
23905
+ * @param callback The function to call when the event was fired
23906
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
23309
23907
  *
23310
- * @category Channel API
23311
- * @async
23312
- * @private
23908
+ * @category Invitation Events
23313
23909
  */
23314
- const getUserMessageFeedMakers = async (channelIds) => {
23910
+ const onLocalInvitationCreated = (callback) => {
23315
23911
  const client = getActiveClient();
23316
- client.log('channel/getUserMessageFeedMakers', channelIds);
23317
- const { data } = await client.http.get(`/api/v1/markers/user-message-feed`, {
23318
- params: {
23319
- channelIds,
23320
- },
23321
- });
23322
- fireEvent('local.userMessageFeedMarker.fetched', { userMessageFeedMarker: data });
23323
- return data;
23912
+ const disposers = [
23913
+ createEventSubscriber(client, 'onLocalInvitationCreated', 'local.invitation.created', payload => callback(payload)),
23914
+ ];
23915
+ return () => {
23916
+ disposers.forEach(fn => fn());
23917
+ };
23324
23918
  };
23325
23919
 
23326
- const prepareUnreadCountInfo = async (rawPayload) => {
23920
+ /**
23921
+ * ```js
23922
+ * import { onLocalInvitationUpdated } from '@amityco/ts-sdk'
23923
+ * const dispose = onLocalInvitationUpdated(data => {
23924
+ * // ...
23925
+ * })
23926
+ * ```
23927
+ *
23928
+ * Fired when an {@link Amity.InvitationPayload} has been updated
23929
+ *
23930
+ * @param callback The function to call when the event was fired
23931
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
23932
+ *
23933
+ * @category Invitation Events
23934
+ */
23935
+ const onLocalInvitationUpdated = (callback) => {
23327
23936
  const client = getActiveClient();
23328
- // if consistent mode is enabled, persist the unread count info to the cache
23329
- // Marker service API uses channelInternalId as channelId
23330
- const queryPayload = await getUserMessageFeedMakers(rawPayload.channels.map(({ channelInternalId }) => channelInternalId));
23331
- const { feedMarkers, userFeedMarkers } = queryPayload;
23332
- persistUnreadCountInfo({
23333
- feedMarkers,
23334
- userFeedMarkers,
23335
- });
23336
- client.log('channel/prepareUnreadCountInfo', rawPayload.channels);
23937
+ const disposers = [
23938
+ createEventSubscriber(client, 'onLocalInvitationUpdated', 'local.invitation.updated', payload => callback(payload)),
23939
+ ];
23940
+ return () => {
23941
+ disposers.forEach(fn => fn());
23942
+ };
23337
23943
  };
23338
23944
 
23339
- const getCachedMarker$1 = (entityId) => {
23340
- var _a;
23341
- const key = {
23342
- entityId,
23343
- userId: getActiveUser()._id,
23344
- };
23345
- return (_a = pullFromCache([
23346
- 'channelMarker',
23347
- 'get',
23348
- getResolver('channelMarker')(key),
23349
- ])) === null || _a === void 0 ? void 0 : _a.data;
23350
- };
23351
- const getUnreadInfoCached$1 = (channelId) => {
23352
- var _a;
23353
- return (_a = pullFromCache(['channelUnreadInfo', 'get', channelId])) === null || _a === void 0 ? void 0 : _a.data;
23354
- };
23355
23945
  /**
23356
- * The function use to get value of hasMentioned or isMentioned field.
23357
- * function will get the value from marker params first, if there is no hasMentioned field, will look in to the cache.
23946
+ * ```js
23947
+ * import { onLocalInvitationDeleted } from '@amityco/ts-sdk'
23948
+ * const dispose = onLocalInvitationDeleted(data => {
23949
+ * // ...
23950
+ * })
23951
+ * ```
23358
23952
  *
23359
- * If consistent mode is enabled, the function will return the value from the channelUnreadCountInfo cache.
23360
- * If not, the function will return the value from the channelMarker cache.
23361
- * If not found in the both cache, use `false` as defaul value.
23953
+ * Fired when an {@link Amity.InvitationPayload} has been deleted
23954
+ *
23955
+ * @param callback The function to call when the event was fired
23956
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
23957
+ *
23958
+ * @category Invitation Events
23362
23959
  */
23363
- const getChannelIsMentioned = (channel, marker) => {
23364
- var _a, _b, _c, _d;
23960
+ const onLocalInvitationDeleted = (callback) => {
23365
23961
  const client = getActiveClient();
23366
- if (client.isUnreadCountEnabled && client.getMarkerSyncConsistentMode()) {
23367
- return (_b = (_a = getUnreadInfoCached$1(channel.channelPublicId)) === null || _a === void 0 ? void 0 : _a.isMentioned) !== null && _b !== void 0 ? _b : false;
23368
- }
23369
- return (marker === null || marker === void 0 ? void 0 : marker.hasMentioned) !== undefined
23370
- ? marker === null || marker === void 0 ? void 0 : marker.hasMentioned
23371
- : (_d = (_c = getCachedMarker$1(channel.channelPublicId)) === null || _c === void 0 ? void 0 : _c.hasMentioned) !== null && _d !== void 0 ? _d : false;
23962
+ const disposers = [
23963
+ createEventSubscriber(client, 'onLocalInvitationDeleted', 'local.invitation.deleted', payload => callback(payload)),
23964
+ ];
23965
+ return () => {
23966
+ disposers.forEach(fn => fn());
23967
+ };
23372
23968
  };
23373
23969
 
23374
- const getCachedMarker = (entityId) => {
23375
- var _a;
23376
- const key = {
23377
- entityId,
23378
- userId: getActiveUser()._id,
23379
- };
23380
- return (_a = pullFromCache([
23381
- 'channelMarker',
23382
- 'get',
23383
- getResolver('channelMarker')(key),
23384
- ])) === null || _a === void 0 ? void 0 : _a.data;
23385
- };
23386
- const getUnreadInfoCached = (channelId) => {
23387
- var _a;
23388
- return (_a = pullFromCache(['channelUnreadInfo', 'get', channelId])) === null || _a === void 0 ? void 0 : _a.data;
23389
- };
23970
+ class InvitationsLiveCollectionController extends LiveCollectionController {
23971
+ constructor(query, callback) {
23972
+ const queryStreamId = hash(query);
23973
+ const cacheKey = ['invitation', 'collection', queryStreamId];
23974
+ const paginationController = new InvitationsPaginationController(query);
23975
+ super(paginationController, queryStreamId, cacheKey, callback);
23976
+ this.query = query;
23977
+ this.queryStreamController = new InvitationsQueryStreamController(this.query, this.cacheKey, this.notifyChange.bind(this), prepareInvitationPayload);
23978
+ this.callback = callback.bind(this);
23979
+ this.loadPage({ initial: true });
23980
+ }
23981
+ setup() {
23982
+ var _a;
23983
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
23984
+ if (!collection) {
23985
+ pushToCache(this.cacheKey, {
23986
+ data: [],
23987
+ params: {},
23988
+ });
23989
+ }
23990
+ }
23991
+ async persistModel(queryPayload) {
23992
+ await this.queryStreamController.saveToMainDB(queryPayload);
23993
+ }
23994
+ persistQueryStream({ response, direction, refresh, }) {
23995
+ this.queryStreamController.appendToQueryStream(response, direction, refresh);
23996
+ }
23997
+ startSubscription() {
23998
+ return this.queryStreamController.subscribeRTE([
23999
+ {
24000
+ fn: onLocalInvitationCreated,
24001
+ action: InvitationActionsEnum.OnLocalInvitationCreated,
24002
+ },
24003
+ {
24004
+ fn: onLocalInvitationUpdated,
24005
+ action: InvitationActionsEnum.OnLocalInvitationUpdated,
24006
+ },
24007
+ {
24008
+ fn: onLocalInvitationDeleted,
24009
+ action: InvitationActionsEnum.OnLocalInvitationDeleted,
24010
+ },
24011
+ ]);
24012
+ }
24013
+ notifyChange({ origin, loading, error }) {
24014
+ var _a, _b;
24015
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
24016
+ if (!collection)
24017
+ return;
24018
+ const data = this.applyFilter((_b = collection.data
24019
+ .map(id => pullFromCache(['invitation', 'get', id]))
24020
+ .filter(isNonNullable)
24021
+ .map(({ data }) => invitationLinkedObject(data))) !== null && _b !== void 0 ? _b : []);
24022
+ if (!this.shouldNotify(data) && origin === 'event')
24023
+ return;
24024
+ this.callback({
24025
+ onNextPage: () => this.loadPage({ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */ }),
24026
+ data,
24027
+ hasNextPage: !!this.paginationController.getNextToken(),
24028
+ loading,
24029
+ error,
24030
+ });
24031
+ }
24032
+ applyFilter(data) {
24033
+ let invitations = data;
24034
+ if (this.query.targetId) {
24035
+ invitations = invitations.filter(invitation => invitation.targetId === this.query.targetId);
24036
+ }
24037
+ if (this.query.statuses) {
24038
+ invitations = invitations.filter(invitation => { var _a; return (_a = this.query.statuses) === null || _a === void 0 ? void 0 : _a.includes(invitation.status); });
24039
+ }
24040
+ if (this.query.targetType) {
24041
+ invitations = invitations.filter(invitation => invitation.targetType === this.query.targetType);
24042
+ }
24043
+ if (this.query.type) {
24044
+ invitations = invitations.filter(invitation => invitation.type === this.query.type);
24045
+ }
24046
+ const sortFn = (() => {
24047
+ switch (this.query.sortBy) {
24048
+ case 'firstCreated':
24049
+ return sortByFirstCreated;
24050
+ case 'lastCreated':
24051
+ return sortByLastCreated;
24052
+ default:
24053
+ return sortByLastCreated;
24054
+ }
24055
+ })();
24056
+ invitations = invitations.sort(sortFn);
24057
+ return invitations;
24058
+ }
24059
+ }
24060
+
23390
24061
  /**
23391
- * The function use to get value of unreadCount field.
23392
- * function will get the value from marker params first, if there is no hasMentioned field, will look in to the cache.
24062
+ * Get invitations
24063
+ *
24064
+ * @param params the query parameters
24065
+ * @param callback the callback to be called when the invitations are updated
24066
+ * @returns invitations
24067
+ *
24068
+ * @category Invitation Live Collection
23393
24069
  *
23394
- * If consistent mode is enabled, the function will return the value from the channelUnreadCountInfo cache.
23395
- * If not, the function will return the value from the channelMarker cache.
23396
- * If not found in the both cache, use `0` as defaul value.
23397
24070
  */
23398
- const getSubChannelsUnreadCount = (channel, marker) => {
23399
- var _a, _b, _c, _d, _e;
23400
- const client = getActiveClient();
23401
- if (client.isUnreadCountEnabled && client.getMarkerSyncConsistentMode()) {
23402
- // Marker service API uses channelInternalId as channelId
23403
- return (_b = (_a = getUnreadInfoCached(channel.channelInternalId)) === null || _a === void 0 ? void 0 : _a.unreadCount) !== null && _b !== void 0 ? _b : 0;
23404
- }
23405
- if (marker === null || marker === void 0 ? void 0 : marker.isDeleted) {
23406
- // NOTE: This is a temporary solution to handle the channel marker when the user is forced to
23407
- // leave the channel because currently backend can't handle this, so every time a user is banned
23408
- // from a channel or the channel is deleted the channel's unread count will reset to zero
23409
- return 0;
24071
+ const getInvitations = (params, callback, config) => {
24072
+ const { log, cache } = getActiveClient();
24073
+ if (!cache) {
24074
+ console.log(ENABLE_CACHE_MESSAGE);
23410
24075
  }
23411
- 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;
24076
+ const timestamp = Date.now();
24077
+ log(`getInvitations: (tmpid: ${timestamp}) > listen`);
24078
+ const invitationsLiveCollection = new InvitationsLiveCollectionController(params, callback);
24079
+ const disposers = invitationsLiveCollection.startSubscription();
24080
+ const cacheKey = invitationsLiveCollection.getCacheKey();
24081
+ disposers.push(() => {
24082
+ dropFromCache(cacheKey);
24083
+ });
24084
+ return () => {
24085
+ log(`getInvitations (tmpid: ${timestamp}) > dispose`);
24086
+ disposers.forEach(fn => fn());
24087
+ };
23412
24088
  };
23413
24089
 
23414
- const getLegacyChannelUnread = (channelId) => {
23415
- var _a;
23416
- return (_a = pullFromCache(['channelUnread', 'get', channelId])) === null || _a === void 0 ? void 0 : _a.data;
24090
+ const communityLinkedObject = (community) => {
24091
+ return Object.assign(Object.assign({}, community), { createInvitations: async (userIds) => {
24092
+ await createInvitations({
24093
+ type: "communityMemberInvite" /* InvitationTypeEnum.CommunityMemberInvite */,
24094
+ targetType: 'community',
24095
+ targetId: community.communityId,
24096
+ userIds,
24097
+ });
24098
+ }, getMemberInvitations: (callback) => {
24099
+ return getInvitations({
24100
+ targetId: community.communityId,
24101
+ targetType: 'community',
24102
+ type: "communityMemberInvite" /* InvitationTypeEnum.CommunityMemberInvite */,
24103
+ }, callback);
24104
+ } });
23417
24105
  };
23418
24106
 
23419
- const constructChannelDynamicValue = (channel) => {
23420
- const client = getActiveClient();
23421
- const rest = __rest(channel, ["messageCount"]);
23422
- return shallowClone(rest, {
23423
- get unreadCount() {
23424
- var _a, _b;
23425
- return (_b = (_a = getLegacyChannelUnread(rest.channelId)) === null || _a === void 0 ? void 0 : _a.unreadCount) !== null && _b !== void 0 ? _b : 0;
23426
- },
23427
- get subChannelsUnreadCount() {
23428
- return getSubChannelsUnreadCount(rest);
23429
- },
23430
- get isMentioned() {
23431
- var _a, _b;
23432
- if (client.useLegacyUnreadCount)
23433
- return (_b = (_a = getLegacyChannelUnread(rest.channelId)) === null || _a === void 0 ? void 0 : _a.isMentioned) !== null && _b !== void 0 ? _b : false;
23434
- return getChannelIsMentioned(rest);
23435
- },
23436
- });
24107
+ const LinkedObject = {
24108
+ ad: adLinkedObject,
24109
+ comment: commentLinkedObject,
24110
+ post: postLinkedObject,
24111
+ user: userLinkedObject,
24112
+ category: categoryLinkedObject,
24113
+ stream: streamLinkedObject,
24114
+ story: storyLinkedObject,
24115
+ storyTarget: storyTargetLinkedObject,
24116
+ message: messageLinkedObject,
24117
+ reactor: reactorLinkedObject,
24118
+ channel: channelLinkedObject,
24119
+ pinnedPost: pinnedPostLinkedObject,
24120
+ notificationTray: notificationTrayLinkedObject,
24121
+ community: communityLinkedObject,
24122
+ invitation: invitationLinkedObject,
23437
24123
  };
23438
24124
 
23439
24125
  const constructChannelObject = (channel) => {
@@ -26155,38 +26841,6 @@ const onMessageMarked = (callback) => {
26155
26841
  return createEventSubscriber(client, 'messageMarker/onMessageMarked', 'marker.marked-message', filter);
26156
26842
  };
26157
26843
 
26158
- function isObject(value) {
26159
- return typeof value === 'object' && value !== null;
26160
- }
26161
- /**
26162
- * convert all object getter property to static value
26163
- */
26164
- const convertGetterPropsToStatic = (obj) => {
26165
- if (!isObject(obj)) {
26166
- return obj;
26167
- }
26168
- const entries = Object.entries(obj).map(([key, value]) => {
26169
- const descriptor = Object.getOwnPropertyDescriptor(obj, key);
26170
- if (typeof (descriptor === null || descriptor === void 0 ? void 0 : descriptor.get) === 'function') {
26171
- return [key, descriptor.get.call(obj)];
26172
- }
26173
- return [key, value];
26174
- });
26175
- return Object.fromEntries(entries);
26176
- };
26177
- const removeFunctionProperties = (obj) => {
26178
- if (!isObject(obj)) {
26179
- return obj;
26180
- }
26181
- const entries = Object.entries(obj).map(([key, value]) => {
26182
- if (typeof value === 'function') {
26183
- return [key, undefined];
26184
- }
26185
- return [key, value];
26186
- });
26187
- return Object.fromEntries(entries);
26188
- };
26189
-
26190
26844
  /**
26191
26845
  *
26192
26846
  * ```js
@@ -26296,7 +26950,7 @@ const getUserUnread = (callback) => {
26296
26950
  };
26297
26951
  };
26298
26952
 
26299
- var index$m = /*#__PURE__*/Object.freeze({
26953
+ var index$n = /*#__PURE__*/Object.freeze({
26300
26954
  __proto__: null,
26301
26955
  getActiveClient: getActiveClient,
26302
26956
  getActiveUser: getActiveUser,
@@ -26800,51 +27454,6 @@ const onLocalFollowRequestAccepted = (callback) => createLocalFollowEventSubscri
26800
27454
 
26801
27455
  const onLocalFollowRequestDeclined = (callback) => createLocalFollowEventSubscriber('local.follow.requestDeclined', callback);
26802
27456
 
26803
- class PaginationController {
26804
- constructor(queryParams) {
26805
- const { http } = getActiveClient();
26806
- this.queryParams = queryParams;
26807
- this.http = http;
26808
- }
26809
- loadFirstPage() {
26810
- return this.onFetch("first" /* Amity.LiveCollectionPageDirection.FIRST */);
26811
- }
26812
- loadNextPage() {
26813
- return this.onFetch("next" /* Amity.LiveCollectionPageDirection.NEXT */);
26814
- }
26815
- loadPreviousPage() {
26816
- return this.onFetch("prev" /* Amity.LiveCollectionPageDirection.PREV */);
26817
- }
26818
- async onFetch(direction = "first" /* Amity.LiveCollectionPageDirection.FIRST */) {
26819
- var _a, _b, _c, _d;
26820
- if (direction === 'prev' && !this.previousToken)
26821
- return;
26822
- if (direction === 'next' && !this.nextToken)
26823
- return;
26824
- let token;
26825
- if (direction === 'prev')
26826
- token = this.previousToken;
26827
- if (direction === 'next')
26828
- token = this.nextToken;
26829
- const queryResponse = await this.getRequest(this.queryParams, token);
26830
- if (direction === 'first') {
26831
- this.nextToken = (_a = queryResponse.paging) === null || _a === void 0 ? void 0 : _a.next;
26832
- this.previousToken = (_b = queryResponse.paging) === null || _b === void 0 ? void 0 : _b.previous;
26833
- }
26834
- if (direction === 'prev')
26835
- this.previousToken = (_c = queryResponse.paging) === null || _c === void 0 ? void 0 : _c.previous;
26836
- if (direction === 'next')
26837
- this.nextToken = (_d = queryResponse.paging) === null || _d === void 0 ? void 0 : _d.next;
26838
- return queryResponse;
26839
- }
26840
- getNextToken() {
26841
- return this.nextToken;
26842
- }
26843
- getPrevToken() {
26844
- return this.previousToken;
26845
- }
26846
- }
26847
-
26848
27457
  class FollowerPaginationController extends PaginationController {
26849
27458
  async getRequest(queryParams, token) {
26850
27459
  const { limit = COLLECTION_DEFAULT_PAGINATION_LIMIT, userId } = queryParams, params = __rest(queryParams, ["limit", "userId"]);
@@ -26858,13 +27467,6 @@ class FollowerPaginationController extends PaginationController {
26858
27467
  }
26859
27468
  }
26860
27469
 
26861
- class QueryStreamController {
26862
- constructor(query, cacheKey) {
26863
- this.query = query;
26864
- this.cacheKey = cacheKey;
26865
- }
26866
- }
26867
-
26868
27470
  var EnumFollowActions;
26869
27471
  (function (EnumFollowActions) {
26870
27472
  EnumFollowActions["OnRequested"] = "onRequested";
@@ -26932,109 +27534,6 @@ class FollowerQueryStreamController extends QueryStreamController {
26932
27534
  }
26933
27535
  }
26934
27536
 
26935
- class PaginationNoPageController {
26936
- constructor(queryParams) {
26937
- const { http } = getActiveClient();
26938
- this.queryParams = queryParams;
26939
- this.http = http;
26940
- }
26941
- async onFetch() {
26942
- const queryResponse = await this.getRequest(this.queryParams);
26943
- return queryResponse;
26944
- }
26945
- }
26946
-
26947
- class LiveCollectionController {
26948
- constructor(paginationController, queryStreamId, cacheKey, callback) {
26949
- this.paginationController = paginationController;
26950
- this.queryStreamId = queryStreamId;
26951
- this.cacheKey = cacheKey;
26952
- this.callback = callback;
26953
- }
26954
- async refresh() {
26955
- try {
26956
- let result;
26957
- if (this.paginationController instanceof PaginationNoPageController) {
26958
- result = await this.paginationController.onFetch();
26959
- }
26960
- else {
26961
- result = await this.paginationController.loadFirstPage();
26962
- }
26963
- if (!result)
26964
- return;
26965
- await this.persistModel(result);
26966
- this.persistQueryStream({
26967
- response: result,
26968
- direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */,
26969
- refresh: true,
26970
- });
26971
- this.notifyChange({ origin: "server" /* Amity.LiveDataOrigin.SERVER */, loading: false });
26972
- }
26973
- catch (e) {
26974
- this.notifyChange({ origin: "server" /* Amity.LiveDataOrigin.SERVER */, loading: false, error: e });
26975
- }
26976
- }
26977
- loadPage({ initial = false, direction = "next" /* Amity.LiveCollectionPageDirection.NEXT */, }) {
26978
- this.setup();
26979
- this.notifyChange({ origin: "local" /* Amity.LiveDataOrigin.LOCAL */, loading: true });
26980
- if (initial) {
26981
- this.refresh();
26982
- }
26983
- else if (direction === "prev" /* Amity.LiveCollectionPageDirection.PREV */) {
26984
- this.loadPrevPage();
26985
- }
26986
- else if (direction === "next" /* Amity.LiveCollectionPageDirection.NEXT */) {
26987
- this.loadNextPage();
26988
- }
26989
- }
26990
- async loadNextPage() {
26991
- try {
26992
- if (this.paginationController instanceof PaginationNoPageController)
26993
- return;
26994
- const result = await this.paginationController.loadNextPage();
26995
- if (!result)
26996
- return;
26997
- await this.persistModel(result);
26998
- this.persistQueryStream({
26999
- response: result,
27000
- direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */,
27001
- });
27002
- this.notifyChange({ origin: "server" /* Amity.LiveDataOrigin.SERVER */, loading: false });
27003
- }
27004
- catch (e) {
27005
- this.notifyChange({ origin: "server" /* Amity.LiveDataOrigin.SERVER */, loading: false, error: e });
27006
- }
27007
- }
27008
- async loadPrevPage() {
27009
- try {
27010
- if (this.paginationController instanceof PaginationNoPageController)
27011
- return;
27012
- const result = await this.paginationController.loadPreviousPage();
27013
- if (!result)
27014
- return;
27015
- await this.persistModel(result);
27016
- this.persistQueryStream({
27017
- response: result,
27018
- direction: "prev" /* Amity.LiveCollectionPageDirection.PREV */,
27019
- });
27020
- this.notifyChange({ origin: "server" /* Amity.LiveDataOrigin.SERVER */, loading: false });
27021
- }
27022
- catch (e) {
27023
- this.notifyChange({ origin: "server" /* Amity.LiveDataOrigin.SERVER */, loading: false, error: e });
27024
- }
27025
- }
27026
- shouldNotify(data) {
27027
- const newData = data.map(convertGetterPropsToStatic).map(removeFunctionProperties);
27028
- if (isEqual(this.snapshot, newData))
27029
- return false;
27030
- this.snapshot = newData;
27031
- return true;
27032
- }
27033
- getCacheKey() {
27034
- return this.cacheKey;
27035
- }
27036
- }
27037
-
27038
27537
  const onFollowerUserDeleted = ({ userId }) => (callback) => {
27039
27538
  const client = getActiveClient();
27040
27539
  const filter = (data) => {
@@ -27503,7 +28002,7 @@ const getMyFollowInfo = (callback) => {
27503
28002
  };
27504
28003
  /* end_public_function */
27505
28004
 
27506
- var index$l = /*#__PURE__*/Object.freeze({
28005
+ var index$m = /*#__PURE__*/Object.freeze({
27507
28006
  __proto__: null,
27508
28007
  blockUser: blockUser,
27509
28008
  unBlockUser: unBlockUser,
@@ -28518,9 +29017,9 @@ var AmityUserSearchMatchType;
28518
29017
  AmityUserSearchMatchType["PARTIAL"] = "partial";
28519
29018
  })(AmityUserSearchMatchType || (AmityUserSearchMatchType = {}));
28520
29019
 
28521
- var index$k = /*#__PURE__*/Object.freeze({
29020
+ var index$l = /*#__PURE__*/Object.freeze({
28522
29021
  __proto__: null,
28523
- Relationship: index$l,
29022
+ Relationship: index$m,
28524
29023
  getUserByIds: getUserByIds,
28525
29024
  updateUser: updateUser,
28526
29025
  flagUser: flagUser,
@@ -28828,7 +29327,7 @@ const updateAltText = async (fileId, altText) => {
28828
29327
  };
28829
29328
  /* end_public_function */
28830
29329
 
28831
- var index$j = /*#__PURE__*/Object.freeze({
29330
+ var index$k = /*#__PURE__*/Object.freeze({
28832
29331
  __proto__: null,
28833
29332
  getFile: getFile,
28834
29333
  uploadFile: uploadFile,
@@ -29199,7 +29698,11 @@ function isCurrentUserPartOfCommunity(c, m) {
29199
29698
  */
29200
29699
  function updateMembershipStatus(communities, communityUsers) {
29201
29700
  return communities.map(c => {
29202
- const cachedCommunity = pullFromCache(['community', 'get', c.communityId]);
29701
+ const cachedCommunity = pullFromCache([
29702
+ 'community',
29703
+ 'get',
29704
+ c.communityId,
29705
+ ]);
29203
29706
  if ((cachedCommunity === null || cachedCommunity === void 0 ? void 0 : cachedCommunity.data) && (cachedCommunity === null || cachedCommunity === void 0 ? void 0 : cachedCommunity.data.hasOwnProperty('isJoined'))) {
29204
29707
  return Object.assign(Object.assign({}, cachedCommunity.data), c);
29205
29708
  }
@@ -30696,7 +31199,7 @@ const getReactions = (params, callback, config) => {
30696
31199
  };
30697
31200
  /* end_public_function */
30698
31201
 
30699
- var index$i = /*#__PURE__*/Object.freeze({
31202
+ var index$j = /*#__PURE__*/Object.freeze({
30700
31203
  __proto__: null,
30701
31204
  addReaction: addReaction,
30702
31205
  removeReaction: removeReaction,
@@ -32519,7 +33022,7 @@ const getMessages = (params, callback, config) => {
32519
33022
  };
32520
33023
  /* end_public_function */
32521
33024
 
32522
- var index$h = /*#__PURE__*/Object.freeze({
33025
+ var index$i = /*#__PURE__*/Object.freeze({
32523
33026
  __proto__: null,
32524
33027
  createMessage: createMessage,
32525
33028
  updateMessage: updateMessage,
@@ -33045,7 +33548,7 @@ const stopMessageReceiptSync = (subChannelId) => {
33045
33548
  };
33046
33549
  /* end_public_function */
33047
33550
 
33048
- var index$g = /*#__PURE__*/Object.freeze({
33551
+ var index$h = /*#__PURE__*/Object.freeze({
33049
33552
  __proto__: null,
33050
33553
  getSubChannelByIds: getSubChannels$1,
33051
33554
  createSubChannel: createSubChannel,
@@ -34359,7 +34862,7 @@ const searchMembers$1 = (params, callback, config) => {
34359
34862
  };
34360
34863
  /* end_public_function */
34361
34864
 
34362
- var index$f = /*#__PURE__*/Object.freeze({
34865
+ var index$g = /*#__PURE__*/Object.freeze({
34363
34866
  __proto__: null,
34364
34867
  addMembers: addMembers$1,
34365
34868
  removeMembers: removeMembers$1,
@@ -34562,7 +35065,7 @@ const unmuteMembers = async (channelId, userIds) => {
34562
35065
  };
34563
35066
  /* end_public_function */
34564
35067
 
34565
- var index$e = /*#__PURE__*/Object.freeze({
35068
+ var index$f = /*#__PURE__*/Object.freeze({
34566
35069
  __proto__: null,
34567
35070
  addRole: addRole,
34568
35071
  removeRole: removeRole,
@@ -34572,10 +35075,10 @@ var index$e = /*#__PURE__*/Object.freeze({
34572
35075
  unmuteMembers: unmuteMembers
34573
35076
  });
34574
35077
 
34575
- var index$d = /*#__PURE__*/Object.freeze({
35078
+ var index$e = /*#__PURE__*/Object.freeze({
34576
35079
  __proto__: null,
34577
- Membership: index$f,
34578
- Moderation: index$e,
35080
+ Membership: index$g,
35081
+ Moderation: index$f,
34579
35082
  getChannelByIds: getChannelByIds$1,
34580
35083
  createChannel: createChannel,
34581
35084
  updateChannel: updateChannel,
@@ -34629,12 +35132,15 @@ const saveCommunityUsers = (communities, communityUsers) => {
34629
35132
  * @category Community API
34630
35133
  * @async
34631
35134
  */
34632
- const getCommunities$1 = async (communityIds) => {
35135
+ const getCommunities$1 = async (communityIds, includeDiscoverablePrivateCommunity) => {
34633
35136
  const client = getActiveClient();
34634
35137
  client.log('community/getCommunities', communityIds);
34635
35138
  // API-FIX: endpoint should not be /list, parameters should be querystring.
34636
35139
  const { data: payload } = await client.http.get(`/api/v3/communities/list`, {
34637
- params: { communityIds },
35140
+ params: {
35141
+ communityIds,
35142
+ includeDiscoverablePrivateCommunity: includeDiscoverablePrivateCommunity !== null && includeDiscoverablePrivateCommunity !== void 0 ? includeDiscoverablePrivateCommunity : true,
35143
+ },
34638
35144
  });
34639
35145
  const data = prepareCommunityPayload(payload);
34640
35146
  const cachedAt = client.cache && Date.now();
@@ -34643,7 +35149,7 @@ const getCommunities$1 = async (communityIds) => {
34643
35149
  saveCommunityUsers(data.communities, data.communityUsers);
34644
35150
  }
34645
35151
  return {
34646
- data: data.communities,
35152
+ data: data.communities.map(community => LinkedObject.community(community)),
34647
35153
  cachedAt,
34648
35154
  };
34649
35155
  };
@@ -34685,7 +35191,7 @@ getCommunities$1.locally = (communityIds) => {
34685
35191
  /**
34686
35192
  * ```js
34687
35193
  * import { createCommunity } from '@amityco/ts-sdk'
34688
- * const created = await createCommunity({ communityId: 'foobar', displayName: 'foobar' })
35194
+ * const created = await createCommunity({ communityId: 'foobar', displayName: 'foobar', isDiscoverable: true, requiresJoinApproval: false })
34689
35195
  * ```
34690
35196
  *
34691
35197
  * Creates an {@link Amity.Community}
@@ -34709,7 +35215,7 @@ const createCommunity = async (bundle) => {
34709
35215
  }
34710
35216
  const { communities } = data;
34711
35217
  return {
34712
- data: communities[0],
35218
+ data: LinkedObject.community(communities[0]),
34713
35219
  cachedAt,
34714
35220
  };
34715
35221
  };
@@ -34721,7 +35227,7 @@ const createCommunity = async (bundle) => {
34721
35227
  /**
34722
35228
  * ```js
34723
35229
  * import { updateCommunity } from '@amityco/ts-sdk'
34724
- * const updated = await updateCommunity(communityId, { displayName: 'foobar' })
35230
+ * const updated = await updateCommunity(communityId, { displayName: 'foobar', isDiscoverable: true, requiresJoinApproval: false })
34725
35231
  * ```
34726
35232
  *
34727
35233
  * Updates an {@link Amity.Community}
@@ -34746,7 +35252,7 @@ const updateCommunity = async (communityId, patch) => {
34746
35252
  }
34747
35253
  const { communities } = data;
34748
35254
  return {
34749
- data: communities.find(community => community.communityId === communityId),
35255
+ data: LinkedObject.community(communities.find(community => community.communityId === communityId)),
34750
35256
  cachedAt,
34751
35257
  };
34752
35258
  };
@@ -34779,7 +35285,7 @@ const getCommunity$1 = async (communityId) => {
34779
35285
  }
34780
35286
  const { communities } = data;
34781
35287
  return {
34782
- data: communities.find(community => community.communityId === communityId),
35288
+ data: LinkedObject.community(communities.find(community => community.communityId === communityId)),
34783
35289
  cachedAt,
34784
35290
  };
34785
35291
  };
@@ -35955,7 +36461,7 @@ const searchMembers = (params, callback, config) => {
35955
36461
  };
35956
36462
  /* end_public_function */
35957
36463
 
35958
- var index$c = /*#__PURE__*/Object.freeze({
36464
+ var index$d = /*#__PURE__*/Object.freeze({
35959
36465
  __proto__: null,
35960
36466
  addMembers: addMembers,
35961
36467
  removeMembers: removeMembers,
@@ -36980,7 +37486,7 @@ const unbanMembers = async (communityId, userIds) => {
36980
37486
  };
36981
37487
  /* end_public_function */
36982
37488
 
36983
- var index$b = /*#__PURE__*/Object.freeze({
37489
+ var index$c = /*#__PURE__*/Object.freeze({
36984
37490
  __proto__: null,
36985
37491
  addRoles: addRoles,
36986
37492
  removeRoles: removeRoles,
@@ -36988,10 +37494,10 @@ var index$b = /*#__PURE__*/Object.freeze({
36988
37494
  unbanMembers: unbanMembers
36989
37495
  });
36990
37496
 
36991
- var index$a = /*#__PURE__*/Object.freeze({
37497
+ var index$b = /*#__PURE__*/Object.freeze({
36992
37498
  __proto__: null,
36993
- Moderation: index$b,
36994
- Membership: index$c,
37499
+ Moderation: index$c,
37500
+ Membership: index$d,
36995
37501
  getCommunityByIds: getCommunities$1,
36996
37502
  createCommunity: createCommunity,
36997
37503
  updateCommunity: updateCommunity,
@@ -37224,7 +37730,7 @@ const getCategories = (params, callback, config) => {
37224
37730
  };
37225
37731
  /* end_public_function */
37226
37732
 
37227
- var index$9 = /*#__PURE__*/Object.freeze({
37733
+ var index$a = /*#__PURE__*/Object.freeze({
37228
37734
  __proto__: null,
37229
37735
  getCategory: getCategory,
37230
37736
  getCategories: getCategories
@@ -37392,7 +37898,7 @@ getCustomRankingGlobalFeed.locally = (query) => {
37392
37898
  : undefined;
37393
37899
  };
37394
37900
 
37395
- var index$8 = /*#__PURE__*/Object.freeze({
37901
+ var index$9 = /*#__PURE__*/Object.freeze({
37396
37902
  __proto__: null,
37397
37903
  queryGlobalFeed: queryGlobalFeed,
37398
37904
  getCustomRankingGlobalFeed: getCustomRankingGlobalFeed
@@ -38721,7 +39227,7 @@ const getComments = (params, callback, config) => {
38721
39227
  };
38722
39228
  /* end_public_function */
38723
39229
 
38724
- var index$7 = /*#__PURE__*/Object.freeze({
39230
+ var index$8 = /*#__PURE__*/Object.freeze({
38725
39231
  __proto__: null,
38726
39232
  getCommentByIds: getCommentByIds,
38727
39233
  createComment: createComment,
@@ -39728,7 +40234,7 @@ const semanticSearchPosts = (params, callback, config) => {
39728
40234
  };
39729
40235
  };
39730
40236
 
39731
- var index$6 = /*#__PURE__*/Object.freeze({
40237
+ var index$7 = /*#__PURE__*/Object.freeze({
39732
40238
  __proto__: null,
39733
40239
  getPostByIds: getPostByIds,
39734
40240
  createPost: createPost,
@@ -40262,7 +40768,7 @@ const getStreams = (params, callback, config) => {
40262
40768
  };
40263
40769
  };
40264
40770
 
40265
- var index$5 = /*#__PURE__*/Object.freeze({
40771
+ var index$6 = /*#__PURE__*/Object.freeze({
40266
40772
  __proto__: null,
40267
40773
  createStream: createStream,
40268
40774
  updateStream: updateStream,
@@ -40549,7 +41055,7 @@ const getPoll = (pollId, callback) => {
40549
41055
  };
40550
41056
  /* end_public_function */
40551
41057
 
40552
- var index$4 = /*#__PURE__*/Object.freeze({
41058
+ var index$5 = /*#__PURE__*/Object.freeze({
40553
41059
  __proto__: null,
40554
41060
  createPoll: createPoll,
40555
41061
  closePoll: closePoll,
@@ -40920,7 +41426,7 @@ const getPlayer = async (parameters) => {
40920
41426
  return video;
40921
41427
  };
40922
41428
 
40923
- var index$3 = /*#__PURE__*/Object.freeze({
41429
+ var index$4 = /*#__PURE__*/Object.freeze({
40924
41430
  __proto__: null,
40925
41431
  getPlayer: getPlayer
40926
41432
  });
@@ -42093,7 +42599,7 @@ const getGlobalStoryTargets = (params, callback, config) => {
42093
42599
  };
42094
42600
  };
42095
42601
 
42096
- var index$2 = /*#__PURE__*/Object.freeze({
42602
+ var index$3 = /*#__PURE__*/Object.freeze({
42097
42603
  __proto__: null,
42098
42604
  createImageStory: createImageStory,
42099
42605
  createVideoStory: createVideoStory,
@@ -42130,7 +42636,7 @@ const getNetworkAds = async () => {
42130
42636
  };
42131
42637
  };
42132
42638
 
42133
- var index$1 = /*#__PURE__*/Object.freeze({
42639
+ var index$2 = /*#__PURE__*/Object.freeze({
42134
42640
  __proto__: null,
42135
42641
  getNetworkAds: getNetworkAds
42136
42642
  });
@@ -42521,7 +43027,7 @@ const markTraySeen = async (lastSeenAt) => {
42521
43027
  };
42522
43028
  /* end_public_function */
42523
43029
 
42524
- var index = /*#__PURE__*/Object.freeze({
43030
+ var index$1 = /*#__PURE__*/Object.freeze({
42525
43031
  __proto__: null,
42526
43032
  getNotificationTraySeen: getNotificationTraySeen,
42527
43033
  getNotificationTrayItems: getNotificationTrayItems,
@@ -42530,4 +43036,11 @@ var index = /*#__PURE__*/Object.freeze({
42530
43036
  onNotificationTraySeenUpdated: onNotificationTraySeenUpdated
42531
43037
  });
42532
43038
 
42533
- export { API_REGIONS, index$1 as AdRepository, index$9 as CategoryRepository, index$d as ChannelRepository, index$m as Client, index$7 as CommentRepository, CommunityPostSettingMaps, CommunityPostSettings, index$a as CommunityRepository, ContentFeedType, ContentFlagReasonEnum, DefaultCommunityPostSetting, index$8 as FeedRepository, FileAccessTypeEnum, index$j as FileRepository, FileType, index$3 as LiveStreamPlayer, MessageContentType, index$h as MessageRepository, index$4 as PollRepository, PostContentType, index$6 as PostRepository, index$i as ReactionRepository, index$2 as StoryRepository, index$5 as StreamRepository, index$g as SubChannelRepository, SubscriptionLevels, index$k as UserRepository, VERSION, VideoResolution, VideoSize, VideoTranscodingStatus, backupCache, createQuery, createReport, createUserToken, deleteReport, disableCache, dropFromCache, enableCache, filterByChannelMembership, filterByCommunityMembership, filterByFeedType, filterByPostDataTypes, filterByPropEquality, filterByPropInclusion, filterByPropIntersection, filterBySearchTerm, filterByStringComparePartially, getChannelTopic, getCommentTopic, getCommunityStoriesTopic, getCommunityTopic, getLiveStreamTopic, getMarkedMessageTopic, getMarkerUserFeedTopic, getMessageTopic, getMyFollowersTopic, getMyFollowingsTopic, getNetworkTopic, getPostTopic, getRole, getSmartFeedChannelTopic, getSmartFeedMessageTopic, getSmartFeedSubChannelTopic, getStoryTopic, getSubChannelTopic, getUserTopic, isAfterBefore, isAfterBeforeRaw, isCachable, isFetcher, isFresh, isLocal, isMutator, isOffline, isPaged, isReportedByMe, isSkip, mergeInCache, index as notificationTray, onChannelMarkerFetched, onFeedMarkerFetched, onFeedMarkerUpdated, onMessageMarked, onMessageMarkerFetched, onSubChannelMarkerFetched, onSubChannelMarkerUpdated, onUserMarkerFetched, onUserMarkerFetchedLegacy, pullFromCache, pushToCache, queryCache, queryOptions, queryRoles, restoreCache, runQuery, sortByChannelSegment, sortByDisplayName, sortByFirstCreated, sortByFirstUpdated, sortByLastActivity, sortByLastCreated, sortByLastUpdated, sortByLocalSortingDate, sortByName, sortBySegmentNumber, subscribeTopic, toPage, toPageRaw, toToken, upsertInCache, wipeCache };
43039
+ var index = /*#__PURE__*/Object.freeze({
43040
+ __proto__: null,
43041
+ onLocalInvitationCreated: onLocalInvitationCreated,
43042
+ onLocalInvitationUpdated: onLocalInvitationUpdated,
43043
+ onLocalInvitationDeleted: onLocalInvitationDeleted
43044
+ });
43045
+
43046
+ export { API_REGIONS, index$2 as AdRepository, index$a as CategoryRepository, index$e as ChannelRepository, index$n as Client, index$8 as CommentRepository, CommunityPostSettingMaps, CommunityPostSettings, index$b as CommunityRepository, ContentFeedType, ContentFlagReasonEnum, DefaultCommunityPostSetting, index$9 as FeedRepository, FileAccessTypeEnum, index$k as FileRepository, FileType, index as InvitationRepository, InvitationSortByEnum, InvitationStatusEnum, InvitationTypeEnum, index$4 as LiveStreamPlayer, MembershipAcceptanceTypeEnum, MessageContentType, index$i as MessageRepository, index$5 as PollRepository, PostContentType, index$7 as PostRepository, index$j as ReactionRepository, index$3 as StoryRepository, index$6 as StreamRepository, index$h as SubChannelRepository, SubscriptionLevels, index$l as UserRepository, VERSION, VideoResolution, VideoSize, VideoTranscodingStatus, backupCache, createQuery, createReport, createUserToken, deleteReport, disableCache, dropFromCache, enableCache, filterByChannelMembership, filterByCommunityMembership, filterByFeedType, filterByPostDataTypes, filterByPropEquality, filterByPropInclusion, filterByPropIntersection, filterBySearchTerm, filterByStringComparePartially, getChannelTopic, getCommentTopic, getCommunityStoriesTopic, getCommunityTopic, getLiveStreamTopic, getMarkedMessageTopic, getMarkerUserFeedTopic, getMessageTopic, getMyFollowersTopic, getMyFollowingsTopic, getNetworkTopic, getPostTopic, getRole, getSmartFeedChannelTopic, getSmartFeedMessageTopic, getSmartFeedSubChannelTopic, getStoryTopic, getSubChannelTopic, getUserTopic, isAfterBefore, isAfterBeforeRaw, isCachable, isFetcher, isFresh, isLocal, isMutator, isOffline, isPaged, isReportedByMe, isSkip, mergeInCache, index$1 as notificationTray, onChannelMarkerFetched, onFeedMarkerFetched, onFeedMarkerUpdated, onMessageMarked, onMessageMarkerFetched, onSubChannelMarkerFetched, onSubChannelMarkerUpdated, onUserMarkerFetched, onUserMarkerFetchedLegacy, pullFromCache, pushToCache, queryCache, queryOptions, queryRoles, restoreCache, runQuery, sortByChannelSegment, sortByDisplayName, sortByFirstCreated, sortByFirstUpdated, sortByLastActivity, sortByLastCreated, sortByLastUpdated, sortByLocalSortingDate, sortByName, sortBySegmentNumber, subscribeTopic, toPage, toPageRaw, toToken, upsertInCache, wipeCache };