@amityco/ts-sdk-react-native 7.22.1-f15e84ea.0 → 7.23.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 (222) hide show
  1. package/dist/@types/core/errors.d.ts +3 -1
  2. package/dist/@types/core/errors.d.ts.map +1 -1
  3. package/dist/@types/core/events.d.ts +7 -1
  4. package/dist/@types/core/events.d.ts.map +1 -1
  5. package/dist/@types/core/model.d.ts +4 -0
  6. package/dist/@types/core/model.d.ts.map +1 -1
  7. package/dist/@types/core/payload.d.ts +15 -0
  8. package/dist/@types/core/payload.d.ts.map +1 -1
  9. package/dist/@types/core/transport.d.ts +1 -0
  10. package/dist/@types/core/transport.d.ts.map +1 -1
  11. package/dist/@types/domains/analytics.d.ts +3 -2
  12. package/dist/@types/domains/analytics.d.ts.map +1 -1
  13. package/dist/@types/domains/block.d.ts +5 -0
  14. package/dist/@types/domains/block.d.ts.map +1 -1
  15. package/dist/@types/domains/channel.d.ts +31 -0
  16. package/dist/@types/domains/channel.d.ts.map +1 -1
  17. package/dist/@types/domains/client.d.ts +31 -2
  18. package/dist/@types/domains/client.d.ts.map +1 -1
  19. package/dist/@types/domains/comment.d.ts +1 -0
  20. package/dist/@types/domains/comment.d.ts.map +1 -1
  21. package/dist/@types/domains/feed.d.ts +14 -0
  22. package/dist/@types/domains/feed.d.ts.map +1 -1
  23. package/dist/@types/domains/message.d.ts +16 -0
  24. package/dist/@types/domains/message.d.ts.map +1 -1
  25. package/dist/@types/domains/post.d.ts +2 -0
  26. package/dist/@types/domains/post.d.ts.map +1 -1
  27. package/dist/@types/domains/sharableContentType.d.ts +9 -0
  28. package/dist/@types/domains/sharableContentType.d.ts.map +1 -0
  29. package/dist/@types/index.d.ts +2 -1
  30. package/dist/@types/index.d.ts.map +1 -1
  31. package/dist/analytic/service/analytic/AnalyticsEngine.d.ts +1 -0
  32. package/dist/analytic/service/analytic/AnalyticsEngine.d.ts.map +1 -1
  33. package/dist/analytic/service/analytic/AnalyticsEventCapturer.d.ts +2 -1
  34. package/dist/analytic/service/analytic/AnalyticsEventCapturer.d.ts.map +1 -1
  35. package/dist/analytic/service/analytic/AnalyticsService.d.ts +1 -0
  36. package/dist/analytic/service/analytic/AnalyticsService.d.ts.map +1 -1
  37. package/dist/channelRepository/api/archiveChannel.d.ts +16 -0
  38. package/dist/channelRepository/api/archiveChannel.d.ts.map +1 -0
  39. package/dist/channelRepository/api/getArchivedChannelIds.d.ts +13 -0
  40. package/dist/channelRepository/api/getArchivedChannelIds.d.ts.map +1 -0
  41. package/dist/channelRepository/api/index.d.ts +3 -0
  42. package/dist/channelRepository/api/index.d.ts.map +1 -1
  43. package/dist/channelRepository/api/unarchiveChannel.d.ts +16 -0
  44. package/dist/channelRepository/api/unarchiveChannel.d.ts.map +1 -0
  45. package/dist/channelRepository/api/updateChannel.d.ts +1 -1
  46. package/dist/channelRepository/api/updateChannel.d.ts.map +1 -1
  47. package/dist/channelRepository/channelMembership/observers/getMembers/ChannelMemberQueryStreamController.d.ts.map +1 -1
  48. package/dist/channelRepository/channelModeration/api/banMembers.d.ts.map +1 -1
  49. package/dist/channelRepository/channelModeration/api/muteMembers.d.ts.map +1 -1
  50. package/dist/channelRepository/channelModeration/api/unbanMembers.d.ts.map +1 -1
  51. package/dist/channelRepository/channelModeration/api/unmuteMembers.d.ts.map +1 -1
  52. package/dist/channelRepository/events/index.d.ts +2 -0
  53. package/dist/channelRepository/events/index.d.ts.map +1 -1
  54. package/dist/channelRepository/events/onChannelArchived.d.ts +10 -0
  55. package/dist/channelRepository/events/onChannelArchived.d.ts.map +1 -0
  56. package/dist/channelRepository/events/onChannelMemberRoleRemoved.d.ts.map +1 -1
  57. package/dist/channelRepository/events/onChannelUnarchived.d.ts +11 -0
  58. package/dist/channelRepository/events/onChannelUnarchived.d.ts.map +1 -0
  59. package/dist/channelRepository/observers/getArchivedChannels/ArchivedChannelLiveCollectionController.d.ts +12 -0
  60. package/dist/channelRepository/observers/getArchivedChannels/ArchivedChannelLiveCollectionController.d.ts.map +1 -0
  61. package/dist/channelRepository/observers/getArchivedChannels/ArchivedChannelPaginationController.d.ts +11 -0
  62. package/dist/channelRepository/observers/getArchivedChannels/ArchivedChannelPaginationController.d.ts.map +1 -0
  63. package/dist/channelRepository/observers/getArchivedChannels/ArchivedChannelQueryStreamController.d.ts +13 -0
  64. package/dist/channelRepository/observers/getArchivedChannels/ArchivedChannelQueryStreamController.d.ts.map +1 -0
  65. package/dist/channelRepository/observers/getArchivedChannels/getArchivedChannels.d.ts +20 -0
  66. package/dist/channelRepository/observers/getArchivedChannels/getArchivedChannels.d.ts.map +1 -0
  67. package/dist/channelRepository/observers/getArchivedChannels/index.d.ts +2 -0
  68. package/dist/channelRepository/observers/getArchivedChannels/index.d.ts.map +1 -0
  69. package/dist/channelRepository/observers/getChannels/ChannelLiveCollectionController.d.ts.map +1 -1
  70. package/dist/channelRepository/observers/getChannels/ChannelQueryStreamController.d.ts.map +1 -1
  71. package/dist/channelRepository/observers/index.d.ts +2 -0
  72. package/dist/channelRepository/observers/index.d.ts.map +1 -1
  73. package/dist/channelRepository/observers/searchChannels/SearchChannelLiveCollectionController.d.ts +14 -0
  74. package/dist/channelRepository/observers/searchChannels/SearchChannelLiveCollectionController.d.ts.map +1 -0
  75. package/dist/channelRepository/observers/searchChannels/SearchChannelPaginationController.d.ts +10 -0
  76. package/dist/channelRepository/observers/searchChannels/SearchChannelPaginationController.d.ts.map +1 -0
  77. package/dist/channelRepository/observers/searchChannels/SearchChannelQueryStreamController.d.ts +13 -0
  78. package/dist/channelRepository/observers/searchChannels/SearchChannelQueryStreamController.d.ts.map +1 -0
  79. package/dist/channelRepository/observers/searchChannels.d.ts +21 -0
  80. package/dist/channelRepository/observers/searchChannels.d.ts.map +1 -0
  81. package/dist/channelRepository/observers/tests/integrations/searchChannels.integration.test.d.ts +2 -0
  82. package/dist/channelRepository/observers/tests/integrations/searchChannels.integration.test.d.ts.map +1 -0
  83. package/dist/channelRepository/utils/prepareChannelPayload.d.ts.map +1 -1
  84. package/dist/client/api/autoSubscription.d.ts +47 -0
  85. package/dist/client/api/autoSubscription.d.ts.map +1 -0
  86. package/dist/client/api/createClient.d.ts.map +1 -1
  87. package/dist/client/api/getCoreUserSettings.d.ts +16 -0
  88. package/dist/client/api/getCoreUserSettings.d.ts.map +1 -0
  89. package/dist/client/api/getForYouFeedSetting.d.ts +17 -0
  90. package/dist/client/api/getForYouFeedSetting.d.ts.map +1 -0
  91. package/dist/client/api/getShareableLinkConfiguration.d.ts.map +1 -1
  92. package/dist/client/api/index.d.ts +4 -0
  93. package/dist/client/api/index.d.ts.map +1 -1
  94. package/dist/client/api/setupLoginSubscriptions.d.ts.map +1 -1
  95. package/dist/client/api/tests/ShareableLinkConfiguration.test.d.ts +2 -0
  96. package/dist/client/api/tests/ShareableLinkConfiguration.test.d.ts.map +1 -0
  97. package/dist/client/api/tests/notifications.integration.test.d.ts +2 -0
  98. package/dist/client/api/tests/notifications.integration.test.d.ts.map +1 -0
  99. package/dist/client/services/ReadReceiptSync/readReceiptSyncEngine.d.ts.map +1 -1
  100. package/dist/client/utils/autoSubscriptionManager.d.ts +21 -0
  101. package/dist/client/utils/autoSubscriptionManager.d.ts.map +1 -0
  102. package/dist/client/utils/subscribeGlobalTopic.d.ts +6 -1
  103. package/dist/client/utils/subscribeGlobalTopic.d.ts.map +1 -1
  104. package/dist/client/utils/tests/autoSubscriptionManager.test.d.ts +2 -0
  105. package/dist/client/utils/tests/autoSubscriptionManager.test.d.ts.map +1 -0
  106. package/dist/commentRepository/observers/getComments/CommentLiveCollectionController.d.ts.map +1 -1
  107. package/dist/commentRepository/observers/tests/integrations/getCommentsExcludeBlockUser.integration.test.d.ts +2 -0
  108. package/dist/commentRepository/observers/tests/integrations/getCommentsExcludeBlockUser.integration.test.d.ts.map +1 -0
  109. package/dist/core/events.d.ts +3 -3
  110. package/dist/core/events.d.ts.map +1 -1
  111. package/dist/core/model/idResolvers.d.ts.map +1 -1
  112. package/dist/core/model/index.d.ts.map +1 -1
  113. package/dist/core/query/filtering.d.ts +32 -0
  114. package/dist/core/query/filtering.d.ts.map +1 -1
  115. package/dist/core/query/paging.d.ts +1 -0
  116. package/dist/core/query/paging.d.ts.map +1 -1
  117. package/dist/core/subscription.d.ts +3 -0
  118. package/dist/core/subscription.d.ts.map +1 -1
  119. package/dist/feedRepository/errors/AmityForYouFeedDisabledError.d.ts +13 -0
  120. package/dist/feedRepository/errors/AmityForYouFeedDisabledError.d.ts.map +1 -0
  121. package/dist/feedRepository/index.d.ts +2 -1
  122. package/dist/feedRepository/index.d.ts.map +1 -1
  123. package/dist/feedRepository/observers/getForYouFeed/CursorController.d.ts +19 -0
  124. package/dist/feedRepository/observers/getForYouFeed/CursorController.d.ts.map +1 -0
  125. package/dist/feedRepository/observers/getForYouFeed/LiveCollectionController.d.ts +13 -0
  126. package/dist/feedRepository/observers/getForYouFeed/LiveCollectionController.d.ts.map +1 -0
  127. package/dist/feedRepository/observers/getForYouFeed/PaginationController.d.ts +13 -0
  128. package/dist/feedRepository/observers/getForYouFeed/PaginationController.d.ts.map +1 -0
  129. package/dist/feedRepository/observers/getForYouFeed/QueryStreamController.d.ts +15 -0
  130. package/dist/feedRepository/observers/getForYouFeed/QueryStreamController.d.ts.map +1 -0
  131. package/dist/feedRepository/observers/getForYouFeed.d.ts +19 -0
  132. package/dist/feedRepository/observers/getForYouFeed.d.ts.map +1 -0
  133. package/dist/feedRepository/observers/index.d.ts +1 -0
  134. package/dist/feedRepository/observers/index.d.ts.map +1 -1
  135. package/dist/feedRepository/observers/tests/integration/getForYouFeed.integration.test.d.ts +2 -0
  136. package/dist/feedRepository/observers/tests/integration/getForYouFeed.integration.test.d.ts.map +1 -0
  137. package/dist/feedRepository/observers/tests/unit/CursorController.test.d.ts +2 -0
  138. package/dist/feedRepository/observers/tests/unit/CursorController.test.d.ts.map +1 -0
  139. package/dist/index.cjs.js +2544 -441
  140. package/dist/index.esm.js +2541 -442
  141. package/dist/index.umd.js +3 -3
  142. package/dist/messagePreview/utils/getChannelMessagePreviewWithUser.d.ts +1 -0
  143. package/dist/messagePreview/utils/getChannelMessagePreviewWithUser.d.ts.map +1 -1
  144. package/dist/messagePreview/utils/updateChannelMessagePreviewCache.d.ts.map +1 -1
  145. package/dist/messageRepository/events/onMessageCreated.d.ts.map +1 -1
  146. package/dist/messageRepository/observers/index.d.ts +1 -0
  147. package/dist/messageRepository/observers/index.d.ts.map +1 -1
  148. package/dist/messageRepository/observers/searchMessage/SearchMessageLiveCollectionController.d.ts +12 -0
  149. package/dist/messageRepository/observers/searchMessage/SearchMessageLiveCollectionController.d.ts.map +1 -0
  150. package/dist/messageRepository/observers/searchMessage/SearchMessagePaginationController.d.ts +10 -0
  151. package/dist/messageRepository/observers/searchMessage/SearchMessagePaginationController.d.ts.map +1 -0
  152. package/dist/messageRepository/observers/searchMessage/SearchMessageQueryStreamController.d.ts +8 -0
  153. package/dist/messageRepository/observers/searchMessage/SearchMessageQueryStreamController.d.ts.map +1 -0
  154. package/dist/messageRepository/observers/searchMessage/index.d.ts +2 -0
  155. package/dist/messageRepository/observers/searchMessage/index.d.ts.map +1 -0
  156. package/dist/messageRepository/observers/searchMessage/searchMessage.d.ts +24 -0
  157. package/dist/messageRepository/observers/searchMessage/searchMessage.d.ts.map +1 -0
  158. package/dist/postRepository/observers/getPosts/PostLiveCollectionController.d.ts.map +1 -1
  159. package/dist/postRepository/observers/tests/getPostsExcludeBlockUser.test.d.ts +2 -0
  160. package/dist/postRepository/observers/tests/getPostsExcludeBlockUser.test.d.ts.map +1 -0
  161. package/dist/postRepository/tests/integration/postAnalytics.integration.test.d.ts +2 -0
  162. package/dist/postRepository/tests/integration/postAnalytics.integration.test.d.ts.map +1 -0
  163. package/dist/postRepository/tests/integration/setup.d.ts +6 -0
  164. package/dist/postRepository/tests/integration/setup.d.ts.map +1 -0
  165. package/dist/reactionRepository/internalApi/addReaction.d.ts.map +1 -1
  166. package/dist/reactionRepository/internalApi/removeReaction.d.ts.map +1 -1
  167. package/dist/streamRepository/observers/getStreams/GetStreamsPageController.d.ts +1 -0
  168. package/dist/streamRepository/observers/getStreams/GetStreamsPageController.d.ts.map +1 -1
  169. package/dist/userRepository/api/getAllBlockedUsers.d.ts.map +1 -1
  170. package/dist/userRepository/api/getAllBlockingUsers.d.ts +20 -0
  171. package/dist/userRepository/api/getAllBlockingUsers.d.ts.map +1 -0
  172. package/dist/userRepository/api/index.d.ts +1 -0
  173. package/dist/userRepository/api/index.d.ts.map +1 -1
  174. package/dist/userRepository/api/tests/integration/getAllBlockingUsers.integration.test.d.ts +2 -0
  175. package/dist/userRepository/api/tests/integration/getAllBlockingUsers.integration.test.d.ts.map +1 -0
  176. package/dist/userRepository/observers/getBlockedUsers/BlockedUserLiveCollectionController.d.ts.map +1 -1
  177. package/dist/userRepository/observers/getBlockedUsers/BlockedUserQueryStreamController.d.ts +4 -3
  178. package/dist/userRepository/observers/getBlockedUsers/BlockedUserQueryStreamController.d.ts.map +1 -1
  179. package/dist/userRepository/observers/getBlockingUsers/LiveCollectionController.d.ts +13 -0
  180. package/dist/userRepository/observers/getBlockingUsers/LiveCollectionController.d.ts.map +1 -0
  181. package/dist/userRepository/observers/getBlockingUsers/PaginationController.d.ts +5 -0
  182. package/dist/userRepository/observers/getBlockingUsers/PaginationController.d.ts.map +1 -0
  183. package/dist/userRepository/observers/getBlockingUsers/QueryStreamController.d.ts +16 -0
  184. package/dist/userRepository/observers/getBlockingUsers/QueryStreamController.d.ts.map +1 -0
  185. package/dist/userRepository/observers/getBlockingUsers.d.ts +17 -0
  186. package/dist/userRepository/observers/getBlockingUsers.d.ts.map +1 -0
  187. package/dist/userRepository/observers/index.d.ts +1 -0
  188. package/dist/userRepository/observers/index.d.ts.map +1 -1
  189. package/dist/userRepository/observers/tests/integrations/getBlockingUsers.integration.test.d.ts +2 -0
  190. package/dist/userRepository/observers/tests/integrations/getBlockingUsers.integration.test.d.ts.map +1 -0
  191. package/dist/userRepository/relationship/block/enum/index.d.ts +5 -0
  192. package/dist/userRepository/relationship/block/enum/index.d.ts.map +1 -0
  193. package/dist/userRepository/relationship/block/events/index.d.ts +3 -0
  194. package/dist/userRepository/relationship/block/events/index.d.ts.map +1 -0
  195. package/dist/userRepository/relationship/block/events/onUserDidBlock.d.ts +20 -0
  196. package/dist/userRepository/relationship/block/events/onUserDidBlock.d.ts.map +1 -0
  197. package/dist/userRepository/relationship/block/events/onUserDidUnblock.d.ts +20 -0
  198. package/dist/userRepository/relationship/block/events/onUserDidUnblock.d.ts.map +1 -0
  199. package/dist/userRepository/relationship/block/index.d.ts +1 -0
  200. package/dist/userRepository/relationship/block/index.d.ts.map +1 -1
  201. package/dist/userRepository/relationship/block/utils/blockRealtimeOnLoginHandler.d.ts +12 -0
  202. package/dist/userRepository/relationship/block/utils/blockRealtimeOnLoginHandler.d.ts.map +1 -0
  203. package/dist/userRepository/relationship/block/utils/createBlockEventSubscriber.d.ts +11 -0
  204. package/dist/userRepository/relationship/block/utils/createBlockEventSubscriber.d.ts.map +1 -0
  205. package/dist/userRepository/services/BlockedUserSyncEngine/blockedUserSyncEngine.d.ts +13 -13
  206. package/dist/userRepository/services/BlockedUserSyncEngine/blockedUserSyncEngine.d.ts.map +1 -1
  207. package/dist/userRepository/services/BlockingUserSyncEngine/blockingUserSyncEngine.d.ts +56 -0
  208. package/dist/userRepository/services/BlockingUserSyncEngine/blockingUserSyncEngine.d.ts.map +1 -0
  209. package/dist/userRepository/services/BlockingUserSyncEngine/blockingUserSyncEngineOnLoginHandler.d.ts +3 -0
  210. package/dist/userRepository/services/BlockingUserSyncEngine/blockingUserSyncEngineOnLoginHandler.d.ts.map +1 -0
  211. package/dist/userRepository/utils/prepareBlockingUserPayload.d.ts +2 -0
  212. package/dist/userRepository/utils/prepareBlockingUserPayload.d.ts.map +1 -0
  213. package/dist/utils/constants.d.ts +4 -0
  214. package/dist/utils/constants.d.ts.map +1 -1
  215. package/dist/utils/linkedObject/channelLinkedObject.d.ts.map +1 -1
  216. package/dist/utils/linkedObject/postLinkedObject.d.ts.map +1 -1
  217. package/dist/utils/tests/dummy/block.d.ts +16 -0
  218. package/dist/utils/tests/dummy/block.d.ts.map +1 -1
  219. package/dist/utils/tests/dummy/community.d.ts +2 -0
  220. package/dist/utils/tests/dummy/community.d.ts.map +1 -1
  221. package/dist/utils/tests/dummy/post.d.ts.map +1 -1
  222. package/package.json +1 -1
package/dist/index.cjs.js CHANGED
@@ -49,6 +49,13 @@ exports.MembershipAcceptanceTypeEnum = void 0;
49
49
  MembershipAcceptanceTypeEnum["AUTOMATIC"] = "automatic";
50
50
  MembershipAcceptanceTypeEnum["INVITATION"] = "invitation";
51
51
  })(exports.MembershipAcceptanceTypeEnum || (exports.MembershipAcceptanceTypeEnum = {}));
52
+ exports.AmityAutoSubscription = void 0;
53
+ (function (AmityAutoSubscription) {
54
+ AmityAutoSubscription["CHAT"] = "chat";
55
+ AmityAutoSubscription["NETWORK"] = "network";
56
+ AmityAutoSubscription["LIVESTREAM"] = "livestream";
57
+ AmityAutoSubscription["BLOCK"] = "block";
58
+ })(exports.AmityAutoSubscription || (exports.AmityAutoSubscription = {}));
52
59
 
53
60
  exports.UserTypeEnum = void 0;
54
61
  (function (UserTypeEnum) {
@@ -95,6 +102,13 @@ exports.FileAccessTypeEnum = void 0;
95
102
  FileAccessTypeEnum["NETWORK"] = "network";
96
103
  })(exports.FileAccessTypeEnum || (exports.FileAccessTypeEnum = {}));
97
104
 
105
+ exports.AmityChannelNotificationModeEnum = void 0;
106
+ (function (AmityChannelNotificationModeEnum) {
107
+ AmityChannelNotificationModeEnum["Default"] = "default";
108
+ AmityChannelNotificationModeEnum["Silent"] = "silent";
109
+ AmityChannelNotificationModeEnum["Subscribe"] = "subscribe";
110
+ })(exports.AmityChannelNotificationModeEnum || (exports.AmityChannelNotificationModeEnum = {}));
111
+
98
112
  const CommunityPostSettings = Object.freeze({
99
113
  ONLY_ADMIN_CAN_POST: 'ONLY_ADMIN_CAN_POST',
100
114
  ADMIN_REVIEW_POST_REQUIRED: 'ADMIN_REVIEW_POST_REQUIRED',
@@ -270,6 +284,15 @@ exports.AmityEventOrderOption = void 0;
270
284
  AmityEventOrderOption["Descending"] = "desc";
271
285
  })(exports.AmityEventOrderOption || (exports.AmityEventOrderOption = {}));
272
286
 
287
+ exports.AmitySharableContentType = void 0;
288
+ (function (AmitySharableContentType) {
289
+ AmitySharableContentType["POST"] = "post";
290
+ AmitySharableContentType["COMMUNITY"] = "community";
291
+ AmitySharableContentType["USER"] = "user";
292
+ AmitySharableContentType["LIVESTREAM"] = "livestream";
293
+ AmitySharableContentType["EVENT"] = "event";
294
+ })(exports.AmitySharableContentType || (exports.AmitySharableContentType = {}));
295
+
273
296
  exports.AnalyticsSourceTypeEnum = void 0;
