@amityco/ts-sdk 7.27.1 → 7.27.2-9bed893.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 (217) hide show
  1. package/dist/@types/core/errors.d.ts +2 -1
  2. package/dist/@types/core/errors.d.ts.map +1 -1
  3. package/dist/@types/core/events.d.ts +5 -0
  4. package/dist/@types/core/events.d.ts.map +1 -1
  5. package/dist/@types/core/payload.d.ts +26 -0
  6. package/dist/@types/core/payload.d.ts.map +1 -1
  7. package/dist/@types/core/permissions.d.ts +10 -4
  8. package/dist/@types/core/permissions.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 -1
  12. package/dist/@types/domains/analytics.d.ts.map +1 -1
  13. package/dist/@types/domains/channel.d.ts +5 -0
  14. package/dist/@types/domains/channel.d.ts.map +1 -1
  15. package/dist/@types/domains/client.d.ts +104 -0
  16. package/dist/@types/domains/client.d.ts.map +1 -1
  17. package/dist/@types/domains/comment.d.ts +27 -0
  18. package/dist/@types/domains/comment.d.ts.map +1 -1
  19. package/dist/@types/domains/community.d.ts +1 -0
  20. package/dist/@types/domains/community.d.ts.map +1 -1
  21. package/dist/@types/domains/curatedContent.d.ts +25 -0
  22. package/dist/@types/domains/curatedContent.d.ts.map +1 -0
  23. package/dist/@types/domains/pinnedMessage.d.ts +43 -0
  24. package/dist/@types/domains/pinnedMessage.d.ts.map +1 -0
  25. package/dist/@types/domains/post.d.ts +11 -0
  26. package/dist/@types/domains/post.d.ts.map +1 -1
  27. package/dist/@types/index.d.ts +3 -1
  28. package/dist/@types/index.d.ts.map +1 -1
  29. package/dist/analytic/service/analytic/AnalyticsEngine.d.ts +3 -0
  30. package/dist/analytic/service/analytic/AnalyticsEngine.d.ts.map +1 -1
  31. package/dist/analytic/service/analytic/AnalyticsEventCapturer.d.ts +3 -0
  32. package/dist/analytic/service/analytic/AnalyticsEventCapturer.d.ts.map +1 -1
  33. package/dist/channelRepository/api/createChannel.d.ts.map +1 -1
  34. package/dist/channelRepository/events/index.d.ts +2 -0
  35. package/dist/channelRepository/events/index.d.ts.map +1 -1
  36. package/dist/channelRepository/events/onChannelMemberRoleAdded.d.ts +22 -0
  37. package/dist/channelRepository/events/onChannelMemberRoleAdded.d.ts.map +1 -1
  38. package/dist/channelRepository/events/onChannelMemberRoleRemoved.d.ts +22 -0
  39. package/dist/channelRepository/events/onChannelMemberRoleRemoved.d.ts.map +1 -1
  40. package/dist/channelRepository/events/onChannelMessagePinned.d.ts +24 -0
  41. package/dist/channelRepository/events/onChannelMessagePinned.d.ts.map +1 -0
  42. package/dist/channelRepository/events/onChannelMessageUnpinned.d.ts +21 -0
  43. package/dist/channelRepository/events/onChannelMessageUnpinned.d.ts.map +1 -0
  44. package/dist/channelRepository/events/onChannelPinnedMessageDeleted.d.ts +12 -0
  45. package/dist/channelRepository/events/onChannelPinnedMessageDeleted.d.ts.map +1 -0
  46. package/dist/channelRepository/events/tests/onChannelMemberRoleAdded.test.d.ts +2 -0
  47. package/dist/channelRepository/events/tests/onChannelMemberRoleAdded.test.d.ts.map +1 -0
  48. package/dist/channelRepository/events/tests/onChannelMemberRoleRemoved.test.d.ts +2 -0
  49. package/dist/channelRepository/events/tests/onChannelMemberRoleRemoved.test.d.ts.map +1 -0
  50. package/dist/channelRepository/events/tests/onChannelMessagePinned.test.d.ts +2 -0
  51. package/dist/channelRepository/events/tests/onChannelMessagePinned.test.d.ts.map +1 -0
  52. package/dist/channelRepository/observers/getChannel.d.ts.map +1 -1
  53. package/dist/channelRepository/observers/getChannels/ChannelLiveCollectionController.d.ts.map +1 -1
  54. package/dist/channelRepository/observers/getMyMembership.d.ts.map +1 -1
  55. package/dist/channelRepository/observers/searchChannels/SearchChannelLiveCollectionController.d.ts.map +1 -1
  56. package/dist/channelRepository/utils/applyChannelRolePayload.d.ts +21 -0
  57. package/dist/channelRepository/utils/applyChannelRolePayload.d.ts.map +1 -0
  58. package/dist/channelRepository/utils/index.d.ts +2 -0
  59. package/dist/channelRepository/utils/index.d.ts.map +1 -1
  60. package/dist/channelRepository/utils/tests/pinnedMessage.test.d.ts +2 -0
  61. package/dist/channelRepository/utils/tests/pinnedMessage.test.d.ts.map +1 -0
  62. package/dist/channelRepository/utils/updatePinnedMessageCache.d.ts +24 -0
  63. package/dist/channelRepository/utils/updatePinnedMessageCache.d.ts.map +1 -0
  64. package/dist/client/api/createClient.d.ts +5 -1
  65. package/dist/client/api/createClient.d.ts.map +1 -1
  66. package/dist/client/api/getModuleSettings.d.ts +25 -0
  67. package/dist/client/api/getModuleSettings.d.ts.map +1 -0
  68. package/dist/client/api/getSocialSettings.d.ts.map +1 -1
  69. package/dist/client/api/index.d.ts +1 -0
  70. package/dist/client/api/index.d.ts.map +1 -1
  71. package/dist/client/api/setupLoginSubscriptions.d.ts.map +1 -1
  72. package/dist/client/api/tests/getSocialSettings.test.d.ts +2 -0
  73. package/dist/client/api/tests/getSocialSettings.test.d.ts.map +1 -0
  74. package/dist/client/api/tests/integration/moduleSettings.integration.test.d.ts +2 -0
  75. package/dist/client/api/tests/integration/moduleSettings.integration.test.d.ts.map +1 -0
  76. package/dist/client/index.d.ts +1 -0
  77. package/dist/client/index.d.ts.map +1 -1
  78. package/dist/client/utils/parseModuleSettings.d.ts +9 -0
  79. package/dist/client/utils/parseModuleSettings.d.ts.map +1 -0
  80. package/dist/client/utils/resolveModuleAvailability.d.ts +39 -0
  81. package/dist/client/utils/resolveModuleAvailability.d.ts.map +1 -0
  82. package/dist/client/utils/tests/resolveModuleAvailability.test.d.ts +2 -0
  83. package/dist/client/utils/tests/resolveModuleAvailability.test.d.ts.map +1 -0
  84. package/dist/commentRepository/api/approveComment.d.ts +17 -0
  85. package/dist/commentRepository/api/approveComment.d.ts.map +1 -0
  86. package/dist/commentRepository/api/createComment.d.ts +12 -1
  87. package/dist/commentRepository/api/createComment.d.ts.map +1 -1
  88. package/dist/commentRepository/api/declineComment.d.ts +18 -0
  89. package/dist/commentRepository/api/declineComment.d.ts.map +1 -0
  90. package/dist/commentRepository/api/deleteComment.d.ts.map +1 -1
  91. package/dist/commentRepository/api/index.d.ts +2 -0
  92. package/dist/commentRepository/api/index.d.ts.map +1 -1
  93. package/dist/commentRepository/api/tests/approveComment.test.d.ts +2 -0
  94. package/dist/commentRepository/api/tests/approveComment.test.d.ts.map +1 -0
  95. package/dist/commentRepository/api/tests/createComment.optimistic.test.d.ts +2 -0
  96. package/dist/commentRepository/api/tests/createComment.optimistic.test.d.ts.map +1 -0
  97. package/dist/commentRepository/api/tests/declineComment.test.d.ts +2 -0
  98. package/dist/commentRepository/api/tests/declineComment.test.d.ts.map +1 -0
  99. package/dist/commentRepository/api/updateComment.d.ts.map +1 -1
  100. package/dist/commentRepository/events/index.d.ts +1 -0
  101. package/dist/commentRepository/events/index.d.ts.map +1 -1
  102. package/dist/commentRepository/events/onCommentApproved.d.ts +17 -0
  103. package/dist/commentRepository/events/onCommentApproved.d.ts.map +1 -0
  104. package/dist/commentRepository/events/tests/onCommentApproved.test.d.ts +2 -0
  105. package/dist/commentRepository/events/tests/onCommentApproved.test.d.ts.map +1 -0
  106. package/dist/commentRepository/events/tests/onCommentCreated.count.test.d.ts +2 -0
  107. package/dist/commentRepository/events/tests/onCommentCreated.count.test.d.ts.map +1 -0
  108. package/dist/commentRepository/events/utils.d.ts.map +1 -1
  109. package/dist/commentRepository/internalApi/getComment.d.ts.map +1 -1
  110. package/dist/commentRepository/observers/getComment.d.ts.map +1 -1
  111. package/dist/commentRepository/observers/getCommentReviewQueue/LiveCollectionController.d.ts +13 -0
  112. package/dist/commentRepository/observers/getCommentReviewQueue/LiveCollectionController.d.ts.map +1 -0
  113. package/dist/commentRepository/observers/getCommentReviewQueue/PaginationController.d.ts +5 -0
  114. package/dist/commentRepository/observers/getCommentReviewQueue/PaginationController.d.ts.map +1 -0
  115. package/dist/commentRepository/observers/getCommentReviewQueue/QueryStreamController.d.ts +15 -0
  116. package/dist/commentRepository/observers/getCommentReviewQueue/QueryStreamController.d.ts.map +1 -0
  117. package/dist/commentRepository/observers/getCommentReviewQueue.d.ts +22 -0
  118. package/dist/commentRepository/observers/getCommentReviewQueue.d.ts.map +1 -0
  119. package/dist/commentRepository/observers/getComments/CommentLiveCollectionController.d.ts +1 -1
  120. package/dist/commentRepository/observers/getComments/CommentLiveCollectionController.d.ts.map +1 -1
  121. package/dist/commentRepository/observers/getComments/CommentQueryStreamController.d.ts.map +1 -1
  122. package/dist/commentRepository/observers/getComments/enums.d.ts +1 -0
  123. package/dist/commentRepository/observers/getComments/enums.d.ts.map +1 -1
  124. package/dist/commentRepository/observers/index.d.ts +1 -0
  125. package/dist/commentRepository/observers/index.d.ts.map +1 -1
  126. package/dist/commentRepository/observers/tests/integrations/getCommentReviewQueue.integration.test.d.ts +2 -0
  127. package/dist/commentRepository/observers/tests/integrations/getCommentReviewQueue.integration.test.d.ts.map +1 -0
  128. package/dist/commentRepository/utils/approval.d.ts +49 -0
  129. package/dist/commentRepository/utils/approval.d.ts.map +1 -0
  130. package/dist/commentRepository/utils/payload.d.ts +6 -0
  131. package/dist/commentRepository/utils/payload.d.ts.map +1 -1
  132. package/dist/commentRepository/utils/tests/approval.test.d.ts +2 -0
  133. package/dist/commentRepository/utils/tests/approval.test.d.ts.map +1 -0
  134. package/dist/commentRepository/utils/tests/payload.test.d.ts +2 -0
  135. package/dist/commentRepository/utils/tests/payload.test.d.ts.map +1 -0
  136. package/dist/communityRepository/api/createCommunity.d.ts +1 -1
  137. package/dist/communityRepository/api/createCommunity.d.ts.map +1 -1
  138. package/dist/communityRepository/api/updateCommunity.d.ts +1 -1
  139. package/dist/communityRepository/api/updateCommunity.d.ts.map +1 -1
  140. package/dist/core/device.d.ts +1 -1
  141. package/dist/core/device.d.ts.map +1 -1
  142. package/dist/core/errors.d.ts +20 -0
  143. package/dist/core/errors.d.ts.map +1 -1
  144. package/dist/core/events.d.ts +3 -3
  145. package/dist/core/events.d.ts.map +1 -1
  146. package/dist/core/tests/device.test.d.ts +2 -0
  147. package/dist/core/tests/device.test.d.ts.map +1 -0
  148. package/dist/core/transports/http.d.ts.map +1 -1
  149. package/dist/core/transports/tests/moduleNotEntitled.test.d.ts +2 -0
  150. package/dist/core/transports/tests/moduleNotEntitled.test.d.ts.map +1 -0
  151. package/dist/core/transports/utils.d.ts +8 -0
  152. package/dist/core/transports/utils.d.ts.map +1 -1
  153. package/dist/curatedContentRepository/api/getPool.d.ts +2 -0
  154. package/dist/curatedContentRepository/api/getPool.d.ts.map +1 -0
  155. package/dist/curatedContentRepository/api/index.d.ts +2 -0
  156. package/dist/curatedContentRepository/api/index.d.ts.map +1 -0
  157. package/dist/curatedContentRepository/api/tests/getPool.test.d.ts +2 -0
  158. package/dist/curatedContentRepository/api/tests/getPool.test.d.ts.map +1 -0
  159. package/dist/curatedContentRepository/api/tests/integration/getPool.integration.test.d.ts +2 -0
  160. package/dist/curatedContentRepository/api/tests/integration/getPool.integration.test.d.ts.map +1 -0
  161. package/dist/curatedContentRepository/index.d.ts +2 -0
  162. package/dist/curatedContentRepository/index.d.ts.map +1 -0
  163. package/dist/index.cjs.js +1970 -478
  164. package/dist/index.d.ts +3 -0
  165. package/dist/index.d.ts.map +1 -1
  166. package/dist/index.esm.js +1943 -454
  167. package/dist/index.umd.js +2 -2
  168. package/dist/messagePreview/utils/getChannelMessagePreviewWithUser.d.ts +1 -0
  169. package/dist/messagePreview/utils/getChannelMessagePreviewWithUser.d.ts.map +1 -1
  170. package/dist/messageRepository/api/index.d.ts +2 -0
  171. package/dist/messageRepository/api/index.d.ts.map +1 -1
  172. package/dist/messageRepository/api/pinMessage.d.ts +29 -0
  173. package/dist/messageRepository/api/pinMessage.d.ts.map +1 -0
  174. package/dist/messageRepository/api/tests/pinMessage.test.d.ts +2 -0
  175. package/dist/messageRepository/api/tests/pinMessage.test.d.ts.map +1 -0
  176. package/dist/messageRepository/api/tests/unpinMessage.test.d.ts +2 -0
  177. package/dist/messageRepository/api/tests/unpinMessage.test.d.ts.map +1 -0
  178. package/dist/messageRepository/api/unpinMessage.d.ts +28 -0
  179. package/dist/messageRepository/api/unpinMessage.d.ts.map +1 -0
  180. package/dist/messageRepository/utils/refreshChannelPermissionsForMessage.d.ts +13 -0
  181. package/dist/messageRepository/utils/refreshChannelPermissionsForMessage.d.ts.map +1 -0
  182. package/dist/postRepository/utils/PostCommentCountEngine/ApproveTask.d.ts +16 -0
  183. package/dist/postRepository/utils/PostCommentCountEngine/ApproveTask.d.ts.map +1 -0
  184. package/dist/postRepository/utils/PostCommentCountEngine/PostCommentCountEngine.d.ts +25 -1
  185. package/dist/postRepository/utils/PostCommentCountEngine/PostCommentCountEngine.d.ts.map +1 -1
  186. package/dist/postRepository/utils/PostCommentCountEngine/postCommentCountEngineOnLoginHandler.d.ts +9 -0
  187. package/dist/postRepository/utils/PostCommentCountEngine/postCommentCountEngineOnLoginHandler.d.ts.map +1 -0
  188. package/dist/postRepository/utils/PostCommentCountEngine/tests/getLocalCommentCount.test.d.ts +2 -0
  189. package/dist/postRepository/utils/PostCommentCountEngine/tests/getLocalCommentCount.test.d.ts.map +1 -0
  190. package/dist/postRepository/utils/PostCommentCountEngine/tests/pendingAuthoredComments.test.d.ts +2 -0
  191. package/dist/postRepository/utils/PostCommentCountEngine/tests/pendingAuthoredComments.test.d.ts.map +1 -0
  192. package/dist/postRepository/utils/latestComments.d.ts +10 -0
  193. package/dist/postRepository/utils/latestComments.d.ts.map +1 -0
  194. package/dist/postRepository/utils/payload.d.ts.map +1 -1
  195. package/dist/postRepository/utils/tests/latestComments.test.d.ts +2 -0
  196. package/dist/postRepository/utils/tests/latestComments.test.d.ts.map +1 -0
  197. package/dist/postRepository/utils/tests/payload.test.d.ts +2 -0
  198. package/dist/postRepository/utils/tests/payload.test.d.ts.map +1 -0
  199. package/dist/utils/constants.d.ts +4 -0
  200. package/dist/utils/constants.d.ts.map +1 -1
  201. package/dist/utils/linkedObject/commentLinkedObject.d.ts.map +1 -1
  202. package/dist/utils/linkedObject/curatedContentTopicLinkedObject.d.ts +2 -0
  203. package/dist/utils/linkedObject/curatedContentTopicLinkedObject.d.ts.map +1 -0
  204. package/dist/utils/linkedObject/index.d.ts +1 -0
  205. package/dist/utils/linkedObject/index.d.ts.map +1 -1
  206. package/dist/utils/linkedObject/messageLinkedObject.d.ts.map +1 -1
  207. package/dist/utils/linkedObject/postLinkedObject.d.ts.map +1 -1
  208. package/dist/utils/linkedObject/tests/postLinkedObject.test.d.ts +2 -0
  209. package/dist/utils/linkedObject/tests/postLinkedObject.test.d.ts.map +1 -0
  210. package/dist/utils/tests/dummy/comment.d.ts +1 -0
  211. package/dist/utils/tests/dummy/comment.d.ts.map +1 -1
  212. package/dist/utils/tests/dummy/index.d.ts +1 -0
  213. package/dist/utils/tests/dummy/index.d.ts.map +1 -1
  214. package/dist/utils/tests/dummy/pinnedMessage.d.ts +2 -0
  215. package/dist/utils/tests/dummy/pinnedMessage.d.ts.map +1 -0
  216. package/dist/utils/tests/dummy/post.d.ts.map +1 -1
  217. package/package.json +3 -2
package/dist/index.cjs.js CHANGED
@@ -7,8 +7,9 @@ var mitt = require('mitt');
7
7
  var debug = require('debug');
8
8
  var axios = require('axios');
9
9
  var HttpAgent = require('agentkeepalive');
10
- var mqtt = require('mqtt');
11
10
  var uuid$1 = require('react-native-uuid');
11
+ var mqtt = require('mqtt');
12
+ var uaParserJs = require('ua-parser-js');
12
13
  var jwtDecode = require('jwt-decode');
13
14
  var hash = require('object-hash');
14
15
  var Hls = require('hls.js');
@@ -19,8 +20,8 @@ var mitt__default = /*#__PURE__*/_interopDefaultLegacy(mitt);
19
20
  var debug__default = /*#__PURE__*/_interopDefaultLegacy(debug);
20
21
  var axios__default = /*#__PURE__*/_interopDefaultLegacy(axios);
21
22
  var HttpAgent__default = /*#__PURE__*/_interopDefaultLegacy(HttpAgent);
22
- var mqtt__default = /*#__PURE__*/_interopDefaultLegacy(mqtt);
23
23
  var uuid__default = /*#__PURE__*/_interopDefaultLegacy(uuid$1);
24
+ var mqtt__default = /*#__PURE__*/_interopDefaultLegacy(mqtt);
24
25
  var jwtDecode__default = /*#__PURE__*/_interopDefaultLegacy(jwtDecode);
25
26
  var hash__default = /*#__PURE__*/_interopDefaultLegacy(hash);
26
27
  var Hls__default = /*#__PURE__*/_interopDefaultLegacy(Hls);
@@ -341,6 +342,7 @@ function getVersion() {
341
342
  const VERSION = getVersion();
342
343
 
343
344
  const COLLECTION_DEFAULT_PAGINATION_LIMIT = 5;
345
+ const LATEST_COMMENTS_LIMIT = 5;
344
346
  const COLLECTION_DEFAULT_PAGINATION_SIZE = 20;
345
347
  const COLLECTION_DEFAULT_CACHING_POLICY = 'cache_then_server';
346
348
  const ENABLE_CACHE_MESSAGE = 'For using Live Collection feature you need to enable Cache!';
@@ -356,7 +358,11 @@ const YEAR = 365 * DAY;
356
358
  const ACCESS_TOKEN_WATCHER_INTERVAL = 10 * MINUTE;
357
359
  const API_ENDPOINTS = {
358
360
  forYouFeed: '/api/v1/feeds/for-you',
361
+ commentReviewQueue: (communityId) => `/api/v3/communities/${encodeURIComponent(communityId)}/comments/review-queue`,
359
362
  };
363
+ // The review-queue route defaults to 10, not the SDK-wide page size, and caps at 100
364
+ const COMMENT_REVIEW_QUEUE_DEFAULT_PAGINATION_SIZE = 10;
365
+ const COMMENT_REVIEW_QUEUE_MAX_PAGINATION_SIZE = 100;
360
366
 
361
367
  // cache constants
362
368
  const CACHE_KEY_GET = 'get';
@@ -806,6 +812,28 @@ class ASCConnectionError extends ASCError {
806
812
  this.event = event;
807
813
  }
808
814
  }
815
+ /**
816
+ * Thrown when the network does not own a module the call needs. Raised from
817
+ * any module endpoint under `enforce` enforcement, mapped from app code
818
+ * `400325` — never from HTTP 403 alone, which already covers a role problem
819
+ * (`400300` / `400301`), a visitor (`403999`) and a bot (`403998`).
820
+ *
821
+ * `modules` carries **every** key the refusal named, as raw strings, so a
822
+ * caller can say which entitlement is absent without a second request.
823
+ *
824
+ * @category Errors
825
+ */
826
+ class AmityModuleNotEntitledError extends ASCApiError {
827
+ /**
828
+ * @param message The server's message, e.g. `Module not entitled: chat, live`
829
+ * @param modules Every module key from the rejection's `data.modules`
830
+ */
831
+ constructor(message, modules = []) {
832
+ super(message, 400325 /* Amity.ServerError.MODULE_NOT_ENTITLED */, "error" /* Amity.ErrorLevel.ERROR */);
833
+ this.modules = modules;
834
+ this.type = 'AmityModuleNotEntitledError';
835
+ }
836
+ }
809
837
 
810
838
  let activeClient = null;
811
839
  /**
@@ -1953,6 +1981,24 @@ function computeUrl(type, region) {
1953
1981
  return URLS[type].replace('{region}', region);
1954
1982
  }
1955
1983
 
1984
+ const uuid = () => uuid__default["default"].v4().toString();
1985
+
1986
+ /**
1987
+ * Reads the module keys a `MODULE_NOT_ENTITLED` rejection named.
1988
+ *
1989
+ * Every entry is kept, as a raw string: one call can need more than one
1990
+ * module, and a key this build predates is still the only part of the
1991
+ * payload a customer can act on.
1992
+ *
1993
+ * @category Transport
1994
+ * @hidden
1995
+ */
1996
+ const extractNotEntitledModules = (data) => {
1997
+ const { modules } = data !== null && data !== void 0 ? data : {};
1998
+ if (!Array.isArray(modules))
1999
+ return [];
2000
+ return modules.filter((module) => typeof module === 'string');
2001
+ };
1956
2002
  /**
1957
2003
  * Unwraps v3 server payload (for error handling and type extraction)
1958
2004
  *
@@ -1972,11 +2018,38 @@ const unwrapPayload = (response) => {
1972
2018
  throw new ASCUnknownError(response.code);
1973
2019
  }
1974
2020
  else if (response.status === 'error') {
2021
+ /*
2022
+ * An entitlement refusal must not arrive as a generic failure: a customer
2023
+ * cannot then tell a module they have not bought from an outage. Keyed on
2024
+ * the app code, never on the HTTP status, so a role or membership problem
2025
+ * still maps to the generic error.
2026
+ */
2027
+ if (response.code === 400325 /* Amity.ServerError.MODULE_NOT_ENTITLED */) {
2028
+ throw new AmityModuleNotEntitledError(response.message, extractNotEntitledModules(response.data));
2029
+ }
1975
2030
  throw new ASCApiError(response.message, response.code, "error" /* Amity.ErrorLevel.ERROR */);
1976
2031
  }
1977
2032
  // unjust, but helps force uncast "T | undefined" to allow deconstruction without warnings
1978
2033
  return undefined;
1979
2034
  };
2035
+ /**
2036
+ * Builds a hex string of `bytes` length from the SDK's uuid helper (a v4 UUID is
2037
+ * 16 bytes / 32 hex chars once hyphens are removed) — avoids a new crypto dependency.
2038
+ */
2039
+ const randomHex = (bytes) => {
2040
+ let hex = '';
2041
+ while (hex.length < bytes * 2)
2042
+ hex += uuid().replace(/-/g, '');
2043
+ return hex.slice(0, bytes * 2);
2044
+ };
2045
+ /**
2046
+ * W3C Trace Context `traceparent`: `version-<16-byte trace-id>-<8-byte span-id>-<flags>`.
2047
+ * The SDK is the trace originator, so it mints a fresh trace + span id per request; flags `01` = sampled.
2048
+ *
2049
+ * @category Transport
2050
+ * @hidden
2051
+ */
2052
+ const generateTraceparent = () => `00-${randomHex(16)}-${randomHex(8)}-01`;
1980
2053
 