274
297
  (function (AnalyticsSourceTypeEnum) {
275
298
  AnalyticsSourceTypeEnum["POST"] = "post";
@@ -311,8 +334,8 @@ exports.NotificationRolesFilterTypeEnum = void 0;
311
334
 
312
335
  function getVersion() {
313
336
  try {
314
- // the string ''v7.22.0-cjs'' should be replaced by actual value by @rollup/plugin-replace
315
- return 'v7.22.0-cjs';
337
+ // the string ''v7.23.0-cjs'' should be replaced by actual value by @rollup/plugin-replace
338
+ return 'v7.23.0-cjs';
316
339
  }
317
340
  catch (error) {
318
341
  return '__dev__';
@@ -321,6 +344,7 @@ function getVersion() {
321
344
  const VERSION = getVersion();
322
345
 
323
346
  const COLLECTION_DEFAULT_PAGINATION_LIMIT = 5;
347
+ const COLLECTION_DEFAULT_PAGINATION_SIZE = 20;
324
348
  const COLLECTION_DEFAULT_CACHING_POLICY = 'cache_then_server';
325
349
  const ENABLE_CACHE_MESSAGE = 'For using Live Collection feature you need to enable Cache!';
326
350
  const LIVE_OBJECT_ENABLE_CACHE_MESSAGE = 'For using Live Object feature you need to enable Cache!';
@@ -333,6 +357,9 @@ const DAY = 24 * HOUR;
333
357
  const WEEK = 7 * DAY;
334
358
  const YEAR = 365 * DAY;
335
359
  const ACCESS_TOKEN_WATCHER_INTERVAL = 10 * MINUTE;
360
+ const API_ENDPOINTS = {
361
+ forYouFeed: '/api/v1/feeds/for-you',
362
+ };
336
363
 
337
364
  // cache constants
338
365
  const CACHE_KEY_GET = 'get';
@@ -713,6 +740,107 @@ function createSnapshot(data, options) {
713
740
  return Object.assign(Object.assign({}, options), { data });
714
741
  }
715
742
 
743
+ /* eslint-disable max-classes-per-file */
744
+ /**
745
+ * Generic ASC error
746
+ * @category Errors
747
+ */
748
+ class ASCError extends Error {
749
+ /**
750
+ * @param message A custom error message
751
+ * @param code A normalized error code
752
+ * @param level A normalized failure level descriptor
753
+ */
754
+ constructor(message, code, level) {
755
+ super(`Amity SDK (${code}): ${message}`);
756
+ this.code = code;
757
+ this.level = level;
758
+ this.type = 'ASC';
759
+ this.timestamp = Date.now();
760
+ if (Error.captureStackTrace)
761
+ Error.captureStackTrace(this, ASCError);
762
+ }
763
+ }
764
+ /**
765
+ * API level error
766
+ * @category Errors
767
+ */
768
+ class ASCApiError extends ASCError {
769
+ /**
770
+ * @param code A normalized error code
771
+ * @param level A normalized failure level descriptor
772
+ */
773
+ // eslint-disable-next-line no-useless-constructor
774
+ constructor(message, code, level) {
775
+ super(message, code, level);
776
+ }
777
+ }
778
+ /**
779
+ * Unexpected error
780
+ * @category Errors
781
+ */
782
+ class ASCUnknownError extends ASCError {
783
+ /**
784
+ * @param code A normalized error code
785
+ * @param level A normalized failure level descriptor
786
+ */
787
+ constructor(code = 800000 /* Amity.ClientError.UNKNOWN_ERROR */, level = "fatal" /* Amity.ErrorLevel.FATAL */) {
788
+ super('Unexpected error', code, level);
789
+ }
790
+ }
791
+ /**
792
+ * Network related error
793
+ * @category Errors
794
+ */
795
+ class ASCConnectionError extends ASCError {
796
+ /**
797
+ * @param message A custom error message
798
+ */
799
+ constructor(event, message = 'SDK client is having connection issues') {
800
+ super(`${message} (${event})`, event === 'disconnected'
801
+ ? 800211 /* Amity.ClientError.DISCONNECTED */
802
+ : 800210 /* Amity.ClientError.CONNECTION_ERROR */, "error" /* Amity.ErrorLevel.ERROR */);
803
+ this.event = event;
804
+ }
805
+ }
806
+ /**
807
+ * Input sanitization related error
808
+ * @category Errors
809
+ */
810
+ class ASCInvalidParameterError extends ASCError {
811
+ /**
812
+ * @param message A custom error message
813
+ */
814
+ constructor(message) {
815
+ super(message, 800110 /* Amity.ClientError.INVALID_PARAMETERS */, "error" /* Amity.ErrorLevel.ERROR */);
816
+ }
817
+ }
818
+
819
+ let activeClient = null;
820
+ /**
821
+ * Get the active client
822
+ *
823
+ * @returns the active client instance
824
+ *
825
+ * @hidden
826
+ */
827
+ const getActiveClient = () => {
828
+ if (!activeClient) {
829
+ throw new ASCError('There is no active client', 800000 /* Amity.ClientError.UNKNOWN_ERROR */, "fatal" /* Amity.ErrorLevel.FATAL */);
830
+ }
831
+ return activeClient;
832
+ };
833
+ /**
834
+ * Sets the active client
835
+ *
836
+ * @param client the client to assume as currently active client
837
+ *
838
+ * @hidden
839
+ */
840
+ const setActiveClient = (client) => {
841
+ activeClient = client;
842
+ };
843
+
716
844
  /** @hidden */
717
845
  const idResolvers = {
718
846
  user: ({ userId }) => userId,
@@ -721,6 +849,7 @@ const idResolvers = {
721
849
  channel: ({ channelInternalId }) => channelInternalId,
722
850
  subChannel: ({ subChannelId }) => subChannelId,
723
851
  channelUsers: ({ channelId, userId }) => `${channelId}#${userId}`,
852
+ archivedChannel: ({ channelId }) => channelId,
724
853
  message: ({ messageId, referenceId }) => referenceId !== null && referenceId !== void 0 ? referenceId : messageId,
725
854
  messagePreviewChannel: ({ channelId }) => `${channelId}`,
726
855
  messagePreviewSubChannel: ({ subChannelId }) => `${subChannelId}`,
@@ -762,6 +891,7 @@ const idResolvers = {
762
891
  event: ({ eventId }) => eventId,
763
892
  eventResponse: ({ userId }) => userId,
764
893
  product: ({ productId }) => productId,
894
+ feedMetadata: ({ postId }) => postId,
765
895
  };
766
896
  /**
767
897
  * Retrieve the id resolver matching a domain name
@@ -784,6 +914,7 @@ const PAYLOAD2MODEL = {
784
914
  channels: 'channel',
785
915
  messageFeeds: 'subChannel',
786
916
  channelUsers: 'channelUsers',
917
+ archives: 'archivedChannel',
787
918
  messages: 'message',
788
919
  messagePreviewChannel: 'messagePreviewChannel',
789
920
  messagePreviewSubChannel: 'messagePreviewSubChannel',
@@ -822,6 +953,7 @@ const PAYLOAD2MODEL = {
822
953
  viewers: 'viewer',
823
954
  eventResponses: 'eventResponse',
824
955
  products: 'product',
956
+ feedMetadata: 'feedMetadata',
825
957
  };
826
958
  /** hidden */
827
959
  const isOutdated = (prevData, nextData) => {
@@ -836,107 +968,6 @@ function getFutureDate(date = new Date().toISOString()) {
836
968
  return new Date(new Date(date).getTime() + 1).toISOString();
837
969
  }
838
970
 
839
- /* eslint-disable max-classes-per-file */
840
- /**
841
- * Generic ASC error
842
- * @category Errors
843
- */
844
- class ASCError extends Error {
845
- /**
846
- * @param message A custom error message
847
- * @param code A normalized error code
848
- * @param level A normalized failure level descriptor
849
- */
850
- constructor(message, code, level) {
851
- super(`Amity SDK (${code}): ${message}`);
852
- this.code = code;
853
- this.level = level;
854
- this.type = 'ASC';
855
- this.timestamp = Date.now();
856
- if (Error.captureStackTrace)
857
- Error.captureStackTrace(this, ASCError);
858
- }
859
- }
860
- /**
861
- * API level error
862
- * @category Errors
863
- */
864
- class ASCApiError extends ASCError {
865
- /**
866
- * @param code A normalized error code
867
- * @param level A normalized failure level descriptor
868
- */
869
- // eslint-disable-next-line no-useless-constructor
870
- constructor(message, code, level) {
871
- super(message, code, level);
872
- }
873
- }
874
- /**
875
- * Unexpected error
876
- * @category Errors
877
- */
878
- class ASCUnknownError extends ASCError {
879
- /**
880
- * @param code A normalized error code
881
- * @param level A normalized failure level descriptor
882
- */
883
- constructor(code = 800000 /* Amity.ClientError.UNKNOWN_ERROR */, level = "fatal" /* Amity.ErrorLevel.FATAL */) {
884
- super('Unexpected error', code, level);
885
- }
886
- }
887
- /**
888
- * Network related error
889
- * @category Errors
890
- */
891
- class ASCConnectionError extends ASCError {
892
- /**
893
- * @param message A custom error message
894
- */
895
- constructor(event, message = 'SDK client is having connection issues') {
896
- super(`${message} (${event})`, event === 'disconnected'
897
- ? 800211 /* Amity.ClientError.DISCONNECTED */
898
- : 800210 /* Amity.ClientError.CONNECTION_ERROR */, "error" /* Amity.ErrorLevel.ERROR */);
899
- this.event = event;
900
- }
901
- }
902
- /**
903
- * Input sanitization related error
904
- * @category Errors
905
- */
906
- class ASCInvalidParameterError extends ASCError {
907
- /**
908
- * @param message A custom error message
909
- */
910
- constructor(message) {
911
- super(message, 800110 /* Amity.ClientError.INVALID_PARAMETERS */, "error" /* Amity.ErrorLevel.ERROR */);
912
- }
913
- }
914
-
915
- let activeClient = null;
916
- /**
917
- * Get the active client
918
- *
919
- * @returns the active client instance
920
- *
921
- * @hidden
922
- */
923
- const getActiveClient = () => {
924
- if (!activeClient) {
925
- throw new ASCError('There is no active client', 800000 /* Amity.ClientError.UNKNOWN_ERROR */, "fatal" /* Amity.ErrorLevel.FATAL */);
926
- }
927
- return activeClient;
928
- };
929
- /**
930
- * Sets the active client
931
- *
932
- * @param client the client to assume as currently active client
933
- *
934
- * @hidden
935
- */
936
- const setActiveClient = (client) => {
937
- activeClient = client;
938
- };
939
-
940
971
  /**
941
972
  * ```js
942
973
  * import { enableCache } from '@amityco/ts-sdk-react-native'
@@ -1444,6 +1475,65 @@ const filterBySearchTerm = (collection, searchTerm) => {
1444
1475
  return m.user && ((_a = m.user.displayName) === null || _a === void 0 ? void 0 : _a.match(containsMatcher));
1445
1476
  });
1446
1477
  };
1478
+ /**
1479
+ * The ids of users in a block relationship with the current user — in BOTH
1480
+ * directions — derived synchronously from the local follow cache. For every
1481
+ * `status === 'blocked'` row that involves the current user, the OTHER party
1482
+ * is collected: `from === me` (users I blocked, outgoing) contributes `to`;
1483
+ * `to === me` (users who blocked me, incoming) contributes `from`.
1484
+ *
1485
+ * @returns a set of block-related user ids (both directions)
1486
+ *
1487
+ * @hidden
1488
+ */
1489
+ const getBlockUsersId = () => {
1490
+ var _a;
1491
+ const { userId } = getActiveClient();
1492
+ const ids = new Set();
1493
+ ((_a = queryCache(['follow', 'get'])) !== null && _a !== void 0 ? _a : [])
1494
+ .map(entry => entry.data)
1495
+ .filter(follow => (follow === null || follow === void 0 ? void 0 : follow.status) === 'blocked' && (follow.from === userId || follow.to === userId))
1496
+ .forEach(follow => {
1497
+ ids.add(follow.from === userId ? follow.to : follow.from);
1498
+ });
1499
+ return ids;
1500
+ };
1501
+ /**
1502
+ * Filter out posts whose author or any mentionee is in a block relationship
1503
+ * with the current user, in either direction (see {@link getBlockUsersId}).
1504
+ *
1505
+ * @param collection the post collection to filter
1506
+ * @returns a filtered collection excluding posts involving block-related users
1507
+ *
1508
+ * @hidden
1509
+ */
1510
+ const filterPostsByBlockUsers = (collection) => {
1511
+ const blockUsersId = getBlockUsersId();
1512
+ if (blockUsersId.size === 0)
1513
+ return collection;
1514
+ return collection.filter(post => {
1515
+ var _a, _b;
1516
+ if (blockUsersId.has(post.postedUserId))
1517
+ return false;
1518
+ const mentionedUserIds = (_b = (_a = post.mentionees) === null || _a === void 0 ? void 0 : _a.flatMap(mention => (mention.type === 'user' ? mention.userIds : []))) !== null && _b !== void 0 ? _b : [];
1519
+ return !mentionedUserIds.some(id => blockUsersId.has(id));
1520
+ });
1521
+ };
1522
+ /**
1523
+ * Filter out comments whose creator is in a block relationship with the
1524
+ * current user, in either direction (see {@link getBlockUsersId}).
1525
+ *
1526
+ * @param collection the comment collection to filter
1527
+ * @returns a filtered collection excluding comments from block-related users
1528
+ *
1529
+ * @hidden
1530
+ */
1531
+ const filterCommentsByBlockUsers = (collection) => {
1532
+ const blockUsersId = getBlockUsersId();
1533
+ if (blockUsersId.size === 0)
1534
+ return collection;
1535
+ return collection.filter(comment => !blockUsersId.has(comment.userId));
1536
+ };
1447
1537
 
1448
1538
  // Note:
1449
1539
  // this file should contain a suite of sorting utilities to help the
@@ -1914,13 +2004,13 @@ class NetworkActivitiesWatcher {
1914
2004
  this._listener.clear();
1915
2005
  }
1916
2006
  }
1917
- let instance$9;
2007
+ let instance$b;
1918
2008
  var NetworkActivitiesWatcher$1 = {
1919
2009
  getInstance: () => {
1920
- if (!instance$9) {
1921
- instance$9 = new NetworkActivitiesWatcher();
2010
+ if (!instance$b) {
2011
+ instance$b = new NetworkActivitiesWatcher();
1922
2012
  }
1923
- return instance$9;
2013
+ return instance$b;
1924
2014
  },
1925
2015
  };
1926
2016
 
@@ -4668,18 +4758,149 @@ walker=walker.next;}if(i===n&&walker!==null){return walker.value;}};Yallist.prot
4668
4758
  walker=walker.prev;}if(i===n&&walker!==null){return walker.value;}};Yallist.prototype.map=function(fn,thisp){thisp=thisp||this;var res=new Yallist();for(var walker=this.head;walker!==null;){res.push(fn.call(thisp,walker.value,this));walker=walker.next;}return res;};Yallist.prototype.mapReverse=function(fn,thisp){thisp=thisp||this;var res=new Yallist();for(var walker=this.tail;walker!==null;){res.push(fn.call(thisp,walker.value,this));walker=walker.prev;}return res;};Yallist.prototype.reduce=function(fn,initial){var acc;var walker=this.head;if(arguments.length>1){acc=initial;}else if(this.head){walker=this.head.next;acc=this.head.value;}else {throw new TypeError('Reduce of empty list with no initial value');}for(var i=0;walker!==null;i++){acc=fn(acc,walker.value,i);walker=walker.next;}return acc;};Yallist.prototype.reduceReverse=function(fn,initial){var acc;var walker=this.tail;if(arguments.length>1){acc=initial;}else if(this.tail){walker=this.tail.prev;acc=this.tail.value;}else {throw new TypeError('Reduce of empty list with no initial value');}for(var i=this.length-1;walker!==null;i--){acc=fn(acc,walker.value,i);walker=walker.prev;}return acc;};Yallist.prototype.toArray=function(){var arr=new Array(this.length);for(var i=0,walker=this.head;walker!==null;i++){arr[i]=walker.value;walker=walker.next;}return arr;};Yallist.prototype.toArrayReverse=function(){var arr=new Array(this.length);for(var i=0,walker=this.tail;walker!==null;i++){arr[i]=walker.value;walker=walker.prev;}return arr;};Yallist.prototype.slice=function(from,to){to=to||this.length;if(to<0){to+=this.length;}from=from||0;if(from<0){from+=this.length;}var ret=new Yallist();if(to<from||to<0){return ret;}if(from<0){from=0;}if(to>this.length){to=this.length;}for(var i=0,walker=this.head;walker!==null&&i<from;i++){walker=walker.next;}for(;walker!==null&&i<to;i++,walker=walker.next){ret.push(walker.value);}return ret;};Yallist.prototype.sliceReverse=function(from,to){to=to||this.length;if(to<0){to+=this.length;}from=from||0;if(from<0){from+=this.length;}var ret=new Yallist();if(to<from||to<0){return ret;}if(from<0){from=0;}if(to>this.length){to=this.length;}for(var i=this.length,walker=this.tail;walker!==null&&i>to;i--){walker=walker.prev;}for(;walker!==null&&i>from;i--,walker=walker.prev){ret.push(walker.value);}return ret;};Yallist.prototype.splice=function(start,deleteCount){if(start>this.length){start=this.length-1;}if(start<0){start=this.length+start;}for(var i=0,walker=this.head;walker!==null&&i<start;i++){walker=walker.next;}var ret=[];for(var i=0;walker&&i<deleteCount;i++){ret.push(walker.value);walker=this.removeNode(walker);}if(walker===null){walker=this.tail;}if(walker!==this.head&&walker!==this.tail){walker=walker.prev;}for(var i=0;i<(arguments.length<=2?0:arguments.length-2);i++){walker=insert(this,walker,i+2<2||arguments.length<=i+2?undefined:arguments[i+2]);}return ret;};Yallist.prototype.reverse=function(){var head=this.head;var tail=this.tail;for(var walker=head;walker!==null;walker=walker.prev){var p=walker.prev;walker.prev=walker.next;walker.next=p;}this.head=tail;this.tail=head;return this;};function insert(self,node,value){var inserted=node===self.head?new Node(value,null,node,self):new Node(value,node,node.next,self);if(inserted.next===null){self.tail=inserted;}if(inserted.prev===null){self.head=inserted;}self.length++;return inserted;}function push(self,item){self.tail=new Node(item,self.tail,null,self);if(!self.head){self.head=self.tail;}self.length++;}function unshift(self,item){self.head=new Node(item,null,self.head,self);if(!self.tail){self.tail=self.head;}self.length++;}function Node(value,prev,next,list){if(!(this instanceof Node)){return new Node(value,prev,next,list);}this.list=list;this.value=value;if(prev){prev.next=this;this.prev=prev;}else {this.prev=null;}if(next){next.prev=this;this.next=next;}else {this.next=null;}}try{// add if support for Symbol.iterator is present
4669
4759
  require('./iterator.js')(Yallist);}catch(er){}},{"./iterator.js":82}]},{},[12])(12);});})(mqtt$1);var mqtt = /*@__PURE__*/getDefaultExportFromCjs(mqtt$1.exports);
4670
4760
 
4761
+ class SessionWatcher {
4762
+ constructor() {
4763
+ this._sessionState = "notLoggedIn" /* Amity.SessionStates.NOT_LOGGED_IN */;
4764
+ this._listener = new Map();
4765
+ }
4766
+ onSessionStateChange(callback) {
4767
+ this._listener.set(callback, callback);
4768
+ return () => {
4769
+ this._listener.delete(callback);
4770
+ };
4771
+ }
4772
+ setSessionState(state, reason) {
4773
+ if (this._sessionState === state)
4774
+ return;
4775
+ this._sessionState = state;
4776
+ this._listener.forEach(cb => cb(state, reason));
4777
+ }
4778
+ destroy() {
4779
+ this._listener.clear();
4780
+ }
4781
+ }
4782
+ let instance$a;
4783
+ var SessionWatcher$1 = {
4784
+ getInstance: () => {
4785
+ if (!instance$a) {
4786
+ instance$a = new SessionWatcher();
4787
+ }
4788
+ return instance$a;
4789
+ },
4790
+ };
4791
+
4792
+ /**
4793
+ * ```js
4794
+ * import { onSessionStateChange } from '@amityco/ts-sdk-react-native'
4795
+ * const dispose = onSessionStateChange((state: Amity.SessionStates) => {
4796
+ * // ...
4797
+ * })
4798
+ * ```
4799
+ *
4800
+ * Fired when any {@link Amity.Client} has a session state change
4801
+ *
4802
+ * @param callback The function to call when the event was fired
4803
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
4804
+ *
4805
+ * @category Client Events
4806
+ */
4807
+ const onSessionStateChange = (callback) => SessionWatcher$1.getInstance().onSessionStateChange(callback);
4808
+
4809
+ const TOPICS = {
4810
+ [exports.AmityAutoSubscription.NETWORK]: [getNetworkTopic],
4811
+ [exports.AmityAutoSubscription.CHAT]: [
4812
+ getSmartFeedChannelTopic,
4813
+ getSmartFeedSubChannelTopic,
4814
+ getSmartFeedMessageTopic,
4815
+ ],
4816
+ [exports.AmityAutoSubscription.LIVESTREAM]: [getLiveStreamTopic],
4817
+ [exports.AmityAutoSubscription.BLOCK]: [getMyFollowersTopic, getMyFollowingsTopic],
4818
+ };
4819
+ const DEFAULT_TOPICS = [
4820
+ exports.AmityAutoSubscription.CHAT,
4821
+ exports.AmityAutoSubscription.NETWORK,
4822
+ exports.AmityAutoSubscription.LIVESTREAM,
4823
+ exports.AmityAutoSubscription.BLOCK,
4824
+ ];
4825
+ const ALL_FEATURES = Object.values(exports.AmityAutoSubscription);
4826
+ /** Ref-counted, reconnect-resilient registry of the managed auto-subscriptions. */
4827
+ class AutoSubscriptionManager {
4828
+ constructor() {
4829
+ this.refCountByFeature = new Map();
4830
+ this.disposers = new Map();
4831
+ this.seed();
4832
+ }
4833
+ seed() {
4834
+ this.refCountByFeature.clear();
4835
+ DEFAULT_TOPICS.forEach(feature => this.refCountByFeature.set(feature, 1));
4836
+ }
4837
+ isActive(feature) {
4838
+ var _a;
4839
+ return ((_a = this.refCountByFeature.get(feature)) !== null && _a !== void 0 ? _a : 0) > 0;
4840
+ }
4841
+ subscribeTopics(feature) {
4842
+ this.unsubscribeTopics(feature);
4843
+ this.disposers.set(feature, TOPICS[feature].map(buildTopic => subscribeTopic(buildTopic())));
4844
+ }
4845
+ unsubscribeTopics(feature) {
4846
+ var _a;
4847
+ ((_a = this.disposers.get(feature)) !== null && _a !== void 0 ? _a : []).forEach(dispose => dispose());
4848
+ this.disposers.delete(feature);
4849
+ }
4850
+ /** Subscribe every enabled handle's topics, converging the broker to the registry. Called on each (re)connect. */
4851
+ initialize() {
4852
+ ALL_FEATURES.forEach(feature => {
4853
+ if (this.isActive(feature))
4854
+ this.subscribeTopics(feature);
4855
+ });
4856
+ }
4857
+ subscribe(feature) {
4858
+ var _a;
4859
+ const next = ((_a = this.refCountByFeature.get(feature)) !== null && _a !== void 0 ? _a : 0) + 1;
4860
+ this.refCountByFeature.set(feature, next);
4861
+ if (next === 1)
4862
+ this.subscribeTopics(feature);
4863
+ }
4864
+ unsubscribe(feature) {
4865
+ var _a;
4866
+ const next = Math.max(0, ((_a = this.refCountByFeature.get(feature)) !== null && _a !== void 0 ? _a : 0) - 1);
4867
+ this.refCountByFeature.set(feature, next);
4868
+ if (next === 0)
4869
+ this.unsubscribeTopics(feature);
4870
+ }
4871
+ subscriptions() {
4872
+ return ALL_FEATURES.map(feature => ({
4873
+ feature,
4874
+ isActive: this.isActive(feature),
4875
+ isSystem: true,
4876
+ topicCount: TOPICS[feature].length,
4877
+ }));
4878
+ }
4879
+ reset() {
4880
+ ALL_FEATURES.forEach(feature => this.unsubscribeTopics(feature));
4881
+ this.disposers.clear();
4882
+ this.seed();
4883
+ }
4884
+ }
4885
+ let instance$9 = null;
4886
+ const getAutoSubscriptionManager = () => {
4887
+ if (!instance$9)
4888
+ instance$9 = new AutoSubscriptionManager();
4889
+ return instance$9;
4890
+ };
4891
+ /** Resets the registry to its default baseline when the session ends. */
4892
+ const resetAutoSubscriptionsOnLogout = () => onSessionStateChange(state => {
4893
+ if (state !== "established" /* Amity.SessionStates.ESTABLISHED */)
4894
+ getAutoSubscriptionManager().reset();
4895
+ });
4896
+
4897
+ /**
4898
+ * (Re)subscribes the managed auto-subscription registry on every (re)connect.
4899
+ * The hardcoded topic list was promoted to the toggleable, ref-counted registry
4900
+ * in {@link getAutoSubscriptionManager} — see `client.manageAutoSubscriptions`.
4901
+ */
4671
4902
  const subscribeGlobalTopic = () => {
4672
- const disposers = [
4673
- subscribeTopic(getNetworkTopic()),
4674
- subscribeTopic(getSmartFeedChannelTopic()),
4675
- subscribeTopic(getSmartFeedSubChannelTopic()),
4676
- subscribeTopic(getSmartFeedMessageTopic()),
4677
- // subscribing to user topic is necessary to handle ban event
4678
- subscribeTopic(getUserTopic(getActiveUser())),
4679
- subscribeTopic(getMarkerUserFeedTopic()),
4680
- subscribeTopic(getLiveStreamTopic()),
4681
- ];
4682
- return () => disposers.forEach(fn => fn());
4903
+ getAutoSubscriptionManager().initialize();
4683
4904
  };
4684
4905
 
4685
4906
  class OnMemoryStorage {
@@ -5236,8 +5457,12 @@ const getChannelMessagePreviewWithUser = (channel) => {
5236
5457
  return Object.assign(Object.assign({}, channel), { messagePreview: messagePreviewWithUser });
5237
5458
  };
5238
5459
 
5460
+ const convertDateStringToTimestamp = (dateString) => {
5461
+ return new Date(dateString).getTime();
5462
+ };
5463
+
5239
5464
  const updateChannelMessagePreviewCache = (rawPayload) => {
5240
- var _a, _b;
5465
+ var _a;
5241
5466
  const withMessageFeedInfo = (messagePreview) => {
5242
5467
  var _a;
5243
5468
  const messageFeedInfo = (_a = rawPayload.messageFeedsInfo) === null || _a === void 0 ? void 0 : _a.find(messageFeed => {
@@ -5259,10 +5484,26 @@ const updateChannelMessagePreviewCache = (rawPayload) => {
5259
5484
  subChannelUpdatedAt: messageFeedInfo === null || messageFeedInfo === void 0 ? void 0 : messageFeedInfo.updatedAt,
5260
5485
  };
5261
5486
  };
5262
- const newData = {
5263
- messagePreviewChannel: (_b = (_a = rawPayload.messagePreviews) === null || _a === void 0 ? void 0 : _a.map(messagePreview => withMessageFeedInfo(messagePreview))) !== null && _b !== void 0 ? _b : [],
5264
- };
5265
- ingestInCache(newData);
5487
+ // Skip server previews older than what's cached — the cache may carry a newer
5488
+ // preview written by handleMessageCreated from an MQTT message that the server
5489
+ // payload hasn't surfaced yet. Mirrors isLastestMessageOnChannel.
5490
+ const newPreviews = ((_a = rawPayload.messagePreviews) !== null && _a !== void 0 ? _a : [])
5491
+ .map(withMessageFeedInfo)
5492
+ .filter(preview => {
5493
+ var _a;
5494
+ const cached = (_a = pullFromCache([
5495
+ 'messagePreviewChannel',
5496
+ 'get',
5497
+ preview.channelId,
5498
+ ])) === null || _a === void 0 ? void 0 : _a.data;
5499
+ if (!cached)
5500
+ return true;
5501
+ return (convertDateStringToTimestamp(cached.createdAt) <=
5502
+ convertDateStringToTimestamp(preview.createdAt));
5503
+ });
5504
+ if (newPreviews.length === 0)
5505
+ return;
5506
+ ingestInCache({ messagePreviewChannel: newPreviews });
5266
5507
  };
5267
5508
 
5268
5509
  const getSubChannelMessagePreview = (subChannelId) => {
@@ -5890,11 +6131,7 @@ getSubChannel$1.locally = (subChannelId) => {
5890
6131
  };
5891
6132
  };
5892
6133
 
5893
- const convertDateStringToTimestamp = (dateString) => {
5894
- return new Date(dateString).getTime();
5895
- };
5896
-
5897
- const getMessagePreviewSetting$1 = async () => {
6134
+ const getMessagePreviewSetting$2 = async () => {
5898
6135
  const client = getActiveClient();
5899
6136
  return client.getMessagePreviewSetting(false);
5900
6137
  };
@@ -5929,7 +6166,7 @@ const isLastestMessageOnChannel = (message) => {
5929
6166
  convertDateStringToTimestamp(cache.createdAt) <= convertDateStringToTimestamp(message.createdAt));
5930
6167
  };
5931
6168
  const handleMessageCreatedOnSubChannel = async (message) => {
5932
- const messagePreviewSetting = await getMessagePreviewSetting$1();
6169
+ const messagePreviewSetting = await getMessagePreviewSetting$2();
5933
6170
  const { channelId, messageId: messagePreviewId, creatorId, createdAt, updatedAt, data, dataType, subChannelId, channelSegment: segment, isDeleted, } = message;
5934
6171
  // 1. get subChannel from cache, if not exist fetch from server
5935
6172
  const subChannelCache = await getSubChannelCache(subChannelId);
@@ -6101,24 +6338,41 @@ const preUpdateChannelCache = (rawPayload, options = { isMessagePreviewUpdated:
6101
6338
  });
6102
6339
  };
6103
6340
  const updateChannelUnread = ({ currentUserId, channels, channelUsers, }) => {
6341
+ var _a, _b;
6104
6342
  const channelsUnread = [];
6105
6343
  for (let i = 0; i < channels.length; i += 1) {
6106
6344
  if (isUnreadCountSupport(channels[i])) {
6107
6345
  const cacheKey = ['channelUnread', 'get', channels[i].channelId];
6108
6346
  const channelUser = channelUsers.find(channelUser => channelUser.channelId === channels[i].channelId && channelUser.userId === currentUserId);
6109
- let unreadCount = 0;
6347
+ // readToSegment, lastMentionedSegment and lastSegment are monotonically non-decreasing;
6348
+ // prefer cached values when ahead of the server so a refetch returning stale data cannot
6349
+ const cached = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
6350
+ const lastSegment = Math.max((_b = cached === null || cached === void 0 ? void 0 : cached.lastSegment) !== null && _b !== void 0 ? _b : 0, channels[i].messageCount);
6110
6351
  let readToSegment = null;
6111
6352
  let lastMentionedSegment = null;
6353
+ let unreadCount = 0;
6112
6354
  let isMentioned = false;
6113
6355
  if (channelUser) {
6114
- readToSegment = channelUser.readToSegment;
6115
- lastMentionedSegment = channelUser.lastMentionedSegment;
6116
- unreadCount = Math.max(channels[i].messageCount - readToSegment, 0);
6117
- isMentioned = lastMentionedSegment > readToSegment;
6356
+ const serverRead = channelUser.readToSegment;
6357
+ const serverMention = channelUser.lastMentionedSegment;
6358
+ readToSegment =
6359
+ typeof (cached === null || cached === void 0 ? void 0 : cached.readToSegment) === 'number' &&
6360
+ (typeof serverRead !== 'number' || cached.readToSegment > serverRead)
6361
+ ? cached.readToSegment
6362
+ : serverRead !== null && serverRead !== void 0 ? serverRead : null;
6363
+ lastMentionedSegment =
6364
+ typeof (cached === null || cached === void 0 ? void 0 : cached.lastMentionedSegment) === 'number' &&
6365
+ (typeof serverMention !== 'number' || cached.lastMentionedSegment > serverMention)
6366
+ ? cached.lastMentionedSegment
6367
+ : serverMention !== null && serverMention !== void 0 ? serverMention : null;
6368
+ const readForCalc = readToSegment !== null && readToSegment !== void 0 ? readToSegment : 0;
6369
+ unreadCount = Math.max(lastSegment - readForCalc, 0);
6370
+ isMentioned =
6371
+ typeof lastMentionedSegment === 'number' && readForCalc < lastMentionedSegment;
6118
6372
  }
6119
6373
  const cacheChannelUnread = {
6120
6374
  channelId: channels[i].channelId,
6121
- lastSegment: channels[i].messageCount,
6375
+ lastSegment,
6122
6376
  readToSegment,
6123
6377
  lastMentionedSegment,
6124
6378
  unreadCount,
@@ -6128,6 +6382,8 @@ const updateChannelUnread = ({ currentUserId, channels, channelUsers, }) => {
6128
6382
  pushToCache(cacheKey, cacheChannelUnread);
6129
6383
  channelsUnread.push(cacheChannelUnread);
6130
6384
  }
6385
+ }
6386
+ if (channelsUnread.length > 0) {
6131
6387
  fireEvent('local.channelUnread.updated', channelsUnread);
6132
6388
  }
6133
6389
  };
@@ -6827,7 +7083,7 @@ const onChannelMemberRoleRemoved = (callback) => {
6827
7083
  const client = getActiveClient();
6828
7084
  const filter = async (payload) => {
6829
7085
  const { channels, channelUsers } = payload;
6830
- callback(channels[0], channelUsers.find(channelUser => channelUser.membership === 'member'));
7086
+ callbacks$1.forEach(cb => cb(channels[0], channelUsers.find(channelUser => channelUser.membership === 'member')));
6831
7087
  };
6832
7088
  mainDisposer$1 = createEventSubscriber(client, 'onChannelMemberRoleRemoved', 'local.channel-moderator.role-removed', filter);
6833
7089
  }
@@ -6835,6 +7091,39 @@ const onChannelMemberRoleRemoved = (callback) => {
6835
7091
  return () => dispose$1(callback);
6836
7092
  };
6837
7093
 
7094
+ /**
7095
+ * Fired when a {@link Amity.Channel} has been archived by the active user.
7096
+ *
7097
+ * @param callback The function to call when the event was fired
7098
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
7099
+ *
7100
+ * @category Channel Events
7101
+ */
7102
+ const onChannelArchived = (callback) => {
7103
+ const client = getActiveClient();
7104
+ const filter = async (payload) => {
7105
+ callback(payload);
7106
+ };
7107
+ return createEventSubscriber(client, 'onChannelArchived', 'local.channel.archived', filter);
7108
+ };
7109
+
7110
+ /**
7111
+ * Fired when a previously archived {@link Amity.Channel} has been unarchived
7112
+ * by the active user.
7113
+ *
7114
+ * @param callback The function to call when the event was fired
7115
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
7116
+ *
7117
+ * @category Channel Events
7118
+ */
7119
+ const onChannelUnarchived = (callback) => {
7120
+ const client = getActiveClient();
7121
+ const filter = async (payload) => {
7122
+ callback(payload);
7123
+ };
7124
+ return createEventSubscriber(client, 'onChannelUnarchived', 'local.channel.unarchived', filter);
7125
+ };
7126
+
6838
7127
  const callbacks = [];
6839
7128
  let mainDisposer = null;
6840
7129
  const dispose = (cb) => {
@@ -6948,6 +7237,17 @@ const channelLinkedObject = (channel) => {
6948
7237
  markAsRead: () => markAsRead(channel.channelInternalId),
6949
7238
  previewMembers,
6950
7239
  myMembership: (callback) => getMyMembership(channel.channelId, callback),
7240
+ get avatar() {
7241
+ var _a;
7242
+ if (!channel.avatarFileId)
7243
+ return undefined;
7244
+ const avatar = (_a = pullFromCache([
7245
+ 'file',
7246
+ 'get',
7247
+ `${channel.avatarFileId}`,
7248
+ ])) === null || _a === void 0 ? void 0 : _a.data;
7249
+ return avatar;
7250
+ },
6951
7251
  });
6952
7252
  };
6953
7253
 
@@ -7046,54 +7346,6 @@ getChannelByIds$1.locally = (channelIds) => {
7046
7346
  };
7047
7347
  };
7048
7348
 
7049
- class SessionWatcher {
7050
- constructor() {
7051
- this._sessionState = "notLoggedIn" /* Amity.SessionStates.NOT_LOGGED_IN */;
7052
- this._listener = new Map();
7053
- }
7054
- onSessionStateChange(callback) {
7055
- this._listener.set(callback, callback);
7056
- return () => {
7057
- this._listener.delete(callback);
7058
- };
7059
- }
7060
- setSessionState(state, reason) {
7061
- if (this._sessionState === state)
7062
- return;
7063
- this._sessionState = state;
7064
- this._listener.forEach(cb => cb(state, reason));
7065
- }
7066
- destroy() {
7067
- this._listener.clear();
7068
- }
7069
- }
7070
- let instance$8;
7071
- var SessionWatcher$1 = {
7072
- getInstance: () => {
7073
- if (!instance$8) {
7074
- instance$8 = new SessionWatcher();
7075
- }
7076
- return instance$8;
7077
- },
7078
- };
7079
-
7080
- /**
7081
- * ```js
7082
- * import { onSessionStateChange } from '@amityco/ts-sdk-react-native'
7083
- * const dispose = onSessionStateChange((state: Amity.SessionStates) => {
7084
- * // ...
7085
- * })
7086
- * ```
7087
- *
7088
- * Fired when any {@link Amity.Client} has a session state change
7089
- *
7090
- * @param callback The function to call when the event was fired
7091
- * @returns an {@link Amity.Unsubscriber} function to stop listening
7092
- *
7093
- * @category Client Events
7094
- */
7095
- const onSessionStateChange = (callback) => SessionWatcher$1.getInstance().onSessionStateChange(callback);
7096
-
7097
7349
  const setIntervalTask = (handler, timeout) => {
7098
7350
  const timer = setInterval(handler, timeout);
7099
7351
  return () => clearInterval(timer);
@@ -7265,7 +7517,7 @@ const convertMessagePreviewSetting = (chatSetting) => {
7265
7517
  * @category private
7266
7518
  * @async
7267
7519
  */
7268
- const getMessagePreviewSetting = async (refresh = true) => {
7520
+ const getMessagePreviewSetting$1 = async (refresh = true) => {
7269
7521
  var _a;
7270
7522
  const messagePreviewSetting = (_a = pullFromCache([
7271
7523
  'MessagePreviewSetting',
@@ -7286,7 +7538,7 @@ const getMessagePreviewSetting = async (refresh = true) => {
7286
7538
  */
7287
7539
  const initializeMessagePreviewSetting = async () => {
7288
7540
  var _a;
7289
- const newMessagePreviewSetting = await getMessagePreviewSetting();
7541
+ const newMessagePreviewSetting = await getMessagePreviewSetting$1();
7290
7542
  const messagePreviewSetting = (_a = pullFromCache([
7291
7543
  'MessagePreviewSetting',
7292
7544
  ])) === null || _a === void 0 ? void 0 : _a.data;
@@ -7357,6 +7609,26 @@ const getSocialSettings = async () => {
7357
7609
  return data.socialNetworkSetting;
7358
7610
  };
7359
7611
 
7612
+ /**
7613
+ * ```js
7614
+ * import { createClient } from '@amityco/ts-sdk'
7615
+ * const client = createClient(apiKey, apiRegion)
7616
+ * const userSettings = await client.getCoreUserSettings()
7617
+ * ```
7618
+ *
7619
+ * Fetches a {@link Amity.CoreUserSettings} object
7620
+ *
7621
+ * @returns A Promise of {@link Amity.CoreUserSettings} object
7622
+ *
7623
+ * @category Client API
7624
+ * @async
7625
+ */
7626
+ const getCoreUserSettings = async () => {
7627
+ const client = getActiveClient();
7628
+ const { data } = await client.http.get(`/api/v3/network-settings/users`);
7629
+ return data;
7630
+ };
7631
+
7360
7632
  /* begin_public_function
7361
7633
  id: client.getProductCatalogueSetting
7362
7634
  */
@@ -7380,6 +7652,33 @@ const getProductCatalogueSetting = async () => {
7380
7652
  };
7381
7653
  /* end_public_function */
7382
7654
 
7655
+ /* begin_public_function
7656
+ id: client.getForYouFeedSetting
7657
+ */
7658
+ /**
7659
+ * ```js
7660
+ * import { Client } from '@amityco/ts-sdk'
7661
+ * const forYouFeedSetting = await Client.getForYouFeedSetting()
7662
+ * ```
7663
+ *
7664
+ * Fetches the network-level {@link Amity.ForYouFeedSetting} — whether the For You
7665
+ * feed feature is enabled for the current network. Use `forYouFeed.enabled` as a
7666
+ * feature gate before querying {@link getForYouFeed}.
7667
+ *
7668
+ * @returns A Promise of {@link Amity.ForYouFeedSetting} object
7669
+ *
7670
+ * @category Client API
7671
+ * @async
7672
+ */
7673
+ const getForYouFeedSetting = async () => {
7674
+ var _a, _b;
7675
+ const client = getActiveClient();
7676
+ const { data } = await client.http.get(`/api/v3/network-settings/for-you-feed`);
7677
+ // Surface only `enabled`; ignore server-side ranking config (scoringConfig, etc.)
7678
+ return { forYouFeed: { enabled: (_b = (_a = data.forYouFeed) === null || _a === void 0 ? void 0 : _a.enabled) !== null && _b !== void 0 ? _b : false } };
7679
+ };
7680
+ /* end_public_function */
7681
+
7383
7682
  const checkUserPermission = (userId, permission) => {
7384
7683
  var _a;
7385
7684
  const user = (_a = pullFromCache(['user', 'get', userId])) === null || _a === void 0 ? void 0 : _a.data;
@@ -7887,7 +8186,7 @@ class AnalyticsEventSyncer {
7887
8186
 
7888
8187
  class AnalyticsEventCapturer {
7889
8188
  constructor() {
7890
- this._expireTime = 5 * MINUTE;
8189
+ this._expireTime = 5 * SECOND$1;
7891
8190
  this._poolLimit = 1000;
7892
8191
  this._recentViewed = {};
7893
8192
  this._recentHighPriorityViewed = {};
@@ -7941,12 +8240,36 @@ class AnalyticsEventCapturer {
7941
8240
  }
7942
8241
  markPostAsViewed(postId) {
7943
8242
  this.markAs({
7944
- uniqueId: postId,
8243
+ uniqueId: `post.${postId}`,
7945
8244
  contentId: postId,
7946
8245
  contentType: "post" /* Amity.AnalyticEventContentType.Post */,
7947
8246
  activityType: "view" /* Amity.AnalyticEventActivityType.View */,
7948
8247
  });
7949
8248
  }
8249
+ markPostAsMeaningfullyViewed(postId, feedRenderPosition) {
8250
+ var _a;
8251
+ const cached = (_a = pullFromCache(['feedMetadata', 'get', postId])) === null || _a === void 0 ? void 0 : _a.data;
8252
+ const metadata = {};
8253
+ if (feedRenderPosition !== undefined)
8254
+ metadata.feedRenderPosition = feedRenderPosition;
8255
+ if (cached) {
8256
+ metadata.feedSnapshotPosition = cached.feedSnapshotPosition;
8257
+ metadata.feedInjectionType = cached.feedInjectionType;
8258
+ metadata.feedRelevanceScore = cached.feedRelevanceScore;
8259
+ metadata.feedPopularityScore = cached.feedPopularityScore;
8260
+ metadata.feedFreshnessScore = cached.feedFreshnessScore;
8261
+ metadata.feedAffinityScore = cached.feedAffinityScore;
8262
+ metadata.feedFinalScore = cached.feedFinalScore;
8263
+ metadata.feedMmrPenalty = cached.feedMmrPenalty;
8264
+ }
8265
+ this.markAs({
8266
+ uniqueId: `post.${postId}.meaningfulView`,
8267
+ contentId: postId,
8268
+ contentType: "post" /* Amity.AnalyticEventContentType.Post */,
8269
+ activityType: "meaningfulView" /* Amity.AnalyticEventActivityType.MeaningfulView */,
8270
+ metadata: Object.keys(metadata).length > 0 ? metadata : undefined,
8271
+ });
8272
+ }
7950
8273
  markStory(story, activityType) {
7951
8274
  if (!story.expiresAt)
7952
8275
  return;
@@ -8086,6 +8409,12 @@ class AnalyticsEngine {
8086
8409
  this._eventCapturer.markPostAsViewed(postId);
8087
8410
  }
8088
8411
  }
8412
+ markPostAsMeaningfullyViewed(postId, feedRenderPosition) {
8413
+ if (this._client.sessionState === "established" /* Amity.SessionStates.ESTABLISHED */ ||
8414
+ this._client.sessionState === "tokenExpired" /* Amity.SessionStates.TOKEN_EXPIRED */) {
8415
+ this._eventCapturer.markPostAsMeaningfullyViewed(postId, feedRenderPosition);
8416
+ }
8417
+ }
8089
8418
  markStoryAsViewed(story) {
8090
8419
  if (this._client.sessionState === "established" /* Amity.SessionStates.ESTABLISHED */ ||
8091
8420
  this._client.sessionState === "tokenExpired" /* Amity.SessionStates.TOKEN_EXPIRED */ // For case token_expired, we assume token is expired and gonna re-connect soon
@@ -8137,13 +8466,13 @@ class AnalyticsEngine {
8137
8466
  this._eventCapturer.resetAllBuckets();
8138
8467
  }
8139
8468
  }
8140
- let instance$7;
8469
+ let instance$8;
8141
8470
  var AnalyticsEngine$1 = {
8142
8471
  getInstance: () => {
8143
- if (!instance$7) {
8144
- instance$7 = new AnalyticsEngine();
8472
+ if (!instance$8) {
8473
+ instance$8 = new AnalyticsEngine();
8145
8474
  }
8146
- return instance$7;
8475
+ return instance$8;
8147
8476
  },
8148
8477
  };
8149
8478
 
@@ -8310,9 +8639,8 @@ class MessageReadReceiptSyncEngine {
8310
8639
  // Step 1: Optimistic update of channelUnread.readToSegment to message.segment and update unreadCount value
8311
8640
  const cacheKey = ['channelUnread', 'get', channelId];
8312
8641
  const channelUnread = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
8313
- if (typeof (channelUnread === null || channelUnread === void 0 ? void 0 : channelUnread.readToSegment) === 'number' &&
8314
- channelUnread &&
8315
- segment > channelUnread.readToSegment) {
8642
+ if (channelUnread &&
8643
+ (typeof channelUnread.readToSegment !== 'number' || segment > channelUnread.readToSegment)) {
8316
8644
  channelUnread.readToSegment = segment;
8317
8645
  channelUnread.unreadCount = Math.max(channelUnread.lastSegment - segment, 0);
8318
8646
  pushToCache(cacheKey, channelUnread);
@@ -8371,12 +8699,12 @@ class MessageReadReceiptSyncEngine {
8371
8699
  }
8372
8700
  }
8373
8701
  }
8374
- let instance$6 = null;
8702
+ let instance$7 = null;
8375
8703
  var ReadReceiptSyncEngine = {
8376
8704
  getInstance: () => {
8377
- if (!instance$6)
8378
- instance$6 = new MessageReadReceiptSyncEngine();
8379
- return instance$6;
8705
+ if (!instance$7)
8706
+ instance$7 = new MessageReadReceiptSyncEngine();
8707
+ return instance$7;
8380
8708
  },
8381
8709
  };
8382
8710
 
@@ -8630,12 +8958,12 @@ class LegacyMessageReadReceiptSyncEngine {
8630
8958
  }
8631
8959
  }
8632
8960
  }
8633
- let instance$5 = null;
8961
+ let instance$6 = null;
8634
8962
  var LegacyReadReceiptSyncEngine = {
8635
8963
  getInstance: () => {
8636
- if (!instance$5)
8637
- instance$5 = new LegacyMessageReadReceiptSyncEngine();
8638
- return instance$5;
8964
+ if (!instance$6)
8965
+ instance$6 = new LegacyMessageReadReceiptSyncEngine();
8966
+ return instance$6;
8639
8967
  },
8640
8968
  };
8641
8969
 
@@ -8911,12 +9239,12 @@ class ObjectResolverEngine {
8911
9239
  this.stopResolver();
8912
9240
  }
8913
9241
  }
8914
- let instance$4 = null;
9242
+ let instance$5 = null;
8915
9243
  var ObjectResolverEngine$1 = {
8916
9244
  getInstance: () => {
8917
- if (!instance$4)
8918
- instance$4 = new ObjectResolverEngine();
8919
- return instance$4;
9245
+ if (!instance$5)
9246
+ instance$5 = new ObjectResolverEngine();
9247
+ return instance$5;
8920
9248
  },
8921
9249
  };
8922
9250
 
@@ -9066,13 +9394,13 @@ class LiveReactionSyncEngine {
9066
9394
  this.stopReactionsSync();
9067
9395
  }
9068
9396
  }
9069
- let instance$3;
9397
+ let instance$4;
9070
9398
  var ReactionSyncEngine = {
9071
9399
  getInstance: () => {
9072
- if (!instance$3) {
9073
- instance$3 = new LiveReactionSyncEngine();
9400
+ if (!instance$4) {
9401
+ instance$4 = new LiveReactionSyncEngine();
9074
9402
  }
9075
- return instance$3;
9403
+ return instance$4;
9076
9404
  },
9077
9405
  };
9078
9406
 
@@ -9102,19 +9430,20 @@ function prepareBlockedUserPayload(response) {
9102
9430
  }), users: users.map(convertRawUserToInternalUser) });
9103
9431
  }
9104
9432
 
9105
- const BLOCK_LIST_LIMIT = 100;
9106
- const TTL_MS = 5 * 60 * 1000; // 5 minutes
9433
+ const BLOCK_LIST_LIMIT$1 = 100;
9434
+ const TTL_MS$1 = 5 * 60 * 1000; // 5 minutes
9107
9435
  /**
9108
9436
  * Session-scoped singleton engine that manages TTL-based fetching and caching
9109
9437
  * of blocked users. Provides a lazy `ensureFetched()` gate for the
9110
9438
  * `getAllBlockedUsers()` API.
9111
9439
  *
9112
9440
  * Key behaviours:
9113
- * - `establish()` is a no-op — fetch is lazy, triggered only by consumer call
9114
- * - `destroy()` resets `lastFetchedAt` to null (ensures fresh fetch on next session)
9441
+ * - `onSessionEstablished()` is a no-op — fetch is lazy, triggered only by consumer call
9442
+ * - `onSessionDestroyed()` resets `lastFetchedAt` to null (ensures fresh fetch on next session)
9115
9443
  * - `ensureFetched()` fetches from server only when cache is expired or never fetched
9116
9444
  * - `lastFetchedAt` is only updated on successful fetch
9117
- * - `blockedUserIds` is kept in sync with each successful fetch
9445
+ * - reads query the follow cache live, so block/unblock changes are reflected
9446
+ * even within the TTL window
9118
9447
  *
9119
9448
  * @internal
9120
9449
  */
@@ -9122,12 +9451,7 @@ class BlockedUserSyncEngine {
9122
9451
  constructor() {
9123
9452
  /** Epoch ms of last successful fetch. null = never fetched in this session. */
9124
9453
  this.lastFetchedAt = null;
9125
- /** Ordered list of userId strings from the most recent successful fetch. */
9126
- this.blockedUserIds = [];
9127
9454
  }
9128
- // ---------------------------------------------------------------------------
9129
- // SessionComponent lifecycle
9130
- // ---------------------------------------------------------------------------
9131
9455
  /** No-op — fetch is lazy, triggered by consumer calling getAllBlockedUsers(). */
9132
9456
  // eslint-disable-next-line class-methods-use-this
9133
9457
  onSessionEstablished() {
@@ -9136,24 +9460,17 @@ class BlockedUserSyncEngine {
9136
9460
  /** Resets state so the next session starts with a cold cache. */
9137
9461
  onSessionDestroyed() {
9138
9462
  this.lastFetchedAt = null;
9139
- this.blockedUserIds = [];
9140
9463
  }
9141
9464
  /** No-op for this engine. */
9142
9465
  // eslint-disable-next-line class-methods-use-this
9143
9466
  onTokenExpired() {
9144
9467
  // intentionally empty
9145
9468
  }
9146
- // ---------------------------------------------------------------------------
9147
- // Cache helpers
9148
- // ---------------------------------------------------------------------------
9149
9469
  isCacheExpired() {
9150
9470
  if (this.lastFetchedAt === null)
9151
9471
  return true;
9152
- return Date.now() - this.lastFetchedAt > TTL_MS;
9472
+ return Date.now() - this.lastFetchedAt > TTL_MS$1;
9153
9473
  }
9154
- // ---------------------------------------------------------------------------
9155
- // Core fetch gate
9156
- // ---------------------------------------------------------------------------
9157
9474
  /**
9158
9475
  * Ensures the local store is populated with fresh blocked-user data.
9159
9476
  *
@@ -9169,52 +9486,50 @@ class BlockedUserSyncEngine {
9169
9486
  if (!this.isCacheExpired())
9170
9487
  return;
9171
9488
  const client = getActiveClient();
9172
- const { data } = await client.http.get('/api/v4/me/user-blocks', { params: { options: { limit: BLOCK_LIST_LIMIT }, isDeleted: false } });
9489
+ const { data } = await client.http.get('/api/v4/me/user-blocks', { params: { options: { limit: BLOCK_LIST_LIMIT$1 }, isDeleted: false } });
9173
9490
  const cachedAt = client.cache && Date.now();
9174
9491
  const payload = prepareBlockedUserPayload(data);
9175
9492
  if (client.cache) {
9176
9493
  ingestInCache(payload, { cachedAt });
9177
9494
  }
9178
- // Keep the ordered list of blocked user IDs for getCachedUsers()
9179
- this.blockedUserIds = payload.users.map(u => u.userId);
9180
9495
  // Only update timestamp on success — failure leaves it unchanged so the
9181
9496
  // next call retries.
9182
9497
  this.lastFetchedAt = Date.now();
9183
9498
  }
9184
- // ---------------------------------------------------------------------------
9185
- // Local store read
9186
- // ---------------------------------------------------------------------------
9187
9499
  /**
9188
- * Returns blocked {@link Amity.InternalUser} objects from the in-memory cache.
9189
- *
9190
- * Applies the spec-mandated filter:
9191
- * - Only users whose `isDeleted` is false or null
9192
- * - Hard limit of 100 results
9500
+ * Returns the blocked users by querying the follow cache live — the outgoing
9501
+ * direction (`from === me`, `status === 'blocked'`). Reading the cache (not a
9502
+ * fetched snapshot) means `blockUser()` / `unblockUser()` changes are reflected
9503
+ * even within the TTL window.
9193
9504
  *
9194
- * This always reads the latest local state, so changes made by `blockUser()`
9195
- * and `unblockUser()` are reflected even within the TTL window.
9505
+ * Applies the spec-mandated query:
9506
+ * - filter `from === currentUserId`, `status === 'blocked'`, blocked user not deleted
9507
+ * - sort by `updatedAt` DESC
9508
+ * - hard limit of 100 results
9196
9509
  */
9510
+ // eslint-disable-next-line class-methods-use-this
9197
9511
  getCachedUsers() {
9512
+ var _a;
9198
9513
  const client = getActiveClient();
9199
- if (!client.cache) {
9200
- // No cache available — fall back to the in-memory list from the last fetch
9514
+ if (!client.cache)
9201
9515
  return [];
9202
- }
9203
- return this.blockedUserIds
9204
- .map(id => { var _a; return (_a = pullFromCache(['user', 'get', id])) === null || _a === void 0 ? void 0 : _a.data; })
9516
+ const { userId } = client;
9517
+ return ((_a = queryCache(['follow', 'get'])) !== null && _a !== void 0 ? _a : [])
9518
+ .map(entry => entry.data)
9519
+ .filter(follow => (follow === null || follow === void 0 ? void 0 : follow.status) === 'blocked' && follow.from === userId)
9520
+ .sort((a, b) => { var _a, _b; return (((_a = a.updatedAt) !== null && _a !== void 0 ? _a : '') < ((_b = b.updatedAt) !== null && _b !== void 0 ? _b : '') ? 1 : -1); })
9521
+ .map(follow => { var _a; return (_a = pullFromCache(['user', 'get', follow.to])) === null || _a === void 0 ? void 0 : _a.data; })
9205
9522
  .filter((user) => user != null && user.isDeleted !== true)
9206
- .slice(0, BLOCK_LIST_LIMIT);
9523
+ .slice(0, BLOCK_LIST_LIMIT$1)
9524
+ .map(userLinkedObject);
9207
9525
  }
9208
9526
  }
9209
- // ---------------------------------------------------------------------------
9210
- // Module-level singleton
9211
- // ---------------------------------------------------------------------------
9212
- let instance$2 = null;
9527
+ let instance$3 = null;
9213
9528
  var BlockedUserSyncEngine$1 = {
9214
9529
  getInstance: () => {
9215
- if (!instance$2)
9216
- instance$2 = new BlockedUserSyncEngine();
9217
- return instance$2;
9530
+ if (!instance$3)
9531
+ instance$3 = new BlockedUserSyncEngine();
9532
+ return instance$3;
9218
9533
  },
9219
9534
  };
9220
9535
 
@@ -9236,6 +9551,290 @@ var blockedUserSyncEngineOnLoginHandler = () => {
9236
9551
  };
9237
9552
  };
9238
9553
 
9554
+ function prepareBlockingUserPayload(response) {
9555
+ const { users, follows } = response, rest = __rest(response, ["users", "follows"]);
9556
+ return Object.assign(Object.assign({}, rest), { follows: follows.map(follow => {
9557
+ const followUser = users.find(user => user.userId === follow.from);
9558
+ return Object.assign(Object.assign({}, follow), { user: convertRawUserToInternalUser(followUser) });
9559
+ }), users: users.map(convertRawUserToInternalUser) });
9560
+ }
9561
+
9562
+ const BLOCK_LIST_LIMIT = 100;
9563
+ const TTL_MS = 5 * 60 * 1000; // 5 minutes
9564
+ /**
9565
+ * Session-scoped singleton engine that manages TTL-based fetching and caching
9566
+ * of blocking users (the "blocked-by" list — users who blocked the current
9567
+ * user). Provides a lazy `ensureFetched()` gate for the `getAllBlockingUsers()`
9568
+ * API. Directional inverse of {@link BlockedUserSyncEngine}.
9569
+ *
9570
+ * Key behaviours:
9571
+ * - `onSessionEstablished()` is a no-op — fetch is lazy, triggered only by consumer call
9572
+ * - `onSessionDestroyed()` resets `lastFetchedAt` to null (ensures fresh fetch on next session)
9573
+ * - `ensureFetched()` fetches from server only when cache is expired or never fetched
9574
+ * - `lastFetchedAt` is only updated on successful fetch
9575
+ * - reads query the follow cache live, so block/unblock changes are reflected
9576
+ * even within the TTL window
9577
+ *
9578
+ * @internal
9579
+ */
9580
+ class BlockingUserSyncEngine {
9581
+ constructor() {
9582
+ /** Epoch ms of last successful fetch. null = never fetched in this session. */
9583
+ this.lastFetchedAt = null;
9584
+ }
9585
+ /** No-op — fetch is lazy, triggered by consumer calling getAllBlockingUsers(). */
9586
+ // eslint-disable-next-line class-methods-use-this
9587
+ onSessionEstablished() {
9588
+ // intentionally empty
9589
+ }
9590
+ /** Resets state so the next session starts with a cold cache. */
9591
+ onSessionDestroyed() {
9592
+ this.lastFetchedAt = null;
9593
+ }
9594
+ /** No-op for this engine. */
9595
+ // eslint-disable-next-line class-methods-use-this
9596
+ onTokenExpired() {
9597
+ // intentionally empty
9598
+ }
9599
+ isCacheExpired() {
9600
+ if (this.lastFetchedAt === null)
9601
+ return true;
9602
+ return Date.now() - this.lastFetchedAt > TTL_MS;
9603
+ }
9604
+ /**
9605
+ * Ensures the local store is populated with fresh blocking-user data.
9606
+ *
9607
+ * - If the cache is still within the 5-minute TTL window: resolves immediately
9608
+ * (no server call).
9609
+ * - If the cache is expired (or never fetched): fetches from the server,
9610
+ * persists the payload to the cache, and updates `lastFetchedAt`.
9611
+ *
9612
+ * On failure the error propagates to the caller and `lastFetchedAt` is NOT
9613
+ * updated, so the next call will retry.
9614
+ */
9615
+ async ensureFetched() {
9616
+ if (!this.isCacheExpired())
9617
+ return;
9618
+ const client = getActiveClient();
9619
+ const { data } = await client.http.get('/api/v4/me/blockers', { params: { options: { limit: BLOCK_LIST_LIMIT }, isDeleted: false } });
9620
+ const cachedAt = client.cache && Date.now();
9621
+ const payload = prepareBlockingUserPayload(data);
9622
+ if (client.cache) {
9623
+ ingestInCache(payload, { cachedAt });
9624
+ }
9625
+ // Only update timestamp on success — failure leaves it unchanged so the
9626
+ // next call retries.
9627
+ this.lastFetchedAt = Date.now();
9628
+ }
9629
+ /**
9630
+ * Returns the "blocked-by" users by querying the follow cache live — the
9631
+ * incoming direction (`to === me`, `status === 'blocked'`). Reading the cache
9632
+ * (not a fetched snapshot) means RTE `user.didBlock` / `user.didUnblock`
9633
+ * changes are reflected even within the TTL window.
9634
+ *
9635
+ * Applies the spec-mandated query (REQ-012/013/014):
9636
+ * - filter `to === currentUserId`, `status === 'blocked'`, blocker not deleted
9637
+ * - sort by `updatedAt` DESC
9638
+ * - hard limit of 100 results
9639
+ */
9640
+ // eslint-disable-next-line class-methods-use-this
9641
+ getCachedUsers() {
9642
+ var _a;
9643
+ const client = getActiveClient();
9644
+ if (!client.cache)
9645
+ return [];
9646
+ const { userId } = client;
9647
+ return ((_a = queryCache(['follow', 'get'])) !== null && _a !== void 0 ? _a : [])
9648
+ .map(entry => entry.data)
9649
+ .filter(follow => (follow === null || follow === void 0 ? void 0 : follow.status) === 'blocked' && follow.to === userId)
9650
+ .sort((a, b) => { var _a, _b; return (((_a = a.updatedAt) !== null && _a !== void 0 ? _a : '') < ((_b = b.updatedAt) !== null && _b !== void 0 ? _b : '') ? 1 : -1); })
9651
+ .map(follow => { var _a; return (_a = pullFromCache(['user', 'get', follow.from])) === null || _a === void 0 ? void 0 : _a.data; })
9652
+ .filter((user) => user != null && user.isDeleted !== true)
9653
+ .slice(0, BLOCK_LIST_LIMIT)
9654
+ .map(userLinkedObject);
9655
+ }
9656
+ }
9657
+ let instance$2 = null;
9658
+ var BlockingUserSyncEngine$1 = {
9659
+ getInstance: () => {
9660
+ if (!instance$2)
9661
+ instance$2 = new BlockingUserSyncEngine();
9662
+ return instance$2;
9663
+ },
9664
+ };
9665
+
9666
+ var blockingUserSyncEngineOnLoginHandler = () => {
9667
+ const blockingUserSyncEngine = BlockingUserSyncEngine$1.getInstance();
9668
+ onSessionStateChange(state => {
9669
+ if (state === "established" /* Amity.SessionStates.ESTABLISHED */) {
9670
+ blockingUserSyncEngine.onSessionEstablished();
9671
+ }
9672
+ else if (state === "tokenExpired" /* Amity.SessionStates.TOKEN_EXPIRED */) {
9673
+ blockingUserSyncEngine.onTokenExpired();
9674
+ }
9675
+ else {
9676
+ blockingUserSyncEngine.onSessionDestroyed();
9677
+ }
9678
+ });
9679
+ return () => {
9680
+ blockingUserSyncEngine.onSessionDestroyed();
9681
+ };
9682
+ };
9683
+
9684
+ function prepareFollowersPayload(response) {
9685
+ const { users, follows } = response, rest = __rest(response, ["users", "follows"]);
9686
+ return Object.assign(Object.assign({}, rest), { follows, users: users.map(convertRawUserToInternalUser) });
9687
+ }
9688
+ function prepareFollowingsPayload(response) {
9689
+ const { users, follows } = response, rest = __rest(response, ["users", "follows"]);
9690
+ return Object.assign(Object.assign({}, rest), { follows, users: users.map(convertRawUserToInternalUser) });
9691
+ }
9692
+ function prepareFollowStatusPayload(response) {
9693
+ const { follows } = response, rest = __rest(response, ["follows"]);
9694
+ return Object.assign(Object.assign({}, rest), { follows });
9695
+ }
9696
+
9697
+ /**
9698
+ * Subscribes to a block MQTT event (`user.didBlock` / `user.didUnblock`),
9699
+ * ingests the carried `FollowersPayload` (follows + users) into the cache so
9700
+ * the block-relationship rows (`['follow', 'get', from#to]`) and user rows are
9701
+ * kept current, then forwards the affected {@link Amity.FollowStatus} to the
9702
+ * caller.
9703
+ *
9704
+ * @hidden
9705
+ */
9706
+ const createBlockEventSubscriber = (event, callback) => {
9707
+ const client = getActiveClient();
9708
+ const filter = (data) => {
9709
+ const payload = prepareFollowersPayload(data);
9710
+ if (client.cache) {
9711
+ ingestInCache(payload);
9712
+ }
9713
+ callback(payload.follows[0]);
9714
+ };
9715
+ return createEventSubscriber(client, event, event, filter);
9716
+ };
9717
+
9718
+ /**
9719
+ * ```js
9720
+ * import { onUserDidBlock } from '@amityco/ts-sdk'
9721
+ * const dispose = onUserDidBlock(status => {
9722
+ * // ...
9723
+ * })
9724
+ * ```
9725
+ *
9726
+ * Fired when a block relationship is created in real time — either a user
9727
+ * blocks the current user (incoming) or the current user blocks someone on
9728
+ * another device (outgoing). The local block-relationship store is updated
9729
+ * before the callback runs.
9730
+ *
9731
+ * @param callback The function to call when the event was fired
9732
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
9733
+ *
9734
+ * @category Block Events
9735
+ */
9736
+ const onUserDidBlock = (callback) => createBlockEventSubscriber('user.didBlock', callback);
9737
+
9738
+ /**
9739
+ * ```js
9740
+ * import { onUserDidUnblock } from '@amityco/ts-sdk'
9741
+ * const dispose = onUserDidUnblock(status => {
9742
+ * // ...
9743
+ * })
9744
+ * ```
9745
+ *
9746
+ * Fired when a block relationship is removed in real time — either a user
9747
+ * unblocks the current user (incoming) or the current user unblocks someone on
9748
+ * another device (outgoing). The local block-relationship store is updated
9749
+ * before the callback runs.
9750
+ *
9751
+ * @param callback The function to call when the event was fired
9752
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
9753
+ *
9754
+ * @category Block Events
9755
+ */
9756
+ const onUserDidUnblock = (callback) => createBlockEventSubscriber('user.didUnblock', callback);
9757
+
9758
+ /**
9759
+ * Keeps the follow cache current for incoming/outgoing block changes for the
9760
+ * whole session — the ingest happens as a side effect inside
9761
+ * createBlockEventSubscriber, so the one-shot `getAllBlockedUsers()` /
9762
+ * `getAllBlockingUsers()` reflect RTE block/unblock within the TTL window.
9763
+ *
9764
+ * Registered via `setupLoginSubscriptions`; the returned unsubscriber is torn
9765
+ * down on logout.
9766
+ */
9767
+ var blockRealtimeOnLoginHandler = () => {
9768
+ const disposers = [onUserDidBlock(() => { }), onUserDidUnblock(() => { })];
9769
+ return () => disposers.forEach(dispose => dispose());
9770
+ };
9771
+
9772
+ class CursorController {
9773
+ constructor(networkId, userId) {
9774
+ this.networkId = networkId;
9775
+ this.userId = userId;
9776
+ }
9777
+ static current() {
9778
+ try {
9779
+ const user = getCurrentUser();
9780
+ if (!user)
9781
+ return null;
9782
+ const networkId = getNetworkId(user);
9783
+ const { userId } = user;
9784
+ return networkId && userId ? new CursorController(networkId, userId) : null;
9785
+ }
9786
+ catch (_a) {
9787
+ return null;
9788
+ }
9789
+ }
9790
+ static isExpired(expiredAt) {
9791
+ return Date.now() >= expiredAt;
9792
+ }
9793
+ static clearOnLogout() {
9794
+ return onSessionStateChange(state => {
9795
+ var _a;
9796
+ if (state === "terminated" /* Amity.SessionStates.TERMINATED */)
9797
+ (_a = CursorController.current()) === null || _a === void 0 ? void 0 : _a.clear();
9798
+ });
9799
+ }
9800
+ get key() {
9801
+ return `amity:forYouFeed:cursor:${this.networkId}:${this.userId}`;
9802
+ }
9803
+ async get() {
9804
+ const raw = await getItem(this.key);
9805
+ if (!raw)
9806
+ return null;
9807
+ try {
9808
+ const parsed = JSON.parse(raw);
9809
+ if (typeof (parsed === null || parsed === void 0 ? void 0 : parsed.cursor) !== 'string' || typeof (parsed === null || parsed === void 0 ? void 0 : parsed.expiredAt) !== 'number')
9810
+ return null;
9811
+ return {
9812
+ cursor: parsed.cursor,
9813
+ expiredAt: parsed.expiredAt,
9814
+ reachedEndOfFeed: parsed.reachedEndOfFeed === true,
9815
+ };
9816
+ }
9817
+ catch (_a) {
9818
+ return null;
9819
+ }
9820
+ }
9821
+ async set(value) {
9822
+ await setItem(this.key, JSON.stringify(value));
9823
+ }
9824
+ async markReachedEndOfFeed(expiredAt) {
9825
+ var _a;
9826
+ const stored = await this.get();
9827
+ await this.set({
9828
+ cursor: (_a = stored === null || stored === void 0 ? void 0 : stored.cursor) !== null && _a !== void 0 ? _a : '',
9829
+ expiredAt,
9830
+ reachedEndOfFeed: true,
9831
+ });
9832
+ }
9833
+ async clear() {
9834
+ await setItem(this.key, '');
9835
+ }
9836
+ }
9837
+
9239
9838
  const EVENTS = [
9240
9839
  'disconnected',
9241
9840
  'error',
@@ -9425,7 +10024,7 @@ const setupLoginSubscriptions = (unsubWatcher) => {
9425
10024
  // NOTE: This is a temporary solution to handle the channel marker when the user is forced to leave
9426
10025
  // the channel because currently backend can't handle this, so every time a user is banned from
9427
10026
  // a channel or the channel is deleted the channel's unread count will not be reset to zero
9428
- onChannelDeleted(removeChannelMarkerCache), onChannelMemberBanned(removeChannelMarkerCache), markReadEngineOnLoginHandler(), analyticsEngineOnLoginHandler(), objectResolverEngineOnLoginHandler(), reactionSyncEngineOnLoginHandler(), blockedUserSyncEngineOnLoginHandler());
10027
+ onChannelDeleted(removeChannelMarkerCache), onChannelMemberBanned(removeChannelMarkerCache), markReadEngineOnLoginHandler(), analyticsEngineOnLoginHandler(), objectResolverEngineOnLoginHandler(), reactionSyncEngineOnLoginHandler(), blockedUserSyncEngineOnLoginHandler(), blockingUserSyncEngineOnLoginHandler(), blockRealtimeOnLoginHandler(), resetAutoSubscriptionsOnLogout(), CursorController.clearOnLogout());
9429
10028
  if (client.useLegacyUnreadCount) {
9430
10029
  subscriptions.push(readReceiptSyncEngineOnLoginHandler());
9431
10030
  }
@@ -10124,16 +10723,13 @@ const onMessageCreatedMqtt = (callback) => {
10124
10723
  }
10125
10724
  if (client.useLegacyUnreadCount) {
10126
10725
  rawPayload.messages.forEach(message => {
10127
- var _a, _b;
10726
+ var _a, _b, _c;
10128
10727
  const channelUnread = (_a = pullFromCache([
10129
10728
  'channelUnread',
10130
10729
  'get',
10131
10730
  message.channelId,
10132
10731
  ])) === null || _a === void 0 ? void 0 : _a.data;
10133
- if (!channelUnread ||
10134
- channelUnread.lastSegment >= message.segment ||
10135
- typeof channelUnread.readToSegment !== 'number' ||
10136
- typeof channelUnread.lastMentionedSegment !== 'number')
10732
+ if (!channelUnread || channelUnread.lastSegment >= message.segment)
10137
10733
  return;
10138
10734
  const lastSegment = message.segment;
10139
10735
  const isMentionedInMessage = (_b = message.mentionedUsers) === null || _b === void 0 ? void 0 : _b.some(mention => {
@@ -10145,7 +10741,8 @@ const onMessageCreatedMqtt = (callback) => {
10145
10741
  const lastMentionedSegment = isMentionedInMessage
10146
10742
  ? message.segment
10147
10743
  : channelUnread.lastMentionedSegment;
10148
- const updatedChannelUnread = Object.assign(Object.assign({}, channelUnread), { lastSegment, unreadCount: Math.max(lastSegment - channelUnread.readToSegment, 0), lastMentionedSegment, isMentioned: !(channelUnread.readToSegment >= lastMentionedSegment) });
10744
+ const readToSegment = (_c = channelUnread.readToSegment) !== null && _c !== void 0 ? _c : 0;
10745
+ const updatedChannelUnread = Object.assign(Object.assign({}, channelUnread), { lastSegment, unreadCount: Math.max(lastSegment - readToSegment, 0), lastMentionedSegment, isMentioned: typeof lastMentionedSegment === 'number' && readToSegment < lastMentionedSegment });
10149
10746
  pushToCache(['channelUnread', 'get', message.channelId], updatedChannelUnread);
10150
10747
  fireEvent('local.channelUnread.updated', [updatedChannelUnread]);
10151
10748
  });
@@ -10528,15 +11125,18 @@ const createClient = (apiKey, apiRegion = API_REGIONS.SG, { debugSession = DEFAU
10528
11125
  validateUrls,
10529
11126
  validateTexts,
10530
11127
  getFeedSettings,
11128
+ getCoreUserSettings,
10531
11129
  getSocialSettings,
11130
+ getChatSettings,
10532
11131
  getVisitorDeviceId: getDeviceId,
10533
- getMessagePreviewSetting,
11132
+ getMessagePreviewSetting: getMessagePreviewSetting$1,
10534
11133
  onRTEConnectionStateChange,
10535
11134
  use: () => setActiveClient(client),
10536
11135
  isUnreadCountEnabled,
10537
11136
  useLegacyUnreadCount,
10538
11137
  getMarkerSyncConsistentMode,
10539
11138
  getProductCatalogueSetting,
11139
+ getForYouFeedSetting,
10540
11140
  /**
10541
11141
  * Prefix for the deviceId key in the local storage or async storage.
10542
11142
  * This is allow user to have multiple SDK client and Mqtt client within the same app.
@@ -10848,6 +11448,13 @@ const getLinkPreviewMetadata = async (url) => {
10848
11448
  return data;
10849
11449
  };
10850
11450
 
11451
+ const CONTENT_TYPE_CONFIG = {
11452
+ [exports.AmitySharableContentType.POST]: { key: 'posts', placeholder: 'postId' },
11453
+ [exports.AmitySharableContentType.COMMUNITY]: { key: 'communities', placeholder: 'communityId' },
11454
+ [exports.AmitySharableContentType.USER]: { key: 'users', placeholder: 'userId' },
11455
+ [exports.AmitySharableContentType.LIVESTREAM]: { key: 'livestream', placeholder: 'livestream' },
11456
+ [exports.AmitySharableContentType.EVENT]: { key: 'events', placeholder: 'eventId' },
11457
+ };
10851
11458
  /**
10852
11459
  * ```js
10853
11460
  * import Client from '@amityco/ts-sdk-react-native'
@@ -10863,9 +11470,29 @@ const getLinkPreviewMetadata = async (url) => {
10863
11470
  * @async
10864
11471
  */
10865
11472
  const getShareableLinkConfiguration = async () => {
11473
+ var _a, _b;
10866
11474
  const client = getActiveClient();
10867
11475
  const { data } = await client.http.get(`/api/v3/network-settings/shareable-deep-links`);
10868
- return data;
11476
+ const domain = (_a = data.domain) !== null && _a !== void 0 ? _a : '';
11477
+ const patterns = (_b = data.patterns) !== null && _b !== void 0 ? _b : {};
11478
+ return {
11479
+ domain,
11480
+ patterns,
11481
+ isEnabled(contentType) {
11482
+ const { key } = CONTENT_TYPE_CONFIG[contentType];
11483
+ return !!domain && !!patterns[key];
11484
+ },
11485
+ getPattern(contentType) {
11486
+ const { key } = CONTENT_TYPE_CONFIG[contentType];
11487
+ return patterns[key] || null;
11488
+ },
11489
+ generateLink(contentType, referenceId) {
11490
+ const { key, placeholder } = CONTENT_TYPE_CONFIG[contentType];
11491
+ if (!domain || !patterns[key])
11492
+ return null;
11493
+ return domain + patterns[key].replace(`{${placeholder}}`, referenceId);
11494
+ },
11495
+ };
10869
11496
  };
10870
11497
 
10871
11498
  /**
@@ -11190,6 +11817,71 @@ class Notifications {
11190
11817
  }
11191
11818
  const notifications = () => new Notifications();
11192
11819
 
11820
+ /* begin_public_function
11821
+ id: client.enable_auto_subscriptions
11822
+ */
11823
+ /**
11824
+ * ```js
11825
+ * import { Client, AmityAutoSubscription } from '@amityco/ts-sdk'
11826
+ * Client.enableAutoSubscriptions([AmityAutoSubscription.BLOCK])
11827
+ * ```
11828
+ *
11829
+ * Enables one or more managed auto-subscription handles. Managed handles are
11830
+ * re-applied on every (re)connect and ref-counted. All handles are on by
11831
+ * default; use this to re-enable handles previously turned off via
11832
+ * {@link disableAutoSubscriptions}. Synchronous fire-and-forget — the registry
11833
+ * updates immediately and the broker subscribe is retried on reconnect.
11834
+ *
11835
+ * @param features the {@link AmityAutoSubscription} handles to enable
11836
+ *
11837
+ * @category Client API
11838
+ */
11839
+ const enableAutoSubscriptions = (features) => {
11840
+ const manager = getAutoSubscriptionManager();
11841
+ features.forEach(feature => manager.subscribe(feature));
11842
+ };
11843
+ /* end_public_function */
11844
+ /* begin_public_function
11845
+ id: client.disable_auto_subscriptions
11846
+ */
11847
+ /**
11848
+ * ```js
11849
+ * import { Client, AmityAutoSubscription } from '@amityco/ts-sdk'
11850
+ * Client.disableAutoSubscriptions([AmityAutoSubscription.LIVESTREAM])
11851
+ * ```
11852
+ *
11853
+ * Disables one or more managed auto-subscription handles. The change persists
11854
+ * across reconnect (it is not silently re-enabled) until
11855
+ * {@link enableAutoSubscriptions} is called again. Synchronous fire-and-forget.
11856
+ *
11857
+ * @param features the {@link AmityAutoSubscription} handles to disable
11858
+ *
11859
+ * @category Client API
11860
+ */
11861
+ const disableAutoSubscriptions = (features) => {
11862
+ const manager = getAutoSubscriptionManager();
11863
+ features.forEach(feature => manager.unsubscribe(feature));
11864
+ };
11865
+ /* end_public_function */
11866
+ /* begin_public_function
11867
+ id: client.auto_subscriptions
11868
+ */
11869
+ /**
11870
+ * ```js
11871
+ * import { Client } from '@amityco/ts-sdk'
11872
+ * Client.autoSubscriptions().forEach(s => console.log(s.feature, s.isActive, s.topicCount))
11873
+ * ```
11874
+ *
11875
+ * Inspects the managed auto-subscription registry — each handle's `isActive`,
11876
+ * `isSystem`, and `topicCount`.
11877
+ *
11878
+ * @returns a snapshot of the managed subscription registry
11879
+ *
11880
+ * @category Client API
11881
+ */
11882
+ const autoSubscriptions = () => getAutoSubscriptionManager().subscriptions();
11883
+ /* end_public_function */
11884
+
11193
11885
  /**
11194
11886
  * ```js
11195
11887
  * import { onChannelMarkerFetched } from '@amityco/ts-sdk-react-native'
@@ -11567,13 +12259,19 @@ var index$s = /*#__PURE__*/Object.freeze({
11567
12259
  getSocialSettings: getSocialSettings,
11568
12260
  getShareableLinkConfiguration: getShareableLinkConfiguration,
11569
12261
  getProductCatalogueSetting: getProductCatalogueSetting,
12262
+ getForYouFeedSetting: getForYouFeedSetting,
11570
12263
  loginAsVisitor: loginAsVisitor,
11571
12264
  loginAsBot: loginAsBot,
11572
12265
  getCurrentUser: getCurrentUser,
11573
12266
  getCurrentUserType: getCurrentUserType,
11574
12267
  setCurrentUserType: setCurrentUserType,
11575
12268
  setAccessTokenHandler: setAccessTokenHandler,
12269
+ getChatSettings: getChatSettings,
12270
+ getCoreUserSettings: getCoreUserSettings,
11576
12271
  notifications: notifications,
12272
+ enableAutoSubscriptions: enableAutoSubscriptions,
12273
+ disableAutoSubscriptions: disableAutoSubscriptions,
12274
+ autoSubscriptions: autoSubscriptions,
11577
12275
  onConnectionError: onConnectionError,
11578
12276
  onClientDisconnected: onClientDisconnected,
11579
12277
  onClientBanned: onClientBanned,
@@ -11591,19 +12289,6 @@ var index$s = /*#__PURE__*/Object.freeze({
11591
12289
  getMarkerSyncConsistentMode: getMarkerSyncConsistentMode
11592
12290
  });
11593
12291
 
11594
- function prepareFollowersPayload(response) {
11595
- const { users, follows } = response, rest = __rest(response, ["users", "follows"]);
11596
- return Object.assign(Object.assign({}, rest), { follows, users: users.map(convertRawUserToInternalUser) });
11597
- }
11598
- function prepareFollowingsPayload(response) {
11599
- const { users, follows } = response, rest = __rest(response, ["users", "follows"]);
11600
- return Object.assign(Object.assign({}, rest), { follows, users: users.map(convertRawUserToInternalUser) });
11601
- }
11602
- function prepareFollowStatusPayload(response) {
11603
- const { follows } = response, rest = __rest(response, ["follows"]);
11604
- return Object.assign(Object.assign({}, rest), { follows });
11605
- }
11606
-
11607
12292
  /* begin_public_function
11608
12293
  id: user.relationship.block
11609
12294
  */
@@ -12781,6 +13466,8 @@ var index$r = /*#__PURE__*/Object.freeze({
12781
13466
  __proto__: null,
12782
13467
  blockUser: blockUser,
12783
13468
  unBlockUser: unBlockUser,
13469
+ onUserDidBlock: onUserDidBlock,
13470
+ onUserDidUnblock: onUserDidUnblock,
12784
13471
  follow: follow,
12785
13472
  unfollow: unfollow,
12786
13473
  acceptMyFollower: acceptMyFollower,
@@ -13610,7 +14297,7 @@ const getWatchSessionStorage = () => {
13610
14297
  return storageInstance;
13611
14298
  };
13612
14299
 
13613
- const privateKey = "-----BEGIN PRIVATE KEY-----\nMIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQDAARz+hmBgi8pJ\nQb8LeY41gtHhk+ACMwRfhsn7GqpqRQNG2qU0755mzZuVDUqjQMGSo8THJB7O+OJs\nflbZRkFXlFoFOVNw1UpNOgwEQZ6wB9oRwzepTJAfF1sVhm/o/ixvXh1zDFNDy6yZ\npXyiiJHUVxqyjllZhxnwdvjoVtDs6hW6awG09bB9nh/TTejlUKXoAgzqVwu/1QMu\nUVViET495elEe19aUarEy+oL2iKeXCEvqda/pWNBdbieFyJvvZ08HN8dPuT88wq2\njZLEAth1vrwQ2IAa4ktaLcBQdLJgIkrbDvAiVZ8lQAjS/bq5vXQikTGvoPlC5bbn\nvuOM/3eLAgMBAAECggEAVZ+peHAghq2QVj71nX5lxsNCKaCyYwixSJBpfouTt7Rz\nE6PpzMOXFi1W1o+I22jDakuSM2SOQKqI/u0QefB0r0O/KVk5NrZHXk0mkrdYtxOp\nUgaGyf8UvmjB+8VqHrNKyZdk9qtmbnNj01kTTcAtmE4H39zPR7eR/8Rul94vaZbs\nwCnKJS3mLT3JxyGug6lxanveKkjG+CKC1nJQYWaxCJxaFSzbwXQPvDhB+TvrIbee\npd5v4EAyEJohpr+T9oDGGJkb/KARBZCtwLyB976PKJwwBA8MRVL1i5QwawuMiMq5\nUtnOnbGKtCeFzaLbNU0Qi8bqyims84EQxC6DOu1fkQKBgQDdvsoBsEhsOXV7hlIJ\naEd0eSJZVkdqimxH8uGoMM2FeNaOrcB6yBXqTSP0R3OIyf8eaY6yjRvP30ZNXcll\n/gD3O1Mu6YmWQdt1W2WA6pKOsUuPXasf0pdOF7IiFZKlSabz5YHXFqwVuqm8loaj\nsXel3YWqPVdHiankE7tz+3ssnQKBgQDdqi4TNdD1MdEpihx19jr0QjUiXW3939FK\nqp30HESPEGDGQzXdmJgif9HhZb+cJSuWaHEbjgBrYahvgCF+y6LbEpOD+D/dmT+s\nDEAQaR84sah6dokwPjV8fjBSrcVFjCS+doxv0d3p/9OUEeyUhFrY03nxtIEYkLIE\n/Zvn37b4RwKBgQCLENVFe9XfsaVhQ5r9dV2iyTlmh7qgMZG5CbTFs12hQGhm8McO\n+Z7s41YSJCFr/yq1WwP4LJDtrBw99vyQr1zRsG35tNLp3gGRNzGQSQyC2uQFVHw2\np+7mNewsfhUK/gbrXNsyFnDz6635rPlhfbII3sWuP2wWXFqkxE9CbMwR7QKBgQC6\nawDMzxmo2/iYArrkyevSuEuPVxvFwpF1RgAI6C0QVCnPE38dmdN4UB7mfHekje4W\nVEercMURidPp0cxZolCYBQtilUjAyL0vqC3In1/Ogjq6oy3FEMxSop1pKxMY5j+Q\nnoqFD+6deLUrddeNH7J3X4LSr4dSbX4JjG+tlgt+yQKBgQCuwTL4hA6KqeInQ0Ta\n9VQX5Qr8hFlqJz1gpymi/k63tW/Ob8yedbg3WWNWyShwRMFYyY9S81ITFWM95uL6\nvF3x9rmRjwElJw9PMwVu6dmf/CO0Z1wzXSp2VVD12gbrUD/0/d7MUoJ9LgC8X8f/\nn0txLHYGHbx+nf95+JUg6lV3hg==\n-----END PRIVATE KEY-----";
14300
+ const privateKey = "-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDHo80SecH7FuF2\nhFYnb+l26/VN8UMLXAQFLnxciNTEwkGVFMpdezlH8rU2HtUJL4RETogbAOLVY0XM\njs6sPn8G1nALmh9qeDpUtVqFOVtBHxEZ910TLOtQiunjqJKO5nWdqZ71EC3OFluR\niGQkO84BiIFbv37ub7xl3S8XarbtKoLcyVpkDHi+1wx1pgCAn6gtBUgckPL5NR8j\nLseabl3HAXQfhTCKo4tmOFM2Dxwl1IUMmIJrJg/aIU/U0tj/1Eoo7mG0JcNWX19l\nW3EecCbi0ncCJOrkUdwlBrcjaMayaX/ubEwyUeTGiLdyc4L3GRLHjyK8xgVNXRMH\nbZWJ2a5NAgMBAAECggEASxuE+35zTFO/XydKgmvIGcWL9FbgMlXb7Vcf0nBoG945\nbiz0NVc2paraIhJXc608xbYF3qLmtAE1MVBI0ORyRdBHNxY024l/6H6SH60Ed+uI\nM4ysp5ourY6Vj+DLwpdRiI9YDjqYAQDIUmhNxJP7XPhOMoZI6st+xZQBM34ic/bv\nAMSJm9OZphSp3+qXVkFZztr2mxD2EZSJJLYxi8BCdgM2qhazalbcJ6zDKHCZWVWm\n8RRxDGldyMb/237JxETzP40tAlzOZDmBAbUgEnurDJ93RVDIE3rbZUshwgeQd18a\nem096mWgvB1AIKYgsTAR3pw+V19YWAjq/glP6fz8wQKBgQD/oQq+ukKF0PRgBeM5\ngeTjSwsdGppQLmf5ndujvoiz/TpdjDEPu6R8kigQr1rG2t4K/yfdZoI8RdmJD1al\n3Q7N9hofooSy4rj6E3txzWZCHJjHad2cnCp/O26HiReGAl7wTcfTmNdiFHhZQzm5\nJBkvWAiwuvQMNfEbnXxw6/vIDwKBgQDH7fX8gsc77JLvAWgp1MaQN/sbqVb6JeT1\nFQfR8E/WFCSmzQBtNzd5KgYuCeelwr/8DyYytvN2BzCYZXp73gI1jF3YlW5jVn74\nOY6TwQ095digwo6Z0yuxopdIOApKgAkL9PRKgNrqAf3NAyMua6lOGifzjDojC3KU\nfylQmxMn4wKBgHp2B9O/H0dEBw5JQ8W0+JX6yWQz7mEjGiR2/1W+XXb8hQ1zr709\nw1r6Gb+EghRpnZ3fBpYGGbYOMFx8wKHM+N6qW3F0ReX8v2juFGE8aRSa5oYBrWzt\nU16Idjbv8hj84cZ1PJmdyvDtpYn9rpWHOZl4rxEbPvbqkIsOMyNVqdT5AoGAOSge\nmwIIU2le2FVeohbibXiToWTYKMuMmURZ5/r72AgKMmWJKbAPe+Q3wBG01/7FRBpQ\noU8Ma0HC8s6QJbliiEyIx9JwrJWd1vkdecBHONrtA4ibm/5zD2WcOllLF+FitLhi\n3qnX6+6F0IaFGFBPJrTzlv0P4dTz/OAdv52V7GECgYEA2TttOKBAqWllgOaZOkql\nLVMJVmgR7s6tLi1+cEP8ZcapV9aRbRzTAKXm4f8AEhtlG9F9kCOvHYCYGi6JaiWJ\nZkHjeex3T+eE6Di6y5Bm/Ift5jtVhJ4jCVwHOKTMej79NPUFTJfv8hCo29haBDv6\nRXFrv+T21KCcw8k3sJeJWWQ=\n-----END PRIVATE KEY-----";
13614
14301
  /*
13615
14302
  * The crypto algorithm used for importing key and signing string
13616
14303
  */
@@ -14932,6 +15619,10 @@ const postLinkedObject = (post) => {
14932
15619
  const analyticsEngineInstance = AnalyticsEngine$1.getInstance();
14933
15620
  analyticsEngineInstance.markPostAsViewed(post.postId);
14934
15621
  },
15622
+ markAsMeaningfullyViewed: (feedRenderPosition) => {
15623
+ const analyticsEngineInstance = AnalyticsEngine$1.getInstance();
15624
+ analyticsEngineInstance.markPostAsMeaningfullyViewed(post.postId, feedRenderPosition);
15625
+ },
14935
15626
  },
14936
15627
  get productTags() {
14937
15628
  var _a, _b;
@@ -15121,6 +15812,11 @@ const addReaction$1 = async (referenceType, referenceId, reactionName, reference
15121
15812
  });
15122
15813
  return true;
15123
15814
  }
15815
+ if (referenceType === 'message') {
15816
+ upsertInCache(['message', 'get', referenceId], updatedModel);
15817
+ fireEvent('local.message.updated', { messages: [updatedModel] });
15818
+ return true;
15819
+ }
15124
15820
  }
15125
15821
  return true;
15126
15822
  };
@@ -15199,7 +15895,7 @@ const removeReaction$1 = async (referenceType, referenceId, reactionName, refere
15199
15895
  return true;
15200
15896
  }
15201
15897
  if (referenceType === 'story') {
15202
- fireEvent('local.story.reactionAdded', {
15898
+ fireEvent('local.story.reactionRemoved', {
15203
15899
  story: updatedModel,
15204
15900
  reactor: {
15205
15901
  userId: client.userId,
@@ -15209,6 +15905,11 @@ const removeReaction$1 = async (referenceType, referenceId, reactionName, refere
15209
15905
  });
15210
15906
  return true;
15211
15907
  }
15908
+ if (referenceType === 'message') {
15909
+ upsertInCache(['message', 'get', referenceId], updatedModel);
15910
+ fireEvent('local.message.updated', { messages: [updatedModel] });
15911
+ return true;
15912
+ }
15212
15913
  }
15213
15914
  return true;
15214
15915
  };
@@ -15481,7 +16182,7 @@ const createEventResponseSubscriber = (event, callback) => {
15481
16182
  const eventResponse = pullFromCache([
15482
16183
  'eventResponse',
15483
16184
  'get',
15484
- payload.eventResponses[0].eventId,
16185
+ unpackedPayload.eventResponses[0].userId,
15485
16186
  ]);
15486
16187
  callback(eventResponse.data);
15487
16188
  }
@@ -16145,7 +16846,38 @@ const getAllBlockedUsers = async () => {
16145
16846
  const engine = BlockedUserSyncEngine$1.getInstance();
16146
16847
  // Ensure data is fetched (no-op if cache is fresh)
16147
16848
  await engine.ensureFetched();
16148
- // Read from the engine's bounded ID list — O(blocked users) not O(cache size)
16849
+ return engine.getCachedUsers();
16850
+ };
16851
+ /* end_public_function */
16852
+
16853
+ /* begin_public_function
16854
+ id: user.get_all_blocking_users
16855
+ */
16856
+ /**
16857
+ * ```js
16858
+ * import { UserRepository } from '@amityco/ts-sdk'
16859
+ * const blockingUsers = await UserRepository.getAllBlockingUsers()
16860
+ * ```
16861
+ *
16862
+ * Returns all users who have blocked the current user
16863
+ * non-paginated list (limit 100) with TTL-based caching (5-minute window). Within the
16864
+ * TTL window, subsequent calls resolve instantly from the local store without any
16865
+ * server call. After the TTL expires, the next call triggers a fresh server fetch.
16866
+ *
16867
+ * The directional inverse of {@link getAllBlockedUsers}.
16868
+ *
16869
+ * @returns A promise that resolves to an array of blocking {@link Amity.User} objects
16870
+ *
16871
+ * @category Block API
16872
+ * @async
16873
+ */
16874
+ const getAllBlockingUsers = async () => {
16875
+ const client = getActiveClient();
16876
+ client.log('user/getAllBlockingUsers');
16877
+ const engine = BlockingUserSyncEngine$1.getInstance();
16878
+ // Ensure data is fetched (no-op if cache is fresh)
16879
+ await engine.ensureFetched();
16880
+ // Read from the engine's bounded ID list — O(blocking users) not O(cache size)
16149
16881
  return engine.getCachedUsers();
16150
16882
  };
16151
16883
  /* end_public_function */
@@ -16528,6 +17260,12 @@ class BlockedUserPaginationController extends PaginationController {
16528
17260
  }
16529
17261
  }
16530
17262
 
17263
+ var EnumBlockActions;
17264
+ (function (EnumBlockActions) {
17265
+ EnumBlockActions["OnBlocked"] = "onBlocked";
17266
+ EnumBlockActions["OnUnblocked"] = "onUnblocked";
17267
+ })(EnumBlockActions || (EnumBlockActions = {}));
17268
+
16531
17269
  class BlockedUserQueryStreamController extends QueryStreamController {
16532
17270
  constructor(query, cacheKey, notifyChange, preparePayload) {
16533
17271
  super(query, cacheKey);
@@ -16557,11 +17295,16 @@ class BlockedUserQueryStreamController extends QueryStreamController {
16557
17295
  }
16558
17296
  reactor(action) {
16559
17297
  return (targetUser) => {
16560
- var _a;
16561
- if (action === EnumFollowActions.OnFollowed) {
17298
+ var _a, _b;
17299
+ const isRemoval = action === EnumFollowActions.OnFollowed || action === EnumBlockActions.OnUnblocked;
17300
+ const isAddition = action === EnumBlockActions.OnBlocked;
17301
+ if (isRemoval || isAddition) {
16562
17302
  const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
16563
- const updatedCollection = collection === null || collection === void 0 ? void 0 : collection.data.filter(id => id !== targetUser.userId);
16564
- pushToCache(this.cacheKey, Object.assign(Object.assign({}, collection), { data: updatedCollection }));
17303
+ const ids = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
17304
+ const data = isAddition
17305
+ ? [...new Set([...ids, targetUser.userId])]
17306
+ : ids.filter(id => id !== targetUser.userId);
17307
+ pushToCache(this.cacheKey, Object.assign(Object.assign({}, collection), { data }));
16565
17308
  }
16566
17309
  this.notifyChange({ origin: "event" /* Amity.LiveDataOrigin.EVENT */, loading: false });
16567
17310
  };
@@ -16616,7 +17359,6 @@ class BlockedUserLiveCollectionController extends LiveCollectionController {
16616
17359
  fn: onUserDeleted$2,
16617
17360
  action: EnumUserActions.OnUserDeleted,
16618
17361
  },
16619
- // In the case of unblocking a user, we need to subscribe to the follow events
16620
17362
  {
16621
17363
  fn: convertEventPayload(onLocalUserFollowed, 'to', 'user'),
16622
17364
  action: EnumFollowActions.OnFollowed,
@@ -16625,6 +17367,28 @@ class BlockedUserLiveCollectionController extends LiveCollectionController {
16625
17367
  fn: convertEventPayload(onUserFollowed, 'to', 'user'),
16626
17368
  action: EnumFollowActions.OnFollowed,
16627
17369
  },
17370
+ {
17371
+ fn: (reactor) => onUserDidBlock(status => {
17372
+ var _a;
17373
+ if (status.from !== getActiveClient().userId)
17374
+ return;
17375
+ const blocked = (_a = pullFromCache(['user', 'get', status.to])) === null || _a === void 0 ? void 0 : _a.data;
17376
+ if (blocked)
17377
+ reactor(blocked);
17378
+ }),
17379
+ action: EnumBlockActions.OnBlocked,
17380
+ },
17381
+ {
17382
+ fn: (reactor) => onUserDidUnblock(status => {
17383
+ var _a;
17384
+ if (status.from !== getActiveClient().userId)
17385
+ return;
17386
+ const blocked = (_a = pullFromCache(['user', 'get', status.to])) === null || _a === void 0 ? void 0 : _a.data;
17387
+ if (blocked)
17388
+ reactor(blocked);
17389
+ }),
17390
+ action: EnumBlockActions.OnUnblocked,
17391
+ },
16628
17392
  ]);
16629
17393
  }
16630
17394
  notifyChange({ origin, loading, error }) {
@@ -16692,6 +17456,184 @@ const getBlockedUsers = (params, callback, config) => {
16692
17456
  };
16693
17457
  /* end_public_function */
16694
17458
 
17459
+ class BlockingUserQueryStreamController extends QueryStreamController {
17460
+ constructor(query, cacheKey, notifyChange, preparePayload) {
17461
+ super(query, cacheKey);
17462
+ this.notifyChange = notifyChange;
17463
+ this.preparePayload = preparePayload;
17464
+ }
17465
+ async saveToMainDB(response) {
17466
+ const processedPayload = await this.preparePayload(response);
17467
+ const client = getActiveClient();
17468
+ const cachedAt = client.cache && Date.now();
17469
+ if (client.cache) {
17470
+ ingestInCache(processedPayload, { cachedAt });
17471
+ }
17472
+ }
17473
+ appendToQueryStream(response, direction, refresh = false) {
17474
+ var _a, _b;
17475
+ if (refresh) {
17476
+ pushToCache(this.cacheKey, {
17477
+ data: response.users.map(getResolver('user')),
17478
+ });
17479
+ }
17480
+ else {
17481
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
17482
+ const users = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
17483
+ pushToCache(this.cacheKey, Object.assign(Object.assign({}, collection), { data: [...new Set([...users, ...response.users.map(getResolver('user'))])] }));
17484
+ }
17485
+ }
17486
+ reactor(action) {
17487
+ return (user) => {
17488
+ var _a, _b;
17489
+ if (user &&
17490
+ (action === EnumBlockActions.OnBlocked || action === EnumBlockActions.OnUnblocked)) {
17491
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
17492
+ const ids = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
17493
+ const data = action === EnumBlockActions.OnBlocked
17494
+ ? [...new Set([...ids, user.userId])]
17495
+ : ids.filter(id => id !== user.userId);
17496
+ pushToCache(this.cacheKey, Object.assign(Object.assign({}, collection), { data }));
17497
+ }
17498
+ this.notifyChange({ origin: "event" /* Amity.LiveDataOrigin.EVENT */, loading: false });
17499
+ };
17500
+ }
17501
+ subscribeRTE(createSubscriber) {
17502
+ return createSubscriber.map(subscriber => subscriber.fn(this.reactor(subscriber.action)));
17503
+ }
17504
+ }
17505
+
17506
+ class BlockingUserPaginationController extends PaginationController {
17507
+ async getRequest(queryParams, token) {
17508
+ const { limit = COLLECTION_DEFAULT_PAGINATION_SIZE } = queryParams, params = __rest(queryParams, ["limit"]);
17509
+ const options = token ? { token } : { limit };
17510
+ const { data: queryResponse } = await this.http.get('/api/v4/me/blockers', {
17511
+ params: Object.assign(Object.assign({}, params), { options, isDeleted: false }),
17512
+ });
17513
+ return queryResponse;
17514
+ }
17515
+ }
17516
+
17517
+ class BlockingUserLiveCollectionController extends LiveCollectionController {
17518
+ constructor(callback) {
17519
+ const queryStreamId = `blocking-users-${getActiveClient().userId}`;
17520
+ const query = {};
17521
+ const cacheKey = ['blockingUsers', 'collection', queryStreamId];
17522
+ const paginationController = new BlockingUserPaginationController(query);
17523
+ super(paginationController, queryStreamId, cacheKey, callback);
17524
+ this.queryStreamController = new BlockingUserQueryStreamController(query, this.cacheKey, this.notifyChange.bind(this), prepareBlockingUserPayload);
17525
+ this.callback = callback.bind(this);
17526
+ this.loadPage({ initial: true });
17527
+ }
17528
+ setup() {
17529
+ var _a;
17530
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
17531
+ if (!collection) {
17532
+ pushToCache(this.cacheKey, {
17533
+ data: [],
17534
+ params: {},
17535
+ });
17536
+ }
17537
+ }
17538
+ async persistModel(queryPayload) {
17539
+ await this.queryStreamController.saveToMainDB(queryPayload);
17540
+ }
17541
+ persistQueryStream({ response, direction, refresh, }) {
17542
+ this.queryStreamController.appendToQueryStream(response, direction, refresh);
17543
+ }
17544
+ startSubscription() {
17545
+ return this.queryStreamController.subscribeRTE([
17546
+ {
17547
+ fn: onUserDeleted$2,
17548
+ action: EnumUserActions.OnUserDeleted,
17549
+ },
17550
+ {
17551
+ fn: (reactor) => onUserDidBlock(status => {
17552
+ var _a;
17553
+ if (status.to !== getActiveClient().userId)
17554
+ return;
17555
+ const blocker = (_a = pullFromCache(['user', 'get', status.from])) === null || _a === void 0 ? void 0 : _a.data;
17556
+ if (blocker)
17557
+ reactor(blocker);
17558
+ }),
17559
+ action: EnumBlockActions.OnBlocked,
17560
+ },
17561
+ {
17562
+ fn: (reactor) => onUserDidUnblock(status => {
17563
+ var _a;
17564
+ if (status.to !== getActiveClient().userId)
17565
+ return;
17566
+ const blocker = (_a = pullFromCache(['user', 'get', status.from])) === null || _a === void 0 ? void 0 : _a.data;
17567
+ if (blocker)
17568
+ reactor(blocker);
17569
+ }),
17570
+ action: EnumBlockActions.OnUnblocked,
17571
+ },
17572
+ ]);
17573
+ }
17574
+ notifyChange({ origin, loading, error }) {
17575
+ var _a, _b;
17576
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
17577
+ if (!collection)
17578
+ return;
17579
+ const data = this.applyFilter((_b = collection.data
17580
+ .map(id => pullFromCache(['user', 'get', id]))
17581
+ .filter(isNonNullable)
17582
+ .map(({ data }) => data)
17583
+ .map(LinkedObject.user)) !== null && _b !== void 0 ? _b : []);
17584
+ if (!this.shouldNotify(data) && origin === 'event')
17585
+ return;
17586
+ this.callback({
17587
+ onNextPage: () => this.loadPage({ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */ }),
17588
+ data,
17589
+ hasNextPage: !!this.paginationController.getNextToken(),
17590
+ loading,
17591
+ error,
17592
+ });
17593
+ }
17594
+ applyFilter(data) {
17595
+ let users = data;
17596
+ users = users.filter(user => user.isDeleted == null || user.isDeleted === false);
17597
+ return users;
17598
+ }
17599
+ }
17600
+
17601
+ /* begin_public_function
17602
+ id: user.get_blocking_users
17603
+ */
17604
+ /**
17605
+ * ```js
17606
+ * import { UserRepository } from '@amityco/ts-sdk'
17607
+ * const unsubscribe = UserRepository.getBlockingUsers(({ data: users }) => {
17608
+ * console.log(users)
17609
+ * })
17610
+ * ```
17611
+ *
17612
+ * Observe the {@link Amity.User}s who have blocked the current user
17613
+ *
17614
+ * @param callback to receive updates on the blocking {@link Amity.User}s
17615
+ * @returns {@link Amity.Unsubscriber} to unsubscribe from collection
17616
+ *
17617
+ * @category User API
17618
+ */
17619
+ const getBlockingUsers = (callback) => {
17620
+ const { log, cache } = getActiveClient();
17621
+ if (!cache)
17622
+ console.log(ENABLE_CACHE_MESSAGE);
17623
+ const timestamp = Date.now();
17624
+ log(`getBlockingUsers(tmpid: ${timestamp}) > listen`);
17625
+ const blockingUserLiveCollection = new BlockingUserLiveCollectionController(callback);
17626
+ const disposers = blockingUserLiveCollection.startSubscription();
17627
+ const cacheKey = blockingUserLiveCollection.getCacheKey();
17628
+ disposers.push(() => dropFromCache(cacheKey));
17629
+ return () => {
17630
+ log(`getBlockingUsers(tmpid: ${timestamp}) > dispose`);
17631
+ disposers.forEach(fn => fn());
17632
+ dropFromCache(cacheKey);
17633
+ };
17634
+ };
17635
+ /* end_public_function */
17636
+
16695
17637
  class SearchUserPaginationController extends PaginationController {
16696
17638
  async getRequest(queryParams, token) {
16697
17639
  const { limit = COLLECTION_DEFAULT_PAGINATION_LIMIT, displayName } = queryParams, params = __rest(queryParams, ["limit", "displayName"]);
@@ -16958,6 +17900,7 @@ var index$q = /*#__PURE__*/Object.freeze({
16958
17900
  unflagUser: unflagUser,
16959
17901
  isUserFlaggedByMe: isUserFlaggedByMe,
16960
17902
  getAllBlockedUsers: getAllBlockedUsers,
17903
+ getAllBlockingUsers: getAllBlockingUsers,
16961
17904
  onUserUpdated: onUserUpdated,
16962
17905
  onUserDeleted: onUserDeleted$2,
16963
17906
  onUserFlagged: onUserFlagged,
@@ -16966,6 +17909,7 @@ var index$q = /*#__PURE__*/Object.freeze({
16966
17909
  getUser: getUser,
16967
17910
  getUsers: getUsers,
16968
17911
  getBlockedUsers: getBlockedUsers,
17912
+ getBlockingUsers: getBlockingUsers,
16969
17913
  searchUserByDisplayName: searchUserByDisplayName,
16970
17914
  getReachedUsers: getReachedUsers,
16971
17915
  get AmityUserSearchMatchType () { return AmityUserSearchMatchType; }
@@ -18132,7 +19076,7 @@ const removeReaction = async (referenceType, referenceId, reactionName) => {
18132
19076
  return true;
18133
19077
  }
18134
19078
  if (referenceType === 'story') {
18135
- fireEvent('local.story.reactionAdded', {
19079
+ fireEvent('local.story.reactionRemoved', {
18136
19080
  story: updatedModel,
18137
19081
  reactor: {
18138
19082
  userId: client.userId,
@@ -19716,6 +20660,104 @@ const unmuteChannel = async (channelId) => {
19716
20660
  };
19717
20661
  /* end_public_function */
19718
20662
 
20663
+ /* begin_public_function
20664
+ id: channel.archive
20665
+ */
20666
+ /**
20667
+ * ```js
20668
+ * import { ChannelRepository } from '@amityco/ts-sdk'
20669
+ * const success = await ChannelRepository.archiveChannel('foobar')
20670
+ * ```
20671
+ *
20672
+ * Archive a {@link Amity.Channel}.
20673
+ *
20674
+ * @param channelId The id of the {@link Amity.Channel} to archive
20675
+ * @returns A success boolean
20676
+ *
20677
+ * @category Channel API
20678
+ * @async
20679
+ */
20680
+ const archiveChannel = async (channelId) => {
20681
+ const client = getActiveClient();
20682
+ client.log('channel/archiveChannel', channelId);
20683
+ await client.http.post(`/api/v1/archives/channels/${encodeURIComponent(channelId)}`);
20684
+ const archive = {
20685
+ channelId,
20686
+ archivedAt: new Date().toISOString(),
20687
+ };
20688
+ if (client.cache) {
20689
+ pushToCache(['archivedChannel', 'get', getResolver('archivedChannel')(archive)], archive);
20690
+ }
20691
+ fireEvent('local.channel.archived', { archives: [archive] });
20692
+ };
20693
+ /* end_public_function */
20694
+
20695
+ /* begin_public_function
20696
+ id: channel.unarchive
20697
+ */
20698
+ /**
20699
+ * ```js
20700
+ * import { ChannelRepository } from '@amityco/ts-sdk'
20701
+ * const success = await ChannelRepository.unarchiveChannel('foobar')
20702
+ * ```
20703
+ *
20704
+ * Unarchive a previously archived {@link Amity.Channel}.
20705
+ *
20706
+ * @param channelId The id of the {@link Amity.Channel} to unarchive
20707
+ * @returns A success boolean
20708
+ *
20709
+ * @category Channel API
20710
+ * @async
20711
+ */
20712
+ const unarchiveChannel = async (channelId) => {
20713
+ var _a;
20714
+ const client = getActiveClient();
20715
+ client.log('channel/unarchiveChannel', channelId);
20716
+ await client.http.delete(`/api/v1/archives/channels/${encodeURIComponent(channelId)}`);
20717
+ const cached = (_a = pullFromCache(['archivedChannel', 'get', channelId])) === null || _a === void 0 ? void 0 : _a.data;
20718
+ const archive = cached !== null && cached !== void 0 ? cached : {
20719
+ channelId,
20720
+ archivedAt: new Date().toISOString(),
20721
+ };
20722
+ if (client.cache) {
20723
+ dropFromCache(['archivedChannel', 'get', channelId], true);
20724
+ }
20725
+ fireEvent('local.channel.unarchived', { archives: [archive] });
20726
+ };
20727
+ /* end_public_function */
20728
+
20729
+ /* begin_public_function
20730
+ id: channel.archive.ids
20731
+ */
20732
+ /**
20733
+ * ```js
20734
+ * import { ChannelRepository } from '@amityco/ts-sdk'
20735
+ * const ids = await ChannelRepository.getArchivedChannelIds()
20736
+ * ```
20737
+ *
20738
+ * @returns A list of archived channel ids sorted by `archivedAt` descending.
20739
+ *
20740
+ * @category Channel API
20741
+ * @async
20742
+ */
20743
+ const getArchivedChannelIds = async () => {
20744
+ var _a;
20745
+ const client = getActiveClient();
20746
+ client.log('channel/getArchivedChannelIds');
20747
+ const { data: payload } = await client.http.get(`/api/v1/archives/channels`);
20748
+ const archives = (_a = payload.archives) !== null && _a !== void 0 ? _a : [];
20749
+ if (client.cache) {
20750
+ dropFromCache(['archivedChannel', 'get']);
20751
+ archives.forEach(archive => {
20752
+ if (!archive.channelId)
20753
+ return;
20754
+ pushToCache(['archivedChannel', 'get', archive.channelId], archive);
20755
+ });
20756
+ }
20757
+ return archives.map(entry => entry.channelId).filter(channelId => !!channelId);
20758
+ };
20759
+ /* end_public_function */
20760
+
19719
20761
  /**
19720
20762
  * ```js
19721
20763
  * import { onMessageUpdated } from '@amityco/ts-sdk-react-native'
@@ -21094,6 +22136,160 @@ const getMessages = (params, callback, config) => {
21094
22136
  };
21095
22137
  /* end_public_function */
21096
22138
 
22139
+ class SearchMessagePaginationController extends PaginationController {
22140
+ async getRequest(queryParams, token) {
22141
+ const { query, exactMatch, channelId, messageFeedId, userIds, tags, types, sortBy, orderBy, limit = COLLECTION_DEFAULT_PAGINATION_LIMIT, } = queryParams;
22142
+ const options = token ? { token } : { limit, sortBy, orderBy };
22143
+ const { data: queryResponse } = await this.http.get(`/api/v2/search/messages`, {
22144
+ params: {
22145
+ query,
22146
+ exactMatch,
22147
+ channelId,
22148
+ messageFeedId,
22149
+ userIds,
22150
+ tags,
22151
+ types,
22152
+ options,
22153
+ },
22154
+ });
22155
+ return queryResponse;
22156
+ }
22157
+ }
22158
+
22159
+ class SearchMessageQueryStreamController extends QueryStreamController {
22160
+ constructor(query, cacheKey, notifyChange) {
22161
+ super(query, cacheKey);
22162
+ this.notifyChange = notifyChange;
22163
+ }
22164
+ async saveToMainDB(response) {
22165
+ var _a;
22166
+ const processedPayload = await prepareMessagePayload(response);
22167
+ const client = getActiveClient();
22168
+ const cachedAt = client.cache && Date.now();
22169
+ if (client.cache) {
22170
+ ingestInCache(processedPayload, { cachedAt });
22171
+ if ((_a = response.channels) === null || _a === void 0 ? void 0 : _a.length) {
22172
+ response.channels.forEach(channel => {
22173
+ pushToCache(['channel', 'get', channel.channelId], channel, { cachedAt });
22174
+ });
22175
+ }
22176
+ }
22177
+ }
22178
+ appendToQueryStream(response, direction, refresh = false) {
22179
+ var _a, _b;
22180
+ if (refresh) {
22181
+ pushToCache(this.cacheKey, {
22182
+ data: response.messages.map(getResolver('message')),
22183
+ });
22184
+ return;
22185
+ }
22186
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
22187
+ const existing = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
22188
+ const incoming = response.messages.map(getResolver('message'));
22189
+ pushToCache(this.cacheKey, Object.assign(Object.assign({}, collection), { data: direction === "prev" /* Amity.LiveCollectionPageDirection.PREV */
22190
+ ? [...new Set([...incoming, ...existing])]
22191
+ : [...new Set([...existing, ...incoming])] }));
22192
+ }
22193
+ }
22194
+
22195
+ class SearchMessageLiveCollectionController extends LiveCollectionController {
22196
+ constructor(query, callback) {
22197
+ const queryStreamId = hash__default["default"](query);
22198
+ const cacheKey = ['message', 'search', queryStreamId];
22199
+ const paginationController = new SearchMessagePaginationController(query);
22200
+ super(paginationController, queryStreamId, cacheKey, callback);
22201
+ this.queryStreamController = new SearchMessageQueryStreamController(query, this.cacheKey, this.notifyChange.bind(this));
22202
+ this.callback = callback.bind(this);
22203
+ this.loadPage({ initial: true });
22204
+ }
22205
+ startSubscription() {
22206
+ return [];
22207
+ }
22208
+ notifyChange({ origin, loading, error }) {
22209
+ var _a, _b;
22210
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
22211
+ if (!collection)
22212
+ return;
22213
+ const data = (_b = collection.data
22214
+ .map(messageId => getMessageFromMainDB(messageId))
22215
+ .filter(isNonNullable)
22216
+ .map(message => LinkedObject.message(message))) !== null && _b !== void 0 ? _b : [];
22217
+ if (!this.shouldNotify(data) && origin === 'event')
22218
+ return;
22219
+ this.callback({
22220
+ onNextPage: () => this.loadPage({ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */ }),
22221
+ data,
22222
+ hasNextPage: !!this.paginationController.getNextToken(),
22223
+ loading,
22224
+ error,
22225
+ });
22226
+ }
22227
+ setup() {
22228
+ var _a;
22229
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
22230
+ if (!collection) {
22231
+ pushToCache(this.cacheKey, {
22232
+ data: [],
22233
+ params: {},
22234
+ });
22235
+ }
22236
+ }
22237
+ async persistModel(response) {
22238
+ await this.queryStreamController.saveToMainDB(response);
22239
+ }
22240
+ persistQueryStream({ response, direction, refresh, }) {
22241
+ this.queryStreamController.appendToQueryStream(response, direction, refresh);
22242
+ }
22243
+ }
22244
+
22245
+ /* begin_public_function
22246
+ id: message.search
22247
+ */
22248
+ /**
22249
+ * ```js
22250
+ * import { MessageRepository } from '@amityco/ts-sdk';
22251
+ *
22252
+ * let messages = [];
22253
+ *
22254
+ * const unsubscribe = MessageRepository.searchMessage(
22255
+ * { query: 'hello' },
22256
+ * response => merge(messages, response.data),
22257
+ * );
22258
+ * ```
22259
+ *
22260
+ * Live collection of {@link Amity.Message}s matching the search query. Backed
22261
+ * by `GET /api/v2/search/messages`. The first emission delivers the first
22262
+ * page; pagination is driven by `response.onNextPage()`.
22263
+ *
22264
+ * @param params Search parameters. `query` is required.
22265
+ * @param callback Called whenever new data are available.
22266
+ * @returns An {@link Amity.Unsubscriber} function to stop observing.
22267
+ *
22268
+ * @category Message Live Collection
22269
+ */
22270
+ const searchMessage = (params, callback) => {
22271
+ if (!params.query || params.query.trim().length === 0) {
22272
+ throw new Error('Query is required for message search');
22273
+ }
22274
+ const { log, cache } = getActiveClient();
22275
+ if (!cache) {
22276
+ console.log(ENABLE_CACHE_MESSAGE);
22277
+ }
22278
+ const timestamp = Date.now();
22279
+ log(`searchMessage(tmpid: ${timestamp}) > listen`);
22280
+ const controller = new SearchMessageLiveCollectionController(params, callback);
22281
+ const disposers = controller.startSubscription();
22282
+ const cacheKey = controller.getCacheKey();
22283
+ disposers.push(() => {
22284
+ dropFromCache(cacheKey);
22285
+ });
22286
+ return () => {
22287
+ log(`searchMessage(tmpid: ${timestamp}) > dispose`);
22288
+ disposers.forEach(fn => fn());
22289
+ };
22290
+ };
22291
+ /* end_public_function */
22292
+
21097
22293
  var index$n = /*#__PURE__*/Object.freeze({
21098
22294
  __proto__: null,
21099
22295
  createMessage: createMessage,
@@ -21119,6 +22315,7 @@ var index$n = /*#__PURE__*/Object.freeze({
21119
22315
  onMessageFetched: onMessageFetched,
21120
22316
  getMessage: getMessage,
21121
22317
  getMessages: getMessages,
22318
+ searchMessage: searchMessage,
21122
22319
  convertFromRaw: convertFromRaw$1,
21123
22320
  prepareMessagePayload: prepareMessagePayload,
21124
22321
  convertParams: convertParams,
@@ -21966,6 +23163,7 @@ class ChannelQueryStreamController extends QueryStreamController {
21966
23163
  "onCreate" /* Amity.ChannelActionType.OnCreate */,
21967
23164
  "onJoin" /* Amity.ChannelActionType.OnJoin */,
21968
23165
  "onResolveChannel" /* Amity.ChannelActionType.OnResolveChannel */,
23166
+ "onUnarchived" /* Amity.ChannelActionType.OnUnarchived */,
21969
23167
  ].includes(action)) {
21970
23168
  if (Array.isArray(payload)) {
21971
23169
  collection.data = [
@@ -21975,6 +23173,12 @@ class ChannelQueryStreamController extends QueryStreamController {
21975
23173
  else
21976
23174
  collection.data = [...new Set([payload.channelInternalId, ...collection.data])];
21977
23175
  }
23176
+ if (action === "onArchived" /* Amity.ChannelActionType.OnArchived */) {
23177
+ const ids = Array.isArray(payload)
23178
+ ? payload.map(getResolver('channel'))
23179
+ : [getResolver('channel')(payload)];
23180
+ collection.data = collection.data.filter(channelInternalId => !ids.includes(channelInternalId));
23181
+ }
21978
23182
  pushToCache(this.cacheKey, collection);
21979
23183
  this.notifyChange({ origin: "event" /* Amity.LiveDataOrigin.EVENT */, loading: false });
21980
23184
  };
@@ -22241,6 +23445,32 @@ class ChannelLiveCollectionController extends LiveCollectionController {
22241
23445
  },
22242
23446
  { fn: onChannelMemberAdded, action: "onMemberAdded" /* Amity.ChannelActionType.OnMemberAdded */ },
22243
23447
  { fn: onChannelMemberRemoved, action: "onMemberRemoved" /* Amity.ChannelActionType.OnMemberRemoved */ },
23448
+ {
23449
+ fn: (reactor) => onChannelArchived(payload => {
23450
+ const channels = payload.archives
23451
+ .map(archive => {
23452
+ var _a;
23453
+ return (_a = pullFromCache(['channel', 'get', archive.channelId])) === null || _a === void 0 ? void 0 : _a.data;
23454
+ })
23455
+ .filter((c) => Boolean(c));
23456
+ if (channels.length > 0)
23457
+ reactor(channels);
23458
+ }),
23459
+ action: "onArchived" /* Amity.ChannelActionType.OnArchived */,
23460
+ },
23461
+ {
23462
+ fn: (reactor) => onChannelUnarchived(payload => {
23463
+ const channels = payload.archives
23464
+ .map(archive => {
23465
+ var _a;
23466
+ return (_a = pullFromCache(['channel', 'get', archive.channelId])) === null || _a === void 0 ? void 0 : _a.data;
23467
+ })
23468
+ .filter((c) => Boolean(c));
23469
+ if (channels.length > 0)
23470
+ reactor(channels);
23471
+ }),
23472
+ action: "onUnarchived" /* Amity.ChannelActionType.OnUnarchived */,
23473
+ },
22244
23474
  {
22245
23475
  fn: convertEventPayload(onChannelMarkerFetched, 'entityId', 'channel'),
22246
23476
  action: "onUpdate" /* Amity.ChannelActionType.OnUpdate */,
@@ -22419,181 +23649,766 @@ class ChannelLiveCollectionController extends LiveCollectionController {
22419
23649
  action: "onUpdate" /* Amity.ChannelActionType.OnUpdate */,
22420
23650
  },
22421
23651
  ];
22422
- if (this.paginationController instanceof PaginationController) {
22423
- return [
22424
- ...subscriptions,
22425
- {
22426
- fn: (callback) => {
22427
- return onChannelCreated(channel => {
22428
- resolveUnreadInfoOnChannelEvent(channel);
22429
- callback(channel);
22430
- });
22431
- },
22432
- action: "onCreate" /* Amity.ChannelActionType.OnCreate */,
22433
- },
22434
- ];
22435
- }
22436
- return subscriptions;
23652
+ if (this.paginationController instanceof PaginationController) {
23653
+ return [
23654
+ ...subscriptions,
23655
+ {
23656
+ fn: (callback) => {
23657
+ return onChannelCreated(channel => {
23658
+ resolveUnreadInfoOnChannelEvent(channel);
23659
+ callback(channel);
23660
+ });
23661
+ },
23662
+ action: "onCreate" /* Amity.ChannelActionType.OnCreate */,
23663
+ },
23664
+ ];
23665
+ }
23666
+ return subscriptions;
23667
+ }
23668
+ }
23669
+
23670
+ /* eslint-disable no-use-before-define */
23671
+ /* begin_public_function
23672
+ id: channel.query
23673
+ */
23674
+ /**
23675
+ * ```js
23676
+ * import { getChannels } from '@amityco/ts-sdk-react-native'
23677
+ *
23678
+ * let channels = []
23679
+ * const unsub = getChannels({
23680
+ * displayName: Amity.Channel['displayName'],
23681
+ * }, response => merge(channels, response.data))
23682
+ * ```
23683
+ *
23684
+ * Observe all mutations on a list of {@link Amity.Channel}s
23685
+ *
23686
+ * @param params for querying channels
23687
+ * @param callback the function to call when new data are available
23688
+ * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the channels
23689
+ *
23690
+ * @category Channel Live Collection
23691
+ */
23692
+ const getChannels = (params, callback, config) => {
23693
+ const { log, cache, userId } = getActiveClient();
23694
+ if (!cache) {
23695
+ console.log(ENABLE_CACHE_MESSAGE);
23696
+ }
23697
+ const timestamp = Date.now();
23698
+ log(`getChannels(tmpid: ${timestamp}) > listen`);
23699
+ const channelLiveCollection = new ChannelLiveCollectionController(params, callback);
23700
+ const disposers = channelLiveCollection.startSubscription();
23701
+ const cacheKey = channelLiveCollection.getCacheKey();
23702
+ disposers.push(() => {
23703
+ dropFromCache(cacheKey);
23704
+ });
23705
+ return () => {
23706
+ log(`getChannels(tmpid: ${timestamp}) > dispose`);
23707
+ disposers.forEach(fn => fn());
23708
+ };
23709
+ };
23710
+ /* end_public_function */
23711
+
23712
+ /**
23713
+ *
23714
+ * Calculate user unread from {@link Amity.ChannelUnread} objects
23715
+ *
23716
+ * @returns the {@link Amity.UserUnread} objects
23717
+ *
23718
+ * @category Channel API
23719
+ * @async
23720
+ */
23721
+ const getTotalChannelsUnread$1 = () => {
23722
+ var _a;
23723
+ const client = getActiveClient();
23724
+ client.log('channel/getTotalChannelsUnread.locally');
23725
+ const cachedChannelsUnread = ((_a = queryCache(['channelUnread', 'get'])) === null || _a === void 0 ? void 0 : _a.filter(({ data }) => {
23726
+ return !data.isDeleted;
23727
+ })) || [];
23728
+ const totalChannelsUnread = (cachedChannelsUnread === null || cachedChannelsUnread === void 0 ? void 0 : cachedChannelsUnread.reduce((acc, { data }) => {
23729
+ acc.unreadCount += data.unreadCount;
23730
+ acc.isMentioned = acc.isMentioned || data.isMentioned;
23731
+ return acc;
23732
+ }, { unreadCount: 0, isMentioned: false })) || { unreadCount: 0, isMentioned: false };
23733
+ const cachedAt = client.cache && Date.now();
23734
+ return {
23735
+ data: totalChannelsUnread,
23736
+ cachedAt,
23737
+ };
23738
+ };
23739
+
23740
+ /* begin_public_function
23741
+ id: totalChannelsUnread.get
23742
+ */
23743
+ /**
23744
+ * ```js
23745
+ * import { ChannelRepository } from '@amityco/ts-sdk-react-native';
23746
+ *
23747
+ * let totalChannelsUnread;
23748
+ *
23749
+ * const unsubscribe = ChannelRepository.getTotalChannelsUnread(response => {
23750
+ * unread = response.data;
23751
+ * });
23752
+ * ```
23753
+ *
23754
+ * Observe all mutation on a given {@link Amity.UserUnread}
23755
+ *
23756
+ * @returns An {@link Amity.UserUnread} function to run when willing to stop observing the message
23757
+ *
23758
+ * @category User Unread Live Object
23759
+ *
23760
+ */
23761
+ const getTotalChannelsUnread = (callback) => {
23762
+ const { _id: userId } = getActiveUser();
23763
+ if (!userId)
23764
+ throw new ASCError('The _id has not been defined in ActiveUser', 800000 /* Amity.ClientError.UNKNOWN_ERROR */, "error" /* Amity.ErrorLevel.ERROR */);
23765
+ const { log, cache } = getActiveClient();
23766
+ if (!cache) {
23767
+ console.log('For using Live Object feature you need to enable Cache!');
23768
+ }
23769
+ const timestamp = Date.now();
23770
+ log(`liveTotalChannelsUnread(tmpid: ${timestamp}) > listen`);
23771
+ const disposers = [];
23772
+ let isUnsyncedModel = false; // for messages
23773
+ let model;
23774
+ const dispatcher = (data) => {
23775
+ const { data: userUnread } = data;
23776
+ const callbackModel = userUnread
23777
+ ? {
23778
+ unreadCount: userUnread.unreadCount,
23779
+ isMentioned: userUnread.isMentioned,
23780
+ }
23781
+ : undefined;
23782
+ model = callbackModel ? convertGetterPropsToStatic(callbackModel) : callbackModel;
23783
+ callback({
23784
+ data: callbackModel
23785
+ ? Object.assign(Object.assign({}, callbackModel), { isMentioned: callbackModel.isMentioned }) : callbackModel,
23786
+ loading: data.loading,
23787
+ error: data.error,
23788
+ });
23789
+ };
23790
+ const realtimeRouter = (_) => {
23791
+ const { data: userUnread } = getTotalChannelsUnread$1();
23792
+ if (isEqual(model, userUnread))
23793
+ return;
23794
+ dispatcher({
23795
+ loading: false,
23796
+ data: userUnread,
23797
+ });
23798
+ };
23799
+ const onFetch = () => {
23800
+ const query = createQuery(async () => getTotalChannelsUnread$1());
23801
+ runQuery(query, ({ error, data, loading, origin, cachedAt }) => {
23802
+ if (cachedAt === UNSYNCED_OBJECT_CACHED_AT_VALUE) {
23803
+ dispatcher({
23804
+ data,
23805
+ origin,
23806
+ loading: false,
23807
+ error: new ASCApiError(UNSYNCED_OBJECT_CACHED_AT_MESSAGE, 800800 /* Amity.ClientError.DISALOOW_UNSYNCED_OBJECT */, "error" /* Amity.ErrorLevel.ERROR */),
23808
+ });
23809
+ isUnsyncedModel = true;
23810
+ disposers.forEach(fn => fn());
23811
+ }
23812
+ else if (!isUnsyncedModel) {
23813
+ dispatcher({ loading, data, origin, error });
23814
+ }
23815
+ if (error) {
23816
+ disposers.forEach(fn => fn());
23817
+ }
23818
+ });
23819
+ };
23820
+ disposers.push(onChannelUnreadUpdatedLocal(realtimeRouter));
23821
+ onFetch();
23822
+ return () => {
23823
+ disposers.forEach(fn => fn());
23824
+ };
23825
+ };
23826
+
23827
+ class ArchivedChannelPaginationController extends PaginationController {
23828
+ async getRequest(queryParams, token) {
23829
+ var _a, _b;
23830
+ const limit = (_a = queryParams.limit) !== null && _a !== void 0 ? _a : COLLECTION_DEFAULT_PAGINATION_LIMIT;
23831
+ const pageIndex = token ? Number.parseInt(token, 10) : 0;
23832
+ if (pageIndex === 0) {
23833
+ await getArchivedChannelIds();
23834
+ }
23835
+ const cached = (_b = queryCache(['archivedChannel', 'get'])) !== null && _b !== void 0 ? _b : [];
23836
+ const archives = cached
23837
+ .map(entry => entry.data)
23838
+ .slice()
23839
+ .sort((a, b) => Number(new Date(b.archivedAt)) - Number(new Date(a.archivedAt)));
23840
+ const start = pageIndex * limit;
23841
+ const end = start + limit;
23842
+ const slice = archives.slice(start, end);
23843
+ const hasMore = end < archives.length;
23844
+ if (slice.length > 0) {
23845
+ await getChannelByIds$1(slice.map(archive => archive.channelId));
23846
+ }
23847
+ return {
23848
+ archives: slice,
23849
+ paging: {
23850
+ next: hasMore ? String(pageIndex + 1) : undefined,
23851
+ previous: undefined,
23852
+ },
23853
+ };
23854
+ }
23855
+ }
23856
+
23857
+ class ArchivedChannelQueryStreamController extends QueryStreamController {
23858
+ constructor(query, cacheKey, notifyChange) {
23859
+ super(query, cacheKey);
23860
+ this.notifyChange = notifyChange;
23861
+ }
23862
+ async saveToMainDB(_response) {
23863
+ //
23864
+ }
23865
+ appendToQueryStream(response, direction, refresh = false) {
23866
+ var _a, _b;
23867
+ const channelIds = response.archives.map(archive => archive.channelId);
23868
+ if (refresh) {
23869
+ pushToCache(this.cacheKey, {
23870
+ data: channelIds,
23871
+ params: {},
23872
+ });
23873
+ return;
23874
+ }
23875
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
23876
+ const existing = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
23877
+ pushToCache(this.cacheKey, Object.assign(Object.assign({}, collection), { data: direction === "prev" /* Amity.LiveCollectionPageDirection.PREV */
23878
+ ? [...new Set([...channelIds, ...existing])]
23879
+ : [...new Set([...existing, ...channelIds])] }));
23880
+ }
23881
+ reactor(action) {
23882
+ return (channelIds) => {
23883
+ var _a;
23884
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
23885
+ if (!collection)
23886
+ return;
23887
+ if (action === "onArchived" /* Amity.ChannelActionType.OnArchived */) {
23888
+ const filtered = collection.data.filter(id => !channelIds.includes(id));
23889
+ collection.data = [...channelIds, ...filtered];
23890
+ }
23891
+ if (action === "onUnarchived" /* Amity.ChannelActionType.OnUnarchived */ ||
23892
+ action === "onDelete" /* Amity.ChannelActionType.OnDelete */) {
23893
+ collection.data = collection.data.filter(id => !channelIds.includes(id));
23894
+ }
23895
+ pushToCache(this.cacheKey, collection);
23896
+ this.notifyChange({ origin: "event" /* Amity.LiveDataOrigin.EVENT */, loading: false });
23897
+ };
23898
+ }
23899
+ subscribeRTE(createSubscriber) {
23900
+ return createSubscriber.map(subscriber => subscriber.fn(this.reactor(subscriber.action)));
23901
+ }
23902
+ }
23903
+
23904
+ class ArchivedChannelLiveCollectionController extends LiveCollectionController {
23905
+ constructor(query, callback) {
23906
+ const queryStreamId = hash__default["default"](query);
23907
+ const cacheKey = ['archivedChannel', 'collection', queryStreamId];
23908
+ const paginationController = new ArchivedChannelPaginationController(query);
23909
+ super(paginationController, queryStreamId, cacheKey, callback);
23910
+ this.queryStreamController = new ArchivedChannelQueryStreamController(query, this.cacheKey, this.notifyChange.bind(this));
23911
+ this.callback = callback.bind(this);
23912
+ this.loadPage({ initial: true });
23913
+ }
23914
+ setup() {
23915
+ var _a;
23916
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
23917
+ if (!collection) {
23918
+ pushToCache(this.cacheKey, {
23919
+ data: [],
23920
+ params: {},
23921
+ });
23922
+ }
23923
+ }
23924
+ async persistModel(response) {
23925
+ await this.queryStreamController.saveToMainDB(response);
23926
+ }
23927
+ persistQueryStream({ response, direction, refresh, }) {
23928
+ this.queryStreamController.appendToQueryStream(response, direction, refresh);
23929
+ }
23930
+ startSubscription() {
23931
+ return this.queryStreamController.subscribeRTE([
23932
+ {
23933
+ fn: reactor => onChannelArchived(payload => reactor(payload.archives.map(archive => archive.channelId))),
23934
+ action: "onArchived" /* Amity.ChannelActionType.OnArchived */,
23935
+ },
23936
+ {
23937
+ fn: reactor => onChannelUnarchived(payload => reactor(payload.archives.map(archive => archive.channelId))),
23938
+ action: "onUnarchived" /* Amity.ChannelActionType.OnUnarchived */,
23939
+ },
23940
+ {
23941
+ fn: reactor => onChannelUpdated(channel => reactor([channel.channelId])),
23942
+ action: "onUpdate" /* Amity.ChannelActionType.OnUpdate */,
23943
+ },
23944
+ {
23945
+ fn: reactor => onChannelDeleted(channel => reactor([channel.channelId])),
23946
+ action: "onDelete" /* Amity.ChannelActionType.OnDelete */,
23947
+ },
23948
+ ]);
23949
+ }
23950
+ notifyChange({ origin, loading, error }) {
23951
+ var _a, _b;
23952
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
23953
+ if (!collection)
23954
+ return;
23955
+ const data = (_b = collection.data
23956
+ .map(channelId => pullFromCache(['channel', 'get', channelId]))
23957
+ .filter((entry) => Boolean(entry))
23958
+ .map(({ data: channel }) => channel)
23959
+ .map(constructChannelObject)) !== null && _b !== void 0 ? _b : [];
23960
+ if (!this.shouldNotify(data) && origin === 'event')
23961
+ return;
23962
+ this.callback({
23963
+ onNextPage: () => this.loadPage({ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */ }),
23964
+ data,
23965
+ hasNextPage: !!this.paginationController.getNextToken(),
23966
+ loading,
23967
+ error,
23968
+ });
23969
+ }
23970
+ }
23971
+
23972
+ /* begin_public_function
23973
+ id: channel.archive.collection
23974
+ */
23975
+ /**
23976
+ * ```js
23977
+ * import { ChannelRepository } from '@amityco/ts-sdk'
23978
+ *
23979
+ * let channels = []
23980
+ * const unsub = ChannelRepository.getArchivedChannels(params, response => merge(channels, response.data))
23981
+ * ```
23982
+ *
23983
+ * Live collection of {@link Amity.Channel}s archived by the active user.
23984
+ *
23985
+ * @param params Live collection parameters (only `limit` is honored; the
23986
+ * archive list takes no other filters).
23987
+ * @param callback the function to call when new data are available
23988
+ * @returns An {@link Amity.Unsubscriber} function to run when willing to
23989
+ * stop observing.
23990
+ *
23991
+ * @category Channel Live Collection
23992
+ */
23993
+ const getArchivedChannels = (params, callback) => {
23994
+ const { log, cache } = getActiveClient();
23995
+ if (!cache) {
23996
+ console.log(ENABLE_CACHE_MESSAGE);
23997
+ }
23998
+ const timestamp = Date.now();
23999
+ log(`getArchivedChannels(tmpid: ${timestamp}) > listen`);
24000
+ const controller = new ArchivedChannelLiveCollectionController(params, callback);
24001
+ const disposers = controller.startSubscription();
24002
+ const cacheKey = controller.getCacheKey();
24003
+ disposers.push(() => {
24004
+ dropFromCache(cacheKey);
24005
+ });
24006
+ return () => {
24007
+ log(`getArchivedChannels(tmpid: ${timestamp}) > dispose`);
24008
+ disposers.forEach(fn => fn());
24009
+ };
24010
+ };
24011
+ /* end_public_function */
24012
+
24013
+ class SearchChannelPaginationController extends PaginationController {
24014
+ async getRequest(queryParams, token) {
24015
+ const { query, exactMatch, isMemberOnly, types, tags, sortBy, orderBy, limit = COLLECTION_DEFAULT_PAGINATION_SIZE, } = queryParams;
24016
+ const options = token ? { token } : { limit: Math.min(100, Math.max(1, limit)) };
24017
+ const { data: queryResponse } = await this.http.get(`/api/v2/search/channels`, {
24018
+ params: {
24019
+ query,
24020
+ exactMatch,
24021
+ isMemberOnly,
24022
+ types,
24023
+ tags,
24024
+ sortBy,
24025
+ orderBy,
24026
+ options,
24027
+ },
24028
+ });
24029
+ return queryResponse;
24030
+ }
24031
+ }
24032
+
24033
+ class SearchChannelQueryStreamController extends QueryStreamController {
24034
+ constructor(query, cacheKey, notifyChange) {
24035
+ super(query, cacheKey);
24036
+ this.notifyChange = notifyChange;
24037
+ }
24038
+ async saveToMainDB(response) {
24039
+ const processedPayload = await prepareChannelPayload(response);
24040
+ const client = getActiveClient();
24041
+ const cachedAt = client.cache && Date.now();
24042
+ if (client.cache) {
24043
+ ingestInCache(processedPayload, { cachedAt });
24044
+ }
24045
+ }
24046
+ appendToQueryStream(response, direction, refresh = false) {
24047
+ var _a, _b;
24048
+ if (refresh) {
24049
+ pushToCache(this.cacheKey, {
24050
+ data: response.channels.map(getResolver('channel')),
24051
+ });
24052
+ return;
24053
+ }
24054
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
24055
+ const existing = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
24056
+ const incoming = response.channels.map(getResolver('channel'));
24057
+ pushToCache(this.cacheKey, Object.assign(Object.assign({}, collection), { data: direction === "prev" /* Amity.LiveCollectionPageDirection.PREV */
24058
+ ? [...new Set([...incoming, ...existing])]
24059
+ : [...new Set([...existing, ...incoming])] }));
24060
+ }
24061
+ reactor() {
24062
+ return () => this.notifyChange({ origin: "event" /* Amity.LiveDataOrigin.EVENT */, loading: false });
24063
+ }
24064
+ subscribeRTE(createSubscriber) {
24065
+ return createSubscriber.map(subscriber => subscriber.fn(this.reactor()));
24066
+ }
24067
+ }
24068
+
24069
+ /* eslint-disable no-use-before-define */
24070
+ const getMessagePreviewSetting = () => {
24071
+ const client = getActiveClient();
24072
+ return client.getMessagePreviewSetting(false);
24073
+ };
24074
+ class SearchChannelLiveCollectionController extends LiveCollectionController {
24075
+ constructor(query, callback) {
24076
+ const queryStreamId = hash__default["default"](query);
24077
+ const cacheKey = ['channel', 'search', queryStreamId];
24078
+ const paginationController = new SearchChannelPaginationController(query);
24079
+ super(paginationController, queryStreamId, cacheKey, callback);
24080
+ this.queryStreamController = new SearchChannelQueryStreamController(query, this.cacheKey, this.notifyChange.bind(this));
24081
+ this.callback = callback.bind(this);
24082
+ this.loadPage({ initial: true });
24083
+ }
24084
+ startSubscription() {
24085
+ return this.queryStreamController.subscribeRTE(this.getSubscriptions());
24086
+ }
24087
+ notifyChange({ origin, loading, error }) {
24088
+ var _a, _b;
24089
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
24090
+ if (!collection)
24091
+ return;
24092
+ const data = (_b = collection.data
24093
+ .map(channelId => pullFromCache(['channel', 'get', channelId]))
24094
+ .filter(Boolean)
24095
+ .map(cached => constructChannelObject(cached.data))) !== null && _b !== void 0 ? _b : [];
24096
+ if (!this.shouldNotify(data) && origin === 'event')
24097
+ return;
24098
+ this.callback({
24099
+ onNextPage: () => this.loadPage({ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */ }),
24100
+ data,
24101
+ hasNextPage: !!this.paginationController.getNextToken(),
24102
+ loading,
24103
+ error,
24104
+ });
24105
+ }
24106
+ setup() {
24107
+ var _a;
24108
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
24109
+ if (!collection) {
24110
+ pushToCache(this.cacheKey, {
24111
+ data: [],
24112
+ params: {},
24113
+ });
24114
+ }
24115
+ }
24116
+ async persistModel(response) {
24117
+ await this.queryStreamController.saveToMainDB(response);
24118
+ }
24119
+ persistQueryStream({ response, direction, refresh, }) {
24120
+ this.queryStreamController.appendToQueryStream(response, direction, refresh);
24121
+ }
24122
+ shouldAbort(targetChannelId) {
24123
+ var _a;
24124
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
24125
+ if (!collection)
24126
+ return true;
24127
+ return !collection.data.find(channelId => channelId === targetChannelId);
24128
+ }
24129
+ getSubscriptions() {
24130
+ return [
24131
+ {
24132
+ fn: convertEventPayload((callback) => {
24133
+ return onMessageCreatedMqtt(message => {
24134
+ var _a;
24135
+ const cacheData = (_a = pullFromCache([
24136
+ 'channel',
24137
+ 'get',
24138
+ message.channelId,
24139
+ ])) === null || _a === void 0 ? void 0 : _a.data;
24140
+ if (!cacheData)
24141
+ return;
24142
+ updateChannelCache(cacheData, {
24143
+ lastActivity: message.createdAt,
24144
+ });
24145
+ callback(message);
24146
+ });
24147
+ }, 'channelId', 'channel'),
24148
+ action: "onUpdate" /* Amity.ChannelActionType.OnUpdate */,
24149
+ },
24150
+ {
24151
+ fn: convertEventPayload((callback) => {
24152
+ return onMessageCreatedLocal(message => {
24153
+ var _a;
24154
+ const cacheData = (_a = pullFromCache([
24155
+ 'channel',
24156
+ 'get',
24157
+ message.channelId,
24158
+ ])) === null || _a === void 0 ? void 0 : _a.data;
24159
+ if (!cacheData)
24160
+ return;
24161
+ updateChannelCache(cacheData, {
24162
+ lastActivity: message.createdAt,
24163
+ });
24164
+ callback(message);
24165
+ });
24166
+ }, 'channelId', 'channel'),
24167
+ action: "onUpdate" /* Amity.ChannelActionType.OnUpdate */,
24168
+ },
24169
+ { fn: onChannelDeleted, action: "onDelete" /* Amity.ChannelActionType.OnDelete */ },
24170
+ { fn: onChannelUpdated, action: "onUpdate" /* Amity.ChannelActionType.OnUpdate */ },
24171
+ { fn: onChannelSetMuted, action: "onMute" /* Amity.ChannelActionType.OnMute */ },
24172
+ {
24173
+ fn: (reactor) => onChannelArchived(payload => {
24174
+ const channels = payload.archives
24175
+ .map(archive => {
24176
+ var _a;
24177
+ return (_a = pullFromCache(['channel', 'get', archive.channelId])) === null || _a === void 0 ? void 0 : _a.data;
24178
+ })
24179
+ .filter((c) => Boolean(c));
24180
+ if (channels.length > 0)
24181
+ reactor(channels);
24182
+ }),
24183
+ action: "onArchived" /* Amity.ChannelActionType.OnArchived */,
24184
+ },
24185
+ {
24186
+ fn: (reactor) => onChannelUnarchived(payload => {
24187
+ const channels = payload.archives
24188
+ .map(archive => {
24189
+ var _a;
24190
+ return (_a = pullFromCache(['channel', 'get', archive.channelId])) === null || _a === void 0 ? void 0 : _a.data;
24191
+ })
24192
+ .filter((c) => Boolean(c));
24193
+ if (channels.length > 0)
24194
+ reactor(channels);
24195
+ }),
24196
+ action: "onUnarchived" /* Amity.ChannelActionType.OnUnarchived */,
24197
+ },
24198
+ {
24199
+ fn: convertEventPayload(onChannelMarkerFetched, 'entityId', 'channel'),
24200
+ action: "onUpdate" /* Amity.ChannelActionType.OnUpdate */,
24201
+ },
24202
+ {
24203
+ fn: convertEventPayload(onChannelMarkerUpdated, 'entityId', 'channel'),
24204
+ action: "onUpdate" /* Amity.ChannelActionType.OnUpdate */,
24205
+ },
24206
+ {
24207
+ fn: convertEventPayload((callback) => {
24208
+ const updateMessagePreview = async (message) => {
24209
+ var _a;
24210
+ const messagePreviewSetting = await getMessagePreviewSetting();
24211
+ if (messagePreviewSetting === "no-message-preview" /* Amity.MessagePreviewSetting.NO_MESSAGE_PREVIEW */)
24212
+ return;
24213
+ handleMessageCreated(message);
24214
+ if (this.shouldAbort(message.channelId))
24215
+ return;
24216
+ const channel = (_a = pullFromCache([
24217
+ 'channel',
24218
+ 'get',
24219
+ message.channelId,
24220
+ ])) === null || _a === void 0 ? void 0 : _a.data;
24221
+ if (!channel)
24222
+ return;
24223
+ updateChannelCache(channel, {
24224
+ messagePreviewId: message.messageId,
24225
+ });
24226
+ callback(message);
24227
+ };
24228
+ return onMessageCreatedMqtt(updateMessagePreview);
24229
+ }, 'channelId', 'channel'),
24230
+ action: "onUpdate" /* Amity.ChannelActionType.OnUpdate */,
24231
+ },
24232
+ {
24233
+ fn: convertEventPayload((callback) => {
24234
+ const updateMessagePreview = async (message) => {
24235
+ var _a;
24236
+ const messagePreviewSetting = await getMessagePreviewSetting();
24237
+ if (messagePreviewSetting === "no-message-preview" /* Amity.MessagePreviewSetting.NO_MESSAGE_PREVIEW */)
24238
+ return;
24239
+ handleMessageCreated(message);
24240
+ if (this.shouldAbort(message.channelId))
24241
+ return;
24242
+ const channel = (_a = pullFromCache([
24243
+ 'channel',
24244
+ 'get',
24245
+ message.channelId,
24246
+ ])) === null || _a === void 0 ? void 0 : _a.data;
24247
+ if (!channel)
24248
+ return;
24249
+ updateChannelCache(channel, {
24250
+ messagePreviewId: message.messageId,
24251
+ });
24252
+ callback(message);
24253
+ };
24254
+ return onMessageCreatedLocal(updateMessagePreview);
24255
+ }, 'channelId', 'channel'),
24256
+ action: "onUpdate" /* Amity.ChannelActionType.OnUpdate */,
24257
+ },
24258
+ {
24259
+ fn: convertEventPayload((callback) => {
24260
+ const updateMessagePreview = async (message) => {
24261
+ const messagePreviewSetting = await getMessagePreviewSetting();
24262
+ if (messagePreviewSetting === "no-message-preview" /* Amity.MessagePreviewSetting.NO_MESSAGE_PREVIEW */)
24263
+ return;
24264
+ handleMessageUpdated(message);
24265
+ if (this.shouldAbort(message.channelId))
24266
+ return;
24267
+ callback(message);
24268
+ };
24269
+ return onMessageUpdated(updateMessagePreview);
24270
+ }, 'channelId', 'channel'),
24271
+ action: "onUpdate" /* Amity.ChannelActionType.OnUpdate */,
24272
+ },
24273
+ {
24274
+ fn: convertEventPayload((callback) => {
24275
+ const updateMessagePreview = async (message) => {
24276
+ const messagePreviewSetting = await getMessagePreviewSetting();
24277
+ if (messagePreviewSetting === "no-message-preview" /* Amity.MessagePreviewSetting.NO_MESSAGE_PREVIEW */)
24278
+ return;
24279
+ if (messagePreviewSetting ===
24280
+ "message-preview-include-deleted" /* Amity.MessagePreviewSetting.MESSAGE_PREVIEW_INCLUDE_DELETED */)
24281
+ await handleMessageUpdated(message);
24282
+ if (this.shouldAbort(message.channelId))
24283
+ return;
24284
+ if (messagePreviewSetting ===
24285
+ "message-preview-not-include-deleted" /* Amity.MessagePreviewSetting.MESSAGE_PREVIEW_NOT_INCLUDE_DELETED */) {
24286
+ await getChannel$1(message.channelId);
24287
+ }
24288
+ callback(message);
24289
+ };
24290
+ return onMessageDeleted(updateMessagePreview);
24291
+ }, 'channelId', 'channel'),
24292
+ action: "onUpdate" /* Amity.ChannelActionType.OnUpdate */,
24293
+ },
24294
+ {
24295
+ fn: convertEventPayload((callback) => {
24296
+ const updateMessagePreview = async (subChannel) => {
24297
+ var _a;
24298
+ const collections = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
24299
+ if (!collections)
24300
+ return;
24301
+ const channelId = collections.data.find(channel => {
24302
+ const messagePreviewCache = getChannelMessagePreview(channel);
24303
+ return (messagePreviewCache === null || messagePreviewCache === void 0 ? void 0 : messagePreviewCache.subChannelId) === subChannel.subChannelId;
24304
+ });
24305
+ if (!channelId)
24306
+ return;
24307
+ await getChannel$1(subChannel.channelId);
24308
+ callback(subChannel);
24309
+ };
24310
+ return onSubChannelDeleted(updateMessagePreview);
24311
+ }, 'channelId', 'channel'),
24312
+ action: "onUpdate" /* Amity.ChannelActionType.OnUpdate */,
24313
+ },
24314
+ {
24315
+ fn: convertEventPayload((callback) => {
24316
+ const updateMessagePreview = async (subChannel) => {
24317
+ var _a;
24318
+ const messagePreviewSetting = await getMessagePreviewSetting();
24319
+ if (messagePreviewSetting === "no-message-preview" /* Amity.MessagePreviewSetting.NO_MESSAGE_PREVIEW */)
24320
+ return;
24321
+ const collections = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
24322
+ if (!collections)
24323
+ return;
24324
+ await handleSubChannelUpdated(subChannel);
24325
+ if (this.shouldAbort(subChannel.channelId))
24326
+ return;
24327
+ callback(subChannel);
24328
+ };
24329
+ return onSubChannelUpdated(updateMessagePreview);
24330
+ }, 'channelId', 'channel'),
24331
+ action: "onUpdate" /* Amity.ChannelActionType.OnUpdate */,
24332
+ },
24333
+ {
24334
+ fn: (callback) => {
24335
+ const handleUserFeedMarkerResolved = async (marker) => {
24336
+ if (marker.feedMarkers) {
24337
+ const channels = marker.feedMarkers
24338
+ .map(feedMarker => {
24339
+ var _a;
24340
+ return (_a = pullFromCache([
24341
+ 'channel',
24342
+ 'get',
24343
+ feedMarker.entityId,
24344
+ ])) === null || _a === void 0 ? void 0 : _a.data;
24345
+ })
24346
+ .filter(Boolean);
24347
+ callback(channels);
24348
+ }
24349
+ };
24350
+ return onUserMessageFeedMarkerResolved(handleUserFeedMarkerResolved);
24351
+ },
24352
+ action: "OnResolveUnread" /* Amity.ChannelActionType.OnResolveUnread */,
24353
+ },
24354
+ {
24355
+ fn: convertEventPayload(onChannelUnreadInfoUpdatedLocal, 'channelId', 'channel'),
24356
+ action: "onUpdate" /* Amity.ChannelActionType.OnUpdate */,
24357
+ },
24358
+ {
24359
+ fn: convertEventPayload((callback) => {
24360
+ const processPayload = (payloads) => {
24361
+ payloads.forEach(callback);
24362
+ };
24363
+ return onChannelUnreadUpdatedLocal(processPayload);
24364
+ }, 'channelId', 'channel'),
24365
+ action: "onUpdate" /* Amity.ChannelActionType.OnUpdate */,
24366
+ },
24367
+ ];
22437
24368
  }
22438
24369
  }
22439
24370
 
22440
- /* eslint-disable no-use-before-define */
22441
24371
  /* begin_public_function
22442
- id: channel.query
24372
+ id: channel.search
22443
24373
  */
22444
24374
  /**
22445
24375
  * ```js
22446
- * import { getChannels } from '@amityco/ts-sdk-react-native'
24376
+ * import { ChannelRepository } from '@amityco/ts-sdk';
22447
24377
  *
22448
- * let channels = []
22449
- * const unsub = getChannels({
22450
- * displayName: Amity.Channel['displayName'],
22451
- * }, response => merge(channels, response.data))
24378
+ * const unsubscribe = ChannelRepository.searchChannels(
24379
+ * { query: 'hello' },
24380
+ * response => response.data,
24381
+ * );
22452
24382
  * ```
22453
24383
  *
22454
- * Observe all mutations on a list of {@link Amity.Channel}s
24384
+ * Live collection of {@link Amity.Channel}s matching the search query. Backed by
24385
+ * `GET /api/v2/search/channels`.
22455
24386
  *
22456
- * @param params for querying channels
22457
- * @param callback the function to call when new data are available
22458
- * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the channels
24387
+ * @param params Search parameters.
24388
+ * @param callback Called whenever new data are available.
24389
+ * @returns An {@link Amity.Unsubscriber} function to stop observing.
22459
24390
  *
22460
24391
  * @category Channel Live Collection
22461
24392
  */
22462
- const getChannels = (params, callback, config) => {
22463
- const { log, cache, userId } = getActiveClient();
22464
- if (!cache) {
24393
+ const searchChannels = (params, callback) => {
24394
+ const { log, cache } = getActiveClient();
24395
+ if (!cache)
22465
24396
  console.log(ENABLE_CACHE_MESSAGE);
22466
- }
22467
24397
  const timestamp = Date.now();
22468
- log(`getChannels(tmpid: ${timestamp}) > listen`);
22469
- const channelLiveCollection = new ChannelLiveCollectionController(params, callback);
22470
- const disposers = channelLiveCollection.startSubscription();
22471
- const cacheKey = channelLiveCollection.getCacheKey();
24398
+ log(`searchChannels(tmpid: ${timestamp}) > listen`);
24399
+ const searchChannelLiveCollection = new SearchChannelLiveCollectionController(params, callback);
24400
+ const disposers = searchChannelLiveCollection.startSubscription();
24401
+ const cacheKey = searchChannelLiveCollection.getCacheKey();
22472
24402
  disposers.push(() => {
22473
24403
  dropFromCache(cacheKey);
22474
24404
  });
22475
24405
  return () => {
22476
- log(`getChannels(tmpid: ${timestamp}) > dispose`);
24406
+ log(`searchChannels(tmpid: ${timestamp}) > dispose`);
22477
24407
  disposers.forEach(fn => fn());
22478
24408
  };
22479
24409
  };
22480
24410
  /* end_public_function */
22481
24411
 
22482
- /**
22483
- *
22484
- * Calculate user unread from {@link Amity.ChannelUnread} objects
22485
- *
22486
- * @returns the {@link Amity.UserUnread} objects
22487
- *
22488
- * @category Channel API
22489
- * @async
22490
- */
22491
- const getTotalChannelsUnread$1 = () => {
22492
- var _a;
22493
- const client = getActiveClient();
22494
- client.log('channel/getTotalChannelsUnread.locally');
22495
- const cachedChannelsUnread = ((_a = queryCache(['channelUnread', 'get'])) === null || _a === void 0 ? void 0 : _a.filter(({ data }) => {
22496
- return !data.isDeleted;
22497
- })) || [];
22498
- const totalChannelsUnread = (cachedChannelsUnread === null || cachedChannelsUnread === void 0 ? void 0 : cachedChannelsUnread.reduce((acc, { data }) => {
22499
- acc.unreadCount += data.unreadCount;
22500
- acc.isMentioned = acc.isMentioned || data.isMentioned;
22501
- return acc;
22502
- }, { unreadCount: 0, isMentioned: false })) || { unreadCount: 0, isMentioned: false };
22503
- const cachedAt = client.cache && Date.now();
22504
- return {
22505
- data: totalChannelsUnread,
22506
- cachedAt,
22507
- };
22508
- };
22509
-
22510
- /* begin_public_function
22511
- id: totalChannelsUnread.get
22512
- */
22513
- /**
22514
- * ```js
22515
- * import { ChannelRepository } from '@amityco/ts-sdk-react-native';
22516
- *
22517
- * let totalChannelsUnread;
22518
- *
22519
- * const unsubscribe = ChannelRepository.getTotalChannelsUnread(response => {
22520
- * unread = response.data;
22521
- * });
22522
- * ```
22523
- *
22524
- * Observe all mutation on a given {@link Amity.UserUnread}
22525
- *
22526
- * @returns An {@link Amity.UserUnread} function to run when willing to stop observing the message
22527
- *
22528
- * @category User Unread Live Object
22529
- *
22530
- */
22531
- const getTotalChannelsUnread = (callback) => {
22532
- const { _id: userId } = getActiveUser();
22533
- if (!userId)
22534
- throw new ASCError('The _id has not been defined in ActiveUser', 800000 /* Amity.ClientError.UNKNOWN_ERROR */, "error" /* Amity.ErrorLevel.ERROR */);
22535
- const { log, cache } = getActiveClient();
22536
- if (!cache) {
22537
- console.log('For using Live Object feature you need to enable Cache!');
22538
- }
22539
- const timestamp = Date.now();
22540
- log(`liveTotalChannelsUnread(tmpid: ${timestamp}) > listen`);
22541
- const disposers = [];
22542
- let isUnsyncedModel = false; // for messages
22543
- let model;
22544
- const dispatcher = (data) => {
22545
- const { data: userUnread } = data;
22546
- const callbackModel = userUnread
22547
- ? {
22548
- unreadCount: userUnread.unreadCount,
22549
- isMentioned: userUnread.isMentioned,
22550
- }
22551
- : undefined;
22552
- model = callbackModel ? convertGetterPropsToStatic(callbackModel) : callbackModel;
22553
- callback({
22554
- data: callbackModel
22555
- ? Object.assign(Object.assign({}, callbackModel), { isMentioned: callbackModel.isMentioned }) : callbackModel,
22556
- loading: data.loading,
22557
- error: data.error,
22558
- });
22559
- };
22560
- const realtimeRouter = (_) => {
22561
- const { data: userUnread } = getTotalChannelsUnread$1();
22562
- if (isEqual(model, userUnread))
22563
- return;
22564
- dispatcher({
22565
- loading: false,
22566
- data: userUnread,
22567
- });
22568
- };
22569
- const onFetch = () => {
22570
- const query = createQuery(async () => getTotalChannelsUnread$1());
22571
- runQuery(query, ({ error, data, loading, origin, cachedAt }) => {
22572
- if (cachedAt === UNSYNCED_OBJECT_CACHED_AT_VALUE) {
22573
- dispatcher({
22574
- data,
22575
- origin,
22576
- loading: false,
22577
- error: new ASCApiError(UNSYNCED_OBJECT_CACHED_AT_MESSAGE, 800800 /* Amity.ClientError.DISALOOW_UNSYNCED_OBJECT */, "error" /* Amity.ErrorLevel.ERROR */),
22578
- });
22579
- isUnsyncedModel = true;
22580
- disposers.forEach(fn => fn());
22581
- }
22582
- else if (!isUnsyncedModel) {
22583
- dispatcher({ loading, data, origin, error });
22584
- }
22585
- if (error) {
22586
- disposers.forEach(fn => fn());
22587
- }
22588
- });
22589
- };
22590
- disposers.push(onChannelUnreadUpdatedLocal(realtimeRouter));
22591
- onFetch();
22592
- return () => {
22593
- disposers.forEach(fn => fn());
22594
- };
22595
- };
22596
-
22597
24412
  /* begin_public_function
22598
24413
  id: channel.member.add
22599
24414
  */
@@ -22725,7 +24540,9 @@ class ChannelMemberQueryStreamController extends QueryStreamController {
22725
24540
  channelId: this.query.channelId,
22726
24541
  userId: channelMember.userId,
22727
24542
  });
22728
- if (channelMember.membership === 'none') {
24543
+ const membershipFilter = this.query.memberships;
24544
+ const isInFilter = !membershipFilter || membershipFilter.includes(channelMember.membership);
24545
+ if (channelMember.membership === 'none' || !isInFilter) {
22729
24546
  collection.data = collection.data.filter(m => m !== channelMemberCacheId);
22730
24547
  }
22731
24548
  else if (!collection.data.includes(channelMemberCacheId)) {
@@ -23061,6 +24878,7 @@ const banMembers$1 = async (channelId, userIds) => {
23061
24878
  const cachedAt = client.cache && Date.now();
23062
24879
  if (client.cache)
23063
24880
  ingestInCache(preparedPayload, { cachedAt });
24881
+ fireEvent('channel.banned', payload);
23064
24882
  return {
23065
24883
  data: channelUsers === null || channelUsers === void 0 ? void 0 : channelUsers.filter(user => user.membership === 'banned'),
23066
24884
  cachedAt,
@@ -23095,6 +24913,7 @@ const unbanMembers$1 = async (channelId, userIds) => {
23095
24913
  const cachedAt = client.cache && Date.now();
23096
24914
  if (client.cache)
23097
24915
  ingestInCache(preparedPayload, { cachedAt });
24916
+ fireEvent('channel.unbanned', payload);
23098
24917
  const { channelUsers } = preparedPayload;
23099
24918
  return {
23100
24919
  data: channelUsers === null || channelUsers === void 0 ? void 0 : channelUsers.filter(user => user.membership === 'member'),
@@ -23123,6 +24942,7 @@ const MUTE_FOREVER = -1;
23123
24942
  * @async
23124
24943
  * */
23125
24944
  const muteMembers = async (channelId, userIds, mutePeriod = MUTE_FOREVER) => {
24945
+ var _a;
23126
24946
  const client = getActiveClient();
23127
24947
  client.log('channel/muteMembers', { userIds, channelId, mutePeriod });
23128
24948
  const { data } = await client.http.put(`/api/v2/channel/${channelId}/users/mute`, {
@@ -23130,6 +24950,15 @@ const muteMembers = async (channelId, userIds, mutePeriod = MUTE_FOREVER) => {
23130
24950
  mutePeriod: mutePeriod === MUTE_FOREVER ? mutePeriod : mutePeriod * 1000,
23131
24951
  });
23132
24952
  const { success } = data;
24953
+ const muteTimeout = mutePeriod === MUTE_FOREVER
24954
+ ? new Date('9999-12-31T23:59:59.999Z').toISOString()
24955
+ : new Date(Date.now() + mutePeriod * 1000).toISOString();
24956
+ fireEvent('channel.setMutedUsers', {
24957
+ channelId,
24958
+ userIds,
24959
+ muteTimeout,
24960
+ actor: (_a = client.userId) !== null && _a !== void 0 ? _a : '',
24961
+ });
23133
24962
  return success;
23134
24963
  };
23135
24964
  /* end_public_function */
@@ -23152,6 +24981,7 @@ const muteMembers = async (channelId, userIds, mutePeriod = MUTE_FOREVER) => {
23152
24981
  * @async
23153
24982
  * */
23154
24983
  const unmuteMembers = async (channelId, userIds) => {
24984
+ var _a;
23155
24985
  const client = getActiveClient();
23156
24986
  client.log('channel/unmuteMembers', { userIds, channelId });
23157
24987
  const { data } = await client.http.put(`/api/v2/channel/${encodeURIComponent(channelId)}/users/mute`, {
@@ -23159,6 +24989,12 @@ const unmuteMembers = async (channelId, userIds) => {
23159
24989
  mutePeriod: 0,
23160
24990
  });
23161
24991
  const { success } = data;
24992
+ fireEvent('channel.setMutedUsers', {
24993
+ channelId,
24994
+ userIds,
24995
+ muteTimeout: new Date(0).toISOString(),
24996
+ actor: (_a = client.userId) !== null && _a !== void 0 ? _a : '',
24997
+ });
23162
24998
  return success;
23163
24999
  };
23164
25000
  /* end_public_function */
@@ -23185,6 +25021,9 @@ var index$j = /*#__PURE__*/Object.freeze({
23185
25021
  leaveChannel: leaveChannel,
23186
25022
  muteChannel: muteChannel,
23187
25023
  unmuteChannel: unmuteChannel,
25024
+ archiveChannel: archiveChannel,
25025
+ unarchiveChannel: unarchiveChannel,
25026
+ getArchivedChannelIds: getArchivedChannelIds,
23188
25027
  onChannelCreated: onChannelCreated,
23189
25028
  onChannelUpdated: onChannelUpdated,
23190
25029
  onChannelDeleted: onChannelDeleted,
@@ -23197,9 +25036,13 @@ var index$j = /*#__PURE__*/Object.freeze({
23197
25036
  onChannelMemberUnbanned: onChannelMemberUnbanned,
23198
25037
  onChannelMemberRoleAdded: onChannelMemberRoleAdded,
23199
25038
  onChannelMemberRoleRemoved: onChannelMemberRoleRemoved,
25039
+ onChannelArchived: onChannelArchived,
25040
+ onChannelUnarchived: onChannelUnarchived,
23200
25041
  getChannel: getChannel,
23201
25042
  getChannels: getChannels,
23202
25043
  getTotalChannelsUnread: getTotalChannelsUnread,
25044
+ getArchivedChannels: getArchivedChannels,
25045
+ searchChannels: searchChannels,
23203
25046
  MARKER_INCLUDED_CHANNEL_TYPE: MARKER_INCLUDED_CHANNEL_TYPE,
23204
25047
  isUnreadCountSupport: isUnreadCountSupport,
23205
25048
  convertFromRaw: convertFromRaw,
@@ -27096,7 +28939,7 @@ class CommentLiveCollectionController extends LiveCollectionController {
27096
28939
  this.queryStreamController.appendToQueryStream(response, direction, refresh);
27097
28940
  }
27098
28941
  startSubscription() {
27099
- return this.queryStreamController.subscribeRTE([
28942
+ const disposers = this.queryStreamController.subscribeRTE([
27100
28943
  { fn: onCommentCreatedLocal, action: EnumCommentActions.OnCommentCreated },
27101
28944
  { fn: onCommentDeleteLocal, action: EnumCommentActions.OnCommentDeleted },
27102
28945
  { fn: onCommentCreated, action: EnumCommentActions.OnCommentCreated },
@@ -27109,6 +28952,11 @@ class CommentLiveCollectionController extends LiveCollectionController {
27109
28952
  { fn: onLocalCommentReactionAdded, action: EnumCommentActions.OnCommentReactionAdded },
27110
28953
  { fn: onLocalCommentReactionRemoved, action: EnumCommentActions.OnCommentReactionRemoved },
27111
28954
  ]);
28955
+ if (this.query.excludeBlockUserComments) {
28956
+ const refresh = () => this.notifyChange({ origin: "event" /* Amity.LiveDataOrigin.EVENT */, loading: false });
28957
+ disposers.push(onUserDidBlock(refresh), onUserDidUnblock(refresh));
28958
+ }
28959
+ return disposers;
27112
28960
  }
27113
28961
  notifyChange({ origin, loading, error }) {
27114
28962
  var _a, _b;
@@ -27161,6 +29009,9 @@ class CommentLiveCollectionController extends LiveCollectionController {
27161
29009
  comments = comments.filter(comment => { var _a; return (_a = this.query.dataTypes) === null || _a === void 0 ? void 0 : _a.values.some(value => { var _a; return (_a = comment.dataTypes) === null || _a === void 0 ? void 0 : _a.includes(value); }); });
27162
29010
  }
27163
29011
  }
29012
+ if (this.query.excludeBlockUserComments) {
29013
+ comments = filterCommentsByBlockUsers(comments);
29014
+ }
27164
29015
  switch (this.query.sortBy) {
27165
29016
  case 'firstCreated':
27166
29017
  comments = comments.sort(sortByFirstCreated);
@@ -28246,13 +30097,253 @@ const getCommunityFeed = (params, callback, config) => {
28246
30097
  };
28247
30098
  /* end_public_function */
28248
30099
 
30100
+ /**
30101
+ * Thrown by `getForYouFeed` when the network has the For You feature
30102
+ * disabled. Mapped from HTTP 404 NOT_FOUND. Distinct from a generic
30103
+ * not-found so consumers can hide the For You tab without retrying.
30104
+ *
30105
+ * @category Errors
30106
+ */
30107
+ class AmityForYouFeedDisabledError extends ASCApiError {
30108
+ constructor(message = 'For You feed is not enabled for this network') {
30109
+ super(message, 400400 /* Amity.ServerError.ITEM_NOT_FOUND */, "error" /* Amity.ErrorLevel.ERROR */);
30110
+ this.type = 'AmityForYouFeedDisabledError';
30111
+ }
30112
+ }
30113
+
30114
+ class ForYouFeedPaginationController extends PaginationController {
30115
+ constructor(query) {
30116
+ super(query);
30117
+ this.checkedDisk = false;
30118
+ this.hasDeliveredPost = false;
30119
+ this.cursor = CursorController.current();
30120
+ }
30121
+ async getRequest(_queryParams, token) {
30122
+ var _a, _b, _c, _d, _e;
30123
+ const isFirstPage = token === undefined;
30124
+ let stored = null;
30125
+ // On the first page of a fresh collection, load the saved cursor from disk once.
30126
+ // Drop it if the snapshot has already expired so we start fresh.
30127
+ if (isFirstPage && !this.checkedDisk && this.cursor) {
30128
+ this.checkedDisk = true;
30129
+ stored = await this.cursor.get();
30130
+ if (stored && CursorController.isExpired(stored.expiredAt)) {
30131
+ await this.cursor.clear();
30132
+ stored = null;
30133
+ }
30134
+ }
30135
+ // Already paged to the end before. Ask the BE fresh (no cursor) and check if it's
30136
+ // still the same snapshot the user finished.
30137
+ if (isFirstPage && (stored === null || stored === void 0 ? void 0 : stored.reachedEndOfFeed)) {
30138
+ const fresh = await this.fetch();
30139
+ const freshExpiredAt = Date.parse((_b = (_a = fresh.paging) === null || _a === void 0 ? void 0 : _a.expiredAt) !== null && _b !== void 0 ? _b : '');
30140
+ const rolledOver = !Number.isNaN(freshExpiredAt) && freshExpiredAt !== stored.expiredAt;
30141
+ // New snapshot → serve it. Same snapshot → user has seen it all, show empty.
30142
+ if (rolledOver) {
30143
+ await this.persistCursor(fresh);
30144
+ if (fresh.posts.length > 0)
30145
+ this.hasDeliveredPost = true;
30146
+ return fresh;
30147
+ }
30148
+ return Object.assign(Object.assign({}, fresh), { posts: [], paging: {} });
30149
+ }
30150
+ // Resume from the saved cursor on re-entry; otherwise use the live-collection token.
30151
+ const effectiveToken = isFirstPage && stored ? stored.cursor : token;
30152
+ const response = await this.fetch(effectiveToken);
30153
+ if (response.posts.length > 0)
30154
+ this.hasDeliveredPost = true;
30155
+ if ((_c = response.paging) === null || _c === void 0 ? void 0 : _c.next) {
30156
+ // More pages left → advance the saved cursor.
30157
+ await this.persistCursor(response);
30158
+ }
30159
+ else if (this.hasDeliveredPost && this.cursor) {
30160
+ // Reached the end and mark end of feed
30161
+ const expiredAt = Date.parse((_e = (_d = response.paging) === null || _d === void 0 ? void 0 : _d.expiredAt) !== null && _e !== void 0 ? _e : '');
30162
+ if (!Number.isNaN(expiredAt))
30163
+ await this.cursor.markReachedEndOfFeed(expiredAt);
30164
+ }
30165
+ return response;
30166
+ }
30167
+ async fetch(token) {
30168
+ const options = { limit: COLLECTION_DEFAULT_PAGINATION_SIZE };
30169
+ if (token)
30170
+ options.token = token;
30171
+ try {
30172
+ const { data } = await this.http.get(API_ENDPOINTS.forYouFeed, {
30173
+ params: { options },
30174
+ });
30175
+ return data;
30176
+ }
30177
+ catch (error) {
30178
+ if (error instanceof ASCApiError && error.code === 400300 /* Amity.ServerError.FORBIDDEN */) {
30179
+ throw new AmityForYouFeedDisabledError();
30180
+ }
30181
+ const recoverable = error instanceof ASCApiError && error.code === 400322 /* Amity.ServerError.FEED_SNAPSHOT_EXPIRED */;
30182
+ if (recoverable && token !== undefined) {
30183
+ if (this.cursor)
30184
+ await this.cursor.clear();
30185
+ const { data } = await this.http.get(API_ENDPOINTS.forYouFeed, {
30186
+ params: { options: { limit: COLLECTION_DEFAULT_PAGINATION_SIZE } },
30187
+ });
30188
+ return data;
30189
+ }
30190
+ throw error;
30191
+ }
30192
+ }
30193
+ async persistCursor(response) {
30194
+ var _a, _b;
30195
+ if (!this.cursor)
30196
+ return;
30197
+ const cursor = (_a = response.paging) === null || _a === void 0 ? void 0 : _a.next;
30198
+ const expiredAtIso = (_b = response.paging) === null || _b === void 0 ? void 0 : _b.expiredAt;
30199
+ if (!cursor || !expiredAtIso)
30200
+ return;
30201
+ const expiredAt = Date.parse(expiredAtIso);
30202
+ if (Number.isNaN(expiredAt))
30203
+ return;
30204
+ await this.cursor.set({ cursor, expiredAt });
30205
+ }
30206
+ }
30207
+
30208
+ class ForYouFeedQueryStreamController extends QueryStreamController {
30209
+ constructor(query, cacheKey, notifyChange, preparePayload) {
30210
+ super(query, cacheKey);
30211
+ this.notifyChange = notifyChange;
30212
+ this.preparePayload = preparePayload;
30213
+ }
30214
+ async saveToMainDB(response) {
30215
+ const processedPayload = await this.preparePayload(response);
30216
+ const client = getActiveClient();
30217
+ const cachedAt = client.cache && Date.now();
30218
+ if (client.cache)
30219
+ ingestInCache(processedPayload, { cachedAt });
30220
+ }
30221
+ appendToQueryStream(response, _direction, refresh = false) {
30222
+ var _a, _b;
30223
+ if (refresh) {
30224
+ pushToCache(this.cacheKey, {
30225
+ data: response.posts.map(getResolver('post')),
30226
+ });
30227
+ }
30228
+ else {
30229
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
30230
+ const posts = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
30231
+ pushToCache(this.cacheKey, Object.assign(Object.assign({}, collection), { data: [...new Set([...posts, ...response.posts.map(getResolver('post'))])] }));
30232
+ }
30233
+ }
30234
+ reactor(action) {
30235
+ return (post) => {
30236
+ var _a;
30237
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
30238
+ if (!collection)
30239
+ return;
30240
+ if (post.parentPostId && !collection.data.includes(post.parentPostId))
30241
+ return;
30242
+ if (action === EnumPostActions.OnPostDeleted || action === EnumPostActions.OnPostDeclined) {
30243
+ collection.data = collection.data.filter(postId => postId !== post.postId);
30244
+ }
30245
+ pushToCache(this.cacheKey, collection);
30246
+ this.notifyChange({ origin: "event" /* Amity.LiveDataOrigin.EVENT */, loading: false });
30247
+ };
30248
+ }
30249
+ subscribeRTE(createSubscriber) {
30250
+ return createSubscriber.map(subscriber => subscriber.fn(this.reactor(subscriber.action)));
30251
+ }
30252
+ }
30253
+
30254
+ const FOR_YOU_FEED_CACHE_KEY = ['forYouFeed', 'collection'];
30255
+ class ForYouFeedLiveCollectionController extends LiveCollectionController {
30256
+ constructor(callback) {
30257
+ const queryStreamId = `for-you-feed-${getActiveClient().userId}`;
30258
+ const query = {};
30259
+ const paginationController = new ForYouFeedPaginationController(query);
30260
+ super(paginationController, queryStreamId, FOR_YOU_FEED_CACHE_KEY, callback);
30261
+ this.queryStreamController = new ForYouFeedQueryStreamController(query, this.cacheKey, this.notifyChange.bind(this), preparePostPayload);
30262
+ this.callback = callback.bind(this);
30263
+ this.loadPage({ initial: true });
30264
+ }
30265
+ setup() {
30266
+ var _a;
30267
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
30268
+ if (!collection)
30269
+ pushToCache(this.cacheKey, { data: [], params: {} });
30270
+ }
30271
+ async persistModel(payload) {
30272
+ await this.queryStreamController.saveToMainDB(payload);
30273
+ }
30274
+ persistQueryStream({ response, direction, refresh, }) {
30275
+ this.queryStreamController.appendToQueryStream(response, direction, refresh);
30276
+ }
30277
+ startSubscription() {
30278
+ return this.queryStreamController.subscribeRTE(getGlobalFeedSubscriptions(this.cacheKey));
30279
+ }
30280
+ notifyChange({ origin, loading, error }) {
30281
+ var _a, _b;
30282
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
30283
+ if (!collection)
30284
+ return;
30285
+ const data = ((_b = collection.data
30286
+ .map(id => pullFromCache(['post', 'get', id]))
30287
+ .filter(isNonNullable)
30288
+ .map(({ data }) => data)) !== null && _b !== void 0 ? _b : []).map(LinkedObject.post);
30289
+ if (!this.shouldNotify(data) && origin === 'event')
30290
+ return;
30291
+ this.callback({
30292
+ onNextPage: () => this.loadPage({ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */ }),
30293
+ data,
30294
+ hasNextPage: !!this.paginationController.getNextToken(),
30295
+ loading,
30296
+ error,
30297
+ });
30298
+ }
30299
+ }
30300
+
30301
+ /* begin_public_function
30302
+ id: feed.query.for_you_feed
30303
+ */
30304
+ /**
30305
+ * ```js
30306
+ * import { FeedRepository } from '@amityco/ts-sdk'
30307
+ *
30308
+ * const unsub = FeedRepository.getForYouFeed(({ data, loading, error, hasNextPage, onNextPage }) => {
30309
+ * // render posts; call onNextPage() to load the next page (20 posts)
30310
+ * })
30311
+ * ```
30312
+ *
30313
+ * Observe the For You feed — a personalized, server-ranked
30314
+ * {@link Amity.LiveCollection} of {@link Amity.Post}.
30315
+ *
30316
+ * @param callback the function to call when new data is available
30317
+ * @returns an {@link Amity.Unsubscriber} function to stop observing
30318
+ *
30319
+ * @category Posts Live Collection
30320
+ */
30321
+ const getForYouFeed = (callback) => {
30322
+ const { log, cache } = getActiveClient();
30323
+ if (!cache)
30324
+ console.log(ENABLE_CACHE_MESSAGE);
30325
+ const timestamp = Date.now();
30326
+ log(`getForYouFeed(tmpid: ${timestamp}) > listen`);
30327
+ const forYouFeedLiveCollection = new ForYouFeedLiveCollectionController(callback);
30328
+ const disposers = forYouFeedLiveCollection.startSubscription();
30329
+ const cacheKey = forYouFeedLiveCollection.getCacheKey();
30330
+ disposers.push(() => dropFromCache(cacheKey));
30331
+ return () => {
30332
+ log(`getForYouFeed(tmpid: ${timestamp}) > dispose`);
30333
+ disposers.forEach(fn => fn());
30334
+ };
30335
+ };
30336
+ /* end_public_function */
30337
+
28249
30338
  var index$d = /*#__PURE__*/Object.freeze({
28250
30339
  __proto__: null,
28251
30340
  queryGlobalFeed: queryGlobalFeed,
28252
30341
  getCustomRankingGlobalFeed: getCustomRankingGlobalFeed,
28253
30342
  getGlobalFeed: getGlobalFeed,
28254
30343
  getUserFeed: getUserFeed,
28255
- getCommunityFeed: getCommunityFeed
30344
+ getCommunityFeed: getCommunityFeed,
30345
+ getForYouFeed: getForYouFeed,
30346
+ AmityForYouFeedDisabledError: AmityForYouFeedDisabledError
28256
30347
  });
28257
30348
 
28258
30349
  /* begin_public_function
@@ -29265,7 +31356,12 @@ class PostLiveCollectionController extends LiveCollectionController {
29265
31356
  this.queryStreamController.appendToQueryStream(response, direction, refresh);
29266
31357
  }
29267
31358
  startSubscription() {
29268
- return this.queryStreamController.subscribeRTE(getPostSubscription(this.cacheKey));
31359
+ const disposers = this.queryStreamController.subscribeRTE(getPostSubscription(this.cacheKey));
31360
+ if (this.query.excludeBlockUserPosts) {
31361
+ const refresh = () => this.notifyChange({ origin: "event" /* Amity.LiveDataOrigin.EVENT */, loading: false });
31362
+ disposers.push(onUserDidBlock(refresh), onUserDidUnblock(refresh));
31363
+ }
31364
+ return disposers;
29269
31365
  }
29270
31366
  notifyChange({ origin, loading, error }) {
29271
31367
  var _a, _b;
@@ -29311,6 +31407,9 @@ class PostLiveCollectionController extends LiveCollectionController {
29311
31407
  const sortBy = this.query.sortBy || 'lastCreated';
29312
31408
  posts = posts.filter(post => !exceedsUntilAtBoundary(post.createdAt, validatedUntilAt, sortBy));
29313
31409
  }
31410
+ if (this.query.excludeBlockUserPosts) {
31411
+ posts = filterPostsByBlockUsers(posts);
31412
+ }
29314
31413
  switch (this.query.sortBy) {
29315
31414
  case 'firstCreated':
29316
31415
  posts = posts.sort(sortByFirstCreated);
@@ -36025,6 +38124,9 @@ exports.filterByPropIntersection = filterByPropIntersection;
36025
38124
  exports.filterBySearchTerm = filterBySearchTerm;
36026
38125
  exports.filterByStringComparePartially = filterByStringComparePartially;
36027
38126
  exports.filterByUntilAt = filterByUntilAt;
38127
+ exports.filterCommentsByBlockUsers = filterCommentsByBlockUsers;
38128
+ exports.filterPostsByBlockUsers = filterPostsByBlockUsers;
38129
+ exports.getBlockUsersId = getBlockUsersId;
36028
38130
  exports.getChannelTopic = getChannelTopic;
36029
38131
  exports.getCommentTopic = getCommentTopic;
36030
38132
  exports.getCommunityStoriesTopic = getCommunityStoriesTopic;
@@ -36036,6 +38138,7 @@ exports.getMarkerUserFeedTopic = getMarkerUserFeedTopic;
36036
38138
  exports.getMessageTopic = getMessageTopic;
36037
38139
  exports.getMyFollowersTopic = getMyFollowersTopic;
36038
38140
  exports.getMyFollowingsTopic = getMyFollowingsTopic;
38141
+ exports.getNetworkId = getNetworkId;
36039
38142
  exports.getNetworkTopic = getNetworkTopic;
36040
38143
  exports.getPostTopic = getPostTopic;
36041
38144
  exports.getRole = getRole;