1981
2054
  class NetworkActivitiesWatcher {
1982
2055
  constructor() {
@@ -2101,6 +2174,10 @@ const createHttpTransport = (endpoint) => {
2101
2174
  });
2102
2175
  instance.defaults.withCredentials = false;
2103
2176
  instance.interceptors.request.use(config => {
2177
+ // Request tracing — set on every outbound request (login included), never persisted.
2178
+ // Must run before the session-url early-return below so /api/v5/sessions carries them too.
2179
+ config.headers.set('x-request-id', uuid());
2180
+ config.headers.set('traceparent', generateTraceparent());
2104
2181
  // do not check expiration for token creation url
2105
2182
  if (config.url === '/api/v5/sessions') {
2106
2183
  return config;
@@ -2144,20 +2221,28 @@ const createHttpTransport = (endpoint) => {
2144
2221
  });
2145
2222
  return response;
2146
2223
  }, error => {
2147
- var _a, _b, _c;
2224
+ var _a, _b, _c, _d;
2148
2225
  const { response } = error;
2149
2226
  // handle unauthorized request
2150
2227
  if ((response === null || response === void 0 ? void 0 : response.data.code) === 400100 /* Amity.ServerError.UNAUTHORIZED */) {
2151
2228
  fireEvent('tokenTerminated', "terminated" /* Amity.SessionStates.TERMINATED */);
2152
2229
  }
2230
+ // handle globally banned user. The realtime `user.didGlobalBan` event can be missed
2231
+ // (e.g. MQTT dropped before delivery), so mirror the 400100 handling above and fire
2232
+ // the same virtual event the login subscriptions already listen to. That terminates
2233
+ // the session with `TokenTerminationReason.GLOBAL_BAN` and notifies `onClientBanned`
2234
+ // consumers, instead of leaving the session `established` with a revoked token.
2235
+ if (((_a = response === null || response === void 0 ? void 0 : response.data) === null || _a === void 0 ? void 0 : _a.code) === 400312 /* Amity.ServerError.GLOBAL_BAN */) {
2236
+ fireEvent('user.didGlobalBan', { users: [], files: [] });
2237
+ }
2153
2238
  // handle visitor daily usage limit exceeded
2154
- if (((_a = response === null || response === void 0 ? void 0 : response.data) === null || _a === void 0 ? void 0 : _a.code) === 400323 /* Amity.ServerError.VISITOR_USAGE_LIMIT_EXCEEDED */) {
2239
+ if (((_b = response === null || response === void 0 ? void 0 : response.data) === null || _b === void 0 ? void 0 : _b.code) === 400323 /* Amity.ServerError.VISITOR_USAGE_LIMIT_EXCEEDED */) {
2155
2240
  throttledFireVisitorUsageLimit();
2156
2241
  throw new ASCError('Visitor usage limit exceeded', 400323 /* Amity.ServerError.VISITOR_USAGE_LIMIT_EXCEEDED */, "error" /* Amity.ErrorLevel.ERROR */);
2157
2242
  }
2158
2243
  // if it's an error with status in the response payload,
2159
2244
  // then it's an expected error.
2160
- if ((_b = response === null || response === void 0 ? void 0 : response.data) === null || _b === void 0 ? void 0 : _b.status) {
2245
+ if ((_c = response === null || response === void 0 ? void 0 : response.data) === null || _c === void 0 ? void 0 : _c.status) {
2161
2246
  unwrapPayload(response === null || response === void 0 ? void 0 : response.data);
2162
2247
  }
2163
2248
  // as on request cancellation error is returned
@@ -2165,7 +2250,7 @@ const createHttpTransport = (endpoint) => {
2165
2250
  throw error;
2166
2251
  }
2167
2252
  // unexpected error.
2168
- throw new Error((_c = response === null || response === void 0 ? void 0 : response.data) !== null && _c !== void 0 ? _c : error);
2253
+ throw new Error((_d = response === null || response === void 0 ? void 0 : response.data) !== null && _d !== void 0 ? _d : error);
2169
2254
  });
2170
2255
  instance.defaults.paramsSerializer = {
2171
2256
  encode: params => encodeURIComponent(params),
@@ -2363,8 +2448,6 @@ const getItem = async (key) => {
2363
2448
  });
2364
2449
  };
2365
2450
 
2366
- const uuid = () => uuid__default["default"].v4().toString();
2367
-
2368
2451
  // TODO: find a way to uniquely identify the device
2369
2452
  let tabIndex = 0;
2370
2453
  // This logic is running on browser only
@@ -2424,22 +2507,60 @@ const getMQTTClientId = async (userId) => {
2424
2507
  };
2425
2508
  /** @hidden */
2426
2509
  const getDeviceModel = () => {
2427
- var _a, _b;
2510
+ var _a;
2428
2511
  if ((_a = safeProcess.versions) === null || _a === void 0 ? void 0 : _a.node)
2429
2512
  return safeProcess.versions.node;
2430
- if (navigator)
2431
- return `${navigator.product.toLowerCase()}#${(_b = navigator.userAgent) !== null && _b !== void 0 ? _b : 'unknown_agent'}`;
2432
- return 'unknown_model';
2513
+ return undefined;
2514
+ };
2515
+ const hasNavigator = () => typeof navigator !== 'undefined' && !!navigator;
2516
+ const getLocale = () => (hasNavigator() ? navigator.language : undefined);
2517
+ const getTimezone = () => {
2518
+ try {
2519
+ return Intl.DateTimeFormat().resolvedOptions().timeZone;
2520
+ }
2521
+ catch (_a) {
2522
+ return undefined;
2523
+ }
2524
+ };
2525
+ const getNetworkType = () => {
2526
+ var _a;
2527
+ if (!hasNavigator())
2528
+ return undefined;
2529
+ return (_a = navigator.connection) === null || _a === void 0 ? void 0 : _a.effectiveType;
2530
+ };
2531
+ const isNode = () => { var _a; return !!((_a = safeProcess.versions) === null || _a === void 0 ? void 0 : _a.node); };
2532
+ const parseUserAgent = () => {
2533
+ if (!hasNavigator() || !navigator.userAgent)
2534
+ return {};
2535
+ const { os, browser, device } = new uaParserJs.UAParser(navigator.userAgent).getResult();
2536
+ const result = {};
2537
+ if (os.name)
2538
+ result.osName = os.name;
2539
+ if (os.version)
2540
+ result.osVersion = os.version;
2541
+ if (browser.name)
2542
+ result.browserName = browser.name;
2543
+ if (browser.version)
2544
+ result.browserVersion = browser.version;
2545
+ if (device.type === 'tablet')
2546
+ result.deviceType = 'tablet';
2547
+ else if (device.type === 'mobile')
2548
+ result.deviceType = 'mobile';
2549
+ else
2550
+ result.deviceType = 'desktop';
2551
+ return result;
2433
2552
  };
2434
2553
  /** @hidden */
2435
2554
  const getDeviceInfo = () => {
2436
- const model = getDeviceModel();
2437
- return {
2438
- // TODO: replace with: kind: process.versions ? 'node' : 'web', when backend has fixed this
2439
- kind: 'web',
2440
- model,
2441
- sdkVersion: VERSION,
2442
- };
2555
+ var _a;
2556
+ let client;
2557
+ try {
2558
+ client = getActiveClient();
2559
+ }
2560
+ catch (_b) {
2561
+ client = undefined;
2562
+ }
2563
+ return Object.assign({ kind: isNode() ? 'node' : 'web', model: getDeviceModel(), sdkVersion: VERSION, product: (_a = client === null || client === void 0 ? void 0 : client.product) !== null && _a !== void 0 ? _a : 'sdk', uikitVersion: client === null || client === void 0 ? void 0 : client.uikitVersion, appId: client === null || client === void 0 ? void 0 : client.appId, appVersion: client === null || client === void 0 ? void 0 : client.appVersion, locale: getLocale(), timezone: getTimezone(), networkType: getNetworkType() }, parseUserAgent());
2443
2564
  };
2444
2565
 
2445
2566
  /* eslint-disable no-console */
@@ -3851,6 +3972,95 @@ const prepareChannelPayload = async (rawPayload, options = { isMessagePreviewUpd
3851
3972
  channelUsers });
3852
3973
  };
3853
3974
 
3975
+ const channelCacheKey = (channel) => [
3976
+ 'channel',
3977
+ 'get',
3978
+ getResolver('channel')(channel),
3979
+ ];
3980
+ /**
3981
+ * Find a cached channel by any of its ids (internal, public, or `channelId`).
3982
+ *
3983
+ * The channel cache is keyed by the channel internal id (see `idResolvers.channel`), but
3984
+ * realtime payloads reference channels by different ids: pin events carry the **public**
3985
+ * id, messages carry `channelId`. Try the cheap direct lookup first, then scan.
3986
+ */
3987
+ const findCachedChannelByAnyId = (id) => {
3988
+ var _a, _b, _c;
3989
+ if (!id)
3990
+ return undefined;
3991
+ const direct = (_a = pullFromCache(['channel', 'get', id])) === null || _a === void 0 ? void 0 : _a.data;
3992
+ if (direct)
3993
+ return direct;
3994
+ return (_c = (_b = queryCache(['channel', 'get'])) === null || _b === void 0 ? void 0 : _b.find(({ data }) => data.channelInternalId === id || data.channelPublicId === id || data.channelId === id)) === null || _c === void 0 ? void 0 : _c.data;
3995
+ };
3996
+ /**
3997
+ * Resolve the cached channel a `channel.messagePinned` / `channel.messageUnpinned` event
3998
+ * refers to. `data.channelId` is the channel public id; a pinned message body (present on
3999
+ * `messagePinned` only) also carries the internal id, which is the direct cache key.
4000
+ */
4001
+ const findCachedChannelForPin = (payload) => {
4002
+ var _a, _b;
4003
+ return (_b = findCachedChannelByAnyId((_a = payload.pinnedMessage) === null || _a === void 0 ? void 0 : _a.channelId)) !== null && _b !== void 0 ? _b : findCachedChannelByAnyId(payload.channelId);
4004
+ };
4005
+ /**
4006
+ * Write a new pin snapshot (or `null` to clear) on a cached channel and ingest any
4007
+ * users delivered with it (the pin author and the message author), so the banner can
4008
+ * render a byline without a second fetch.
4009
+ *
4010
+ * Every `messagePinned` payload is a full snapshot — "this is the pin now" — so the last
4011
+ * one received always wins; there is no merging with the previous pin.
4012
+ */
4013
+ const updatePinnedMessageCache = (channel, pinnedMessage, users) => {
4014
+ if (users && users.length > 0) {
4015
+ ingestInCache({ users: users.map(convertRawUserToInternalUser) });
4016
+ }
4017
+ const updated = Object.assign(Object.assign({}, channel), { pinnedMessage });
4018
+ pushToCache(channelCacheKey(channel), updated);
4019
+ return updated;
4020
+ };
4021
+
4022
+ /**
4023
+ * Applies a `channel.roleAdded` / `channel.roleRemoved` realtime payload to the cache.
4024
+ *
4025
+ * The event names every member the role request affected together with the
4026
+ * roles and channel-scoped permissions each of them is left holding. That is a
4027
+ * full state, not a delta, so it is written straight over the cached membership.
4028
+ *
4029
+ * Members the SDK has not fetched yet are skipped: the payload does not carry
4030
+ * enough to build a full {@link Amity.Membership} and the live collections only
4031
+ * emit rows that already exist in cache.
4032
+ *
4033
+ * @param payload the `data` of the realtime event
4034
+ * @returns the refreshed channel (when resolvable) and the updated cached memberships
4035
+ *
4036
+ * @hidden
4037
+ */
4038
+ const applyChannelRolePayload = (payload) => {
4039
+ var _a, _b, _c;
4040
+ const { channelId, users = [], channels = [] } = payload;
4041
+ const rawChannel = (_a = channels.find(channel => channel.channelId === channelId)) !== null && _a !== void 0 ? _a : channels[0];
4042
+ let channel;
4043
+ if (rawChannel) {
4044
+ const channelKey = ['channel', 'get', getResolver('channel')(rawChannel)];
4045
+ // the role event does not touch message previews, keep whatever preview is cached
4046
+ const converted = convertFromRaw(rawChannel, { isMessagePreviewUpdated: false });
4047
+ upsertInCache(channelKey, converted);
4048
+ channel = (_c = (_b = pullFromCache(channelKey)) === null || _b === void 0 ? void 0 : _b.data) !== null && _c !== void 0 ? _c : converted;
4049
+ }
4050
+ const members = [];
4051
+ users.forEach(({ userId, roles, permissions }) => {
4052
+ var _a, _b, _c;
4053
+ const memberKey = ['channelUsers', 'get', getResolver('channelUsers')({ channelId, userId })];
4054
+ const cached = (_a = pullFromCache(memberKey)) === null || _a === void 0 ? void 0 : _a.data;
4055
+ if (!cached)
4056
+ return;
4057
+ const updated = Object.assign(Object.assign({}, cached), { roles, permissions });
4058
+ pushToCache(memberKey, updated);
4059
+ members.push((_c = (_b = pullFromCache(memberKey)) === null || _b === void 0 ? void 0 : _b.data) !== null && _c !== void 0 ? _c : updated);
4060
+ });
4061
+ return { channel, members };
4062
+ };
4063
+
3854
4064
  /**
3855
4065
  * ```js
3856
4066
  * import { getSubChannelMarkers } from '@amityco/ts-sdk'
@@ -4036,32 +4246,6 @@ const channelMemberLinkedObject = (channelMember) => {
4036
4246
  } });
4037
4247
  };
4038
4248
 
4039
- /**
4040
- *
4041
- * get current user's membership data
4042
- *
4043
- * @returns the {@link Amity.Membership<'channel'>} objects
4044
- *
4045
- * @category Channel API
4046
- * @async
4047
- */
4048
- const getMyMembership$1 = (channelId) => {
4049
- const client = getActiveClient();
4050
- client.log('channel/getMyMembership.locally');
4051
- const cacheChannelUser = pullFromCache([
4052
- 'channelUsers',
4053
- 'get',
4054
- `${channelId}#${client.userId}`,
4055
- ]);
4056
- if (!cacheChannelUser) {
4057
- throw new ASCApiError('Item not found!', 400400 /* Amity.ServerError.ITEM_NOT_FOUND */, "error" /* Amity.ErrorLevel.ERROR */);
4058
- }
4059
- return {
4060
- data: cacheChannelUser.data,
4061
- cachedAt: cacheChannelUser.cachedAt,
4062
- };
4063
- };
4064
-
4065
4249
  /**
4066
4250
  * ```js
4067
4251
  * import { isEqual } from '~/utils/isEqual'
@@ -4132,55 +4316,81 @@ function isEqual(x, y) {
4132
4316
  }));
4133
4317
  }
4134
4318
 
4135
- const callbacks$c = [];
4319
+ /**
4320
+ *
4321
+ * get current user's membership data
4322
+ *
4323
+ * @returns the {@link Amity.Membership<'channel'>} objects
4324
+ *
4325
+ * @category Channel API
4326
+ * @async
4327
+ */
4328
+ const getMyMembership$1 = (channelId) => {
4329
+ const client = getActiveClient();
4330
+ client.log('channel/getMyMembership.locally');
4331
+ const cacheChannelUser = pullFromCache([
4332
+ 'channelUsers',
4333
+ 'get',
4334
+ `${channelId}#${client.userId}`,
4335
+ ]);
4336
+ if (!cacheChannelUser) {
4337
+ throw new ASCApiError('Item not found!', 400400 /* Amity.ServerError.ITEM_NOT_FOUND */, "error" /* Amity.ErrorLevel.ERROR */);
4338
+ }
4339
+ return {
4340
+ data: cacheChannelUser.data,
4341
+ cachedAt: cacheChannelUser.cachedAt,
4342
+ };
4343
+ };
4344
+
4345
+ const callbacks$e = [];
4136
4346
  let mainDisposer$b = null;
4137
- const dispose$c = (cb) => {
4138
- const index = callbacks$c.indexOf(cb);
4347
+ const dispose$e = (cb) => {
4348
+ const index = callbacks$e.indexOf(cb);
4139
4349
  if (index > -1) {
4140
- callbacks$c.splice(index, 1);
4350
+ callbacks$e.splice(index, 1);
4141
4351
  }
4142
- if (callbacks$c.length === 0) {
4352
+ if (callbacks$e.length === 0) {
4143
4353
  mainDisposer$b === null || mainDisposer$b === void 0 ? void 0 : mainDisposer$b();
4144
4354
  }
4145
4355
  };
4146
4356
  const onChannelCreated = (callback) => {
4147
- if (callbacks$c.length === 0) {
4357
+ if (callbacks$e.length === 0) {
4148
4358
  const client = getActiveClient();
4149
4359
  const filter = async (payload) => {
4150
4360
  const data = await prepareChannelPayload(payload);
4151
4361
  ingestInCache(data);
4152
- callbacks$c.forEach(cb => cb(data.channels[0]));
4362
+ callbacks$e.forEach(cb => cb(data.channels[0]));
4153
4363
  };
4154
4364
  mainDisposer$b = createEventSubscriber(client, 'onChannelCreated', 'channel.created', filter);
4155
4365
  }
4156
- callbacks$c.push(callback);
4157
- return () => dispose$c(callback);
4366
+ callbacks$e.push(callback);
4367
+ return () => dispose$e(callback);
4158
4368
  };
4159
4369
 
4160
- const callbacks$b = [];
4161
- const mainDisposers = [];
4162
- const dispose$b = (cb) => {
4163
- const index = callbacks$b.indexOf(cb);
4370
+ const callbacks$d = [];
4371
+ const mainDisposers$2 = [];
4372
+ const dispose$d = (cb) => {
4373
+ const index = callbacks$d.indexOf(cb);
4164
4374
  if (index > -1) {
4165
- callbacks$b.splice(index, 1);
4375
+ callbacks$d.splice(index, 1);
4166
4376
  }
4167
- if (callbacks$b.length === 0) {
4168
- mainDisposers.forEach(fn => fn());
4377
+ if (callbacks$d.length === 0) {
4378
+ mainDisposers$2.forEach(fn => fn());
4169
4379
  }
4170
4380
  };
4171
4381
  const onChannelUpdated = (callback) => {
4172
4382
  const client = getActiveClient();
4173
- if (callbacks$b.length === 0) {
4383
+ if (callbacks$d.length === 0) {
4174
4384
  const filter = async (payload) => {
4175
4385
  const data = await prepareChannelPayload(payload);
4176
4386
  ingestInCache(data);
4177
- callbacks$b.forEach(cb => cb(data.channels[0]));
4387
+ callbacks$d.forEach(cb => cb(data.channels[0]));
4178
4388
  };
4179
- mainDisposers.push(createEventSubscriber(client, 'onChannelUpdated', 'channel.updated', filter));
4180
- mainDisposers.push(createEventSubscriber(client, 'onChannelUpdated', 'local.channel.updated', payload => callbacks$b.forEach(cb => cb(payload.channels[0]))));
4389
+ mainDisposers$2.push(createEventSubscriber(client, 'onChannelUpdated', 'channel.updated', filter));
4390
+ mainDisposers$2.push(createEventSubscriber(client, 'onChannelUpdated', 'local.channel.updated', payload => callbacks$d.forEach(cb => cb(payload.channels[0]))));
4181
4391
  }
4182
- callbacks$b.push(callback);
4183
- return () => dispose$b(callback);
4392
+ callbacks$d.push(callback);
4393
+ return () => dispose$d(callback);
4184
4394
  };
4185
4395
 
4186
4396
  const addFlagIsDeletedSubChannelUnreadByChannelId = (channelId) => {
@@ -4203,19 +4413,19 @@ const deleteChannelUnreadByChannelId = (channelId) => {
4203
4413
  }
4204
4414
  };
4205
4415
 
4206
- const callbacks$a = [];
4416
+ const callbacks$c = [];
4207
4417
  let mainDisposer$a = null;
4208
- const dispose$a = (cb) => {
4209
- const index = callbacks$a.indexOf(cb);
4418
+ const dispose$c = (cb) => {
4419
+ const index = callbacks$c.indexOf(cb);
4210
4420
  if (index > -1) {
4211
- callbacks$a.splice(index, 1);
4421
+ callbacks$c.splice(index, 1);
4212
4422
  }
4213
- if (callbacks$a.length === 0) {
4423
+ if (callbacks$c.length === 0) {
4214
4424
  mainDisposer$a === null || mainDisposer$a === void 0 ? void 0 : mainDisposer$a();
4215
4425
  }
4216
4426
  };
4217
4427
  const onChannelDeleted = (callback) => {
4218
- if (callbacks$a.length === 0) {
4428
+ if (callbacks$c.length === 0) {
4219
4429
  const client = getActiveClient();
4220
4430
  const filter = async (payload) => {
4221
4431
  const data = await prepareChannelPayload(payload);
@@ -4235,53 +4445,53 @@ const onChannelDeleted = (callback) => {
4235
4445
  }
4236
4446
  });
4237
4447
  ingestInCache(data);
4238
- callbacks$a.forEach(cb => cb(data.channels[0]));
4448
+ callbacks$c.forEach(cb => cb(data.channels[0]));
4239
4449
  };
4240
4450
  mainDisposer$a = createEventSubscriber(client, 'onChannelDeleted', 'channel.deleted', filter);
4241
4451
  }
4242
- callbacks$a.push(callback);
4243
- return () => dispose$a(callback);
4452
+ callbacks$c.push(callback);
4453
+ return () => dispose$c(callback);
4244
4454
  };
4245
4455
 
4246
- const callbacks$9 = [];
4456
+ const callbacks$b = [];
4247
4457
  let mainDisposer$9 = null;
4248
- const dispose$9 = (cb) => {
4249
- const index = callbacks$9.indexOf(cb);
4458
+ const dispose$b = (cb) => {
4459
+ const index = callbacks$b.indexOf(cb);
4250
4460
  if (index > -1) {
4251
- callbacks$9.splice(index, 1);
4461
+ callbacks$b.splice(index, 1);
4252
4462
  }
4253
- if (callbacks$9.length === 0) {
4463
+ if (callbacks$b.length === 0) {
4254
4464
  mainDisposer$9 === null || mainDisposer$9 === void 0 ? void 0 : mainDisposer$9();
4255
4465
  }
4256
4466
  };
4257
4467
  const onChannelJoined = (callback) => {
4258
- if (callbacks$9.length === 0) {
4468
+ if (callbacks$b.length === 0) {
4259
4469
  const client = getActiveClient();
4260
4470
  const filter = async (payload) => {
4261
4471
  const preparedPayload = await prepareChannelPayload(payload);
4262
4472
  const { channels, channelUsers } = preparedPayload;
4263
4473
  ingestInCache(preparedPayload);
4264
- callbacks$9.forEach(cb => cb(channels[0], channelUsers[0]));
4474
+ callbacks$b.forEach(cb => cb(channels[0], channelUsers[0]));
4265
4475
  };
4266
4476
  mainDisposer$9 = createEventSubscriber(client, 'onChannelJoined', 'channel.joined', filter);
4267
4477
  }
4268
- callbacks$9.push(callback);
4269
- return () => dispose$9(callback);
4478
+ callbacks$b.push(callback);
4479
+ return () => dispose$b(callback);
4270
4480
  };
4271
4481
 
4272
- const callbacks$8 = [];
4482
+ const callbacks$a = [];
4273
4483
  let mainDisposer$8 = null;
4274
- const dispose$8 = (cb) => {
4275
- const index = callbacks$8.indexOf(cb);
4484
+ const dispose$a = (cb) => {
4485
+ const index = callbacks$a.indexOf(cb);
4276
4486
  if (index > -1) {
4277
- callbacks$8.splice(index, 1);
4487
+ callbacks$a.splice(index, 1);
4278
4488
  }
4279
- if (callbacks$8.length === 0) {
4489
+ if (callbacks$a.length === 0) {
4280
4490
  mainDisposer$8 === null || mainDisposer$8 === void 0 ? void 0 : mainDisposer$8();
4281
4491
  }
4282
4492
  };
4283
4493
  const onChannelLeft = (callback) => {
4284
- if (callbacks$8.length === 0) {
4494
+ if (callbacks$a.length === 0) {
4285
4495
  const client = getActiveClient();
4286
4496
  const filter = async (payload) => {
4287
4497
  const { userId } = getActiveClient();
@@ -4305,27 +4515,27 @@ const onChannelLeft = (callback) => {
4305
4515
  }
4306
4516
  const { channels, channelUsers } = preparedPayload;
4307
4517
  ingestInCache(preparedPayload);
4308
- callbacks$8.forEach(cb => cb(channels[0], channelUsers[0]));
4518
+ callbacks$a.forEach(cb => cb(channels[0], channelUsers[0]));
4309
4519
  };
4310
4520
  mainDisposer$8 = createEventSubscriber(client, 'onChannelLeft', 'channel.left', filter);
4311
4521
  }
4312
- callbacks$8.push(callback);
4313
- return () => dispose$8(callback);
4522
+ callbacks$a.push(callback);
4523
+ return () => dispose$a(callback);
4314
4524
  };
4315
4525
 
4316
- const callbacks$7 = [];
4526
+ const callbacks$9 = [];
4317
4527
  let mainDisposer$7 = null;
4318
- const dispose$7 = (cb) => {
4319
- const index = callbacks$7.indexOf(cb);
4528
+ const dispose$9 = (cb) => {
4529
+ const index = callbacks$9.indexOf(cb);
4320
4530
  if (index > -1) {
4321
- callbacks$7.splice(index, 1);
4531
+ callbacks$9.splice(index, 1);
4322
4532
  }
4323
- if (callbacks$7.length === 0) {
4533
+ if (callbacks$9.length === 0) {
4324
4534
  mainDisposer$7 === null || mainDisposer$7 === void 0 ? void 0 : mainDisposer$7();
4325
4535
  }
4326
4536
  };
4327
4537
  const onChannelSetMuted = (callback) => {
4328
- if (callbacks$7.length === 0) {
4538
+ if (callbacks$9.length === 0) {
4329
4539
  const client = getActiveClient();
4330
4540
  const filter = async (payload) => {
4331
4541
  var _a;
@@ -4340,24 +4550,124 @@ const onChannelSetMuted = (callback) => {
4340
4550
  payload.channelId,
4341
4551
  ])) === null || _a === void 0 ? void 0 : _a.data;
4342
4552
  if (channel) {
4343
- callbacks$7.forEach(cb => cb(channel));
4553
+ callbacks$9.forEach(cb => cb(channel));
4344
4554
  }
4345
4555
  };
4346
4556
  mainDisposer$7 = createEventSubscriber(client, 'onChannelMute', 'channel.setMuted', filter);
4347
4557
  }
4558
+ callbacks$9.push(callback);
4559
+ return () => dispose$9(callback);
4560
+ };
4561
+
4562
+ const callbacks$8 = [];
4563
+ let mainDisposer$6 = null;
4564
+ const dispose$8 = (cb) => {
4565
+ const index = callbacks$8.indexOf(cb);
4566
+ if (index > -1) {
4567
+ callbacks$8.splice(index, 1);
4568
+ }
4569
+ if (callbacks$8.length === 0) {
4570
+ mainDisposer$6 === null || mainDisposer$6 === void 0 ? void 0 : mainDisposer$6();
4571
+ }
4572
+ };
4573
+ /* begin_public_function
4574
+ id: channel.event.message_pinned
4575
+ */
4576
+ /**
4577
+ * ```js
4578
+ * import { onChannelMessagePinned } from '@amityco/ts-sdk'
4579
+ * const dispose = onChannelMessagePinned(channel => {
4580
+ * // channel.pinnedMessage is the new pin
4581
+ * })
4582
+ * ```
4583
+ *
4584
+ * Fired when a message is pinned in a channel (the `channel.messagePinned` realtime
4585
+ * event). Pinning a different message while one is already pinned emits a single
4586
+ * `messagePinned` carrying the replacement — treat every payload as a full snapshot.
4587
+ *
4588
+ * The updated channel is written to cache before the callback runs, so
4589
+ * `ChannelRepository.getChannel` observers see `channel.pinnedMessage` change.
4590
+ *
4591
+ * @param callback The function to call when the event was fired
4592
+ * @returns an {@link Amity.Unsubscriber} function to run when willing to stop listening
4593
+ *
4594
+ * @category Channel Events
4595
+ */
4596
+ const onChannelMessagePinned = (callback) => {
4597
+ if (callbacks$8.length === 0) {
4598
+ const client = getActiveClient();
4599
+ const filter = (payload) => {
4600
+ var _a;
4601
+ const channel = findCachedChannelForPin(payload);
4602
+ if (!channel)
4603
+ return;
4604
+ const updated = updatePinnedMessageCache(channel, (_a = payload.pinnedMessage) !== null && _a !== void 0 ? _a : null, payload.users);
4605
+ callbacks$8.forEach(cb => cb(updated));
4606
+ };
4607
+ mainDisposer$6 = createEventSubscriber(client, 'onChannelMessagePinned', 'channel.messagePinned', filter);
4608
+ }
4609
+ callbacks$8.push(callback);
4610
+ return () => dispose$8(callback);
4611
+ };
4612
+ /* end_public_function */
4613
+
4614
+ const callbacks$7 = [];
4615
+ let mainDisposer$5 = null;
4616
+ const dispose$7 = (cb) => {
4617
+ const index = callbacks$7.indexOf(cb);
4618
+ if (index > -1) {
4619
+ callbacks$7.splice(index, 1);
4620
+ }
4621
+ if (callbacks$7.length === 0) {
4622
+ mainDisposer$5 === null || mainDisposer$5 === void 0 ? void 0 : mainDisposer$5();
4623
+ }
4624
+ };
4625
+ /* begin_public_function
4626
+ id: channel.event.message_unpinned
4627
+ */
4628
+ /**
4629
+ * ```js
4630
+ * import { onChannelMessageUnpinned } from '@amityco/ts-sdk'
4631
+ * const dispose = onChannelMessageUnpinned(channel => {
4632
+ * // channel.pinnedMessage is now null
4633
+ * })
4634
+ * ```
4635
+ *
4636
+ * Fired when a channel's pinned message is removed (the `channel.messageUnpinned`
4637
+ * realtime event) — either by an explicit unpin or automatically by the server when the
4638
+ * pinned message is deleted or its author is banned from the channel / globally.
4639
+ *
4640
+ * @param callback The function to call when the event was fired
4641
+ * @returns an {@link Amity.Unsubscriber} function to run when willing to stop listening
4642
+ *
4643
+ * @category Channel Events
4644
+ */
4645
+ const onChannelMessageUnpinned = (callback) => {
4646
+ if (callbacks$7.length === 0) {
4647
+ const client = getActiveClient();
4648
+ const filter = (payload) => {
4649
+ const channel = findCachedChannelForPin(payload);
4650
+ if (!channel)
4651
+ return;
4652
+ const updated = updatePinnedMessageCache(channel, null);
4653
+ callbacks$7.forEach(cb => cb(updated));
4654
+ };
4655
+ mainDisposer$5 = createEventSubscriber(client, 'onChannelMessageUnpinned', 'channel.messageUnpinned', filter);
4656
+ }
4348
4657
  callbacks$7.push(callback);
4349
4658
  return () => dispose$7(callback);
4350
4659
  };
4660
+ /* end_public_function */
4351
4661
 
4352
4662
  const callbacks$6 = [];
4353
- let mainDisposer$6 = null;
4663
+ let mainDisposer$4 = null;
4354
4664
  const dispose$6 = (cb) => {
4355
4665
  const index = callbacks$6.indexOf(cb);
4356
4666
  if (index > -1) {
4357
4667
  callbacks$6.splice(index, 1);
4358
4668
  }
4359
4669
  if (callbacks$6.length === 0) {
4360
- mainDisposer$6 === null || mainDisposer$6 === void 0 ? void 0 : mainDisposer$6();
4670
+ mainDisposer$4 === null || mainDisposer$4 === void 0 ? void 0 : mainDisposer$4();
4361
4671
  }
4362
4672
  };
4363
4673
  const onChannelMemberAdded = (callback) => {
@@ -4369,21 +4679,21 @@ const onChannelMemberAdded = (callback) => {
4369
4679
  ingestInCache(preparedPayload);
4370
4680
  callbacks$6.forEach(cb => cb(channels[0], channelUsers.find(cu => cu.membership === 'member')));
4371
4681
  };
4372
- mainDisposer$6 = createEventSubscriber(client, 'onChannelMemberAdded', 'channel.membersAdded', filter);
4682
+ mainDisposer$4 = createEventSubscriber(client, 'onChannelMemberAdded', 'channel.membersAdded', filter);
4373
4683
  }
4374
4684
  callbacks$6.push(callback);
4375
4685
  return () => dispose$6(callback);
4376
4686
  };
4377
4687
 
4378
4688
  const callbacks$5 = [];
4379
- let mainDisposer$5 = null;
4689
+ let mainDisposer$3 = null;
4380
4690
  const dispose$5 = (cb) => {
4381
4691
  const index = callbacks$5.indexOf(cb);
4382
4692
  if (index > -1) {
4383
4693
  callbacks$5.splice(index, 1);
4384
4694
  }
4385
4695
  if (callbacks$5.length === 0) {
4386
- mainDisposer$5 === null || mainDisposer$5 === void 0 ? void 0 : mainDisposer$5();
4696
+ mainDisposer$3 === null || mainDisposer$3 === void 0 ? void 0 : mainDisposer$3();
4387
4697
  }
4388
4698
  };
4389
4699
  const onChannelMemberRemoved = (callback) => {
@@ -4395,21 +4705,21 @@ const onChannelMemberRemoved = (callback) => {
4395
4705
  ingestInCache(preparedPayload);
4396
4706
  callbacks$5.forEach(cb => cb(channels[0], channelUsers[0]));
4397
4707
  };
4398
- mainDisposer$5 = createEventSubscriber(client, 'onChannelMemberRemoved', 'channel.membersRemoved', filter);
4708
+ mainDisposer$3 = createEventSubscriber(client, 'onChannelMemberRemoved', 'channel.membersRemoved', filter);
4399
4709
  }
4400
4710
  callbacks$5.push(callback);
4401
4711
  return () => dispose$5(callback);
4402
4712
  };
4403
4713
 
4404
4714
  const callbacks$4 = [];
4405
- let mainDisposer$4 = null;
4715
+ let mainDisposer$2 = null;
4406
4716
  const dispose$4 = (cb) => {
4407
4717
  const index = callbacks$4.indexOf(cb);
4408
4718
  if (index > -1) {
4409
4719
  callbacks$4.splice(index, 1);
4410
4720
  }
4411
4721
  if (callbacks$4.length === 0) {
4412
- mainDisposer$4 === null || mainDisposer$4 === void 0 ? void 0 : mainDisposer$4();
4722
+ mainDisposer$2 === null || mainDisposer$2 === void 0 ? void 0 : mainDisposer$2();
4413
4723
  }
4414
4724
  };
4415
4725
  const onChannelMemberBanned = (callback) => {
@@ -4429,20 +4739,20 @@ const onChannelMemberBanned = (callback) => {
4429
4739
  ingestInCache(preparedPayload);
4430
4740
  callbacks$4.forEach(cb => cb(channels[0], channelUsers.find(cu => cu.membership === 'banned')));
4431
4741
  };
4432
- mainDisposer$4 = createEventSubscriber(client, 'onChannelMemberBanned', 'channel.banned', filter);
4742
+ mainDisposer$2 = createEventSubscriber(client, 'onChannelMemberBanned', 'channel.banned', filter);
4433
4743
  callbacks$4.push(callback);
4434
4744
  return () => dispose$4(callback);
4435
4745
  };
4436
4746
 
4437
4747
  const callbacks$3 = [];
4438
- let mainDisposer$3 = null;
4748
+ let mainDisposer$1 = null;
4439
4749
  const dispose$3 = (cb) => {
4440
4750
  const index = callbacks$3.indexOf(cb);
4441
4751
  if (index > -1) {
4442
4752
  callbacks$3.splice(index, 1);
4443
4753
  }
4444
4754
  if (callbacks$3.length === 0) {
4445
- mainDisposer$3 === null || mainDisposer$3 === void 0 ? void 0 : mainDisposer$3();
4755
+ mainDisposer$1 === null || mainDisposer$1 === void 0 ? void 0 : mainDisposer$1();
4446
4756
  }
4447
4757
  };
4448
4758
  const onChannelMemberUnbanned = (callback) => {
@@ -4454,59 +4764,127 @@ const onChannelMemberUnbanned = (callback) => {
4454
4764
  ingestInCache(preparedPayload);
4455
4765
  callbacks$3.forEach(cb => cb(channels[0], channelUsers.find(cu => cu.membership === 'none')));
4456
4766
  };
4457
- mainDisposer$3 = createEventSubscriber(client, 'onChannelMemberUnbanned', 'channel.unbanned', filter);
4767
+ mainDisposer$1 = createEventSubscriber(client, 'onChannelMemberUnbanned', 'channel.unbanned', filter);
4458
4768
  }
4459
4769
  callbacks$3.push(callback);
4460
4770
  return () => dispose$3(callback);
4461
4771
  };
4462
4772
 
4463
4773
  const callbacks$2 = [];
4464
- let mainDisposer$2 = null;
4774
+ const mainDisposers$1 = [];
4465
4775
  const dispose$2 = (cb) => {
4466
4776
  const index = callbacks$2.indexOf(cb);
4467
4777
  if (index > -1) {
4468
4778
  callbacks$2.splice(index, 1);
4469
4779
  }
4470
4780
  if (callbacks$2.length === 0) {
4471
- mainDisposer$2 === null || mainDisposer$2 === void 0 ? void 0 : mainDisposer$2();
4781
+ mainDisposers$1.forEach(fn => fn());
4782
+ mainDisposers$1.length = 0;
4472
4783
  }
4473
4784
  };
4785
+ /* begin_public_function
4786
+ id: channel.event.member_role_added
4787
+ */
4788
+ /**
4789
+ * ```js
4790
+ * import { onChannelMemberRoleAdded } from '@amityco/ts-sdk'
4791
+ * const dispose = onChannelMemberRoleAdded((channel, member) => {
4792
+ * // member.roles and member.permissions are the member's resulting state
4793
+ * })
4794
+ * ```
4795
+ *
4796
+ * Fired when a role is added to a member of a {@link Amity.Channel}, either by the
4797
+ * local `ChannelRepository.Moderation.addRole` call or by the `channel.roleAdded` realtime
4798
+ * event coming from any client or the admin console.
4799
+ *
4800
+ * The realtime event reaches every subscriber of the channel topic (see `getChannelTopic`),
4801
+ * not only the actor or the affected members. It carries the affected members' resulting
4802
+ * channel roles and channel-scoped permissions, which are written to cache before the
4803
+ * callback runs. The callback is invoked once per affected member already held in cache.
4804
+ *
4805
+ * @param callback The function to call when the event was fired
4806
+ * @returns an {@link Amity.Unsubscriber} function to run when willing to stop listening
4807
+ *
4808
+ * @category Channel Events
4809
+ */
4474
4810
  const onChannelMemberRoleAdded = (callback) => {
4475
4811
  if (callbacks$2.length === 0) {
4476
4812
  const client = getActiveClient();
4477
- const filter = async (payload) => {
4813
+ const onLocal = async (payload) => {
4478
4814
  const { channels, channelUsers } = payload;
4479
4815
  callbacks$2.forEach(cb => cb(channels[0], channelUsers.find(channelUser => channelUser.membership === 'member')));
4480
4816
  };
4481
- mainDisposer$2 = createEventSubscriber(client, 'onChannelMemberRoleAdded', 'local.channel-moderator.role-added', filter);
4817
+ const onRealtime = (payload) => {
4818
+ const { channel, members } = applyChannelRolePayload(payload);
4819
+ if (!channel)
4820
+ return;
4821
+ members.forEach(member => callbacks$2.forEach(cb => cb(channel, member)));
4822
+ };
4823
+ mainDisposers$1.push(createEventSubscriber(client, 'onChannelMemberRoleAdded', 'local.channel-moderator.role-added', onLocal));
4824
+ mainDisposers$1.push(createEventSubscriber(client, 'onChannelMemberRoleAdded', 'channel.roleAdded', onRealtime));
4482
4825
  }
4483
4826
  callbacks$2.push(callback);
4484
4827
  return () => dispose$2(callback);
4485
4828
  };
4829
+ /* end_public_function */
4486
4830
 
4487
4831
  const callbacks$1 = [];
4488
- let mainDisposer$1 = null;
4832
+ const mainDisposers = [];
4489
4833
  const dispose$1 = (cb) => {
4490
4834
  const index = callbacks$1.indexOf(cb);
4491
4835
  if (index > -1) {
4492
4836
  callbacks$1.splice(index, 1);
4493
4837
  }
4494
4838
  if (callbacks$1.length === 0) {
4495
- mainDisposer$1 === null || mainDisposer$1 === void 0 ? void 0 : mainDisposer$1();
4839
+ mainDisposers.forEach(fn => fn());
4840
+ mainDisposers.length = 0;
4496
4841
  }
4497
4842
  };
4843
+ /* begin_public_function
4844
+ id: channel.event.member_role_removed
4845
+ */
4846
+ /**
4847
+ * ```js
4848
+ * import { onChannelMemberRoleRemoved } from '@amityco/ts-sdk'
4849
+ * const dispose = onChannelMemberRoleRemoved((channel, member) => {
4850
+ * // member.roles and member.permissions are the member's resulting state
4851
+ * })
4852
+ * ```
4853
+ *
4854
+ * Fired when a role is removed from a member of a {@link Amity.Channel}, either by the
4855
+ * local `ChannelRepository.Moderation.removeRole` call or by the `channel.roleRemoved` realtime
4856
+ * event coming from any client or the admin console.
4857
+ *
4858
+ * The realtime event reaches every subscriber of the channel topic (see `getChannelTopic`),
4859
+ * not only the actor or the affected members. It carries the affected members' resulting
4860
+ * channel roles and channel-scoped permissions, which are written to cache before the
4861
+ * callback runs. The callback is invoked once per affected member already held in cache.
4862
+ *
4863
+ * @param callback The function to call when the event was fired
4864
+ * @returns an {@link Amity.Unsubscriber} function to run when willing to stop listening
4865
+ *
4866
+ * @category Channel Events
4867
+ */
4498
4868
  const onChannelMemberRoleRemoved = (callback) => {
4499
4869
  if (callbacks$1.length === 0) {
4500
4870
  const client = getActiveClient();
4501
- const filter = async (payload) => {
4871
+ const onLocal = async (payload) => {
4502
4872
  const { channels, channelUsers } = payload;
4503
4873
  callbacks$1.forEach(cb => cb(channels[0], channelUsers.find(channelUser => channelUser.membership === 'member')));
4504
4874
  };
4505
- mainDisposer$1 = createEventSubscriber(client, 'onChannelMemberRoleRemoved', 'local.channel-moderator.role-removed', filter);
4875
+ const onRealtime = (payload) => {
4876
+ const { channel, members } = applyChannelRolePayload(payload);
4877
+ if (!channel)
4878
+ return;
4879
+ members.forEach(member => callbacks$1.forEach(cb => cb(channel, member)));
4880
+ };
4881
+ mainDisposers.push(createEventSubscriber(client, 'onChannelMemberRoleRemoved', 'local.channel-moderator.role-removed', onLocal));
4882
+ mainDisposers.push(createEventSubscriber(client, 'onChannelMemberRoleRemoved', 'channel.roleRemoved', onRealtime));
4506
4883
  }
4507
4884
  callbacks$1.push(callback);
4508
4885
  return () => dispose$1(callback);
4509
4886
  };
4887
+ /* end_public_function */
4510
4888
 
4511
4889
  /**
4512
4890
  * Fired when a {@link Amity.Channel} has been archived by the active user.
@@ -4630,6 +5008,8 @@ const getMyMembership = (channelId, callback) => {
4630
5008
  disposers.push(onChannelMemberBanned(realtimeRouter));
4631
5009
  disposers.push(onChannelMemberUnbanned(realtimeRouter));
4632
5010
  disposers.push(onChannelSetUserMuted(realtimeRouter));
5011
+ disposers.push(onChannelMemberRoleAdded(realtimeRouter));
5012
+ disposers.push(onChannelMemberRoleRemoved(realtimeRouter));
4633
5013
  onFetch();
4634
5014
  return () => {
4635
5015
  disposers.forEach(fn => fn());
@@ -5023,7 +5403,9 @@ const initializeMessagePreviewSetting = async () => {
5023
5403
  const getSocialSettings = async () => {
5024
5404
  const client = getActiveClient();
5025
5405
  const { data } = await client.http.get(`/api/v3/network-settings/social`);
5026
- return data.socialNetworkSetting;
5406
+ return Object.assign(Object.assign({}, data.socialNetworkSetting), {
5407
+ // Networks that never set the comment edit switch allow the edit
5408
+ isAllowEditCommentWhenReviewingEnabled: data.socialNetworkSetting.isAllowEditCommentWhenReviewingEnabled });
5027
5409
  };
5028
5410
 
5029
5411
  /**
@@ -5141,6 +5523,95 @@ const getForYouFeedSetting = async () => {
5141
5523
  };
5142
5524
  /* end_public_function */
5143
5525
 
5526
+ const ENFORCEMENT_MODES = ['off', 'shadow', 'enforce'];
5527
+ /**
5528
+ * An unrecognised mode decodes to `off`, and so does an absent one. A mode
5529
+ * this build does not know must not withhold anything — defaulting to
5530
+ * `enforce` would let a server-side rename black out a customer's app.
5531
+ *
5532
+ * @category private
5533
+ */
5534
+ const parseEnforcement = (mode) => {
5535
+ const match = ENFORCEMENT_MODES.find(value => value === mode);
5536
+ return match !== null && match !== void 0 ? match : 'off';
5537
+ };
5538
+ const parseGrants = (modules) => {
5539
+ const grants = {};
5540
+ Object.entries(modules !== null && modules !== void 0 ? modules : {}).forEach(([key, granted]) => {
5541
+ grants[key] = granted === true;
5542
+ });
5543
+ return grants;
5544
+ };
5545
+ /**
5546
+ * Every catalog entry survives, including one whose key this build has never
5547
+ * heard of, so a module added server-side is still listable.
5548
+ *
5549
+ * @category private
5550
+ */
5551
+ const parseCatalog = (catalog) => {
5552
+ const parsed = {};
5553
+ Object.entries(catalog !== null && catalog !== void 0 ? catalog : {}).forEach(([key, definition]) => {
5554
+ const rawRequires = definition === null || definition === void 0 ? void 0 : definition.requires;
5555
+ const requires = Array.isArray(rawRequires)
5556
+ ? rawRequires.filter((entry) => typeof entry === 'string')
5557
+ : [];
5558
+ parsed[key] = {
5559
+ label: typeof (definition === null || definition === void 0 ? void 0 : definition.label) === 'string' ? definition.label : key,
5560
+ kind: (definition === null || definition === void 0 ? void 0 : definition.kind) === 'setting' ? 'setting' : 'api',
5561
+ requires,
5562
+ };
5563
+ });
5564
+ return parsed;
5565
+ };
5566
+ /**
5567
+ * Decodes `GET /api/v3/network-settings/modules`. Nothing is trimmed: the
5568
+ * catalog is the dependency table callers resolve against, and a client that
5569
+ * cannot see it has to hardcode one.
5570
+ *
5571
+ * @category private
5572
+ */
5573
+ const parseModuleSettings = (raw) => {
5574
+ var _a;
5575
+ return ({
5576
+ enforcement: parseEnforcement((_a = raw === null || raw === void 0 ? void 0 : raw.enforcement) !== null && _a !== void 0 ? _a : raw === null || raw === void 0 ? void 0 : raw.mode),
5577
+ modules: parseGrants(raw === null || raw === void 0 ? void 0 : raw.modules),
5578
+ catalog: parseCatalog(raw === null || raw === void 0 ? void 0 : raw.catalog),
5579
+ });
5580
+ };
5581
+
5582
+ /* begin_public_function
5583
+ id: client.getModuleSettings
5584
+ */
5585
+ /**
5586
+ * ```js
5587
+ * import { Client } from '@amityco/ts-sdk'
5588
+ * const moduleSettings = await Client.getModuleSettings()
5589
+ * ```
5590
+ *
5591
+ * Fetches the network's module entitlements: which modules the network was
5592
+ * granted, whether core is enforcing those grants, and the catalog of all
5593
+ * modules with their dependency chains.
5594
+ *
5595
+ * The payload is returned whole — `catalog` is the dependency table
5596
+ * {@link resolveModuleAvailability} reads, and a client that cannot see it has
5597
+ * to hardcode one.
5598
+ *
5599
+ * The read is **advisory**. It tells a host what to offer; under `enforce` the
5600
+ * backend refuses a call to an unowned module regardless of what was resolved
5601
+ * here, and that refusal arrives as `AmityModuleNotEntitledError`.
5602
+ *
5603
+ * @returns A Promise of {@link Amity.ModuleSettings} object
5604
+ *
5605
+ * @category Client API
5606
+ * @async
5607
+ */
5608
+ const getModuleSettings = async () => {
5609
+ const client = getActiveClient();
5610
+ const { data } = await client.http.get(`/api/v3/network-settings/modules`);
5611
+ return parseModuleSettings(data);
5612
+ };
5613
+ /* end_public_function */
5614
+
5144
5615
  const checkUserPermission = (userId, permission) => {
5145
5616
  var _a;
5146
5617
  const user = (_a = pullFromCache(['user', 'get', userId])) === null || _a === void 0 ? void 0 : _a.data;
@@ -5709,6 +6180,32 @@ class AnalyticsEventCapturer {
5709
6180
  activityType: "view" /* Amity.AnalyticEventActivityType.View */,
5710
6181
  });
5711
6182
  }
6183
+ markCuratedContentWidgetAsViewed(topicId) {
6184
+ this.markAs({
6185
+ uniqueId: `curatedContentWidget.${topicId}`,
6186
+ contentId: topicId,
6187
+ contentType: "curated_content_widget" /* Amity.AnalyticEventContentType.CuratedContentWidget */,
6188
+ activityType: "view" /* Amity.AnalyticEventActivityType.View */,
6189
+ });
6190
+ }
6191
+ markCuratedContentPostAsViewed(postId, topicId) {
6192
+ this.markAs({
6193
+ uniqueId: `curatedContentPost.${postId}.view`,
6194
+ contentId: postId,
6195
+ contentType: "curated_content_post" /* Amity.AnalyticEventContentType.CuratedContentPost */,
6196
+ activityType: "view" /* Amity.AnalyticEventActivityType.View */,
6197
+ metadata: { topicId },
6198
+ });
6199
+ }
6200
+ markCuratedContentPostAsClicked(postId, topicId) {
6201
+ this.markAs({
6202
+ uniqueId: `curatedContentPost.${postId}.click`,
6203
+ contentId: postId,
6204
+ contentType: "curated_content_post" /* Amity.AnalyticEventContentType.CuratedContentPost */,
6205
+ activityType: "linkClicked" /* Amity.AnalyticEventActivityType.Click */,
6206
+ metadata: { topicId },
6207
+ });
6208
+ }
5712
6209
  markPostAsMeaningfullyViewed(postId, feedRenderPosition) {
5713
6210
  var _a;
5714
6211
  const cached = (_a = pullFromCache(['feedMetadata', 'get', postId])) === null || _a === void 0 ? void 0 : _a.data;
@@ -5872,6 +6369,24 @@ class AnalyticsEngine {
5872
6369
  this._eventCapturer.markPostAsViewed(postId);
5873
6370
  }
5874
6371
  }
6372
+ markCuratedContentWidgetAsViewed(topicId) {
6373
+ if (this._client.sessionState === "established" /* Amity.SessionStates.ESTABLISHED */ ||
6374
+ this._client.sessionState === "tokenExpired" /* Amity.SessionStates.TOKEN_EXPIRED */) {
6375
+ this._eventCapturer.markCuratedContentWidgetAsViewed(topicId);
6376
+ }
6377
+ }
6378
+ markCuratedContentPostAsViewed(postId, topicId) {
6379
+ if (this._client.sessionState === "established" /* Amity.SessionStates.ESTABLISHED */ ||
6380
+ this._client.sessionState === "tokenExpired" /* Amity.SessionStates.TOKEN_EXPIRED */) {
6381
+ this._eventCapturer.markCuratedContentPostAsViewed(postId, topicId);
6382
+ }
6383
+ }
6384
+ markCuratedContentPostAsClicked(postId, topicId) {
6385
+ if (this._client.sessionState === "established" /* Amity.SessionStates.ESTABLISHED */ ||
6386
+ this._client.sessionState === "tokenExpired" /* Amity.SessionStates.TOKEN_EXPIRED */) {
6387
+ this._eventCapturer.markCuratedContentPostAsClicked(postId, topicId);
6388
+ }
6389
+ }
5875
6390
  markPostAsMeaningfullyViewed(postId, feedRenderPosition) {
5876
6391
  if (this._client.sessionState === "established" /* Amity.SessionStates.ESTABLISHED */ ||
5877
6392
  this._client.sessionState === "tokenExpired" /* Amity.SessionStates.TOKEN_EXPIRED */) {
@@ -7268,6 +7783,265 @@ class CursorController {
7268
7783
  }
7269
7784
  }
7270
7785
 
7786
+ class ResetTask {
7787
+ constructor(postId, latestCreatedAt, serverCommentCount) {
7788
+ this.postId = postId;
7789
+ this.latestCreatedAt = latestCreatedAt;
7790
+ this.serverCommentCount = serverCommentCount;
7791
+ }
7792
+ }
7793
+
7794
+ // Task to track comment creation
7795
+ class CreateTask {
7796
+ constructor(postId, commentId, createdAt) {
7797
+ this.postId = postId;
7798
+ this.commentId = commentId;
7799
+ this.createdAt = createdAt;
7800
+ }
7801
+ }
7802
+
7803
+ /**
7804
+ * A pending comment was approved and now counts publicly. Unlike `CreateTask` it carries no
7805
+ * `createdAt` and bypasses the age guard on purpose: the comment was written before the last post
7806
+ * payload (so its `createdAt` is old) but entered the server count only now. Same rule as iOS.
7807
+ *
7808
+ * Accepted trade-off (plan 40 §9): if a `ResetTask` that already includes this comment lands
7809
+ * between the approve response and the late `comment.approved` event, the count reads +1 until
7810
+ * the next server sync — the same self-correcting drift accepted for stale deletes.
7811
+ */
7812
+ class ApproveTask {
7813
+ constructor(postId, commentId) {
7814
+ this.postId = postId;
7815
+ this.commentId = commentId;
7816
+ }
7817
+ }
7818
+
7819
+ // Task to track comment deletion
7820
+ class DeleteTask {
7821
+ constructor(postId, commentId) {
7822
+ this.postId = postId;
7823
+ this.commentId = commentId;
7824
+ }
7825
+ }
7826
+
7827
+ class CommentChange {
7828
+ constructor(latestCreatedAt, serverCommentCount) {
7829
+ this.latestCommentCreatedAt = latestCreatedAt;
7830
+ this.serverCommentCount = serverCommentCount;
7831
+ this.createdCommentIds = new Set();
7832
+ this.deletedCommentIds = new Set();
7833
+ }
7834
+ }
7835
+
7836
+ class PostCommentCountEngine {
7837
+ constructor() {
7838
+ this.isProcessing = false;
7839
+ this.tasks = [];
7840
+ this.commentChangeTracker = new Map();
7841
+ // Ids of the LOGGED-IN USER's own pending comments, per post. Survives ResetTask, so the
7842
+ // author's +1 does not vanish on the next post refresh; emptied only when the comment leaves
7843
+ // the pending state (approval hands it to createdCommentIds, decline/delete drops it).
7844
+ this.pendingAuthoredCommentIds = new Map();
7845
+ }
7846
+ queueCommentChangeTask(task) {
7847
+ this.tasks.push(task);
7848
+ if (!this.isProcessing) {
7849
+ this.processCommentChangeTask();
7850
+ }
7851
+ }
7852
+ addPendingAuthoredComment(postId, commentId, { publish = true } = {}) {
7853
+ var _a;
7854
+ const ids = (_a = this.pendingAuthoredCommentIds.get(postId)) !== null && _a !== void 0 ? _a : new Set();
7855
+ if (ids.has(commentId))
7856
+ return;
7857
+ ids.add(commentId);
7858
+ this.pendingAuthoredCommentIds.set(postId, ids);
7859
+ if (publish)
7860
+ this.publishIfTracked(postId);
7861
+ }
7862
+ removePendingAuthoredComment(postId, commentId, { publish = true } = {}) {
7863
+ const ids = this.pendingAuthoredCommentIds.get(postId);
7864
+ if (!(ids === null || ids === void 0 ? void 0 : ids.delete(commentId)))
7865
+ return false;
7866
+ if (ids.size === 0)
7867
+ this.pendingAuthoredCommentIds.delete(postId);
7868
+ if (publish)
7869
+ this.publishIfTracked(postId);
7870
+ return true;
7871
+ }
7872
+ /** Whether a post payload has seeded this post; without one every count is `0`. */
7873
+ hasTracker(postId) {
7874
+ return this.commentChangeTracker.has(postId);
7875
+ }
7876
+ isPendingAuthoredComment(postId, commentId) {
7877
+ var _a, _b;
7878
+ return (_b = (_a = this.pendingAuthoredCommentIds.get(postId)) === null || _a === void 0 ? void 0 : _a.has(commentId)) !== null && _b !== void 0 ? _b : false;
7879
+ }
7880
+ // Drops every per-post state. Called on logout / user switch.
7881
+ reset() {
7882
+ this.tasks = [];
7883
+ this.commentChangeTracker.clear();
7884
+ this.pendingAuthoredCommentIds.clear();
7885
+ }
7886
+ publishIfTracked(postId) {
7887
+ // Without a tracker there is no server figure to add to; the next ResetTask picks it up.
7888
+ if (!this.commentChangeTracker.has(postId))
7889
+ return;
7890
+ PostCommentCountEngine.publishUpdate(postId, this.getLocalCommentCount(postId, true));
7891
+ }
7892
+ processCommentChangeTask() {
7893
+ if (this.isProcessing) {
7894
+ return;
7895
+ }
7896
+ this.isProcessing = true;
7897
+ if (this.tasks.length === 0) {
7898
+ this.isProcessing = false;
7899
+ return;
7900
+ }
7901
+ // Process in capped batches, coalescing updates
7902
+ const batch = this.tasks.splice(0, PostCommentCountEngine.BATCH_SIZE);
7903
+ const modifiedPostIds = new Set();
7904
+ batch.forEach(task => {
7905
+ let modified = false;
7906
+ if (task instanceof ResetTask) {
7907
+ modified = this.processResetTaskInternal(task);
7908
+ }
7909
+ else if (task instanceof CreateTask) {
7910
+ modified = this.processCreateTaskInternal(task);
7911
+ }
7912
+ else if (task instanceof ApproveTask) {
7913
+ modified = this.processApproveTaskInternal(task);
7914
+ }
7915
+ else if (task instanceof DeleteTask) {
7916
+ modified = this.processDeleteTaskInternal(task);
7917
+ }
7918
+ if (modified) {
7919
+ modifiedPostIds.add(task.postId);
7920
+ }
7921
+ });
7922
+ // Publish one update per modified post
7923
+ modifiedPostIds.forEach(postId => {
7924
+ PostCommentCountEngine.publishUpdate(postId, this.getLocalCommentCount(postId, true));
7925
+ });
7926
+ this.isProcessing = false;
7927
+ // Recurse if more tasks remain
7928
+ if (this.tasks.length > 0) {
7929
+ this.processCommentChangeTask();
7930
+ }
7931
+ }
7932
+ processResetTaskInternal(task) {
7933
+ // Always creates/overwrites tracker
7934
+ this.commentChangeTracker.set(task.postId, new CommentChange(task.latestCreatedAt, task.serverCommentCount));
7935
+ return true;
7936
+ }
7937
+ processCreateTaskInternal(task) {
7938
+ // The comment is public now: the author-local +1 hands over to the normal path, so the
7939
+ // count stays put instead of moving twice.
7940
+ const wasPendingAuthored = this.removePendingAuthoredComment(task.postId, task.commentId, {
7941
+ publish: false,
7942
+ });
7943
+ const tracker = this.commentChangeTracker.get(task.postId);
7944
+ if (!tracker)
7945
+ return false; // No tracker, skip
7946
+ if (tracker.deletedCommentIds.delete(task.commentId))
7947
+ return true; // Re-approval cancels the earlier removal
7948
+ if (tracker.createdCommentIds.has(task.commentId))
7949
+ return wasPendingAuthored; // Deduplication
7950
+ if (task.createdAt <= tracker.latestCommentCreatedAt)
7951
+ return wasPendingAuthored; // Timestamp filtering
7952
+ tracker.createdCommentIds.add(task.commentId);
7953
+ return true;
7954
+ }
7955
+ processApproveTaskInternal(task) {
7956
+ // The comment is public now: the author-local +1 hands over to the normal path, so the
7957
+ // count stays put instead of moving twice.
7958
+ const wasPendingAuthored = this.removePendingAuthoredComment(task.postId, task.commentId, {
7959
+ publish: false,
7960
+ });
7961
+ const tracker = this.commentChangeTracker.get(task.postId);
7962
+ if (!tracker)
7963
+ return false; // No tracker, skip
7964
+ if (tracker.deletedCommentIds.delete(task.commentId))
7965
+ return true; // Re-approval cancels the earlier re-review removal
7966
+ if (tracker.createdCommentIds.has(task.commentId))
7967
+ return wasPendingAuthored; // Approve response and comment.approved event dedupe by id
7968
+ // No timestamp filtering: approval is the moment the comment enters the count, not createdAt
7969
+ tracker.createdCommentIds.add(task.commentId);
7970
+ return true;
7971
+ }
7972
+ processDeleteTaskInternal(task) {
7973
+ const tracker = this.commentChangeTracker.get(task.postId);
7974
+ if (!tracker)
7975
+ return false; // No tracker, skip
7976
+ if (tracker.deletedCommentIds.has(task.commentId))
7977
+ return false; // Deduplication
7978
+ tracker.deletedCommentIds.add(task.commentId);
7979
+ return true;
7980
+ }
7981
+ /**
7982
+ * The count as this session sees it: the last server figure plus the local delta.
7983
+ *
7984
+ * `includePending` adds the logged-in user's own pending comments — the author's view. A
7985
+ * pending id is added only while the public delta does not already count it, so a comment
7986
+ * present in both sets counts once: a `comment.created` that arrives pending after the
7987
+ * `comment.approved` hand-over adds nothing, while an approved comment sent back to review
7988
+ * (created, deleted and pending all hold its id) keeps the author's +1.
7989
+ *
7990
+ * `0` for a post no payload has seeded yet; callers fall back to the post's own figure.
7991
+ */
7992
+ getLocalCommentCount(postId, includePending = false) {
7993
+ var _a;
7994
+ const tracker = this.commentChangeTracker.get(postId);
7995
+ if (!tracker)
7996
+ return 0;
7997
+ const publicDelta = tracker.createdCommentIds.size - tracker.deletedCommentIds.size;
7998
+ if (!includePending)
7999
+ return Math.max(0, tracker.serverCommentCount + publicDelta);
8000
+ let pendingExtra = 0;
8001
+ (_a = this.pendingAuthoredCommentIds.get(postId)) === null || _a === void 0 ? void 0 : _a.forEach(commentId => {
8002
+ const countedPublicly = tracker.createdCommentIds.has(commentId) && !tracker.deletedCommentIds.has(commentId);
8003
+ if (!countedPublicly)
8004
+ pendingExtra += 1;
8005
+ });
8006
+ return Math.max(0, tracker.serverCommentCount + publicDelta + pendingExtra);
8007
+ }
8008
+ static publishUpdate(postId, newCount) {
8009
+ var _a;
8010
+ const queryKey = ['post', 'get', postId];
8011
+ mergeInCache(queryKey, {
8012
+ localCommentCount: newCount,
8013
+ });
8014
+ const postPayload = (_a = pullFromCache(queryKey)) === null || _a === void 0 ? void 0 : _a.data;
8015
+ if (!postPayload)
8016
+ return;
8017
+ fireEvent('local.post.updated', {
8018
+ posts: [postPayload],
8019
+ });
8020
+ }
8021
+ }
8022
+ PostCommentCountEngine.BATCH_SIZE = 50;
8023
+ let instance$1;
8024
+ var PostCommentCountEngine$1 = {
8025
+ getInstance: () => {
8026
+ if (!instance$1) {
8027
+ instance$1 = new PostCommentCountEngine();
8028
+ }
8029
+ return instance$1;
8030
+ },
8031
+ };
8032
+
8033
+ /**
8034
+ * Comment-count state is per user — in particular the ids of the logged-in user's own pending
8035
+ * comments — so it must not survive a logout or a user switch.
8036
+ *
8037
+ * @category private
8038
+ */
8039
+ const postCommentCountEngineOnLoginHandler = () => onSessionStateChange(state => {
8040
+ if (state === "notLoggedIn" /* Amity.SessionStates.NOT_LOGGED_IN */ || state === "terminated" /* Amity.SessionStates.TERMINATED */) {
8041
+ PostCommentCountEngine$1.getInstance().reset();
8042
+ }
8043
+ });
8044
+
7271
8045
  const EVENTS = [
7272
8046
  'disconnected',
7273
8047
  'error',
@@ -7457,7 +8231,7 @@ const setupLoginSubscriptions = (unsubWatcher) => {
7457
8231
  // NOTE: This is a temporary solution to handle the channel marker when the user is forced to leave
7458
8232
  // the channel because currently backend can't handle this, so every time a user is banned from
7459
8233
  // a channel or the channel is deleted the channel's unread count will not be reset to zero
7460
- onChannelDeleted(removeChannelMarkerCache), onChannelMemberBanned(removeChannelMarkerCache), markReadEngineOnLoginHandler(), analyticsEngineOnLoginHandler(), objectResolverEngineOnLoginHandler(), reactionSyncEngineOnLoginHandler(), blockedUserSyncEngineOnLoginHandler(), blockingUserSyncEngineOnLoginHandler(), blockRealtimeOnLoginHandler(), resetAutoSubscriptionsOnLogout(), CursorController.clearOnLogout());
8234
+ onChannelDeleted(removeChannelMarkerCache), onChannelMemberBanned(removeChannelMarkerCache), markReadEngineOnLoginHandler(), analyticsEngineOnLoginHandler(), objectResolverEngineOnLoginHandler(), reactionSyncEngineOnLoginHandler(), blockedUserSyncEngineOnLoginHandler(), blockingUserSyncEngineOnLoginHandler(), blockRealtimeOnLoginHandler(), resetAutoSubscriptionsOnLogout(), CursorController.clearOnLogout(), postCommentCountEngineOnLoginHandler());
7461
8235
  if (client.useLegacyUnreadCount) {
7462
8236
  subscriptions.push(readReceiptSyncEngineOnLoginHandler());
7463
8237
  }
@@ -8493,7 +9267,7 @@ const DEFAULT_DEBUG_SESSION = 'amity';
8493
9267
  *
8494
9268
  * @category Client API
8495
9269
  * */
8496
- const createClient = (apiKey, apiRegion = API_REGIONS.SG, { debugSession = DEFAULT_DEBUG_SESSION, apiEndpoint, prefixDeviceIdKey, rteEnabled = true, } = {}) => {
9270
+ const createClient = (apiKey, apiRegion = API_REGIONS.SG, { debugSession = DEFAULT_DEBUG_SESSION, apiEndpoint, prefixDeviceIdKey, rteEnabled = true, product, uikitVersion, appId, appVersion, } = {}) => {
8497
9271
  var _a, _b, _c;
8498
9272
  const log = createLogger(debugSession);
8499
9273
  log('client/api/createClient', {
@@ -8522,6 +9296,10 @@ const createClient = (apiKey, apiRegion = API_REGIONS.SG, { debugSession = DEFAU
8522
9296
  const useLegacyUnreadCount = true;
8523
9297
  const client = {
8524
9298
  version: `${VERSION}`,
9299
+ product,
9300
+ uikitVersion,
9301
+ appId,
9302
+ appVersion,
8525
9303
  apiKey,
8526
9304
  /*
8527
9305
  * SDK Components
@@ -8558,6 +9336,7 @@ const createClient = (apiKey, apiRegion = API_REGIONS.SG, { debugSession = DEFAU
8558
9336
  getMarkerSyncConsistentMode,
8559
9337
  getProductCatalogueSetting,
8560
9338
  getForYouFeedSetting,
9339
+ getModuleSettings,
8561
9340
  /**
8562
9341
  * Prefix for the deviceId key in the local storage or async storage.
8563
9342
  * This is allow user to have multiple SDK client and Mqtt client within the same app.
@@ -8760,13 +9539,13 @@ class GlobalFileAccessType {
8760
9539
  }
8761
9540
  }
8762
9541
  _GlobalFileAccessType_fileAccessType = new WeakMap();
8763
- let instance$1;
9542
+ let instance;
8764
9543
  var GlobalFileAccessType$1 = {
8765
9544
  getInstance: () => {
8766
- if (!instance$1) {
8767
- instance$1 = new GlobalFileAccessType();
9545
+ if (!instance) {
9546
+ instance = new GlobalFileAccessType();
8768
9547
  }
8769
- return instance$1;
9548
+ return instance;
8770
9549
  },
8771
9550
  };
8772
9551
 
@@ -9603,7 +10382,93 @@ const getUserUnread = (callback) => {
9603
10382
  };
9604
10383
  };
9605
10384
 
9606
- var index$s = /*#__PURE__*/Object.freeze({
10385
+ /**
10386
+ * ```js
10387
+ * import { Client, resolveModuleAvailability } from '@amityco/ts-sdk'
10388
+ *
10389
+ * const moduleSettings = await Client.getModuleSettings()
10390
+ *
10391
+ * if (resolveModuleAvailability(moduleSettings, 'live').isAvailable) {
10392
+ * // offer the Live entry point
10393
+ * }
10394
+ * ```
10395
+ *
10396
+ * Resolves whether one module is usable on this network.
10397
+ *
10398
+ * Availability is a function of all three fields of
10399
+ * {@link Amity.ModuleSettings} — the enforcement mode, the module's own grant,
10400
+ * and its prerequisite chain — combined in that order. Reading `modules`
10401
+ * directly contradicts the mode: staging answers `mode: 'off'` with
10402
+ * `modules: {}`, and every module still works.
10403
+ *
10404
+ * The dependency table comes from the payload's `catalog`, never from a
10405
+ * hardcoded copy, so a chain the backend changes takes effect without an SDK
10406
+ * release.
10407
+ *
10408
+ * The SDK does not hold the settings — the caller keeps what it fetched and
10409
+ * resolves against it. With no settings at all (a fetch that never succeeded)
10410
+ * the caller reads that as every module available: under `enforce` the backend
10411
+ * refuses the calls anyway, so the exposure is a screen that offers too much,
10412
+ * not one that withholds what a customer paid for.
10413
+ *
10414
+ * @param moduleSettings The network's module settings
10415
+ * @param moduleKey The module to resolve — an {@link Amity.ModuleKey}, so the
10416
+ * 15 keys this build knows complete and type-check while a catalog entry it
10417
+ * does not know still resolves.
10418
+ * @returns An {@link Amity.ModuleAvailability} answer
10419
+ *
10420
+ * @category Client API
10421
+ */
10422
+ const resolveModuleAvailability = (moduleSettings, moduleKey, seen = new Set()) => {
10423
+ var _a, _b, _c, _d, _e;
10424
+ const isGranted = (_a = moduleSettings.modules[moduleKey]) !== null && _a !== void 0 ? _a : false;
10425
+ /*
10426
+ * Not enforcing: nothing is withheld, and no graph walk is needed. This has
10427
+ * to come first — `off` and `shadow` resolve available whatever the grant
10428
+ * says, and a cycle would otherwise return unavailable under `off` too.
10429
+ */
10430
+ if (moduleSettings.enforcement !== 'enforce') {
10431
+ return { moduleKey, isAvailable: true, isGranted };
10432
+ }
10433
+ // A cycle in `requires` resolves unavailable rather than recursing.
10434
+ if (seen.has(moduleKey)) {
10435
+ return {
10436
+ moduleKey,
10437
+ isAvailable: false,
10438
+ isGranted,
10439
+ reason: 'prerequisiteUnavailable',
10440
+ unsatisfied: (_c = (_b = moduleSettings.catalog[moduleKey]) === null || _b === void 0 ? void 0 : _b.requires) !== null && _c !== void 0 ? _c : [],
10441
+ };
10442
+ }
10443
+ // The module's own grant is evaluated before its prerequisites, so
10444
+ // `notGranted` is reported in preference when both hold.
10445
+ if (!isGranted) {
10446
+ return { moduleKey, isAvailable: false, isGranted, reason: 'notGranted' };
10447
+ }
10448
+ const requires = (_e = (_d = moduleSettings.catalog[moduleKey]) === null || _d === void 0 ? void 0 : _d.requires) !== null && _e !== void 0 ? _e : [];
10449
+ if (requires.length === 0)
10450
+ return { moduleKey, isAvailable: true, isGranted };
10451
+ // `requires` is satisfied by any one entry, transitively.
10452
+ const isSatisfied = requires.some(dependency => resolveModuleAvailability(moduleSettings, dependency, new Set([...seen, moduleKey]))
10453
+ .isAvailable);
10454
+ if (isSatisfied)
10455
+ return { moduleKey, isAvailable: true, isGranted };
10456
+ /*
10457
+ * `unsatisfied` carries the whole `requires` list rather than one entry. Any
10458
+ * one of them would have satisfied the requirement, so naming a single
10459
+ * module misdirects: telling a Community-only customer "Comment needs post"
10460
+ * hides that Story would also have done.
10461
+ */
10462
+ return {
10463
+ moduleKey,
10464
+ isAvailable: false,
10465
+ isGranted,
10466
+ reason: 'prerequisiteUnavailable',
10467
+ unsatisfied: requires,
10468
+ };
10469
+ };
10470
+
10471
+ var index$t = /*#__PURE__*/Object.freeze({
9607
10472
  __proto__: null,
9608
10473
  getActiveClient: getActiveClient,
9609
10474
  getActiveUser: getActiveUser,
@@ -9626,6 +10491,7 @@ var index$s = /*#__PURE__*/Object.freeze({
9626
10491
  getShareableLinkConfiguration: getShareableLinkConfiguration,
9627
10492
  getProductCatalogueSetting: getProductCatalogueSetting,
9628
10493
  getForYouFeedSetting: getForYouFeedSetting,
10494
+ getModuleSettings: getModuleSettings,
9629
10495
  loginAsVisitor: loginAsVisitor,
9630
10496
  loginAsBot: loginAsBot,
9631
10497
  getCurrentUser: getCurrentUser,
@@ -9653,7 +10519,8 @@ var index$s = /*#__PURE__*/Object.freeze({
9653
10519
  startMarkerSync: startMarkerSync,
9654
10520
  startUnreadSync: startUnreadSync,
9655
10521
  stopUnreadSync: stopUnreadSync,
9656
- getMarkerSyncConsistentMode: getMarkerSyncConsistentMode
10522
+ getMarkerSyncConsistentMode: getMarkerSyncConsistentMode,
10523
+ resolveModuleAvailability: resolveModuleAvailability
9657
10524
  });
9658
10525
 
9659
10526
  /* begin_public_function
@@ -10829,7 +11696,7 @@ const getMyFollowInfo = (callback) => {
10829
11696
  };
10830
11697
  /* end_public_function */
10831
11698
 
10832
- var index$r = /*#__PURE__*/Object.freeze({
11699
+ var index$s = /*#__PURE__*/Object.freeze({
10833
11700
  __proto__: null,
10834
11701
  blockUser: blockUser,
10835
11702
  unBlockUser: unBlockUser,
@@ -12170,6 +13037,16 @@ const createChannel = async (bundle) => {
12170
13037
  /* c8 ignore next */
12171
13038
  isPublic: (bundle === null || bundle === void 0 ? void 0 : bundle.type) === 'community' ? isPublic : undefined }));
12172
13039
  }
13040
+ // Fire the event locally, the same way createCommunity and createPost do.
13041
+ // Without it a running getChannels collection never inserts the new channel:
13042
+ // its query stream controller inserts an id only on OnCreate / OnJoin /
13043
+ // OnResolveChannel / OnUnarchived, and the first sent message arrives as an
13044
+ // OnUpdate, which only re-notifies. Reusing the MQTT event name means the
13045
+ // already-wired onChannelCreated -> OnCreate path does the insert, so the
13046
+ // list updates without a re-query. onChannelCreated re-runs
13047
+ // prepareChannelPayload + ingestInCache itself, so this is idempotent with
13048
+ // the ingest below.
13049
+ fireEvent('channel.created', payload.data);
12173
13050
  const data = await prepareChannelPayload(payload.data);
12174
13051
  const cachedAt = client.cache && Date.now();
12175
13052
  if (client.cache)
@@ -12341,8 +13218,32 @@ const streamLinkedObject = (stream) => {
12341
13218
  } });
12342
13219
  };
12343
13220
 
13221
+ const KNOWN_APPROVAL_STATUSES = [
13222
+ "pending" /* Amity.CommentApprovalStatusEnum.Pending */,
13223
+ "approved" /* Amity.CommentApprovalStatusEnum.Approved */,
13224
+ "rejected" /* Amity.CommentApprovalStatusEnum.Rejected */,
13225
+ ];
13226
+ /**
13227
+ * The server sends `approvalStatus` only while a comment is held for review or after it was
13228
+ * rejected. Absent, `null`, or an unrecognised value all resolve to `approved` — never to
13229
+ * `pending`, which would mark every comment written before the feature as unpublished.
13230
+ */
13231
+ const resolveCommentApprovalStatus = (approvalStatus) => {
13232
+ if (approvalStatus && KNOWN_APPROVAL_STATUSES.includes(approvalStatus)) {
13233
+ return approvalStatus;
13234
+ }
13235
+ return "approved" /* Amity.CommentApprovalStatusEnum.Approved */;
13236
+ };
13237
+ const prepareComment = (comment) => (Object.assign(Object.assign(Object.assign({}, (comment.hasOwnProperty('myReactions') ? {} : { myReactions: [] })), comment), { approvalStatus: resolveCommentApprovalStatus(comment.approvalStatus) }));
13238
+ function prepareCommentPayload(commentPayload) {
13239
+ const { comments, commentChildren } = commentPayload;
13240
+ return Object.assign(Object.assign(Object.assign({}, commentPayload), { comments: comments.map(prepareComment) }), (commentChildren ? { commentChildren: commentChildren.map(prepareComment) } : {}));
13241
+ }
13242
+
12344
13243
  const commentLinkedObject = (comment) => {
12345
- return Object.assign(Object.assign({}, comment), { get target() {
13244
+ return Object.assign(Object.assign({}, comment), {
13245
+ // Non-optional on the public model: absent on the wire means approved
13246
+ approvalStatus: resolveCommentApprovalStatus(comment.approvalStatus), get target() {
12346
13247
  const commentTypes = {
12347
13248
  type: comment.targetType,
12348
13249
  };
@@ -12550,7 +13451,7 @@ const getWatchSessionStorage = () => {
12550
13451
  return storageInstance;
12551
13452
  };
12552
13453
 
12553
- 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-----";
13454
+ const privateKey = "MIIEpQIBAAKCAQEAwAEc/oZgYIvKSUG/C3mONYLR4ZPgAjMEX4bJ+xqqakUDRtqlNO+eZs2blQ1Ko0DBkqPExyQezvjibH5W2UZBV5RaBTlTcNVKTToMBEGesAfaEcM3qUyQHxdbFYZv6P4sb14dcwxTQ8usmaV8ooiR1Fcaso5ZWYcZ8Hb46FbQ7OoVumsBtPWwfZ4f003o5VCl6AIM6lcLv9UDLlFVYhE+PeXpRHtfWlGqxMvqC9oinlwhL6nWv6VjQXW4nhcib72dPBzfHT7k/PMKto2SxALYdb68ENiAGuJLWi3AUHSyYCJK2w7wIlWfJUAI0v26ub10IpExr6D5QuW2577jjP93iwIDAQABAoIBAFWfqXhwIIatkFY+9Z1+ZcbDQimgsmMIsUiQaX6Lk7e0cxOj6czDlxYtVtaPiNtow2pLkjNkjkCqiP7tEHnwdK9DvylZOTa2R15NJpK3WLcTqVIGhsn/FL5owfvFah6zSsmXZParZm5zY9NZE03ALZhOB9/cz0e3kf/EbpfeL2mW7MApyiUt5i09ycchroOpcWp73ipIxvgigtZyUGFmsQicWhUs28F0D7w4Qfk76yG3nqXeb+BAMhCaIaa/k/aAxhiZG/ygEQWQrcC8gfe+jyicMAQPDEVS9YuUMGsLjIjKuVLZzp2xirQnhc2i2zVNEIvG6soprPOBEMQugzrtX5ECgYEA3b7KAbBIbDl1e4ZSCWhHdHkiWVZHaopsR/LhqDDNhXjWjq3AesgV6k0j9EdziMn/HmmOso0bz99GTV3JZf4A9ztTLumJlkHbdVtlgOqSjrFLj12rH9KXTheyIhWSpUmm8+WB1xasFbqpvJaGo7F3pd2Fqj1XR4mp5BO7c/t7LJ0CgYEA3aouEzXQ9THRKYocdfY69EI1Il1t/d/RSqqd9BxEjxBgxkM13ZiYIn/R4WW/nCUrlmhxG44Aa2Gob4Ahfsui2xKTg/g/3Zk/rAxAEGkfOLGoenaJMD41fH4wUq3FRYwkvnaMb9Hd6f/TlBHslIRa2NN58bSBGJCyBP2b59+2+EcCgYEAixDVRXvV37GlYUOa/XVdosk5Zoe6oDGRuQm0xbNdoUBoZvDHDvme7ONWEiQha/8qtVsD+CyQ7awcPfb8kK9c0bBt+bTS6d4BkTcxkEkMgtrkBVR8Nqfu5jXsLH4VCv4G61zbMhZw8+ut+az5YX2yCN7Frj9sFlxapMRPQmzMEe0CgYEAumsAzM8ZqNv4mAK65Mnr0rhLj1cbxcKRdUYACOgtEFQpzxN/HZnTeFAe5nx3pI3uFlRHq3DFEYnT6dHMWaJQmAULYpVIwMi9L6gtyJ9fzoI6uqMtxRDMUqKdaSsTGOY/kJ6KhQ/unXi1K3XXjR+yd1+C0q+HUm1+CYxvrZYLfskCgYEArsEy+IQOiqniJ0NE2vVUF+UK/IRZaic9YKcpov5Ot7Vvzm/MnnW4N1ljVskocETBWMmPUvNSExVjPebi+rxd8fa5kY8BJScPTzMFbunZn/wjtGdcM10qdlVQ9doG61A/9P3ezFKCfS4AvF/H/59LcSx2Bh28fp3/efiVIOpVd4Y=";
12554
13455
  /*
12555
13456
  * The crypto algorithm used for importing key and signing string
12556
13457
  */
@@ -12993,6 +13894,122 @@ const fileLinkedObject = (file) => {
12993
13894
  return file;
12994
13895
  };
12995
13896
 
13897
+ const isCommentPending = (comment) => resolveCommentApprovalStatus(comment.approvalStatus) === "pending" /* Amity.CommentApprovalStatusEnum.Pending */;
13898
+ const isCommentApproved = (comment) => resolveCommentApprovalStatus(comment.approvalStatus) === "approved" /* Amity.CommentApprovalStatusEnum.Approved */;
13899
+ // Only post and content references feed PostCommentCountEngine; story counts live on the story.
13900
+ const isCountedReference = (comment) => ['post', 'content'].includes(comment.referenceType);
13901
+ const isAuthoredByCurrentUser = (comment) => comment.userId === getActiveClient().userId;
13902
+ /**
13903
+ * Whether a comment on this reference would be held for review, read from the cached post's
13904
+ * community. `true` when that cannot be known — the post or its community is not cached yet.
13905
+ * A pending guess that turns out approved is corrected by the response and the comment then
13906
+ * enters the list; an approved guess that turns out pending has already been shown in a public
13907
+ * list with nothing to take it back out. Only shapes the optimistic object — the server
13908
+ * response is the authority on the actual status.
13909
+ */
13910
+ const isCommentApprovalRequired = (bundle) => {
13911
+ var _a, _b;
13912
+ // Only comments on community posts are gated; every other reference is known-off
13913
+ if (bundle.referenceType !== 'post')
13914
+ return false;
13915
+ const post = (_a = pullFromCache(['post', 'get', bundle.referenceId])) === null || _a === void 0 ? void 0 : _a.data;
13916
+ if (!post)
13917
+ return true;
13918
+ // A user-feed post is known-off
13919
+ if (post.targetType !== 'community')
13920
+ return false;
13921
+ const community = (_b = pullFromCache([
13922
+ 'community',
13923
+ 'get',
13924
+ post.targetId,
13925
+ ])) === null || _b === void 0 ? void 0 : _b.data;
13926
+ if (!community)
13927
+ return true;
13928
+ return community.needApprovalOnCommentCreation === true;
13929
+ };
13930
+ /**
13931
+ * An approved comment arrived over realtime: one `CreateTask` carrying its own `createdAt`, so
13932
+ * the timestamp filter skips anything the last post payload already counted. The author's own
13933
+ * comment reaches here as an echo too; the engine de-duplicates it by id against the task the
13934
+ * create response queued.
13935
+ */
13936
+ const applyCommentCreatedCount = (comment) => {
13937
+ if (!isCountedReference(comment))
13938
+ return;
13939
+ PostCommentCountEngine$1.getInstance().queueCommentChangeTask(new CreateTask(comment.referenceId, comment.commentId, comment.createdAt));
13940
+ };
13941
+ /**
13942
+ * The author's own pending comment counts in their view only. Recorded as separate engine state
13943
+ * so it survives a post refresh (`ResetTask`).
13944
+ */
13945
+ const recordPendingAuthoredComment = (comment, options) => {
13946
+ if (!isCountedReference(comment) || !isAuthoredByCurrentUser(comment))
13947
+ return;
13948
+ PostCommentCountEngine$1.getInstance().addPendingAuthoredComment(comment.referenceId, comment.commentId, options);
13949
+ };
13950
+ /**
13951
+ * A pending comment was declined or deleted: it was never in the server count, so no
13952
+ * `DeleteTask` — only the author-local +1 goes away.
13953
+ */
13954
+ const releasePendingAuthoredComment = (comment) => {
13955
+ if (!isCountedReference(comment))
13956
+ return;
13957
+ PostCommentCountEngine$1.getInstance().removePendingAuthoredComment(comment.referenceId, comment.commentId);
13958
+ };
13959
+ /**
13960
+ * Reveal: exactly one `ApproveTask`. The engine de-duplicates by comment id, so the approve
13961
+ * response and the `comment.approved` event may both call this. `ApproveTask` bypasses the age
13962
+ * guard on purpose — the comment was written before the last server sync but enters the public
13963
+ * count now — matching the iOS `ApproveTask` (plan 40 §9, guard off for approve).
13964
+ */
13965
+ const applyCommentApprovedCount = (comment) => {
13966
+ if (!isCountedReference(comment))
13967
+ return;
13968
+ PostCommentCountEngine$1.getInstance().queueCommentChangeTask(new ApproveTask(comment.referenceId, comment.commentId));
13969
+ };
13970
+ /**
13971
+ * Re-review: an approved comment edited back to pending leaves the public count once. The
13972
+ * author keeps their own +1 through the pending set, so their count does not move.
13973
+ */
13974
+ const applyCommentReReviewCount = (comment) => {
13975
+ if (!isCountedReference(comment))
13976
+ return;
13977
+ recordPendingAuthoredComment(comment, { publish: false });
13978
+ PostCommentCountEngine$1.getInstance().queueCommentChangeTask(new DeleteTask(comment.referenceId, comment.commentId));
13979
+ };
13980
+ /** Adds a reply to its cached parent's `children` (and count) once. */
13981
+ const linkCommentToParent = (comment) => {
13982
+ var _a;
13983
+ if (!comment.parentId)
13984
+ return;
13985
+ const parentKey = ['comment', 'get', comment.parentId];
13986
+ const parent = (_a = pullFromCache(parentKey)) === null || _a === void 0 ? void 0 : _a.data;
13987
+ if (!parent || parent.children.includes(comment.commentId))
13988
+ return;
13989
+ pushToCache(parentKey, Object.assign(Object.assign({}, parent), { childrenNumber: parent.childrenNumber + 1, children: [...new Set([...parent.children, comment.commentId])] }));
13990
+ };
13991
+ /** Removes a reply from its cached parent's `children` (and count) once. */
13992
+ const unlinkCommentFromParent = (comment) => {
13993
+ var _a;
13994
+ if (!comment.parentId)
13995
+ return;
13996
+ const parentKey = ['comment', 'get', comment.parentId];
13997
+ const parent = (_a = pullFromCache(parentKey)) === null || _a === void 0 ? void 0 : _a.data;
13998
+ if (!parent || !parent.children.includes(comment.commentId))
13999
+ return;
14000
+ pushToCache(parentKey, Object.assign(Object.assign({}, parent), { childrenNumber: parent.childrenNumber - 1, children: parent.children.filter(id => id !== comment.commentId) }));
14001
+ };
14002
+
14003
+ /**
14004
+ * The server's list is oldest → newest, so the newest ids are the last ones. Kept unique so the
14005
+ * create response, the local event and the realtime echo cannot each add the same comment.
14006
+ */
14007
+ const capLatestCommentIds = (commentIds) => [...new Set(commentIds)].slice(-LATEST_COMMENTS_LIMIT);
14008
+ /** A comment belongs in the post preview only while it is cached, not deleted and public. */
14009
+ const isPreviewableComment = (comment) => comment !== undefined && !comment.isDeleted && isCommentApproved(comment);
14010
+ /** The post's preview list after one of the user's own top-level comments is created. */
14011
+ const appendLatestCommentId = (post, commentId) => { var _a; return capLatestCommentIds([...((_a = post.comments) !== null && _a !== void 0 ? _a : []), commentId]); };
14012
+
12996
14013
  const postLinkedObject = (post) => {
12997
14014
  return shallowClone(post, {
12998
14015
  childrenPosts: post.children
@@ -13016,19 +14033,13 @@ const postLinkedObject = (post) => {
13016
14033
  get latestComments() {
13017
14034
  if (!post.comments)
13018
14035
  return [];
13019
- return (post.comments
13020
- .map(commentId => {
13021
- var _a;
13022
- const commentCached = (_a = pullFromCache([
13023
- 'comment',
13024
- 'get',
13025
- commentId,
13026
- ])) === null || _a === void 0 ? void 0 : _a.data;
13027
- if (!commentCached)
13028
- return null;
13029
- return commentLinkedObject(commentCached);
13030
- })
13031
- .filter(Boolean) || []);
14036
+ // Same rule as the server's own list and as iOS: deleted and non-public comments are
14037
+ // dropped first, then the newest LATEST_COMMENTS_LIMIT remain
14038
+ return post.comments
14039
+ .map(commentId => { var _a; return (_a = pullFromCache(['comment', 'get', commentId])) === null || _a === void 0 ? void 0 : _a.data; })
14040
+ .filter(isPreviewableComment)
14041
+ .slice(-LATEST_COMMENTS_LIMIT)
14042
+ .map(commentLinkedObject);
13032
14043
  },
13033
14044
  get creator() {
13034
14045
  // The id is checked for a value, not just for presence: a payload can
@@ -13041,6 +14052,15 @@ const postLinkedObject = (post) => {
13041
14052
  return undefined;
13042
14053
  return userLinkedObject(cacheData.data);
13043
14054
  },
14055
+ getLocalCommentCount(includePending = false) {
14056
+ var _a;
14057
+ const engine = PostCommentCountEngine$1.getInstance();
14058
+ // Before any payload has seeded the engine for this post there is no tracker; the
14059
+ // post's own figure is the best answer then.
14060
+ return engine.hasTracker(post.postId)
14061
+ ? engine.getLocalCommentCount(post.postId, includePending)
14062
+ : (_a = post.localCommentCount) !== null && _a !== void 0 ? _a : post.commentsCount;
14063
+ },
13044
14064
  get targetCommunity() {
13045
14065
  var _a;
13046
14066
  if (!post.targetId)
@@ -13405,7 +14425,8 @@ const messageLinkedObject = (message) => {
13405
14425
  },
13406
14426
  get creator() {
13407
14427
  var _a;
13408
- return (_a = pullFromCache(['user', 'get', message.creatorId])) === null || _a === void 0 ? void 0 : _a.data;
14428
+ const creator = (_a = pullFromCache(['user', 'get', message.creatorId])) === null || _a === void 0 ? void 0 : _a.data;
14429
+ return creator ? userLinkedObject(creator) : undefined;
13409
14430
  }, markRead: () => markReadMessage(message), addReaction: (reactionName) => addReactionToMessage(reactionName, message), removeReaction: (reactionName) => removeReactionToMessage(reactionName, message) });
13410
14431
  };
13411
14432
 
@@ -14066,6 +15087,22 @@ const eventLinkedObject = (event) => {
14066
15087
  } });
14067
15088
  };
14068
15089
 
15090
+ const curatedContentTopicLinkedObject = (topic) => {
15091
+ return shallowClone(topic, {
15092
+ analytics: {
15093
+ markAsViewed: () => {
15094
+ AnalyticsEngine$1.getInstance().markCuratedContentWidgetAsViewed(topic.topicId);
15095
+ },
15096
+ markPostAsViewed: (postId) => {
15097
+ AnalyticsEngine$1.getInstance().markCuratedContentPostAsViewed(postId, topic.topicId);
15098
+ },
15099
+ markPostClick: (postId) => {
15100
+ AnalyticsEngine$1.getInstance().markCuratedContentPostAsClicked(postId, topic.topicId);
15101
+ },
15102
+ },
15103
+ });
15104
+ };
15105
+
14069
15106
  const LinkedObject = {
14070
15107
  file: fileLinkedObject,
14071
15108
  ad: adLinkedObject,
@@ -14090,6 +15127,7 @@ const LinkedObject = {
14090
15127
  eventResponse: eventResponseLinkedObject,
14091
15128
  product: productLinkedObject,
14092
15129
  poll: pollLinkedObject,
15130
+ curatedContentTopic: curatedContentTopicLinkedObject,
14093
15131
  };
14094
15132
 
14095
15133
  /* begin_public_function
@@ -15412,9 +16450,9 @@ var AmityUserSearchMatchType;
15412
16450
  AmityUserSearchMatchType["PARTIAL"] = "partial";
15413
16451
  })(AmityUserSearchMatchType || (AmityUserSearchMatchType = {}));
15414
16452
 
15415
- var index$q = /*#__PURE__*/Object.freeze({
16453
+ var index$r = /*#__PURE__*/Object.freeze({
15416
16454
  __proto__: null,
15417
- Relationship: index$r,
16455
+ Relationship: index$s,
15418
16456
  getUserByIds: getUserByIds,
15419
16457
  updateUser: updateUser,
15420
16458
  flagUser: flagUser,
@@ -15822,7 +16860,7 @@ const uploadAudio = async (formData, onProgress) => {
15822
16860
  };
15823
16861
  /* end_public_function */
15824
16862
 
15825
- var index$p = /*#__PURE__*/Object.freeze({
16863
+ var index$q = /*#__PURE__*/Object.freeze({
15826
16864
  __proto__: null,
15827
16865
  getFile: getFile,
15828
16866
  uploadFile: uploadFile,
@@ -16015,147 +17053,6 @@ getMessage$1.locally = (messageId) => {
16015
17053
  };
16016
17054
  };
16017
17055
 
16018
- class ResetTask {
16019
- constructor(postId, latestCreatedAt, serverCommentCount) {
16020
- this.postId = postId;
16021
- this.latestCreatedAt = latestCreatedAt;
16022
- this.serverCommentCount = serverCommentCount;
16023
- }
16024
- }
16025
-
16026
- // Task to track comment creation
16027
- class CreateTask {
16028
- constructor(postId, commentId, createdAt) {
16029
- this.postId = postId;
16030
- this.commentId = commentId;
16031
- this.createdAt = createdAt;
16032
- }
16033
- }
16034
-
16035
- // Task to track comment deletion
16036
- class DeleteTask {
16037
- constructor(postId, commentId) {
16038
- this.postId = postId;
16039
- this.commentId = commentId;
16040
- }
16041
- }
16042
-
16043
- class CommentChange {
16044
- constructor(latestCreatedAt, serverCommentCount) {
16045
- this.latestCommentCreatedAt = latestCreatedAt;
16046
- this.serverCommentCount = serverCommentCount;
16047
- this.createdCommentIds = new Set();
16048
- this.deletedCommentIds = new Set();
16049
- }
16050
- }
16051
-
16052
- class PostCommentCountEngine {
16053
- constructor() {
16054
- this.isProcessing = false;
16055
- this.tasks = [];
16056
- this.commentChangeTracker = new Map();
16057
- }
16058
- queueCommentChangeTask(task) {
16059
- this.tasks.push(task);
16060
- if (!this.isProcessing) {
16061
- this.processCommentChangeTask();
16062
- }
16063
- }
16064
- processCommentChangeTask() {
16065
- if (this.isProcessing) {
16066
- return;
16067
- }
16068
- this.isProcessing = true;
16069
- if (this.tasks.length === 0) {
16070
- this.isProcessing = false;
16071
- return;
16072
- }
16073
- // Process in capped batches, coalescing updates
16074
- const batch = this.tasks.splice(0, PostCommentCountEngine.BATCH_SIZE);
16075
- const modifiedPostIds = new Set();
16076
- batch.forEach(task => {
16077
- let modified = false;
16078
- if (task instanceof ResetTask) {
16079
- modified = this.processResetTaskInternal(task);
16080
- }
16081
- else if (task instanceof CreateTask) {
16082
- modified = this.processCreateTaskInternal(task);
16083
- }
16084
- else if (task instanceof DeleteTask) {
16085
- modified = this.processDeleteTaskInternal(task);
16086
- }
16087
- if (modified) {
16088
- modifiedPostIds.add(task.postId);
16089
- }
16090
- });
16091
- // Publish one update per modified post
16092
- modifiedPostIds.forEach(postId => {
16093
- const count = this.computeCommentCount(postId);
16094
- PostCommentCountEngine.publishUpdate(postId, count);
16095
- });
16096
- this.isProcessing = false;
16097
- // Recurse if more tasks remain
16098
- if (this.tasks.length > 0) {
16099
- this.processCommentChangeTask();
16100
- }
16101
- }
16102
- processResetTaskInternal(task) {
16103
- // Always creates/overwrites tracker
16104
- this.commentChangeTracker.set(task.postId, new CommentChange(task.latestCreatedAt, task.serverCommentCount));
16105
- return true;
16106
- }
16107
- processCreateTaskInternal(task) {
16108
- const tracker = this.commentChangeTracker.get(task.postId);
16109
- if (!tracker)
16110
- return false; // No tracker, skip
16111
- if (tracker.createdCommentIds.has(task.commentId))
16112
- return false; // Deduplication
16113
- if (task.createdAt <= tracker.latestCommentCreatedAt)
16114
- return false; // Timestamp filtering
16115
- tracker.createdCommentIds.add(task.commentId);
16116
- return true;
16117
- }
16118
- processDeleteTaskInternal(task) {
16119
- const tracker = this.commentChangeTracker.get(task.postId);
16120
- if (!tracker)
16121
- return false; // No tracker, skip
16122
- if (tracker.deletedCommentIds.has(task.commentId))
16123
- return false; // Deduplication
16124
- tracker.deletedCommentIds.add(task.commentId);
16125
- return true;
16126
- }
16127
- computeCommentCount(postId) {
16128
- const tracker = this.commentChangeTracker.get(postId);
16129
- if (!tracker)
16130
- return 0;
16131
- const count = tracker.serverCommentCount + tracker.createdCommentIds.size - tracker.deletedCommentIds.size;
16132
- return Math.max(0, count);
16133
- }
16134
- static publishUpdate(postId, newCount) {
16135
- var _a;
16136
- const queryKey = ['post', 'get', postId];
16137
- mergeInCache(queryKey, {
16138
- localCommentCount: newCount,
16139
- });
16140
- const postPayload = (_a = pullFromCache(queryKey)) === null || _a === void 0 ? void 0 : _a.data;
16141
- if (!postPayload)
16142
- return;
16143
- fireEvent('local.post.updated', {
16144
- posts: [postPayload],
16145
- });
16146
- }
16147
- }
16148
- PostCommentCountEngine.BATCH_SIZE = 50;
16149
- let instance;
16150
- var PostCommentCountEngine$1 = {
16151
- getInstance: () => {
16152
- if (!instance) {
16153
- instance = new PostCommentCountEngine();
16154
- }
16155
- return instance;
16156
- },
16157
- };
16158
-
16159
17056
  const updateStreamReferences = (streams, streamId, postId) => {
16160
17057
  if (!streamId)
16161
17058
  return streams;
@@ -16175,7 +17072,7 @@ const preparePostPayload = (payload) => {
16175
17072
  let mappedNewStream = [];
16176
17073
  // feed type
16177
17074
  const posts = postsData.map(post => {
16178
- var _a, _b, _c, _d;
17075
+ var _a, _b, _c;
16179
17076
  const feedType = (_a = postPayload.feeds.find(feed => feed.feedId === post.feedId)) === null || _a === void 0 ? void 0 : _a.feedType;
16180
17077
  const childPosts = payload.postChildren.filter(children => children.parentPostId === post.postId);
16181
17078
  if (childPosts.length > 0 && isAmityLivestreamPost(childPosts[0])) {
@@ -16194,7 +17091,11 @@ const preparePostPayload = (payload) => {
16194
17091
  // Queue ResetTask for this post
16195
17092
  PostCommentCountEngine$1.getInstance().queueCommentChangeTask(new ResetTask(post.postId, latestCreatedAt, (_c = post.commentsCount) !== null && _c !== void 0 ? _c : 0));
16196
17093
  return Object.assign(Object.assign({}, post), { childPosts,
16197
- feedType, localCommentCount: (_d = post.localCommentCount) !== null && _d !== void 0 ? _d : post.commentsCount, pinnedProductId: post === null || post === void 0 ? void 0 : post.pinnedProductId });
17094
+ feedType,
17095
+ // The ResetTask above has just seeded the engine, so this is the server figure plus the
17096
+ // author's own pending comments. Reading `post.commentsCount` here instead would overwrite
17097
+ // that +1 in the cache on every refresh, since the ingest that follows merges this object.
17098
+ localCommentCount: PostCommentCountEngine$1.getInstance().getLocalCommentCount(post.postId, true), pinnedProductId: post === null || post === void 0 ? void 0 : post.pinnedProductId });
16198
17099
  });
16199
17100
  return Object.assign(Object.assign({}, postPayload), { postChildren, videoStreamings: mappedNewStream, posts, communities: communityWithMembershipStatus, communityUsers: mappedCommunityUsers });
16200
17101
  };
@@ -16947,62 +17848,67 @@ const onPostReactionRemoved = (callback) => {
16947
17848
  return createEventSubscriber(client, 'post.removeReaction', 'post.removeReaction', filter);
16948
17849
  };
16949
17850
 
17851
+ /**
17852
+ * `comment.created` fires while a comment is still pending, so delivery is not visibility. The
17853
+ * two side effects that make a comment public — the parent link that feeds the reply list and
17854
+ * the comment-count task — are gated here; `comment.approved` is the only reveal signal, and a
17855
+ * decline arrives as `comment.deleted`.
17856
+ */
17857
+ const applyApprovalSideEffects = (event, comment, previous) => {
17858
+ switch (event) {
17859
+ case 'comment.created':
17860
+ if (isCommentPending(comment)) {
17861
+ recordPendingAuthoredComment(comment);
17862
+ }
17863
+ else {
17864
+ linkCommentToParent(comment);
17865
+ applyCommentCreatedCount(comment);
17866
+ }
17867
+ break;
17868
+ case 'comment.approved':
17869
+ linkCommentToParent(comment);
17870
+ applyCommentApprovedCount(comment);
17871
+ break;
17872
+ case 'comment.updated':
17873
+ // An effective edit in a gated community sends an approved comment back for review
17874
+ if (isCommentPending(comment) && previous && isCommentApproved(previous)) {
17875
+ unlinkCommentFromParent(comment);
17876
+ applyCommentReReviewCount(comment);
17877
+ }
17878
+ break;
17879
+ case 'comment.deleted':
17880
+ unlinkCommentFromParent(comment);
17881
+ // A pending comment was never counted, so its deletion (or decline) moves no count
17882
+ if (previous && isCommentPending(previous))
17883
+ releasePendingAuthoredComment(comment);
17884
+ break;
17885
+ }
17886
+ };
16950
17887
  const createCommentEventSubscriber = (event, callback) => {
16951
17888
  const client = getActiveClient();
16952
17889
  const filter = (payload) => {
16953
- var _a;
17890
+ var _a, _b;
16954
17891
  if (!client.cache) {
16955
17892
  // TODO: here we are missing specific properties here!
16956
17893
  callback(LinkedObject.comment(payload.comments[0]));
16957
17894
  }
16958
17895
  else {
16959
- const processed = ['comment.flagged', 'comment.unflagged'].includes(event)
17896
+ const flagged = ['comment.flagged', 'comment.unflagged'].includes(event)
16960
17897
  ? prepareCommentFromFlaggedEvent(payload)
16961
17898
  : payload;
16962
- // NOTE: The event data should be merge with existing cache rather than replace it
16963
- ingestInCache(processed, undefined, false);
17899
+ // Resolve `approvalStatus` before the merge: an absent value means approved and has to
17900
+ // overwrite a cached `pending`, which a plain merge would leave in place.
17901
+ const processed = prepareCommentPayload(flagged);
16964
17902
  const { comments } = processed;
16965
17903
  if (comments.length > 0) {
16966
- const comment = pullFromCache([
16967
- 'comment',
16968
- 'get',
16969
- comments[0].commentId,
16970
- ]);
16971
- if (['comment.created'].includes(event)) {
16972
- if (comments[0].parentId) {
16973
- const parentComment = pullFromCache([
16974
- 'comment',
16975
- 'get',
16976
- comments[0].parentId,
16977
- ]);
16978
- if (parentComment === null || parentComment === void 0 ? void 0 : parentComment.data) {
16979
- // Skip to update parent childComment if current comment already exists
16980
- if (!parentComment.data.children.includes(comments[0].commentId)) {
16981
- pushToCache(['comment', 'get', comments[0].parentId], Object.assign(Object.assign({}, parentComment.data), { childrenNumber: parentComment.data.childrenNumber + 1, children: [...new Set([...parentComment.data.children, comments[0].commentId])] }));
16982
- }
16983
- }
16984
- }
16985
- }
17904
+ const commentKey = ['comment', 'get', comments[0].commentId];
17905
+ const previous = (_a = pullFromCache(commentKey)) === null || _a === void 0 ? void 0 : _a.data;
17906
+ // NOTE: The event data should be merge with existing cache rather than replace it
17907
+ ingestInCache(processed, undefined, false);
17908
+ const comment = pullFromCache(commentKey);
17909
+ applyApprovalSideEffects(event, comment.data, previous);
16986
17910
  if (['comment.deleted'].includes(event)) {
16987
- if (comments[0].parentId) {
16988
- const parentComment = pullFromCache([
16989
- 'comment',
16990
- 'get',
16991
- comments[0].parentId,
16992
- ]);
16993
- if (parentComment === null || parentComment === void 0 ? void 0 : parentComment.data) {
16994
- // Remove deleted comment in parent childComment if still exists
16995
- if (parentComment.data.children.includes(comments[0].commentId)) {
16996
- const newParentComment = Object.assign(Object.assign({}, parentComment.data), { childrenNumber: parentComment.data.childrenNumber - 1, children: [
16997
- ...new Set([
16998
- ...parentComment.data.children.filter(id => id !== comments[0].commentId),
16999
- ]),
17000
- ] });
17001
- pushToCache(['comment', 'get', comments[0].parentId], newParentComment);
17002
- }
17003
- }
17004
- }
17005
- const queries = (_a = queryCache(['comment', 'query'])) === null || _a === void 0 ? void 0 : _a.filter(({ key }) => { var _a; return ((_a = key[2]) === null || _a === void 0 ? void 0 : _a.referenceId) === comment.data.referenceId; });
17911
+ const queries = (_b = queryCache(['comment', 'query'])) === null || _b === void 0 ? void 0 : _b.filter(({ key }) => { var _a; return ((_a = key[2]) === null || _a === void 0 ? void 0 : _a.referenceId) === comment.data.referenceId; });
17006
17912
  queries === null || queries === void 0 ? void 0 : queries.map(({ key, data }) => upsertInCache(key, data, { cachedAt: -1 }));
17007
17913
  }
17008
17914
  callback(LinkedObject.comment(comment.data));
@@ -17014,13 +17920,13 @@ const createCommentEventSubscriber = (event, callback) => {
17014
17920
  const createLocalCommentEventSubscriber = (event, callback) => {
17015
17921
  const client = getActiveClient();
17016
17922
  const filter = (payload) => {
17017
- var _a, _b, _c, _d, _e;
17923
+ var _a, _b, _c, _d;
17018
17924
  if (!client.cache) {
17019
17925
  // TODO: here we are missing specific properties here!
17020
17926
  callback(LinkedObject.comment(payload.comments[0]));
17021
17927
  }
17022
17928
  else {
17023
- const processed = payload;
17929
+ const processed = prepareCommentPayload(payload);
17024
17930
  ingestInCache(processed);
17025
17931
  const { comments } = processed;
17026
17932
  if (comments.length > 0) {
@@ -17029,7 +17935,9 @@ const createLocalCommentEventSubscriber = (event, callback) => {
17029
17935
  'get',
17030
17936
  comments[0].commentId,
17031
17937
  ]);
17032
- if (['local.comment.created'].includes(event)) {
17938
+ // A pending comment is persisted for its author but never linked into the public
17939
+ // surfaces (parent reply list, post comment list)
17940
+ if (['local.comment.created'].includes(event) && isCommentApproved(comments[0])) {
17033
17941
  if (comments[0].parentId) {
17034
17942
  const parentComment = pullFromCache([
17035
17943
  'comment',
@@ -17058,11 +17966,11 @@ const createLocalCommentEventSubscriber = (event, callback) => {
17058
17966
  const postCacheKey = ['post', 'get', comments[0].referenceId];
17059
17967
  const postCache = (_a = pullFromCache(postCacheKey)) === null || _a === void 0 ? void 0 : _a.data;
17060
17968
  if (postCache) {
17061
- const updatedPostCache = Object.assign(Object.assign({}, postCache), { comments: [...postCache.comments, (_b = comments[0]) === null || _b === void 0 ? void 0 : _b.commentId] });
17969
+ const updatedPostCache = Object.assign(Object.assign({}, postCache), { comments: appendLatestCommentId(postCache, comments[0].commentId) });
17062
17970
  pushToCache(postCacheKey, updatedPostCache);
17063
17971
  }
17064
17972
  }
17065
- const queries = (_c = queryCache(['comment', 'query'])) === null || _c === void 0 ? void 0 : _c.filter(({ key }) => { var _a; return ((_a = key[2]) === null || _a === void 0 ? void 0 : _a.referenceId) === comment.data.referenceId; });
17973
+ const queries = (_b = queryCache(['comment', 'query'])) === null || _b === void 0 ? void 0 : _b.filter(({ key }) => { var _a; return ((_a = key[2]) === null || _a === void 0 ? void 0 : _a.referenceId) === comment.data.referenceId; });
17066
17974
  queries === null || queries === void 0 ? void 0 : queries.map(({ key, data }) => upsertInCache(key, data, { cachedAt: -1 }));
17067
17975
  }
17068
17976
  if (['local.comment.deleted'].includes(event)) {
@@ -17096,13 +18004,13 @@ const createLocalCommentEventSubscriber = (event, callback) => {
17096
18004
  }
17097
18005
  else {
17098
18006
  const postCacheKey = ['post', 'get', comments[0].referenceId];
17099
- const postCache = (_d = pullFromCache(postCacheKey)) === null || _d === void 0 ? void 0 : _d.data;
18007
+ const postCache = (_c = pullFromCache(postCacheKey)) === null || _c === void 0 ? void 0 : _c.data;
17100
18008
  if (postCache) {
17101
18009
  const updatedPost = Object.assign(Object.assign({}, postCache), { comments: postCache === null || postCache === void 0 ? void 0 : postCache.comments.filter(commentId => { var _a; return commentId !== ((_a = comments[0]) === null || _a === void 0 ? void 0 : _a.commentId); }) });
17102
18010
  pushToCache(postCacheKey, updatedPost);
17103
18011
  }
17104
18012
  }
17105
- const queries = (_e = queryCache(['comment', 'query'])) === null || _e === void 0 ? void 0 : _e.filter(({ key }) => { var _a; return ((_a = key[2]) === null || _a === void 0 ? void 0 : _a.referenceId) === comment.data.referenceId; });
18013
+ const queries = (_d = queryCache(['comment', 'query'])) === null || _d === void 0 ? void 0 : _d.filter(({ key }) => { var _a; return ((_a = key[2]) === null || _a === void 0 ? void 0 : _a.referenceId) === comment.data.referenceId; });
17106
18014
  queries === null || queries === void 0 ? void 0 : queries.map(({ key, data }) => upsertInCache(key, data, { cachedAt: -1 }));
17107
18015
  }
17108
18016
  callback(LinkedObject.comment(comment.data));
@@ -17163,6 +18071,23 @@ const onCommentUpdated = (callback) => createCommentEventSubscriber('comment.upd
17163
18071
  */
17164
18072
  const onCommentDeleted = (callback) => createCommentEventSubscriber('comment.deleted', callback);
17165
18073
 
18074
+ /**
18075
+ * ```js
18076
+ * import { onCommentApproved } from '@amityco/ts-sdk'
18077
+ * const dispose = onCommentApproved(comment => {
18078
+ * // ...
18079
+ * })
18080
+ * ```
18081
+ *
18082
+ * Fired when a {@link Amity.InternalComment} held for review has been approved
18083
+ *
18084
+ * @param callback The function to call when the event was fired
18085
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
18086
+ *
18087
+ * @category Comment Events
18088
+ */
18089
+ const onCommentApproved = (callback) => createCommentEventSubscriber('comment.approved', callback);
18090
+
17166
18091
  /**
17167
18092
  * ```js
17168
18093
  * import { onCommentFlagged } from '@amityco/ts-sdk'
@@ -17795,7 +18720,7 @@ const getReactions$1 = (params, callback, config) => {
17795
18720
  };
17796
18721
  /* end_public_function */
17797
18722
 
17798
- var index$o = /*#__PURE__*/Object.freeze({
18723
+ var index$p = /*#__PURE__*/Object.freeze({
17799
18724
  __proto__: null,
17800
18725
  addReaction: addReaction,
17801
18726
  removeReaction: removeReaction,
@@ -17806,17 +18731,6 @@ var index$o = /*#__PURE__*/Object.freeze({
17806
18731
  getReactions: getReactions$1
17807
18732
  });
17808
18733
 
17809
- function prepareCommentPayload(commentPayload) {
17810
- const { comments } = commentPayload;
17811
- return Object.assign(Object.assign({}, commentPayload), { comments: comments.map(comment => {
17812
- if (comment.hasOwnProperty('myReactions'))
17813
- return comment;
17814
- // Sometimes `myReactions` field will not come with BE response because that field is empty
17815
- // We need to put it with an empty array manually to make it show up in client side
17816
- return Object.assign({ myReactions: [] }, comment);
17817
- }) });
17818
- }
17819
-
17820
18734
  const createMessageReport = async ({ client, referenceId, }) => {
17821
18735
  const { data: payload } = await client.http.post(`/api/v5/messages/${encodeURIComponent(referenceId)}/flags`);
17822
18736
  if (client.cache) {
@@ -18280,20 +19194,20 @@ const getArchivedChannelIds = async () => {
18280
19194
 
18281
19195
  /**
18282
19196
  * ```js
18283
- * import { onMessageUpdated } from '@amityco/ts-sdk'
18284
- * const dispose = onMessageUpdated(message => {
19197
+ * import { onMessageDeleted } from '@amityco/ts-sdk'
19198
+ * const dispose = onMessageDeleted(message => {
18285
19199
  * // ...
18286
19200
  * })
18287
19201
  * ```
18288
19202
  *
18289
- * Fired when an {@link Amity.Message} has been updated
19203
+ * Fired when an {@link Amity.Message} was deleted
18290
19204
  *
18291
19205
  * @param callback The function to call when the event was fired
18292
19206
  * @returns an {@link Amity.Unsubscriber} function to stop listening
18293
19207
  *
18294
19208
  * @category Message Events
18295
19209
  */
18296
- const onMessageUpdated = (callback) => {
19210
+ const onMessageDeleted = (callback) => {
18297
19211
  const client = getActiveClient();
18298
19212
  const filter = async (rawPayload) => {
18299
19213
  const payload = await prepareMessagePayload(rawPayload);
@@ -18301,30 +19215,48 @@ const onMessageUpdated = (callback) => {
18301
19215
  callback(payload.messages[0]);
18302
19216
  };
18303
19217
  const disposers = [
18304
- createEventSubscriber(client, 'onMessageUpdated', 'message.updated', filter),
18305
- createEventSubscriber(client, 'onMessageUpdated', 'local.message.updated', payload => callback(payload.messages[0])),
19218
+ createEventSubscriber(client, 'message/onMessageDeleted', 'message.deleted', filter),
19219
+ createEventSubscriber(client, 'message/onMessageDeleted', 'local.message.deleted', payload => callback(payload.messages[0])),
18306
19220
  ];
18307
19221
  return () => {
18308
19222
  disposers.forEach(fn => fn());
18309
19223
  };
18310
19224
  };
18311
19225
 
19226
+ /**
19227
+ * Defensive clear of `channel.pinnedMessage` when the pinned message itself is deleted.
19228
+ *
19229
+ * The server also emits `channel.messageUnpinned` in this case, but realtime events are
19230
+ * fire-and-forget and their order is not guaranteed. Clearing on `message.deleted`
19231
+ * (MQTT or local) makes the banner disappear even if the unpin event is lost; the
19232
+ * server's own `messageUnpinned` then becomes a no-op.
19233
+ *
19234
+ * Internal — wired into the `getChannel` live object; not exported publicly.
19235
+ */
19236
+ const onChannelPinnedMessageDeleted = (callback) => onMessageDeleted(message => {
19237
+ var _a;
19238
+ const channel = findCachedChannelByAnyId(message.channelId);
19239
+ if (!channel || ((_a = channel.pinnedMessage) === null || _a === void 0 ? void 0 : _a.messageId) !== message.messageId)
19240
+ return;
19241
+ callback(updatePinnedMessageCache(channel, null));
19242
+ });
19243
+
18312
19244
  /**
18313
19245
  * ```js
18314
- * import { onMessageDeleted } from '@amityco/ts-sdk'
18315
- * const dispose = onMessageDeleted(message => {
19246
+ * import { onMessageUpdated } from '@amityco/ts-sdk'
19247
+ * const dispose = onMessageUpdated(message => {
18316
19248
  * // ...
18317
19249
  * })
18318
19250
  * ```
18319
19251
  *
18320
- * Fired when an {@link Amity.Message} was deleted
19252
+ * Fired when an {@link Amity.Message} has been updated
18321
19253
  *
18322
19254
  * @param callback The function to call when the event was fired
18323
19255
  * @returns an {@link Amity.Unsubscriber} function to stop listening
18324
19256
  *
18325
19257
  * @category Message Events
18326
19258
  */
18327
- const onMessageDeleted = (callback) => {
19259
+ const onMessageUpdated = (callback) => {
18328
19260
  const client = getActiveClient();
18329
19261
  const filter = async (rawPayload) => {
18330
19262
  const payload = await prepareMessagePayload(rawPayload);
@@ -18332,8 +19264,8 @@ const onMessageDeleted = (callback) => {
18332
19264
  callback(payload.messages[0]);
18333
19265
  };
18334
19266
  const disposers = [
18335
- createEventSubscriber(client, 'message/onMessageDeleted', 'message.deleted', filter),
18336
- createEventSubscriber(client, 'message/onMessageDeleted', 'local.message.deleted', payload => callback(payload.messages[0])),
19267
+ createEventSubscriber(client, 'onMessageUpdated', 'message.updated', filter),
19268
+ createEventSubscriber(client, 'onMessageUpdated', 'local.message.updated', payload => callback(payload.messages[0])),
18337
19269
  ];
18338
19270
  return () => {
18339
19271
  disposers.forEach(fn => fn());
@@ -18914,6 +19846,132 @@ softDeleteMessage.optimistically = (messageId) => {
18914
19846
  };
18915
19847
  /* end_public_function */
18916
19848
 
19849
+ /**
19850
+ * Fire-and-forget refresh of `channelUsers[...].permissions` for the channel a
19851
+ * message belongs to. Used by `pinMessage` / `unpinMessage` on `403` so the next
19852
+ * `hasPermission(PIN_MESSAGE).channel(channelId)` reflects a revoked role
19853
+ * ([`pinMessage` REQ-010](../../@types/../..) / [`unpinMessage` REQ-008](../../@types/../..)).
19854
+ *
19855
+ * The API only receives a `messageId`, so the channel is resolved through the
19856
+ * local cache: first the message row, then any cached channel whose current pin
19857
+ * is that message. When nothing matches the refresh is skipped — the next
19858
+ * channel read picks up the fresh permissions anyway.
19859
+ */
19860
+ const refreshChannelPermissionsForMessage = (messageId) => {
19861
+ var _a, _b, _c;
19862
+ const cachedMessage = (_a = getMessage$1.locally(messageId)) === null || _a === void 0 ? void 0 : _a.data;
19863
+ let channelId = cachedMessage === null || cachedMessage === void 0 ? void 0 : cachedMessage.channelId;
19864
+ if (!channelId) {
19865
+ channelId = (_c = (_b = queryCache(['channel', 'get'])) === null || _b === void 0 ? void 0 : _b.find(({ data }) => { var _a; return ((_a = data.pinnedMessage) === null || _a === void 0 ? void 0 : _a.messageId) === messageId; })) === null || _c === void 0 ? void 0 : _c.data.channelId;
19866
+ }
19867
+ if (!channelId)
19868
+ return;
19869
+ getChannel$1(channelId).catch(() => {
19870
+ /* silent per spec; UIKit renders no error toast */
19871
+ });
19872
+ };
19873
+
19874
+ /* begin_public_function
19875
+ id: message.pin
19876
+ */
19877
+ /**
19878
+ * ```js
19879
+ * import { MessageRepository } from '@amityco/ts-sdk'
19880
+ * const channel = await MessageRepository.pinMessage(messageId)
19881
+ * console.log(channel.pinnedMessage)
19882
+ * ```
19883
+ *
19884
+ * Pins a {@link Amity.Message} in its livestream (`live`) channel. A channel holds at
19885
+ * most one pinned message: pinning a different message replaces the current pin in a
19886
+ * single step — no unpin is needed first. Pinning the message that is already pinned is
19887
+ * rejected by the server (400).
19888
+ *
19889
+ * The caller must hold the `PIN_MESSAGE` permission in the channel (or be an admin with
19890
+ * `ModerateChannel`). The server also rejects pinning a deleted message, a message whose
19891
+ * author is banned from the channel or globally banned, and pinning in any channel type
19892
+ * other than `live`. On any error the pin state is left unchanged.
19893
+ *
19894
+ * The response is the affected channel; it is ingested into cache and fires
19895
+ * `local.channel.updated`, so `ChannelRepository.getChannel` observers update without
19896
+ * waiting for the `channel.messagePinned` realtime event.
19897
+ *
19898
+ * @param messageId the **internal** ID of the {@link Amity.Message} to pin
19899
+ * @returns the updated {@link Amity.Channel}, with `pinnedMessage` set
19900
+ *
19901
+ * @category Message API
19902
+ * @async
19903
+ */
19904
+ const pinMessage = async (messageId) => {
19905
+ const client = getActiveClient();
19906
+ client.log('message/pinMessage', messageId);
19907
+ let payload;
19908
+ try {
19909
+ ({ data: payload } = await client.http.post(`/api/v5/messages/${encodeURIComponent(messageId)}/pin`));
19910
+ }
19911
+ catch (error) {
19912
+ if ((error === null || error === void 0 ? void 0 : error.code) === 400301 /* Amity.ServerError.PERMISSION_DENIED */) {
19913
+ refreshChannelPermissionsForMessage(messageId);
19914
+ }
19915
+ throw error;
19916
+ }
19917
+ const data = await prepareChannelPayload(payload);
19918
+ if (client.cache)
19919
+ ingestInCache(data);
19920
+ fireEvent('local.channel.updated', data);
19921
+ return constructChannelObject(data.channels[0]);
19922
+ };
19923
+ /* end_public_function */
19924
+
19925
+ /* begin_public_function
19926
+ id: message.unpin
19927
+ */
19928
+ /**
19929
+ * ```js
19930
+ * import { MessageRepository } from '@amityco/ts-sdk'
19931
+ * const channel = await MessageRepository.unpinMessage(messageId)
19932
+ * console.log(channel.pinnedMessage) // null
19933
+ * ```
19934
+ *
19935
+ * Removes the pin from a {@link Amity.Message}. `messageId` must be the message that is
19936
+ * **currently** pinned in its channel; otherwise the server answers 400 — this is
19937
+ * deliberate, so a stale client cannot clear a pin that someone else has since replaced.
19938
+ * On that error, re-read the channel (or rely on the `channel.messagePinned` event) to
19939
+ * get the current pin.
19940
+ *
19941
+ * The caller must hold the `PIN_MESSAGE` permission in the channel (or be an admin with
19942
+ * `ModerateChannel`). Unpinning is allowed regardless of channel type and stream state.
19943
+ *
19944
+ * The response is the affected channel; it is ingested into cache and fires
19945
+ * `local.channel.updated`, so `ChannelRepository.getChannel` observers update without
19946
+ * waiting for the `channel.messageUnpinned` realtime event.
19947
+ *
19948
+ * @param messageId the **internal** ID of the currently pinned {@link Amity.Message}
19949
+ * @returns the updated {@link Amity.Channel}, with `pinnedMessage` cleared
19950
+ *
19951
+ * @category Message API
19952
+ * @async
19953
+ */
19954
+ const unpinMessage = async (messageId) => {
19955
+ const client = getActiveClient();
19956
+ client.log('message/unpinMessage', messageId);
19957
+ let payload;
19958
+ try {
19959
+ ({ data: payload } = await client.http.delete(`/api/v5/messages/${encodeURIComponent(messageId)}/pin`));
19960
+ }
19961
+ catch (error) {
19962
+ if ((error === null || error === void 0 ? void 0 : error.code) === 400301 /* Amity.ServerError.PERMISSION_DENIED */) {
19963
+ refreshChannelPermissionsForMessage(messageId);
19964
+ }
19965
+ throw error;
19966
+ }
19967
+ const data = await prepareChannelPayload(payload);
19968
+ if (client.cache)
19969
+ ingestInCache(data);
19970
+ fireEvent('local.channel.updated', data);
19971
+ return constructChannelObject(data.channels[0]);
19972
+ };
19973
+ /* end_public_function */
19974
+
18917
19975
  /**
18918
19976
  * ```js
18919
19977
  * import { MessageRepository } from '@amityco/ts-sdk'
@@ -19810,13 +20868,15 @@ const searchMessage = (params, callback) => {
19810
20868
  };
19811
20869
  /* end_public_function */
19812
20870
 
19813
- var index$n = /*#__PURE__*/Object.freeze({
20871
+ var index$o = /*#__PURE__*/Object.freeze({
19814
20872
  __proto__: null,
19815
20873
  createMessage: createMessage,
19816
20874
  updateMessage: updateMessage,
19817
20875
  editMessage: editMessage,
19818
20876
  deleteMessage: deleteMessage,
19819
20877
  softDeleteMessage: softDeleteMessage,
20878
+ pinMessage: pinMessage,
20879
+ unpinMessage: unpinMessage,
19820
20880
  markAsDelivered: markAsDelivered,
19821
20881
  getReadUsers: getReadUsers,
19822
20882
  getDeliveredUsers: getDeliveredUsers,
@@ -20346,7 +21406,7 @@ const stopMessageReceiptSync = (subChannelId) => {
20346
21406
  };
20347
21407
  /* end_public_function */
20348
21408
 
20349
- var index$m = /*#__PURE__*/Object.freeze({
21409
+ var index$n = /*#__PURE__*/Object.freeze({
20350
21410
  __proto__: null,
20351
21411
  getSubChannelByIds: getSubChannels$1,
20352
21412
  createSubChannel: createSubChannel,
@@ -20453,7 +21513,12 @@ const getChannel = (channelId, callback) => {
20453
21513
  onChannelMemberRemoved,
20454
21514
  onChannelMemberBanned,
20455
21515
  onChannelMemberUnbanned,
21516
+ onChannelMemberRoleAdded,
21517
+ onChannelMemberRoleRemoved,
20456
21518
  onChannelSetMuted,
21519
+ onChannelMessagePinned,
21520
+ onChannelMessageUnpinned,
21521
+ onChannelPinnedMessageDeleted,
20457
21522
  convertEventPayload(onChannelMarkerFetched, 'entityId', 'channel'),
20458
21523
  convertEventPayload(onChannelMarkerUpdated, 'entityId', 'channel'),
20459
21524
  convertEventPayload((callback) => {
@@ -21079,6 +22144,14 @@ class ChannelLiveCollectionController extends LiveCollectionController {
21079
22144
  return;
21080
22145
  if (messagePreviewSetting ===
21081
22146
  "message-preview-not-include-deleted" /* Amity.MessagePreviewSetting.MESSAGE_PREVIEW_NOT_INCLUDE_DELETED */) {
22147
+ // The replacement preview the server sends back is an OLDER
22148
+ // message than the one just deleted, and
22149
+ // updateChannelMessagePreviewCache drops any preview that is not
22150
+ // newer than what is cached — so without clearing the entry
22151
+ // first the refetch is a no-op and the channel keeps showing the
22152
+ // deleted message. getChannel's own live object already does
22153
+ // this; the live collections did not.
22154
+ dropFromCache(['messagePreviewChannel', 'get', message.channelId]);
21082
22155
  await getChannel$1(message.channelId);
21083
22156
  }
21084
22157
  callback(message);
@@ -21803,6 +22876,14 @@ class SearchChannelLiveCollectionController extends LiveCollectionController {
21803
22876
  return;
21804
22877
  if (messagePreviewSetting ===
21805
22878
  "message-preview-not-include-deleted" /* Amity.MessagePreviewSetting.MESSAGE_PREVIEW_NOT_INCLUDE_DELETED */) {
22879
+ // The replacement preview the server sends back is an OLDER
22880
+ // message than the one just deleted, and
22881
+ // updateChannelMessagePreviewCache drops any preview that is not
22882
+ // newer than what is cached — so without clearing the entry
22883
+ // first the refetch is a no-op and the channel keeps showing the
22884
+ // deleted message. getChannel's own live object already does
22885
+ // this; the live collections did not.
22886
+ dropFromCache(['messagePreviewChannel', 'get', message.channelId]);
21806
22887
  await getChannel$1(message.channelId);
21807
22888
  }
21808
22889
  callback(message);
@@ -22297,7 +23378,7 @@ const searchMembers$1 = (params, callback, config) => {
22297
23378
  };
22298
23379
  /* end_public_function */
22299
23380
 
22300
- var index$l = /*#__PURE__*/Object.freeze({
23381
+ var index$m = /*#__PURE__*/Object.freeze({
22301
23382
  __proto__: null,
22302
23383
  addMembers: addMembers$1,
22303
23384
  removeMembers: removeMembers$1,
@@ -22519,7 +23600,7 @@ const unmuteMembers = async (channelId, userIds) => {
22519
23600
  };
22520
23601
  /* end_public_function */
22521
23602
 
22522
- var index$k = /*#__PURE__*/Object.freeze({
23603
+ var index$l = /*#__PURE__*/Object.freeze({
22523
23604
  __proto__: null,
22524
23605
  addRole: addRole,
22525
23606
  removeRole: removeRole,
@@ -22529,10 +23610,10 @@ var index$k = /*#__PURE__*/Object.freeze({
22529
23610
  unmuteMembers: unmuteMembers
22530
23611
  });
22531
23612
 
22532
- var index$j = /*#__PURE__*/Object.freeze({
23613
+ var index$k = /*#__PURE__*/Object.freeze({
22533
23614
  __proto__: null,
22534
- Membership: index$l,
22535
- Moderation: index$k,
23615
+ Membership: index$m,
23616
+ Moderation: index$l,
22536
23617
  getChannelByIds: getChannelByIds$1,
22537
23618
  createChannel: createChannel,
22538
23619
  updateChannel: updateChannel,
@@ -22550,6 +23631,8 @@ var index$j = /*#__PURE__*/Object.freeze({
22550
23631
  onChannelJoined: onChannelJoined,
22551
23632
  onChannelLeft: onChannelLeft,
22552
23633
  onChannelSetMuted: onChannelSetMuted,
23634
+ onChannelMessagePinned: onChannelMessagePinned,
23635
+ onChannelMessageUnpinned: onChannelMessageUnpinned,
22553
23636
  onChannelMemberAdded: onChannelMemberAdded,
22554
23637
  onChannelMemberRemoved: onChannelMemberRemoved,
22555
23638
  onChannelMemberBanned: onChannelMemberBanned,
@@ -22567,7 +23650,11 @@ var index$j = /*#__PURE__*/Object.freeze({
22567
23650
  isUnreadCountSupport: isUnreadCountSupport,
22568
23651
  convertFromRaw: convertFromRaw,
22569
23652
  preUpdateChannelCache: preUpdateChannelCache,
22570
- prepareChannelPayload: prepareChannelPayload
23653
+ prepareChannelPayload: prepareChannelPayload,
23654
+ findCachedChannelByAnyId: findCachedChannelByAnyId,
23655
+ findCachedChannelForPin: findCachedChannelForPin,
23656
+ updatePinnedMessageCache: updatePinnedMessageCache,
23657
+ applyChannelRolePayload: applyChannelRolePayload
22571
23658
  });
22572
23659
 
22573
23660
  const saveCommunityUsers = (communities, communityUsers) => {
@@ -23961,7 +25048,7 @@ const searchMembers = (params, callback, config) => {
23961
25048
  };
23962
25049
  /* end_public_function */
23963
25050
 
23964
- var index$i = /*#__PURE__*/Object.freeze({
25051
+ var index$j = /*#__PURE__*/Object.freeze({
23965
25052
  __proto__: null,
23966
25053
  addMembers: addMembers,
23967
25054
  removeMembers: removeMembers,
@@ -25212,7 +26299,7 @@ const unbanMembers = async (communityId, userIds) => {
25212
26299
  };
25213
26300
  /* end_public_function */
25214
26301
 
25215
- var index$h = /*#__PURE__*/Object.freeze({
26302
+ var index$i = /*#__PURE__*/Object.freeze({
25216
26303
  __proto__: null,
25217
26304
  addRoles: addRoles,
25218
26305
  removeRoles: removeRoles,
@@ -25220,10 +26307,10 @@ var index$h = /*#__PURE__*/Object.freeze({
25220
26307
  unbanMembers: unbanMembers
25221
26308
  });
25222
26309
 
25223
- var index$g = /*#__PURE__*/Object.freeze({
26310
+ var index$h = /*#__PURE__*/Object.freeze({
25224
26311
  __proto__: null,
25225
- Moderation: index$h,
25226
- Membership: index$i,
26312
+ Moderation: index$i,
26313
+ Membership: index$j,
25227
26314
  getCommunityByIds: getCommunities$1,
25228
26315
  createCommunity: createCommunity,
25229
26316
  updateCommunity: updateCommunity,
@@ -25459,7 +26546,7 @@ const getCategories = (params, callback, config) => {
25459
26546
  };
25460
26547
  /* end_public_function */
25461
26548
 
25462
- var index$f = /*#__PURE__*/Object.freeze({
26549
+ var index$g = /*#__PURE__*/Object.freeze({
25463
26550
  __proto__: null,
25464
26551
  getCategory: getCategory,
25465
26552
  getCategories: getCategories
@@ -25758,6 +26845,11 @@ const createCommentOptimistic = (bundle) => {
25758
26845
  targetType: 'community',
25759
26846
  dataType: 'text',
25760
26847
  syncState: "syncing" /* Amity.SyncState.Syncing */,
26848
+ // In a gated community the optimistic object stays out of public collections until the
26849
+ // response settles the status; the author's own view still updates through the local event
26850
+ approvalStatus: isCommentApprovalRequired(bundle)
26851
+ ? "pending" /* Amity.CommentApprovalStatusEnum.Pending */
26852
+ : "approved" /* Amity.CommentApprovalStatusEnum.Approved */,
25761
26853
  };
25762
26854
  const cachedAt = UNSYNCED_OBJECT_CACHED_AT_VALUE;
25763
26855
  pushToCache(['comment', 'get', comment.commentId], comment, { cachedAt });
@@ -25774,32 +26866,57 @@ const createCommentOptimistic = (bundle) => {
25774
26866
  * ```js
25775
26867
  * import { CommentRepository } from '@amityco/ts-sdk'
25776
26868
  * const newComment = await CommentRepository.createComment(bundle)
26869
+ *
26870
+ * // Server-confirmed only: nothing is shown until the request succeeds
26871
+ * const confirmed = await CommentRepository.createComment(bundle, false)
25777
26872
  * ```
25778
26873
  *
25779
26874
  * Creates an {@link Amity.Comment}
25780
26875
  *
26876
+ * With `isOptimistic` (the default) a local comment appears at once with `syncState: 'syncing'`,
26877
+ * moves to `'synced'` when the server confirms it and to `'error'` if the request fails, so the
26878
+ * caller can offer a retry. With `isOptimistic: false` nothing is created locally until the
26879
+ * server answers: on success the comment arrives already `'synced'`; on failure no comment
26880
+ * entity exists anywhere and the promise rejects.
26881
+ *
25781
26882
  * @param bundle The data necessary to create a new {@link Amity.Comment}
26883
+ * @param isOptimistic Show a local comment before the server confirms it. Default `true`.
26884
+ * Ignored when the client cache is disabled, since there is nowhere to hold the local comment.
25782
26885
  * @returns The newly created {@link Amity.Comment}
25783
26886
  *
25784
26887
  * @category Comment API
25785
26888
  * @async
25786
26889
  */
25787
- const createComment = async (bundle) => {
26890
+ const createComment = async (bundle, isOptimistic = true) => {
25788
26891
  const client = getActiveClient();
25789
- client.log('comment/createComment', bundle);
25790
- const optimisticData = createCommentOptimistic(bundle);
26892
+ client.log('comment/createComment', Object.assign(Object.assign({}, bundle), { isOptimistic }));
26893
+ // Without a local comment the server assigns the id; with one, the same id travels through the
26894
+ // optimistic object, the response and every realtime event so each step recognises it.
26895
+ const optimisticData = isOptimistic ? createCommentOptimistic(bundle) : undefined;
25791
26896
  const commentId = optimisticData === null || optimisticData === void 0 ? void 0 : optimisticData.commentId;
25792
26897
  try {
25793
- const { data } = await client.http.post('/api/v3/comments', Object.assign(Object.assign({}, bundle), { commentId }));
25794
- const { comments } = data;
26898
+ const { data: payload } = await client.http.post('/api/v3/comments', Object.assign(Object.assign({}, bundle), { commentId }));
25795
26899
  // BE always returns an array of comments If it got record 0 from BE it might have a problem on creation logic
25796
- if (comments.length === 0)
26900
+ if (payload.comments.length === 0)
25797
26901
  throw new Error('Comment not created');
26902
+ // Absent `approvalStatus` means approved; the result is the only source of the status.
26903
+ // The confirmed comment is written as `synced` so the cache itself tells the two states apart
26904
+ // (a local-event subscriber is not guaranteed to be listening).
26905
+ const prepared = prepareCommentPayload(payload);
26906
+ const data = Object.assign(Object.assign({}, prepared), { comments: prepared.comments.map(comment => comment.commentId === (commentId !== null && commentId !== void 0 ? commentId : comment.commentId)
26907
+ ? Object.assign(Object.assign({}, comment), { syncState: "synced" /* Amity.SyncState.Synced */ }) : comment) });
26908
+ const { comments } = data;
25798
26909
  const cachedAt = client.cache && Date.now();
25799
26910
  if (client.cache)
25800
26911
  ingestInCache(data, { cachedAt });
25801
26912
  if (['post', 'content'].includes(bundle.referenceType)) {
25802
- PostCommentCountEngine$1.getInstance().queueCommentChangeTask(new CreateTask(bundle.referenceId, comments[0].commentId, data.comments[0].createdAt));
26913
+ if (isCommentPending(comments[0])) {
26914
+ // Not counted for anyone else until approved; the author sees their own +1
26915
+ recordPendingAuthoredComment(comments[0]);
26916
+ }
26917
+ else {
26918
+ PostCommentCountEngine$1.getInstance().queueCommentChangeTask(new CreateTask(bundle.referenceId, comments[0].commentId, comments[0].createdAt));
26919
+ }
25803
26920
  }
25804
26921
  else if (bundle.referenceType === 'story') {
25805
26922
  const storyIndex = pullFromCache([
@@ -25820,9 +26937,9 @@ const createComment = async (bundle) => {
25820
26937
  categories: [],
25821
26938
  comments,
25822
26939
  communities: [],
25823
- communityUsers: data.communityUsers,
25824
- files: data.files,
25825
- users: data.users,
26940
+ communityUsers: payload.communityUsers,
26941
+ files: payload.files,
26942
+ users: payload.users,
25826
26943
  });
25827
26944
  }
25828
26945
  }
@@ -25830,9 +26947,9 @@ const createComment = async (bundle) => {
25830
26947
  fireEvent('local.comment.created', {
25831
26948
  comments: [Object.assign(Object.assign({}, comments[0]), { syncState: "synced" /* Amity.SyncState.Synced */ })],
25832
26949
  commentChildren: data.commentChildren,
25833
- users: data.users,
25834
- files: data.files,
25835
- communityUsers: data.communityUsers,
26950
+ users: payload.users,
26951
+ files: payload.files,
26952
+ communityUsers: payload.communityUsers,
25836
26953
  });
25837
26954
  return {
25838
26955
  data: LinkedObject.comment(comments[0]),
@@ -25840,9 +26957,17 @@ const createComment = async (bundle) => {
25840
26957
  };
25841
26958
  }
25842
26959
  catch (e) {
26960
+ // Only a local comment has anything to mark as failed; a server-confirmed-only create leaves
26961
+ // no entity behind
25843
26962
  if (optimisticData) {
26963
+ const failed = Object.assign(Object.assign({}, optimisticData), { syncState: "error" /* Amity.SyncState.Error */ });
26964
+ // Write the failure to the cache directly: the local event below only reaches pages that
26965
+ // observe comments, and the caller's retry UI reads the cached state
26966
+ pushToCache(['comment', 'get', failed.commentId], failed, {
26967
+ cachedAt: UNSYNCED_OBJECT_CACHED_AT_VALUE,
26968
+ });
25844
26969
  fireEvent('local.comment.created', {
25845
- comments: [Object.assign(Object.assign({}, optimisticData), { syncState: "error" /* Amity.SyncState.Error */ })],
26970
+ comments: [failed],
25846
26971
  commentChildren: [],
25847
26972
  users: [],
25848
26973
  files: [],
@@ -25875,16 +27000,26 @@ const createComment = async (bundle) => {
25875
27000
  * @async
25876
27001
  */
25877
27002
  const updateComment = async (commentId, patch) => {
27003
+ var _a;
25878
27004
  const client = getActiveClient();
25879
27005
  client.log('user/updateComment', patch);
25880
- const { data } = await client.http.put(`/api/v3/comments/${encodeURIComponent(commentId)}`, patch);
27006
+ const previous = (_a = pullFromCache(['comment', 'get', commentId])) === null || _a === void 0 ? void 0 : _a.data;
27007
+ const { data: payload } = await client.http.put(`/api/v3/comments/${encodeURIComponent(commentId)}`, patch);
27008
+ const data = prepareCommentPayload(payload);
27009
+ const updated = data.comments.find(comment => comment.commentId === commentId);
25881
27010
  const cachedAt = client.cache && Date.now();
25882
27011
  if (client.cache)
25883
27012
  ingestInCache(data, { cachedAt });
25884
- fireEvent('comment.updated', data);
25885
- const { comments } = data;
27013
+ // An effective edit in a gated community sends the comment back for review: it leaves the
27014
+ // public reply list and the public count once. The `comment.updated` event below removes it
27015
+ // from the comment collections; the realtime echo finds it already pending and does nothing.
27016
+ if (isCommentPending(updated) && previous && isCommentApproved(previous)) {
27017
+ unlinkCommentFromParent(updated);
27018
+ applyCommentReReviewCount(updated);
27019
+ }
27020
+ fireEvent('comment.updated', payload);
25886
27021
  return {
25887
- data: LinkedObject.comment(comments.find(comment => comment.commentId === commentId)),
27022
+ data: LinkedObject.comment(updated),
25888
27023
  cachedAt,
25889
27024
  };
25890
27025
  };
@@ -26024,7 +27159,13 @@ const deleteComment = async (commentId, permanent = false) => {
26024
27159
  const post = (_b = pullFromCache(['post', 'get', comment.data.referenceId])) === null || _b === void 0 ? void 0 : _b.data;
26025
27160
  if (post) {
26026
27161
  const engine = PostCommentCountEngine$1.getInstance();
26027
- engine.queueCommentChangeTask(new DeleteTask(post.postId, commentId));
27162
+ if (isCommentPending(comment.data)) {
27163
+ // Never counted for anyone else; only the author's own +1 goes away
27164
+ engine.removePendingAuthoredComment(post.postId, commentId);
27165
+ }
27166
+ else {
27167
+ engine.queueCommentChangeTask(new DeleteTask(post.postId, commentId));
27168
+ }
26028
27169
  if (!deleted.parentId && ((_c = deleted.children /* c8 ignore next */) === null || _c === void 0 ? void 0 : _c.length) > 0) {
26029
27170
  // NOTE: delete the parent comment will also remove all children comments
26030
27171
  deleted.children.forEach((childCommentId) => {
@@ -26094,6 +27235,109 @@ const hardDeleteComment = async (commentId) => {
26094
27235
  };
26095
27236
  /* end_public_function */
26096
27237
 
27238
+ /* begin_public_function
27239
+ id: comment.approve
27240
+ */
27241
+ /**
27242
+ * ```js
27243
+ * import { CommentRepository } from '@amityco/ts-sdk'
27244
+ *
27245
+ * const { data: comment } = await CommentRepository.approveComment('commentId')
27246
+ * ```
27247
+ *
27248
+ * Approves a {@link Amity.Comment} held for review, making it visible to everyone
27249
+ *
27250
+ * @param commentId The {@link Amity.Comment} ID to be approved
27251
+ * @return The {@link Amity.Comment} that was approved
27252
+ *
27253
+ * @category Comment API
27254
+ * @async
27255
+ */
27256
+ const approveComment = async (commentId) => {
27257
+ const client = getActiveClient();
27258
+ client.log('comment/approveComment', commentId);
27259
+ // No request body, and nothing is revealed before the server confirms
27260
+ const { data: payload } = await client.http.post(`/api/v3/comments/${encodeURIComponent(commentId)}/approve`);
27261
+ const data = prepareCommentPayload(prepareMembershipPayload(payload, 'communityUsers'));
27262
+ const approved = data.comments.find(comment => comment.commentId === commentId);
27263
+ const cachedAt = client.cache && Date.now();
27264
+ if (client.cache)
27265
+ ingestInCache(data, { cachedAt });
27266
+ // The reveal path: parent link and exactly one count task. Applied here so it does not depend
27267
+ // on an observer being open; the event below and the realtime `comment.approved` that follows
27268
+ // find the work done and reconcile by comment id (collection insert, queue removal).
27269
+ linkCommentToParent(approved);
27270
+ applyCommentApprovedCount(approved);
27271
+ fireEvent('comment.approved', payload);
27272
+ return {
27273
+ data: LinkedObject.comment(approved),
27274
+ cachedAt,
27275
+ };
27276
+ };
27277
+ /* end_public_function */
27278
+
27279
+ // Rejected is terminal and implies deleted
27280
+ const markRejected = (comment) => (Object.assign(Object.assign({}, comment), { approvalStatus: "rejected" /* Amity.CommentApprovalStatusEnum.Rejected */, isDeleted: true }));
27281
+ /* begin_public_function
27282
+ id: comment.decline
27283
+ */
27284
+ /**
27285
+ * ```js
27286
+ * import { CommentRepository } from '@amityco/ts-sdk'
27287
+ *
27288
+ * const { data: comment } = await CommentRepository.declineComment('commentId', 'Off-topic')
27289
+ * ```
27290
+ *
27291
+ * Declines a {@link Amity.Comment} held for review. A declined comment is also a deleted comment
27292
+ *
27293
+ * @param commentId The {@link Amity.Comment} ID to be declined
27294
+ * @param reason Optional reviewer's note, at most 250 characters, kept for the moderation record only
27295
+ * @return The {@link Amity.Comment} that was declined
27296
+ *
27297
+ * @category Comment API
27298
+ * @async
27299
+ */
27300
+ const declineComment = async (commentId, reason) => {
27301
+ var _a, _b, _c, _d, _e, _f;
27302
+ const client = getActiveClient();
27303
+ client.log('comment/declineComment', commentId, reason);
27304
+ // Read before the request: the fallback when the response carries no comment
27305
+ const cached = (_a = pullFromCache(['comment', 'get', commentId])) === null || _a === void 0 ? void 0 : _a.data;
27306
+ // `reason` is surfaced to nobody; the key is absent from the body when the caller gives none
27307
+ const { data: payload } = await client.http.post(`/api/v3/comments/${encodeURIComponent(commentId)}/decline`, reason ? { reason } : undefined);
27308
+ // The BE contract (PDT-5135 §3) states the response body for approve only; for decline the
27309
+ // standard comment payload is assumed. Ingest whatever came back, and when the body carries no
27310
+ // comment fall back to the cached one so the delete path below still runs.
27311
+ const returned = (_b = payload === null || payload === void 0 ? void 0 : payload.comments) === null || _b === void 0 ? void 0 : _b.some(comment => comment.commentId === commentId);
27312
+ if (!returned && !cached)
27313
+ throw new Error('Comment not found after decline');
27314
+ const comments = returned
27315
+ ? payload.comments.map(comment => comment.commentId === commentId ? markRejected(comment) : comment)
27316
+ : [markRejected(cached)];
27317
+ const declined = {
27318
+ comments,
27319
+ commentChildren: (_c = payload === null || payload === void 0 ? void 0 : payload.commentChildren) !== null && _c !== void 0 ? _c : [],
27320
+ users: (_d = payload === null || payload === void 0 ? void 0 : payload.users) !== null && _d !== void 0 ? _d : [],
27321
+ files: (_e = payload === null || payload === void 0 ? void 0 : payload.files) !== null && _e !== void 0 ? _e : [],
27322
+ communityUsers: (_f = payload === null || payload === void 0 ? void 0 : payload.communityUsers) !== null && _f !== void 0 ? _f : [],
27323
+ };
27324
+ // There is no `comment.declined` event: the existing delete path drops the comment from every
27325
+ // collection and the review queue, and moves no count because a pending comment was never counted.
27326
+ const data = prepareCommentPayload(prepareMembershipPayload(declined, 'communityUsers'));
27327
+ const rejected = data.comments.find(comment => comment.commentId === commentId);
27328
+ const cachedAt = client.cache && Date.now();
27329
+ if (client.cache)
27330
+ ingestInCache(data, { cachedAt });
27331
+ unlinkCommentFromParent(rejected);
27332
+ releasePendingAuthoredComment(rejected);
27333
+ fireEvent('comment.deleted', declined);
27334
+ return {
27335
+ data: LinkedObject.comment(rejected),
27336
+ cachedAt,
27337
+ };
27338
+ };
27339
+ /* end_public_function */
27340
+
26097
27341
  /* begin_public_function
26098
27342
  id: comment.flag
26099
27343
  */
@@ -26179,6 +27423,7 @@ const isCommentFlaggedByMe = async (commentId) => {
26179
27423
  /* end_public_function */
26180
27424
 
26181
27425
  const getComment$1 = async (commentId) => {
27426
+ var _a;
26182
27427
  const client = getActiveClient();
26183
27428
  client.log('comment/getComment', commentId);
26184
27429
  isInTombstone('comment', commentId);
@@ -26189,7 +27434,11 @@ const getComment$1 = async (commentId) => {
26189
27434
  data = response.data;
26190
27435
  }
26191
27436
  catch (error) {
26192
- if (checkIfShouldGoesToTombstone(error === null || error === void 0 ? void 0 : error.code)) {
27437
+ // A pending comment answers 404 to anyone but its author and reviewers. That is a
27438
+ // visibility answer, not a deletion — never tombstone a comment known to be pending.
27439
+ const cached = (_a = pullFromCache(['comment', 'get', commentId])) === null || _a === void 0 ? void 0 : _a.data;
27440
+ const isKnownPending = !!cached && isCommentPending(cached);
27441
+ if (!isKnownPending && checkIfShouldGoesToTombstone(error === null || error === void 0 ? void 0 : error.code)) {
26193
27442
  pushToTombstone('comment', commentId);
26194
27443
  }
26195
27444
  throw error;
@@ -26316,6 +27565,7 @@ const onLocalCommentReactionRemoved = (callback) => {
26316
27565
  */
26317
27566
  const getComment = (commentId, callback) => {
26318
27567
  return liveObject(commentId, callback, 'commentId', getComment$1, [
27568
+ onCommentApproved,
26319
27569
  onCommentDeleteLocal,
26320
27570
  onCommentDeleted,
26321
27571
  onCommentFlagged,
@@ -26329,28 +27579,31 @@ const getComment = (commentId, callback) => {
26329
27579
  };
26330
27580
  /* end_public_function */
26331
27581
 
26332
- class CommentPaginationController extends PaginationController {
26333
- async getRequest(queryParams, token) {
26334
- var _a;
26335
- const { pageSize, limit, includeDeleted } = queryParams, params = __rest(queryParams, ["pageSize", "limit", "includeDeleted"]);
26336
- const effectiveLimit = (_a = pageSize !== null && pageSize !== void 0 ? pageSize : limit) !== null && _a !== void 0 ? _a : COLLECTION_DEFAULT_PAGINATION_LIMIT;
26337
- const baseOptions = {
26338
- type: params.sortBy || queryParams.limit || queryParams.pageSize ? 'pagination' : undefined,
26339
- };
26340
- const options = token
26341
- ? Object.assign(Object.assign({}, baseOptions), { token }) : Object.assign(Object.assign({}, baseOptions), { pageSize: effectiveLimit, limit: effectiveLimit });
26342
- const { data: queryResponse } = await this.http.get(`/api/v3/comments`, {
26343
- params: Object.assign(Object.assign({}, params), { isDeleted: inferIsDeleted(includeDeleted), options }),
26344
- });
26345
- return queryResponse;
26346
- }
26347
- }
27582
+ /**
27583
+ * ```js
27584
+ * import { onCommentCreated } from '@amityco/ts-sdk'
27585
+ * const dispose = onCommentCreated(comment => {
27586
+ * // ...
27587
+ * })
27588
+ * ```
27589
+ *
27590
+ * Fired when a {@link Amity.InternalComment} has been created
27591
+ *
27592
+ * @param callback The function to call when the event was fired
27593
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
27594
+ *
27595
+ * @category Comment Events
27596
+ */
27597
+ const onCommentCreatedLocal = (callback) => {
27598
+ return createLocalCommentEventSubscriber('local.comment.created', callback);
27599
+ };
26348
27600
 
26349
27601
  var EnumCommentActions;
26350
27602
  (function (EnumCommentActions) {
26351
27603
  EnumCommentActions["OnCommentCreated"] = "onCommentCreated";
26352
27604
  EnumCommentActions["OnCommentUpdated"] = "onCommentUpdated";
26353
27605
  EnumCommentActions["OnCommentDeleted"] = "onCommentDeleted";
27606
+ EnumCommentActions["OnCommentApproved"] = "onCommentApproved";
26354
27607
  EnumCommentActions["OnCommentFlagged"] = "onCommentFlagged";
26355
27608
  EnumCommentActions["OnCommentUnflagged"] = "onCommentUnflagged";
26356
27609
  EnumCommentActions["OnCommentReactionAdded"] = "onCommentReactionAdded";
@@ -26373,15 +27626,17 @@ class CommentQueryStreamController extends QueryStreamController {
26373
27626
  }
26374
27627
  appendToQueryStream(response, direction, refresh = false) {
26375
27628
  var _a, _b;
27629
+ // The public list is approved-only even when the server widens the read for a reviewer
27630
+ const commentIds = response.comments.filter(isCommentApproved).map(getResolver('comment'));
26376
27631
  if (refresh) {
26377
27632
  pushToCache(this.cacheKey, {
26378
- data: response.comments.map(getResolver('comment')),
27633
+ data: commentIds,
26379
27634
  });
26380
27635
  }
26381
27636
  else {
26382
27637
  const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
26383
27638
  const comments = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
26384
- pushToCache(this.cacheKey, Object.assign(Object.assign({}, collection), { data: [...new Set([...comments, ...response.comments.map(getResolver('comment'))])] }));
27639
+ pushToCache(this.cacheKey, Object.assign(Object.assign({}, collection), { data: [...new Set([...comments, ...commentIds])] }));
26385
27640
  }
26386
27641
  }
26387
27642
  reactor(action) {
@@ -26400,8 +27655,19 @@ class CommentQueryStreamController extends QueryStreamController {
26400
27655
  return;
26401
27656
  }
26402
27657
  if (action === EnumCommentActions.OnCommentCreated) {
27658
+ // A pending comment reaches clients over realtime before anyone may see it: persist
27659
+ // only, no insert and no emit. `comment.approved` is the reveal signal.
27660
+ if (!isCommentApproved(comment))
27661
+ return;
26403
27662
  collection.data = [...new Set([comment.commentId, ...collection.data])];
26404
27663
  }
27664
+ if (action === EnumCommentActions.OnCommentApproved) {
27665
+ collection.data = [...new Set([comment.commentId, ...collection.data])];
27666
+ }
27667
+ // An effective edit in a gated community returns the comment to review: it leaves the list
27668
+ if (action === EnumCommentActions.OnCommentUpdated && isCommentPending(comment)) {
27669
+ collection.data = collection.data.filter(commentId => commentId !== comment.commentId);
27670
+ }
26405
27671
  pushToCache(this.cacheKey, collection);
26406
27672
  this.notifyChange({ origin: "event" /* Amity.LiveDataOrigin.EVENT */, loading: false });
26407
27673
  };
@@ -26411,24 +27677,22 @@ class CommentQueryStreamController extends QueryStreamController {
26411
27677
  }
26412
27678
  }
26413
27679
 
26414
- /**
26415
- * ```js
26416
- * import { onCommentCreated } from '@amityco/ts-sdk'
26417
- * const dispose = onCommentCreated(comment => {
26418
- * // ...
26419
- * })
26420
- * ```
26421
- *
26422
- * Fired when a {@link Amity.InternalComment} has been created
26423
- *
26424
- * @param callback The function to call when the event was fired
26425
- * @returns an {@link Amity.Unsubscriber} function to stop listening
26426
- *
26427
- * @category Comment Events
26428
- */
26429
- const onCommentCreatedLocal = (callback) => {
26430
- return createLocalCommentEventSubscriber('local.comment.created', callback);
26431
- };
27680
+ class CommentPaginationController extends PaginationController {
27681
+ async getRequest(queryParams, token) {
27682
+ var _a;
27683
+ const { pageSize, limit, includeDeleted } = queryParams, params = __rest(queryParams, ["pageSize", "limit", "includeDeleted"]);
27684
+ const effectiveLimit = (_a = pageSize !== null && pageSize !== void 0 ? pageSize : limit) !== null && _a !== void 0 ? _a : COLLECTION_DEFAULT_PAGINATION_LIMIT;
27685
+ const baseOptions = {
27686
+ type: params.sortBy || queryParams.limit || queryParams.pageSize ? 'pagination' : undefined,
27687
+ };
27688
+ const options = token
27689
+ ? Object.assign(Object.assign({}, baseOptions), { token }) : Object.assign(Object.assign({}, baseOptions), { pageSize: effectiveLimit, limit: effectiveLimit });
27690
+ const { data: queryResponse } = await this.http.get(`/api/v3/comments`, {
27691
+ params: Object.assign(Object.assign({}, params), { isDeleted: inferIsDeleted(includeDeleted), options }),
27692
+ });
27693
+ return queryResponse;
27694
+ }
27695
+ }
26432
27696
 
26433
27697
  class CommentLiveCollectionController extends LiveCollectionController {
26434
27698
  constructor(query, callback) {
@@ -26464,6 +27728,7 @@ class CommentLiveCollectionController extends LiveCollectionController {
26464
27728
  { fn: onCommentCreated, action: EnumCommentActions.OnCommentCreated },
26465
27729
  { fn: onCommentUpdated, action: EnumCommentActions.OnCommentUpdated },
26466
27730
  { fn: onCommentDeleted, action: EnumCommentActions.OnCommentDeleted },
27731
+ { fn: onCommentApproved, action: EnumCommentActions.OnCommentApproved },
26467
27732
  { fn: onCommentFlagged, action: EnumCommentActions.OnCommentFlagged },
26468
27733
  { fn: onCommentUnflagged, action: EnumCommentActions.OnCommentUnflagged },
26469
27734
  { fn: onCommentReactionAdded, action: EnumCommentActions.OnCommentReactionAdded },
@@ -26497,7 +27762,8 @@ class CommentLiveCollectionController extends LiveCollectionController {
26497
27762
  });
26498
27763
  }
26499
27764
  applyFilter(data) {
26500
- let comments = data;
27765
+ // Approved-only, for every caller including the author of a pending comment
27766
+ let comments = data.filter(isCommentApproved);
26501
27767
  if (!this.query.includeDeleted) {
26502
27768
  comments = filterByPropEquality(comments, 'isDeleted', false);
26503
27769
  }
@@ -26585,7 +27851,202 @@ const getComments = (params, callback, config) => {
26585
27851
  };
26586
27852
  /* end_public_function */
26587
27853
 
26588
- var index$e = /*#__PURE__*/Object.freeze({
27854
+ class CommentReviewQueuePaginationController extends PaginationController {
27855
+ async getRequest(queryParams, token) {
27856
+ const { communityId, limit } = queryParams, params = __rest(queryParams, ["communityId", "limit"]);
27857
+ // The route defaults to 10, not the SDK-wide 20, and rejects anything above 100
27858
+ const effectiveLimit = Math.min(limit !== null && limit !== void 0 ? limit : COMMENT_REVIEW_QUEUE_DEFAULT_PAGINATION_SIZE, COMMENT_REVIEW_QUEUE_MAX_PAGINATION_SIZE);
27859
+ // Token paging only. The route also accepts options[skip], but offset paging over a queue that
27860
+ // drains from the front skips items, so the SDK never sends it.
27861
+ const options = token ? { token } : { limit: effectiveLimit };
27862
+ const { data: queryResponse } = await this.http.get(API_ENDPOINTS.commentReviewQueue(communityId), {
27863
+ params: Object.assign(Object.assign({}, params), { options }),
27864
+ });
27865
+ return queryResponse;
27866
+ }
27867
+ }
27868
+
27869
+ class CommentReviewQueueQueryStreamController extends QueryStreamController {
27870
+ constructor(query, cacheKey, notifyChange) {
27871
+ super(query, cacheKey);
27872
+ this.notifyChange = notifyChange;
27873
+ }
27874
+ async saveToMainDB(response) {
27875
+ const processedPayload = prepareCommentPayload(response);
27876
+ const client = getActiveClient();
27877
+ const cachedAt = client.cache && Date.now();
27878
+ if (client.cache) {
27879
+ ingestInCache(processedPayload, { cachedAt });
27880
+ }
27881
+ }
27882
+ appendToQueryStream(response, direction, refresh = false) {
27883
+ var _a, _b;
27884
+ // Server order is queue-entry order, oldest first. Keep it: later pages append, nothing
27885
+ // re-sorts by createdAt (the two diverge on re-review).
27886
+ const commentIds = response.comments.map(getResolver('comment'));
27887
+ if (refresh) {
27888
+ pushToCache(this.cacheKey, {
27889
+ data: commentIds,
27890
+ });
27891
+ }
27892
+ else {
27893
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
27894
+ const comments = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
27895
+ pushToCache(this.cacheKey, Object.assign(Object.assign({}, collection), { data: [...new Set([...comments, ...commentIds])] }));
27896
+ }
27897
+ }
27898
+ matchesQuery(comment) {
27899
+ return (comment.targetType === 'community' &&
27900
+ comment.targetId === this.query.communityId &&
27901
+ (!this.query.postId || comment.referenceId === this.query.postId));
27902
+ }
27903
+ reactor(action) {
27904
+ return (comment) => {
27905
+ var _a;
27906
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
27907
+ if (!collection || !this.matchesQuery(comment))
27908
+ return;
27909
+ const isQueued = collection.data.includes(comment.commentId);
27910
+ // A date-filtered queue is the server's to shape; live events only remove from it
27911
+ const acceptsLiveInserts = !this.query.startDate && !this.query.endDate;
27912
+ switch (action) {
27913
+ case EnumCommentActions.OnCommentCreated:
27914
+ case EnumCommentActions.OnCommentUpdated:
27915
+ if (isCommentPending(comment) && !comment.isDeleted) {
27916
+ if (isQueued || !acceptsLiveInserts)
27917
+ return;
27918
+ // Enters (or, after an edit, re-enters) the queue at the end
27919
+ collection.data = [...collection.data, comment.commentId];
27920
+ }
27921
+ else {
27922
+ if (!isQueued)
27923
+ return;
27924
+ collection.data = collection.data.filter(commentId => commentId !== comment.commentId);
27925
+ }
27926
+ break;
27927
+ case EnumCommentActions.OnCommentApproved:
27928
+ case EnumCommentActions.OnCommentDeleted:
27929
+ if (!isQueued)
27930
+ return;
27931
+ collection.data = collection.data.filter(commentId => commentId !== comment.commentId);
27932
+ break;
27933
+ default:
27934
+ return;
27935
+ }
27936
+ pushToCache(this.cacheKey, collection);
27937
+ this.notifyChange({ origin: "event" /* Amity.LiveDataOrigin.EVENT */, loading: false });
27938
+ };
27939
+ }
27940
+ subscribeRTE(createSubscriber) {
27941
+ return createSubscriber.map(subscriber => subscriber.fn(this.reactor(subscriber.action)));
27942
+ }
27943
+ }
27944
+
27945
+ class CommentReviewQueueLiveCollectionController extends LiveCollectionController {
27946
+ constructor(query, callback) {
27947
+ const queryStreamId = hash__default["default"](query);
27948
+ const cacheKey = ['commentReviewQueue', 'collection', queryStreamId];
27949
+ const paginationController = new CommentReviewQueuePaginationController(query);
27950
+ super(paginationController, queryStreamId, cacheKey, callback);
27951
+ this.query = query;
27952
+ this.queryStreamController = new CommentReviewQueueQueryStreamController(this.query, this.cacheKey, this.notifyChange.bind(this));
27953
+ this.callback = callback.bind(this);
27954
+ this.loadPage({ initial: true });
27955
+ }
27956
+ setup() {
27957
+ var _a;
27958
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
27959
+ if (!collection) {
27960
+ pushToCache(this.cacheKey, {
27961
+ data: [],
27962
+ params: {},
27963
+ });
27964
+ }
27965
+ }
27966
+ async persistModel(queryPayload) {
27967
+ await this.queryStreamController.saveToMainDB(queryPayload);
27968
+ }
27969
+ persistQueryStream({ response, direction, refresh, }) {
27970
+ this.queryStreamController.appendToQueryStream(response, direction, refresh);
27971
+ }
27972
+ startSubscription() {
27973
+ // No `comment.declined` exists: a decline arrives as `comment.deleted`
27974
+ return this.queryStreamController.subscribeRTE([
27975
+ { fn: onCommentCreated, action: EnumCommentActions.OnCommentCreated },
27976
+ { fn: onCommentUpdated, action: EnumCommentActions.OnCommentUpdated },
27977
+ { fn: onCommentApproved, action: EnumCommentActions.OnCommentApproved },
27978
+ { fn: onCommentDeleted, action: EnumCommentActions.OnCommentDeleted },
27979
+ { fn: onCommentDeleteLocal, action: EnumCommentActions.OnCommentDeleted },
27980
+ ]);
27981
+ }
27982
+ notifyChange({ origin, loading, error }) {
27983
+ var _a;
27984
+ // A caller who lost REVIEW_COMMUNITY_COMMENT must not keep reading stale pending content
27985
+ if ((error === null || error === void 0 ? void 0 : error.code) === 400301 /* Amity.ServerError.PERMISSION_DENIED */) {
27986
+ pushToCache(this.cacheKey, { data: [], params: {} });
27987
+ }
27988
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
27989
+ if (!collection)
27990
+ return;
27991
+ const data = collection.data
27992
+ .map(id => pullFromCache(['comment', 'get', id]))
27993
+ .filter(isNonNullable)
27994
+ .map(({ data }) => data)
27995
+ .filter(comment => isCommentPending(comment) && !comment.isDeleted)
27996
+ .map(LinkedObject.comment);
27997
+ if (!this.shouldNotify(data) && origin === 'event')
27998
+ return;
27999
+ this.callback({
28000
+ onNextPage: () => this.loadPage({ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */ }),
28001
+ data,
28002
+ hasNextPage: !!this.paginationController.getNextToken(),
28003
+ loading,
28004
+ error,
28005
+ });
28006
+ }
28007
+ }
28008
+
28009
+ /* begin_public_function
28010
+ id: comment.review_queue
28011
+ */
28012
+ /**
28013
+ * ```js
28014
+ * import { CommentRepository } from '@amityco/ts-sdk'
28015
+ *
28016
+ * const unsub = CommentRepository.getCommentReviewQueue(
28017
+ * { communityId: 'communityId' },
28018
+ * ({ data: comments, hasNextPage, onNextPage }) => {
28019
+ * // every comment is awaiting review
28020
+ * },
28021
+ * )
28022
+ * ```
28023
+ *
28024
+ * Observe the {@link Amity.Comment} list awaiting moderator review in a community, oldest first
28025
+ *
28026
+ * @param params the community to read the queue of, optionally narrowed to one post and a date range
28027
+ * @param callback the function to call when new data are available
28028
+ * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the queue
28029
+ *
28030
+ * @category Comments Live Collection
28031
+ */
28032
+ const getCommentReviewQueue = (params, callback) => {
28033
+ const { log, cache } = getActiveClient();
28034
+ if (!cache)
28035
+ console.log(ENABLE_CACHE_MESSAGE);
28036
+ const timestamp = Date.now();
28037
+ log(`getCommentReviewQueue(tmpid: ${timestamp}) > listen`);
28038
+ const commentReviewQueueLiveCollection = new CommentReviewQueueLiveCollectionController(params, callback);
28039
+ const disposers = commentReviewQueueLiveCollection.startSubscription();
28040
+ const cacheKey = commentReviewQueueLiveCollection.getCacheKey();
28041
+ disposers.push(() => dropFromCache(cacheKey));
28042
+ return () => {
28043
+ log(`getCommentReviewQueue(tmpid: ${timestamp}) > dispose`);
28044
+ disposers.forEach(fn => fn());
28045
+ };
28046
+ };
28047
+ /* end_public_function */
28048
+
28049
+ var index$f = /*#__PURE__*/Object.freeze({
26589
28050
  __proto__: null,
26590
28051
  getCommentByIds: getCommentByIds,
26591
28052
  createComment: createComment,
@@ -26593,18 +28054,22 @@ var index$e = /*#__PURE__*/Object.freeze({
26593
28054
  deleteComment: deleteComment,
26594
28055
  softDeleteComment: softDeleteComment,
26595
28056
  hardDeleteComment: hardDeleteComment,
28057
+ approveComment: approveComment,
28058
+ declineComment: declineComment,
26596
28059
  flagComment: flagComment,
26597
28060
  unflagComment: unflagComment,
26598
28061
  isCommentFlaggedByMe: isCommentFlaggedByMe,
26599
28062
  onCommentCreated: onCommentCreated,
26600
28063
  onCommentUpdated: onCommentUpdated,
26601
28064
  onCommentDeleted: onCommentDeleted,
28065
+ onCommentApproved: onCommentApproved,
26602
28066
  onCommentFlagged: onCommentFlagged,
26603
28067
  onCommentUnflagged: onCommentUnflagged,
26604
28068
  onCommentReactionAdded: onCommentReactionAdded,
26605
28069
  onCommentReactionRemoved: onCommentReactionRemoved,
26606
28070
  getComment: getComment,
26607
- getComments: getComments
28071
+ getComments: getComments,
28072
+ getCommentReviewQueue: getCommentReviewQueue
26608
28073
  });
26609
28074
 
26610
28075
  /**
@@ -27854,7 +29319,7 @@ const getForYouFeed = (callback) => {
27854
29319
  };
27855
29320
  /* end_public_function */
27856
29321
 
27857
- var index$d = /*#__PURE__*/Object.freeze({
29322
+ var index$e = /*#__PURE__*/Object.freeze({
27858
29323
  __proto__: null,
27859
29324
  queryGlobalFeed: queryGlobalFeed,
27860
29325
  getCustomRankingGlobalFeed: getCustomRankingGlobalFeed,
@@ -30999,7 +32464,7 @@ const getRooms = (params, callback, config) => {
30999
32464
  };
31000
32465
  /* end_public_function */
31001
32466
 
31002
- var index$c = /*#__PURE__*/Object.freeze({
32467
+ var index$d = /*#__PURE__*/Object.freeze({
31003
32468
  __proto__: null,
31004
32469
  createRoom: createRoom,
31005
32470
  updateRoom: updateRoom,
@@ -31298,7 +32763,7 @@ const getCommunityLiveRoomPosts = (params, callback, config) => {
31298
32763
  };
31299
32764
  /* end_public_function */
31300
32765
 
31301
- var index$b = /*#__PURE__*/Object.freeze({
32766
+ var index$c = /*#__PURE__*/Object.freeze({
31302
32767
  __proto__: null,
31303
32768
  getPostByIds: getPostByIds,
31304
32769
  createPost: createPost,
@@ -31913,7 +33378,7 @@ const getStreams = (params, callback, config) => {
31913
33378
  };
31914
33379
  };
31915
33380
 
31916
- var index$a = /*#__PURE__*/Object.freeze({
33381
+ var index$b = /*#__PURE__*/Object.freeze({
31917
33382
  __proto__: null,
31918
33383
  createStream: createStream,
31919
33384
  updateStream: updateStream,
@@ -32216,7 +33681,7 @@ const stopHeartbeat = (roomId) => {
32216
33681
  };
32217
33682
  /* end_public_function */
32218
33683
 
32219
- var index$9 = /*#__PURE__*/Object.freeze({
33684
+ var index$a = /*#__PURE__*/Object.freeze({
32220
33685
  __proto__: null,
32221
33686
  getRoomOnlineUsers: getRoomOnlineUsers,
32222
33687
  getRoomUserCount: getRoomUserCount,
@@ -32527,7 +33992,7 @@ const getPoll = (pollId, callback) => {
32527
33992
  };
32528
33993
  /* end_public_function */
32529
33994
 
32530
- var index$8 = /*#__PURE__*/Object.freeze({
33995
+ var index$9 = /*#__PURE__*/Object.freeze({
32531
33996
  __proto__: null,
32532
33997
  createPoll: createPoll,
32533
33998
  closePoll: closePoll,
@@ -32831,7 +34296,7 @@ const getPlayer = async (parameters) => {
32831
34296
  return video;
32832
34297
  };
32833
34298
 
32834
- var index$7 = /*#__PURE__*/Object.freeze({
34299
+ var index$8 = /*#__PURE__*/Object.freeze({
32835
34300
  __proto__: null,
32836
34301
  getPlayer: getPlayer
32837
34302
  });
@@ -34004,7 +35469,7 @@ const getGlobalStoryTargets = (params, callback, config) => {
34004
35469
  };
34005
35470
  };
34006
35471
 
34007
- var index$6 = /*#__PURE__*/Object.freeze({
35472
+ var index$7 = /*#__PURE__*/Object.freeze({
34008
35473
  __proto__: null,
34009
35474
  createImageStory: createImageStory,
34010
35475
  createVideoStory: createVideoStory,
@@ -34041,7 +35506,7 @@ const getNetworkAds = async () => {
34041
35506
  };
34042
35507
  };
34043
35508
 
34044
- var index$5 = /*#__PURE__*/Object.freeze({
35509
+ var index$6 = /*#__PURE__*/Object.freeze({
34045
35510
  __proto__: null,
34046
35511
  getNetworkAds: getNetworkAds
34047
35512
  });
@@ -34432,7 +35897,7 @@ const markTraySeen = async (lastSeenAt) => {
34432
35897
  };
34433
35898
  /* end_public_function */
34434
35899
 
34435
- var index$4 = /*#__PURE__*/Object.freeze({
35900
+ var index$5 = /*#__PURE__*/Object.freeze({
34436
35901
  __proto__: null,
34437
35902
  getNotificationTraySeen: getNotificationTraySeen,
34438
35903
  getNotificationTrayItems: getNotificationTrayItems,
@@ -34734,7 +36199,7 @@ const getInvitations = (params, callback) => {
34734
36199
  };
34735
36200
  };
34736
36201
 
34737
- var index$3 = /*#__PURE__*/Object.freeze({
36202
+ var index$4 = /*#__PURE__*/Object.freeze({
34738
36203
  __proto__: null,
34739
36204
  cancelInvitation: cancelInvitation,
34740
36205
  onLocalInvitationCreated: onLocalInvitationCreated,
@@ -34883,7 +36348,7 @@ const getReactions = (postId, callback) => {
34883
36348
  };
34884
36349
  };
34885
36350
 
34886
- var index$2 = /*#__PURE__*/Object.freeze({
36351
+ var index$3 = /*#__PURE__*/Object.freeze({
34887
36352
  __proto__: null,
34888
36353
  createReaction: createReaction,
34889
36354
  onLiveReactionCreated: onLiveReactionCreated,
@@ -35366,7 +36831,7 @@ const getMyEvents = (params, callback, config) => {
35366
36831
  };
35367
36832
  };
35368
36833
 
35369
- var index$1 = /*#__PURE__*/Object.freeze({
36834
+ var index$2 = /*#__PURE__*/Object.freeze({
35370
36835
  __proto__: null,
35371
36836
  createEvent: createEvent,
35372
36837
  updateEvent: updateEvent,
@@ -35593,12 +37058,36 @@ const searchProducts = (params, callback, config) => {
35593
37058
  };
35594
37059
  /* end_public_function */
35595
37060
 
35596
- var index = /*#__PURE__*/Object.freeze({
37061
+ var index$1 = /*#__PURE__*/Object.freeze({
35597
37062
  __proto__: null,
35598
37063
  getProduct: getProduct,
35599
37064
  searchProducts: searchProducts
35600
37065
  });
35601
37066
 
37067
+ const getPool = async (topicId, limit) => {
37068
+ const client = getActiveClient();
37069
+ if (!topicId)
37070
+ throw new ASCError('topicId must not be empty', 800110 /* Amity.ClientError.INVALID_PARAMETERS */, "error" /* Amity.ErrorLevel.ERROR */);
37071
+ if (limit !== undefined && (limit < 1 || limit > 100))
37072
+ throw new ASCError('limit must be between 1 and 100', 800110 /* Amity.ClientError.INVALID_PARAMETERS */, "error" /* Amity.ErrorLevel.ERROR */);
37073
+ const { data } = await client.http.get('/api/v5/curated-content/pool', { params: { topicId, limit } });
37074
+ const { topic } = data, payload = __rest(data, ["topic"]);
37075
+ const processedPayload = preparePostPayload(payload);
37076
+ const cachedAt = client.cache && Date.now();
37077
+ if (client.cache) {
37078
+ ingestInCache(processedPayload, { cachedAt });
37079
+ }
37080
+ return {
37081
+ topic: LinkedObject.curatedContentTopic(topic),
37082
+ posts: processedPayload.posts.map(LinkedObject.post),
37083
+ };
37084
+ };
37085
+
37086
+ var index = /*#__PURE__*/Object.freeze({
37087
+ __proto__: null,
37088
+ getPool: getPool
37089
+ });
37090
+
35602
37091
  /**
35603
37092
  * Helper class for managing product tags per media attachment.
35604
37093
  *
@@ -35647,39 +37136,41 @@ class AmityAttachmentProductTags {
35647
37136
  }
35648
37137
 
35649
37138
  exports.API_REGIONS = API_REGIONS;
35650
- exports.AdRepository = index$5;
37139
+ exports.AdRepository = index$6;
35651
37140
  exports.AmityAttachmentProductTags = AmityAttachmentProductTags;
35652
- exports.CategoryRepository = index$f;
35653
- exports.ChannelRepository = index$j;
35654
- exports.Client = index$s;
35655
- exports.CommentRepository = index$e;
37141
+ exports.AmityModuleNotEntitledError = AmityModuleNotEntitledError;
37142
+ exports.CategoryRepository = index$g;
37143
+ exports.ChannelRepository = index$k;
37144
+ exports.Client = index$t;
37145
+ exports.CommentRepository = index$f;
35656
37146
  exports.CommunityPostSettingMaps = CommunityPostSettingMaps;
35657
37147
  exports.CommunityPostSettings = CommunityPostSettings;
35658
- exports.CommunityRepository = index$g;
37148
+ exports.CommunityRepository = index$h;
35659
37149
  exports.ContentFeedType = ContentFeedType;
37150
+ exports.CuratedContentRepository = index;
35660
37151
  exports.DefaultCommunityPostSetting = DefaultCommunityPostSetting;
35661
- exports.EventRepository = index$1;
35662
- exports.FeedRepository = index$d;
35663
- exports.FileRepository = index$p;
37152
+ exports.EventRepository = index$2;
37153
+ exports.FeedRepository = index$e;
37154
+ exports.FileRepository = index$q;
35664
37155
  exports.FileType = FileType;
35665
37156
  exports.GET_WATCHER_URLS = GET_WATCHER_URLS;
35666
- exports.InvitationRepository = index$3;
35667
- exports.LiveReactionRepository = index$2;
35668
- exports.LiveStreamPlayer = index$7;
37157
+ exports.InvitationRepository = index$4;
37158
+ exports.LiveReactionRepository = index$3;
37159
+ exports.LiveStreamPlayer = index$8;
35669
37160
  exports.MessageContentType = MessageContentType;
35670
- exports.MessageRepository = index$n;
35671
- exports.PollRepository = index$8;
37161
+ exports.MessageRepository = index$o;
37162
+ exports.PollRepository = index$9;
35672
37163
  exports.PostContentType = PostContentType;
35673
- exports.PostRepository = index$b;
37164
+ exports.PostRepository = index$c;
35674
37165
  exports.PostStructureType = PostStructureType;
35675
- exports.ProductRepository = index;
35676
- exports.ReactionRepository = index$o;
35677
- exports.RoomPresenceRepository = index$9;
35678
- exports.RoomRepository = index$c;
35679
- exports.StoryRepository = index$6;
35680
- exports.StreamRepository = index$a;
35681
- exports.SubChannelRepository = index$m;
35682
- exports.UserRepository = index$q;
37166
+ exports.ProductRepository = index$1;
37167
+ exports.ReactionRepository = index$p;
37168
+ exports.RoomPresenceRepository = index$a;
37169
+ exports.RoomRepository = index$d;
37170
+ exports.StoryRepository = index$7;
37171
+ exports.StreamRepository = index$b;
37172
+ exports.SubChannelRepository = index$n;
37173
+ exports.UserRepository = index$r;
35683
37174
  exports.VERSION = VERSION;
35684
37175
  exports.VideoResolution = VideoResolution;
35685
37176
  exports.VideoSize = VideoSize;
@@ -35741,7 +37232,7 @@ exports.isPaged = isPaged;
35741
37232
  exports.isReportedByMe = isReportedByMe;
35742
37233
  exports.isSkip = isSkip;
35743
37234
  exports.mergeInCache = mergeInCache;
35744
- exports.notificationTray = index$4;
37235
+ exports.notificationTray = index$5;
35745
37236
  exports.onChannelMarkerFetched = onChannelMarkerFetched;
35746
37237
  exports.onFeedMarkerFetched = onFeedMarkerFetched;
35747
37238
  exports.onFeedMarkerUpdated = onFeedMarkerUpdated;
@@ -35756,6 +37247,7 @@ exports.pushToCache = pushToCache;
35756
37247
  exports.queryCache = queryCache;
35757
37248
  exports.queryOptions = queryOptions;
35758
37249
  exports.queryRoles = queryRoles;
37250
+ exports.resolveModuleAvailability = resolveModuleAvailability;
35759
37251
  exports.restoreCache = restoreCache;
35760
37252
  exports.runQuery = runQuery;
35761
37253
  exports.sortByChannelSegment = sortByChannelSegment;