@amityco/ts-sdk 0.0.1-beta.8 → 0.0.1-beta.9

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 (244) hide show
  1. package/dist/@types/core/events.d.ts +63 -17
  2. package/dist/@types/core/events.d.ts.map +1 -1
  3. package/dist/@types/core/transport.d.ts +15 -0
  4. package/dist/@types/core/transport.d.ts.map +1 -1
  5. package/dist/@types/domains/client.d.ts +3 -0
  6. package/dist/@types/domains/client.d.ts.map +1 -1
  7. package/dist/@types/domains/comment.d.ts +1 -1
  8. package/dist/@types/domains/comment.d.ts.map +1 -1
  9. package/dist/@types/domains/community.d.ts +1 -1
  10. package/dist/@types/domains/community.d.ts.map +1 -1
  11. package/dist/@types/domains/group.d.ts +2 -2
  12. package/dist/@types/domains/group.d.ts.map +1 -1
  13. package/dist/@types/domains/partials.d.ts +3 -0
  14. package/dist/@types/domains/partials.d.ts.map +1 -1
  15. package/dist/@types/domains/post.d.ts +1 -1
  16. package/dist/@types/domains/post.d.ts.map +1 -1
  17. package/dist/@types/domains/user.d.ts +2 -1
  18. package/dist/@types/domains/user.d.ts.map +1 -1
  19. package/dist/client/api/connectClient.d.ts.map +1 -1
  20. package/dist/client/api/createClient.d.ts +2 -1
  21. package/dist/client/api/createClient.d.ts.map +1 -1
  22. package/dist/client/api/disconnectClient.d.ts.map +1 -1
  23. package/dist/client/api/getToken.d.ts +3 -1
  24. package/dist/client/api/getToken.d.ts.map +1 -1
  25. package/dist/comment/api/deleteComment.d.ts +1 -0
  26. package/dist/comment/api/deleteComment.d.ts.map +1 -1
  27. package/dist/comment/events/index.d.ts +4 -0
  28. package/dist/comment/events/index.d.ts.map +1 -1
  29. package/dist/comment/events/onCommentCreated.d.ts +1 -1
  30. package/dist/comment/events/onCommentCreated.d.ts.map +1 -1
  31. package/dist/comment/events/onCommentDeleted.d.ts +1 -1
  32. package/dist/comment/events/onCommentDeleted.d.ts.map +1 -1
  33. package/dist/comment/events/onCommentFlagged.d.ts +17 -0
  34. package/dist/comment/events/onCommentFlagged.d.ts.map +1 -0
  35. package/dist/comment/events/onCommentReactionAdded.d.ts +17 -0
  36. package/dist/comment/events/onCommentReactionAdded.d.ts.map +1 -0
  37. package/dist/comment/events/onCommentReactionRemoved.d.ts +17 -0
  38. package/dist/comment/events/onCommentReactionRemoved.d.ts.map +1 -0
  39. package/dist/comment/events/onCommentUnflagged.d.ts +17 -0
  40. package/dist/comment/events/onCommentUnflagged.d.ts.map +1 -0
  41. package/dist/comment/events/onCommentUpdated.d.ts +1 -1
  42. package/dist/comment/events/onCommentUpdated.d.ts.map +1 -1
  43. package/dist/comment/events/utils.d.ts +2 -0
  44. package/dist/comment/events/utils.d.ts.map +1 -0
  45. package/dist/comment/observers/observeComment.d.ts +1 -1
  46. package/dist/comment/observers/observeComment.d.ts.map +1 -1
  47. package/dist/comment/observers/observeComments.d.ts +5 -1
  48. package/dist/comment/observers/observeComments.d.ts.map +1 -1
  49. package/dist/community/events/index.d.ts +4 -0
  50. package/dist/community/events/index.d.ts.map +1 -1
  51. package/dist/community/events/onCommunityCreated.d.ts +2 -2
  52. package/dist/community/events/onCommunityCreated.d.ts.map +1 -1
  53. package/dist/community/events/onCommunityDeleted.d.ts +2 -2
  54. package/dist/community/events/onCommunityDeleted.d.ts.map +1 -1
  55. package/dist/community/events/onCommunityJoined.d.ts +3 -3
  56. package/dist/community/events/onCommunityJoined.d.ts.map +1 -1
  57. package/dist/community/events/onCommunityLeft.d.ts +3 -3
  58. package/dist/community/events/onCommunityLeft.d.ts.map +1 -1
  59. package/dist/community/events/onCommunityUpdated.d.ts +2 -2
  60. package/dist/community/events/onCommunityUpdated.d.ts.map +1 -1
  61. package/dist/community/events/onCommunityUserAdded.d.ts +17 -0
  62. package/dist/community/events/onCommunityUserAdded.d.ts.map +1 -0
  63. package/dist/community/events/onCommunityUserBanned.d.ts +17 -0
  64. package/dist/community/events/onCommunityUserBanned.d.ts.map +1 -0
  65. package/dist/community/events/onCommunityUserRemoved.d.ts +17 -0
  66. package/dist/community/events/onCommunityUserRemoved.d.ts.map +1 -0
  67. package/dist/community/events/onCommunityUserUnbanned.d.ts +17 -0
  68. package/dist/community/events/onCommunityUserUnbanned.d.ts.map +1 -0
  69. package/dist/community/events/utils.d.ts +3 -0
  70. package/dist/community/events/utils.d.ts.map +1 -0
  71. package/dist/community/observers/observeCommunity.d.ts +1 -1
  72. package/dist/community/observers/observeCommunity.d.ts.map +1 -1
  73. package/dist/core/cache/ingest.d.ts.map +1 -1
  74. package/dist/core/events.d.ts +4 -2
  75. package/dist/core/events.d.ts.map +1 -1
  76. package/dist/core/model/index.d.ts +1 -0
  77. package/dist/core/model/index.d.ts.map +1 -1
  78. package/dist/core/model/isMatch.d.ts +3 -0
  79. package/dist/core/model/isMatch.d.ts.map +1 -0
  80. package/dist/core/network.d.ts +11 -0
  81. package/dist/core/network.d.ts.map +1 -0
  82. package/dist/core/subscription.d.ts +14 -0
  83. package/dist/core/subscription.d.ts.map +1 -0
  84. package/dist/core/transports/http.d.ts +11 -0
  85. package/dist/core/transports/http.d.ts.map +1 -0
  86. package/dist/core/transports/index.d.ts +4 -0
  87. package/dist/core/transports/index.d.ts.map +1 -0
  88. package/dist/core/transports/mqtt.d.ts +17 -0
  89. package/dist/core/transports/mqtt.d.ts.map +1 -0
  90. package/dist/core/transports/utils.d.ts +13 -0
  91. package/dist/core/transports/utils.d.ts.map +1 -0
  92. package/dist/core/transports/ws.d.ts +27 -0
  93. package/dist/core/transports/ws.d.ts.map +1 -0
  94. package/dist/index.cjs.js +1208 -514
  95. package/dist/index.d.ts +1 -0
  96. package/dist/index.d.ts.map +1 -1
  97. package/dist/index.esm.js +1185 -515
  98. package/dist/index.umd.js +5 -3
  99. package/dist/post/api/deletePost.d.ts +1 -0
  100. package/dist/post/api/deletePost.d.ts.map +1 -1
  101. package/dist/post/events/index.d.ts +6 -0
  102. package/dist/post/events/index.d.ts.map +1 -1
  103. package/dist/post/events/onPostApproved.d.ts +17 -0
  104. package/dist/post/events/onPostApproved.d.ts.map +1 -0
  105. package/dist/post/events/onPostCreated.d.ts +1 -1
  106. package/dist/post/events/onPostCreated.d.ts.map +1 -1
  107. package/dist/post/events/onPostDeclined.d.ts +17 -0
  108. package/dist/post/events/onPostDeclined.d.ts.map +1 -0
  109. package/dist/post/events/onPostDeleted.d.ts +1 -1
  110. package/dist/post/events/onPostDeleted.d.ts.map +1 -1
  111. package/dist/post/events/onPostFlagged.d.ts +17 -0
  112. package/dist/post/events/onPostFlagged.d.ts.map +1 -0
  113. package/dist/post/events/onPostReactionAdded.d.ts +17 -0
  114. package/dist/post/events/onPostReactionAdded.d.ts.map +1 -0
  115. package/dist/post/events/onPostReactionRemoved.d.ts +17 -0
  116. package/dist/post/events/onPostReactionRemoved.d.ts.map +1 -0
  117. package/dist/post/events/onPostUnflagged.d.ts +17 -0
  118. package/dist/post/events/onPostUnflagged.d.ts.map +1 -0
  119. package/dist/post/events/onPostUpdated.d.ts +1 -1
  120. package/dist/post/events/onPostUpdated.d.ts.map +1 -1
  121. package/dist/post/events/utils.d.ts +2 -0
  122. package/dist/post/events/utils.d.ts.map +1 -0
  123. package/dist/post/observers/observePost.d.ts +1 -1
  124. package/dist/post/observers/observePost.d.ts.map +1 -1
  125. package/dist/post/observers/observePosts.d.ts +1 -1
  126. package/dist/post/observers/observePosts.d.ts.map +1 -1
  127. package/dist/reaction/events/onReactionAdded.d.ts +4 -2
  128. package/dist/reaction/events/onReactionAdded.d.ts.map +1 -1
  129. package/dist/reaction/events/onReactionRemoved.d.ts +4 -2
  130. package/dist/reaction/events/onReactionRemoved.d.ts.map +1 -1
  131. package/dist/reaction/utils/index.d.ts +1 -0
  132. package/dist/reaction/utils/index.d.ts.map +1 -1
  133. package/dist/reaction/utils/preparePayloadForCache.d.ts +3 -0
  134. package/dist/reaction/utils/preparePayloadForCache.d.ts.map +1 -0
  135. package/dist/report/api/createReport.d.ts.map +1 -1
  136. package/dist/report/api/deleteReport.d.ts.map +1 -1
  137. package/dist/user/events/index.d.ts +3 -0
  138. package/dist/user/events/index.d.ts.map +1 -1
  139. package/dist/user/events/onUserFlagCleared.d.ts +17 -0
  140. package/dist/user/events/onUserFlagCleared.d.ts.map +1 -0
  141. package/dist/user/events/onUserFlagged.d.ts +17 -0
  142. package/dist/user/events/onUserFlagged.d.ts.map +1 -0
  143. package/dist/user/events/onUserUnflagged.d.ts +17 -0
  144. package/dist/user/events/onUserUnflagged.d.ts.map +1 -0
  145. package/dist/user/events/onUserUpdated.d.ts +1 -1
  146. package/dist/user/events/onUserUpdated.d.ts.map +1 -1
  147. package/dist/user/events/utils.d.ts +2 -0
  148. package/dist/user/events/utils.d.ts.map +1 -0
  149. package/dist/user/observers/observeUser.d.ts +1 -1
  150. package/dist/user/observers/observeUser.d.ts.map +1 -1
  151. package/package.json +4 -1
  152. package/rollup.config.js +2 -2
  153. package/src/@types/core/events.ts +64 -23
  154. package/src/@types/core/transport.ts +14 -0
  155. package/src/@types/domains/client.ts +3 -0
  156. package/src/@types/domains/comment.ts +1 -0
  157. package/src/@types/domains/community.ts +1 -0
  158. package/src/@types/domains/group.ts +2 -2
  159. package/src/@types/domains/partials.ts +4 -0
  160. package/src/@types/domains/post.ts +1 -0
  161. package/src/@types/domains/user.ts +2 -0
  162. package/src/client/api/connectClient.ts +12 -2
  163. package/src/client/api/createClient.ts +7 -7
  164. package/src/client/api/disconnectClient.ts +5 -0
  165. package/src/client/api/getToken.ts +1 -1
  166. package/src/client/events/onConnectionError.ts +1 -1
  167. package/src/comment/api/createComment.ts +2 -2
  168. package/src/comment/api/deleteComment.ts +2 -2
  169. package/src/comment/api/updateComment.ts +1 -1
  170. package/src/comment/events/index.ts +6 -0
  171. package/src/comment/events/onCommentCreated.ts +4 -22
  172. package/src/comment/events/onCommentDeleted.ts +4 -22
  173. package/src/comment/events/onCommentFlagged.ts +21 -0
  174. package/src/comment/events/onCommentReactionAdded.ts +52 -0
  175. package/src/comment/events/onCommentReactionRemoved.ts +52 -0
  176. package/src/comment/events/onCommentUnflagged.ts +21 -0
  177. package/src/comment/events/onCommentUpdated.ts +4 -22
  178. package/src/comment/events/utils.ts +34 -0
  179. package/src/comment/observers/observeComment.ts +21 -7
  180. package/src/comment/observers/observeComments.ts +11 -3
  181. package/src/community/api/addCommunityMembers.ts +1 -1
  182. package/src/community/api/createCommunity.ts +1 -1
  183. package/src/community/api/deleteCommunity.ts +1 -1
  184. package/src/community/api/joinCommunity.ts +1 -1
  185. package/src/community/api/leaveCommunity.ts +1 -1
  186. package/src/community/api/removeCommunityMembers.ts +1 -1
  187. package/src/community/api/updateCommunity.ts +1 -1
  188. package/src/community/events/index.ts +5 -0
  189. package/src/community/events/onCommunityCreated.ts +5 -23
  190. package/src/community/events/onCommunityDeleted.ts +5 -23
  191. package/src/community/events/onCommunityJoined.ts +5 -23
  192. package/src/community/events/onCommunityLeft.ts +5 -23
  193. package/src/community/events/onCommunityUpdated.ts +5 -23
  194. package/src/community/events/onCommunityUserAdded.ts +19 -0
  195. package/src/community/events/onCommunityUserBanned.ts +19 -0
  196. package/src/community/events/onCommunityUserRemoved.ts +19 -0
  197. package/src/community/events/onCommunityUserUnbanned.ts +19 -0
  198. package/src/community/events/utils.ts +108 -0
  199. package/src/community/observers/observeCommunity.ts +23 -9
  200. package/src/core/cache/ingest.ts +19 -3
  201. package/src/core/events.ts +45 -4
  202. package/src/core/model/index.ts +1 -0
  203. package/src/core/model/isMatch.ts +12 -0
  204. package/src/core/network.ts +14 -0
  205. package/src/core/subscription.ts +75 -0
  206. package/src/core/transports/http.ts +63 -0
  207. package/src/core/transports/index.ts +3 -0
  208. package/src/core/transports/mqtt.ts +141 -0
  209. package/src/core/transports/utils.ts +25 -0
  210. package/src/core/transports/ws.ts +61 -0
  211. package/src/index.ts +1 -0
  212. package/src/post/api/createPost.ts +2 -2
  213. package/src/post/api/deletePost.ts +2 -2
  214. package/src/post/api/updatePost.ts +1 -1
  215. package/src/post/events/index.ts +9 -0
  216. package/src/post/events/onPostApproved.ts +19 -0
  217. package/src/post/events/onPostCreated.ts +4 -24
  218. package/src/post/events/onPostDeclined.ts +19 -0
  219. package/src/post/events/onPostDeleted.ts +4 -24
  220. package/src/post/events/onPostFlagged.ts +19 -0
  221. package/src/post/events/onPostReactionAdded.ts +50 -0
  222. package/src/post/events/onPostReactionRemoved.ts +50 -0
  223. package/src/post/events/onPostUnflagged.ts +19 -0
  224. package/src/post/events/onPostUpdated.ts +4 -24
  225. package/src/post/events/utils.ts +40 -0
  226. package/src/post/observers/observePost.ts +25 -7
  227. package/src/post/observers/observePosts.ts +12 -2
  228. package/src/reaction/events/onReactionAdded.ts +36 -15
  229. package/src/reaction/events/onReactionRemoved.ts +37 -14
  230. package/src/reaction/utils/dispatchReactable.ts +2 -2
  231. package/src/reaction/utils/index.ts +1 -0
  232. package/src/reaction/utils/preparePayloadForCache.ts +45 -0
  233. package/src/report/api/createReport.ts +5 -1
  234. package/src/report/api/deleteReport.ts +5 -1
  235. package/src/user/events/index.ts +4 -0
  236. package/src/user/events/onUserFlagCleared.ts +19 -0
  237. package/src/user/events/onUserFlagged.ts +19 -0
  238. package/src/user/events/onUserUnflagged.ts +19 -0
  239. package/src/user/events/onUserUpdated.ts +4 -24
  240. package/src/user/events/utils.ts +24 -0
  241. package/src/user/observers/observeUser.ts +11 -3
  242. package/dist/core/transports.d.ts +0 -49
  243. package/dist/core/transports.d.ts.map +0 -1
  244. package/src/core/transports.ts +0 -151
package/dist/index.esm.js CHANGED
@@ -1,15 +1,17 @@
1
+ import isMatchWith from 'lodash.ismatchwith';
1
2
  import { encode, decode } from 'js-base64';
2
3
  import nativeIdGenerator from 'react-native-uuid';
3
4
  import debug from 'debug';
4
5
  import axios from 'axios';
5
6
  import HttpAgent, { HttpsAgent } from 'agentkeepalive';
6
7
  import io from 'socket.io-client';
8
+ import mqtt from 'mqtt';
7
9
  import mitt from 'mitt';
8
10
  import AsyncStorage from '@react-native-async-storage/async-storage';
9
11
 
10
12
  var _a;
11
13
  // used in createClient
12
- const VERSION$1 = (_a = 'v0.0.1-beta.8-esm') !== null && _a !== void 0 ? _a : '__dev__';
14
+ const VERSION$1 = (_a = 'v0.0.1-beta.9-esm') !== null && _a !== void 0 ? _a : '__dev__';
13
15
 
14
16
  /**
15
17
  * Generic ASC error
@@ -276,24 +278,6 @@ const syncInCache = (original, replacement) => {
276
278
  pushToCache(name, replacement);
277
279
  };
278
280
 
279
- /**
280
- * Ingest a payload (v3) into the cache
281
- *
282
- * @param payload a "backend v3" payload object
283
- * @param order the order of the keys to process (in case of need)
284
- *
285
- * @category Cache
286
- */
287
- const ingestInCache = (payload = {}, order = Object.keys(payload)) => {
288
- order
289
- .forEach(key => {
290
- const name = storeInterests[key];
291
- if (!name)
292
- return;
293
- pushToCache(name, ...payload[key]);
294
- });
295
- };
296
-
297
281
  /**
298
282
  * Apply partial mutation to objects in the cache
299
283
  *
@@ -325,6 +309,58 @@ const mergeInCache = (name, mutation) => {
325
309
  mutateCache(name, key, model => (Object.assign(Object.assign({}, model), mutation)));
326
310
  };
327
311
 
312
+ /**
313
+ * converts an array looking collection to an object collection, grouped by localId
314
+ *
315
+ * @param array array of {@link Amity.Syncable}
316
+ * @returns array converted to object, grouped by localId
317
+ *
318
+ * @hidden
319
+ */
320
+ const toRecord = (array) => (array.reduce((acc, item) => (Object.assign(Object.assign({}, acc), { [item.localId]: item })), {}));
321
+
322
+ /** @hidden */
323
+ const isMatch = (model1, model2) => {
324
+ const customizer = (oldValue, newValue, key) => {
325
+ if (key === 'syncedAt') {
326
+ return true;
327
+ }
328
+ };
329
+ return isMatchWith(model1, model2, customizer);
330
+ };
331
+
332
+ /**
333
+ * Ingest a payload (v3) into the cache
334
+ *
335
+ * @param payload a "backend v3" payload object
336
+ * @param order the order of the keys to process (in case of need)
337
+ *
338
+ * @category Cache
339
+ */
340
+ const ingestInCache = (payload = {}, order = Object.keys(payload)) => {
341
+ order
342
+ .forEach(key => {
343
+ const name = storeInterests[key];
344
+ if (!name)
345
+ return;
346
+ payload[key].forEach(model => {
347
+ var _a;
348
+ const [cached] = (_a = pullFromCache(name, getResolver(name)(model))) !== null && _a !== void 0 ? _a : [];
349
+ if (cached) {
350
+ // > instead of >= - some updates like reactions do not change updatedAt
351
+ if (cached.updatedAt && cached.updatedAt > model.updatedAt) {
352
+ return;
353
+ }
354
+ // personal fields like isJoined, myReactions are missed from real time event payload
355
+ mergeInCache(name, model);
356
+ }
357
+ else {
358
+ pushToCache(name, model);
359
+ }
360
+ });
361
+ });
362
+ };
363
+
328
364
  /**
329
365
  * Creates a cache instance. The cache instance will handle stores
330
366
  * given to it as input, and will be used as the first source of cached data
@@ -755,6 +791,45 @@ const createLogger = (session) => {
755
791
  return print;
756
792
  };
757
793
 
794
+ const API_ENDPOINT = {
795
+ EU: 'eu',
796
+ SG: 'sg',
797
+ US: 'us',
798
+ };
799
+ var UrlTemplate;
800
+ (function (UrlTemplate) {
801
+ UrlTemplate["HTTP"] = "https://api.{region}.amity.co";
802
+ UrlTemplate["MQTT"] = "wss://sse.{region}.amity.co:443/mqtt";
803
+ })(UrlTemplate || (UrlTemplate = {}));
804
+ const getUrlFromTemplate = (template, region) => {
805
+ return template.replace('{region}', region);
806
+ };
807
+
808
+ /**
809
+ * Unwraps v3 server payload (for error handling and type extraction)
810
+ *
811
+ * @param response A typical "v3" response (related to backend's service strategy)
812
+ *
813
+ * @returns The data returned by the backend
814
+ * @throws An error related to backend's rejection
815
+ *
816
+ * @category Transport
817
+ * @hidden
818
+ */
819
+ const unwrapPayload = (response) => {
820
+ if (response.status === 'success') {
821
+ return response.data;
822
+ }
823
+ else if (response.status === 'fail') {
824
+ throw new ASCUnknownError(response.code);
825
+ }
826
+ else if (response.status === 'error') {
827
+ throw new ASCApiError(response.message, response.code, "error" /* ERROR */);
828
+ }
829
+ // unjust, but helps force uncast "T | undefined" to allow deconstruction without warnings
830
+ return undefined;
831
+ };
832
+
758
833
  /**
759
834
  * Axios param serializer (for querystring)
760
835
  * @hidden
@@ -783,7 +858,7 @@ const stringify = (params, prefix) => {
783
858
  * @category Transport
784
859
  * @hidden
785
860
  */
786
- const createHttpTransport = (endpoint = 'https://api.amity.co') => {
861
+ const createHttpTransport = (endpoint) => {
787
862
  const options = {
788
863
  maxSockets: 100,
789
864
  maxFreeSockets: 10,
@@ -804,7 +879,8 @@ const createHttpTransport = (endpoint = 'https://api.amity.co') => {
804
879
  unwrapPayload(response.data);
805
880
  });
806
881
  return instance;
807
- };
882
+ };
883
+
808
884
  /**
809
885
  * Creates a pre-configured socket.io instance
810
886
  *
@@ -814,42 +890,19 @@ const createHttpTransport = (endpoint = 'https://api.amity.co') => {
814
890
  * @category Transport
815
891
  * @hidden
816
892
  */
817
- const createWebsocketTransport = (endpoint = 'https://api.ekomedia.technology') => {
893
+ const createWebsocketTransport = (endpoint) => {
818
894
  const socket = io(endpoint, {
819
895
  autoConnect: false,
820
896
  reconnectionDelay: 2000,
821
897
  transports: ['websocket'],
822
898
  });
899
+ // FIXME: disconnectClient removes this listener and client can get global ban event
823
900
  socket.on('disconnect', (reason) => {
824
901
  if (reason === 'io server disconnect')
825
902
  socket.connect();
826
903
  });
827
904
  return socket;
828
905
  };
829
- /**
830
- * Unwraps v3 server payload (for error handling and type extraction)
831
- *
832
- * @param response A typical "v3" response (related to backend's service strategy)
833
- *
834
- * @returns The data returned by the backend
835
- * @throws An error related to backend's rejection
836
- *
837
- * @category Transport
838
- * @hidden
839
- */
840
- const unwrapPayload = (response) => {
841
- if (response.status === 'success') {
842
- return response.data;
843
- }
844
- else if (response.status === 'fail') {
845
- throw new ASCUnknownError(response.code);
846
- }
847
- else if (response.status === 'error') {
848
- throw new ASCApiError(response.message, response.code, "error" /* ERROR */);
849
- }
850
- // unjust, but helps force uncast "T | undefined" to allow deconstruction without warnings
851
- return undefined;
852
- };
853
906
  /**
854
907
  * Promisify a websocket event emission - resulting in a synchronous http-like XHR (ws legacy)
855
908
  *
@@ -879,14 +932,131 @@ const synchronousWSCall = async (client, event, data) => {
879
932
  return value;
880
933
  };
881
934
 
935
+ const QOS_FAILURE_CODE = 128;
936
+ const RETRY_BASE_TIMEOUT = 1000;
937
+ const RETRY_COUNT_MAX = 10;
938
+ var MqttError;
939
+ (function (MqttError) {
940
+ MqttError[MqttError["IDENTIFIER_REJECTED"] = 2] = "IDENTIFIER_REJECTED";
941
+ MqttError[MqttError["BAD_USERNAME_OR_PASSWORD"] = 4] = "BAD_USERNAME_OR_PASSWORD";
942
+ MqttError[MqttError["NOT_AUTHORIZED"] = 5] = "NOT_AUTHORIZED";
943
+ })(MqttError || (MqttError = {}));
944
+ function getMqttOptions(params) {
945
+ return Object.assign({ clean: false, clientId: `mqttjs_ + ${Math.random().toString(16).substr(2, 8)}`, protocolId: 'MQTT', protocolVersion: 4, reconnectPeriod: 0, will: {
946
+ topic: 'WillMsg',
947
+ payload: 'Connection Closed abnormally..!',
948
+ qos: 0,
949
+ retain: false
950
+ } }, params);
951
+ }
952
+ /**
953
+ * Creates a pre-configured socket.io instance
954
+ *
955
+ * @param endpoint The mqtt server's URL
956
+ * @returns A pre-configured (non-connected) mqtt client instance
957
+ *
958
+ * @category Transport
959
+ * @hidden
960
+ */
961
+ const createMqttTransport = (endpoint) => {
962
+ let mqttClient;
963
+ let retryCount = 0;
964
+ let allowReconnection = true;
965
+ async function connect(params) {
966
+ if (mqttClient) {
967
+ mqttClient.removeAllListeners();
968
+ mqttClient.end(true);
969
+ }
970
+ mqttClient = mqtt.connect(endpoint, getMqttOptions({ username: params.userId, password: params.accessToken }));
971
+ mqttClient.on('connect', () => {
972
+ retryCount = 0;
973
+ allowReconnection = true;
974
+ });
975
+ mqttClient.on('error', (error) => {
976
+ switch (error.code) {
977
+ case 2 /* IDENTIFIER_REJECTED */:
978
+ case 4 /* BAD_USERNAME_OR_PASSWORD */:
979
+ case 5 /* NOT_AUTHORIZED */:
980
+ allowReconnection = false;
981
+ }
982
+ });
983
+ mqttClient.on('close', () => {
984
+ if (allowReconnection) {
985
+ reconnect();
986
+ }
987
+ });
988
+ return new Promise(resolve => mqttClient.once('connect', () => resolve()));
989
+ }
990
+ const reconnect = () => {
991
+ setTimeout(() => {
992
+ retryCount = retryCount + 1;
993
+ mqttClient.reconnect();
994
+ }, RETRY_BASE_TIMEOUT * Math.pow(2, retryCount > RETRY_COUNT_MAX ? RETRY_COUNT_MAX : retryCount));
995
+ };
996
+ return {
997
+ connect,
998
+ async disconnect() {
999
+ allowReconnection = false;
1000
+ if (this.connected) {
1001
+ return new Promise(resolve => mqttClient === null || mqttClient === void 0 ? void 0 : mqttClient.end(true, undefined, () => resolve()));
1002
+ }
1003
+ },
1004
+ get connected() {
1005
+ return !!(mqttClient === null || mqttClient === void 0 ? void 0 : mqttClient.connected);
1006
+ },
1007
+ on(event, handler) {
1008
+ mqttClient === null || mqttClient === void 0 ? void 0 : mqttClient.on(event, handler);
1009
+ },
1010
+ once(event, handler) {
1011
+ mqttClient === null || mqttClient === void 0 ? void 0 : mqttClient.once(event, handler);
1012
+ },
1013
+ off(event, handler) {
1014
+ if (handler !== undefined) {
1015
+ mqttClient === null || mqttClient === void 0 ? void 0 : mqttClient.off(event, handler);
1016
+ }
1017
+ else {
1018
+ mqttClient === null || mqttClient === void 0 ? void 0 : mqttClient.removeAllListeners(event);
1019
+ }
1020
+ },
1021
+ removeAllListeners() {
1022
+ mqttClient === null || mqttClient === void 0 ? void 0 : mqttClient.removeAllListeners();
1023
+ },
1024
+ subscribe(topic, callback) {
1025
+ const callbackWrapper = (error, granted) => {
1026
+ if (error || granted[0].qos === QOS_FAILURE_CODE) {
1027
+ const ascError = error
1028
+ ? new ASCError(error.message, 800000 /* UNKNOWN_ERROR */, "error" /* ERROR */)
1029
+ // TODO throw the actual error, once BE can tell us the actual error code
1030
+ : new ASCUnknownError(800000 /* UNKNOWN_ERROR */, "error" /* ERROR */);
1031
+ console.error(`Failed to subscribe to topic ${topic}`, ascError);
1032
+ callback === null || callback === void 0 ? void 0 : callback(ascError);
1033
+ }
1034
+ else {
1035
+ console.log(`Subscribed to topic ${granted[0].topic}`);
1036
+ callback === null || callback === void 0 ? void 0 : callback();
1037
+ }
1038
+ };
1039
+ if (mqttClient) {
1040
+ mqttClient.subscribe(topic, { qos: 0 }, callbackWrapper);
1041
+ }
1042
+ else {
1043
+ callbackWrapper(new Error('No connection to broker'), []);
1044
+ }
1045
+ return () => mqttClient === null || mqttClient === void 0 ? void 0 : mqttClient.unsubscribe(topic);
1046
+ },
1047
+ unsubscribe(topic) {
1048
+ mqttClient === null || mqttClient === void 0 ? void 0 : mqttClient.unsubscribe(topic);
1049
+ }
1050
+ };
1051
+ };
1052
+
882
1053
  // need to sync up the list
883
- const EVENTS$1 = [
1054
+ const WS_EVENTS = [
884
1055
  'disconnected',
885
1056
  'error',
886
1057
  'connect_error',
887
1058
  'reconnect_error',
888
1059
  'reconnect_failed',
889
- 'v3.user.didUpdate',
890
1060
  'v3.channel.didUpdate',
891
1061
  'v3.channel.didUpdate',
892
1062
  'v3.channel.didJoin',
@@ -899,6 +1069,15 @@ const EVENTS$1 = [
899
1069
  'v3.message.didUpdate',
900
1070
  'v3.message.didDelete',
901
1071
  ];
1072
+ const MQTT_EVENTS = [
1073
+ 'connect',
1074
+ 'message',
1075
+ 'disconnect',
1076
+ 'error',
1077
+ 'close',
1078
+ 'end',
1079
+ 'reconnect'
1080
+ ];
902
1081
  /** @hidden */
903
1082
  const createEventEmitter = () => {
904
1083
  return mitt();
@@ -914,10 +1093,20 @@ const createEventEmitter = () => {
914
1093
  * @hidden
915
1094
  */
916
1095
  const proxyWebsocketEvents = (ws, emitter) => {
917
- EVENTS$1.forEach(event => {
1096
+ WS_EVENTS.forEach(event => {
918
1097
  ws.on(event, (param) => emitter.emit(event, param));
919
1098
  });
920
1099
  };
1100
+ const proxyMqttEvents = (mqttClient, emitter) => {
1101
+ MQTT_EVENTS.forEach(event => {
1102
+ mqttClient.on(event, (...params) => emitter.emit(event, params.length === 1 ? params[0] : params));
1103
+ });
1104
+ // @ts-ignore
1105
+ mqttClient.on('message', (topic, payload) => {
1106
+ const message = JSON.parse(payload.toString());
1107
+ emitter.emit(message.eventType, message.data);
1108
+ });
1109
+ };
921
1110
  /**
922
1111
  * Standardize the subscription of SSE through web sockets
923
1112
  *
@@ -969,14 +1158,15 @@ const fireEvent = (event, payload) => {
969
1158
  *
970
1159
  * @category Client API
971
1160
  **/
972
- const createClient = (apiKey, apiEndpoint = 'https://api.amity.co', debugSession = 'amity') => {
1161
+ const createClient = (apiKey, apiEndpoint = API_ENDPOINT.SG, debugSession = 'amity') => {
973
1162
  const log = createLogger(debugSession);
974
1163
  log('client/api/createClient', {
975
1164
  apiKey: apiKey.replace(/.{5}$/g, 'xxxxx'),
976
1165
  apiEndpoint,
977
1166
  });
978
- const http = createHttpTransport(apiEndpoint);
979
- const ws = createWebsocketTransport(apiEndpoint);
1167
+ const http = createHttpTransport(getUrlFromTemplate(UrlTemplate.HTTP, apiEndpoint));
1168
+ const ws = createWebsocketTransport(getUrlFromTemplate(UrlTemplate.HTTP, apiEndpoint));
1169
+ const mqtt = createMqttTransport(getUrlFromTemplate(UrlTemplate.MQTT, apiEndpoint));
980
1170
  const emitter = createEventEmitter();
981
1171
  const client = {
982
1172
  version: `${VERSION$1}`,
@@ -984,6 +1174,7 @@ const createClient = (apiKey, apiEndpoint = 'https://api.amity.co', debugSession
984
1174
  log,
985
1175
  http,
986
1176
  ws,
1177
+ mqtt,
987
1178
  emitter,
988
1179
  use: () => setActiveClient(client),
989
1180
  };
@@ -996,6 +1187,38 @@ const createClient = (apiKey, apiEndpoint = 'https://api.amity.co', debugSession
996
1187
  return client;
997
1188
  };
998
1189
 
1190
+ /**
1191
+ * ```js
1192
+ * import { disconnectClient } from '@amityco/ts-sdk'
1193
+ * const success = await disconnectClient()
1194
+ * ```
1195
+ *
1196
+ * Disconnects an {@link Amity.Client} instance from ASC servers
1197
+ *
1198
+ * @param client The {@link Amity.Client} instance to disconnect
1199
+ * @returns a success boolean if disconnected
1200
+ *
1201
+ * @category Client API
1202
+ * @async
1203
+ */
1204
+ const disconnectClient = async () => {
1205
+ const client = getActiveClient();
1206
+ client.log('client/api/disconnectClient');
1207
+ await new Promise(resolve => {
1208
+ client.ws.once('disconnect', resolve);
1209
+ client.ws.disconnect();
1210
+ client.mqtt.disconnect();
1211
+ });
1212
+ client.emitter.all.clear();
1213
+ // FIXME: it removes listener in ws.ts, it breaks global ban event
1214
+ client.ws.removeAllListeners();
1215
+ client.mqtt.removeAllListeners();
1216
+ client.userId = undefined;
1217
+ client.user = undefined;
1218
+ client.accessToken = undefined;
1219
+ return !client.ws.connected;
1220
+ };
1221
+
999
1222
  // TODO: find a way to uniquely identify the device
1000
1223
  // import { getStorage } from './storage'
1001
1224
  /** @hidden */
@@ -1052,6 +1275,83 @@ const getToken = async (params) => {
1052
1275
  return data;
1053
1276
  };
1054
1277
 
1278
+ const EVENTS = [
1279
+ 'disconnected',
1280
+ 'error',
1281
+ 'connect_error',
1282
+ 'reconnect_error',
1283
+ 'reconnect_failed',
1284
+ ];
1285
+ /**
1286
+ * ```js
1287
+ * import { onConnectionError } from '@amityco/ts-sdk'
1288
+ * const dispose = onClientBanned(() => {
1289
+ * // ...
1290
+ * })
1291
+ * ```
1292
+ *
1293
+ * Fired when any {@link Amity.Client} have been banned from the platform
1294
+ *
1295
+ * @param callback The function to call when the event was fired
1296
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
1297
+ *
1298
+ * @category Client Events
1299
+ */
1300
+ const onConnectionError = (callback) => {
1301
+ const client = getActiveClient();
1302
+ const subscribers = EVENTS.map(event => (createEventSubscriber(client, `client/onConnectionError(${event})`, event, (response) => {
1303
+ const error = (response && 'code' in response)
1304
+ ? new ASCError(response.message, response.code, "fatal" /* FATAL */)
1305
+ : new ASCConnectionError(event);
1306
+ callback(error);
1307
+ })));
1308
+ return () => {
1309
+ subscribers.forEach(fn => fn());
1310
+ };
1311
+ };
1312
+
1313
+ /**
1314
+ * ```js
1315
+ * import { onClientDisconnected } from '@amityco/ts-sdk'
1316
+ * const dispose = onClientDisconnected(() => {
1317
+ * // ...
1318
+ * })
1319
+ * ```
1320
+ *
1321
+ * Fired when any {@link Amity.Client} have been disconnected
1322
+ *
1323
+ * @param callback The function to call when the event was fired
1324
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
1325
+ *
1326
+ * @category Client Events
1327
+ */
1328
+ const onClientDisconnected = (callback) => {
1329
+ return onConnectionError(({ code }) => {
1330
+ code === 800211 /* DISCONNECTED */ && callback();
1331
+ });
1332
+ };
1333
+
1334
+ /**
1335
+ * ```js
1336
+ * import { onClientBanned } from '@amityco/ts-sdk'
1337
+ * const dispose = onClientBanned(() => {
1338
+ * // ...
1339
+ * })
1340
+ * ```
1341
+ *
1342
+ * Fired when any {@link Amity.Client} have been banned from the platform
1343
+ *
1344
+ * @param callback The function to call when the event was fired
1345
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
1346
+ *
1347
+ * @category Client Events
1348
+ */
1349
+ const onClientBanned = (callback) => {
1350
+ return onConnectionError(({ code }) => {
1351
+ code === 400312 /* GLOBAL_BAN */ && callback();
1352
+ });
1353
+ };
1354
+
1055
1355
  /**
1056
1356
  * ```js
1057
1357
  * import { connectClient } from '@amityco/ts-sdk/client/api'
@@ -1080,11 +1380,12 @@ const connectClient = async (params) => {
1080
1380
  (_b = params.deviceId) !== null && _b !== void 0 ? _b : (params.deviceId = getDeviceId());
1081
1381
  // @ts-ignore: in that particular case, typing can be
1082
1382
  // ignored since we enforce default values just before.
1083
- const { accessToken } = await getToken(params);
1383
+ const { accessToken, users } = await getToken(params);
1084
1384
  // manually setup the token for http transport
1085
1385
  client.http.defaults.headers.common['Authorization'] = `Bearer ${accessToken}`;
1086
1386
  // manually setup the token for ws transport
1087
1387
  client.ws.io.opts.query = { token: accessToken };
1388
+ // FIXME: events are duplicated if connectClient is called few times without disconnectClient
1088
1389
  // wire websocket events to our event emitter
1089
1390
  proxyWebsocketEvents(client.ws, client.emitter);
1090
1391
  // TODO: in phase 2, this should not be necessary. we should have WS
@@ -1093,41 +1394,20 @@ const connectClient = async (params) => {
1093
1394
  client.ws.once('connect', resolve);
1094
1395
  client.ws.open();
1095
1396
  });
1397
+ const unsubscribe = onClientBanned(() => {
1398
+ disconnectClient();
1399
+ unsubscribe();
1400
+ });
1096
1401
  client.userId = params.userId;
1402
+ client.user = users[0];
1403
+ client.accessToken = accessToken;
1097
1404
  return client.ws.connected;
1098
1405
  };
1099
1406
 
1100
1407
  /**
1101
1408
  * ```js
1102
- * import { disconnectClient } from '@amityco/ts-sdk'
1103
- * const success = await disconnectClient()
1104
- * ```
1105
- *
1106
- * Disconnects an {@link Amity.Client} instance from ASC servers
1107
- *
1108
- * @param client The {@link Amity.Client} instance to disconnect
1109
- * @returns a success boolean if disconnected
1110
- *
1111
- * @category Client API
1112
- * @async
1113
- */
1114
- const disconnectClient = async () => {
1115
- const client = getActiveClient();
1116
- client.log('client/api/disconnectClient');
1117
- await new Promise(resolve => {
1118
- client.ws.once('disconnect', resolve);
1119
- client.ws.disconnect();
1120
- });
1121
- client.emitter.all.clear();
1122
- client.ws.removeAllListeners();
1123
- client.userId = undefined;
1124
- return !client.ws.connected;
1125
- };
1126
-
1127
- /**
1128
- * ```js
1129
- * import { isConnected } from '@amityco/ts-sdk'
1130
- * const connected = isConnected()
1409
+ * import { isConnected } from '@amityco/ts-sdk'
1410
+ * const connected = isConnected()
1131
1411
  * ```
1132
1412
  *
1133
1413
  * Checks if a {@link Amity.Client} instance is connected to ASC servers
@@ -1280,16 +1560,6 @@ const clearCache = (stores = ['user', 'file', 'channel', 'message', 'community',
1280
1560
  stores.forEach(store => { var _a, _b; return (_b = (_a = client.cache) === null || _a === void 0 ? void 0 : _a[store]) === null || _b === void 0 ? void 0 : _b.erase(); });
1281
1561
  };
1282
1562
 
1283
- /**
1284
- * converts an array looking collection to an object collection, grouped by localId
1285
- *
1286
- * @param array array of {@link Amity.Syncable}
1287
- * @returns array converted to object, grouped by localId
1288
- *
1289
- * @hidden
1290
- */
1291
- const toRecord = (array) => (array.reduce((acc, item) => (Object.assign(Object.assign({}, acc), { [item.localId]: item })), {}));
1292
-
1293
1563
  /**
1294
1564
  * Set the model's syncedAt property and localId
1295
1565
  *
@@ -1375,82 +1645,51 @@ const sortByLastCreated = ({ createdAt: a }, { createdAt: b }) => new Date(b).va
1375
1645
  */
1376
1646
  const sortByLastActivity = ({ lastActivity: a }, { lastActivity: b }) => new Date(b).valueOf() - new Date(a).valueOf();
1377
1647
 
1378
- const EVENTS = [
1379
- 'disconnected',
1380
- 'error',
1381
- 'connect_error',
1382
- 'reconnect_error',
1383
- 'reconnect_failed',
1384
- ];
1385
- /**
1386
- * ```js
1387
- * import { onConnectionError } from '@amityco/ts-sdk'
1388
- * const dispose = onClientBanned(() => {
1389
- * // ...
1390
- * })
1391
- * ```
1392
- *
1393
- * Fired when any {@link Amity.Client} have been banned from the platform
1394
- *
1395
- * @param callback The function to call when the event was fired
1396
- * @returns an {@link Amity.Unsubscriber} function to stop listening
1397
- *
1398
- * @category Client Events
1399
- */
1400
- const onConnectionError = (callback) => {
1401
- const client = getActiveClient();
1402
- const subscribers = EVENTS.map(event => (createEventSubscriber(client, `client/onConnectionError(${event})`, event, (response) => {
1403
- const error = (response && 'code' in response)
1404
- ? new ASCError(response.message, response.code, "fatal" /* FATAL */)
1405
- : new ASCConnectionError(event);
1406
- callback(error);
1407
- })));
1408
- return () => {
1409
- subscribers.forEach(fn => fn());
1410
- };
1411
- };
1412
-
1413
- /**
1414
- * ```js
1415
- * import { onClientDisconnected } from '@amityco/ts-sdk'
1416
- * const dispose = onClientDisconnected(() => {
1417
- * // ...
1418
- * })
1419
- * ```
1420
- *
1421
- * Fired when any {@link Amity.Client} have been disconnected
1422
- *
1423
- * @param callback The function to call when the event was fired
1424
- * @returns an {@link Amity.Unsubscriber} function to stop listening
1425
- *
1426
- * @category Client Events
1427
- */
1428
- const onClientDisconnected = (callback) => {
1429
- return onConnectionError(({ code }) => {
1430
- code === 800211 /* DISCONNECTED */ && callback();
1431
- });
1432
- };
1433
-
1434
- /**
1435
- * ```js
1436
- * import { onClientBanned } from '@amityco/ts-sdk'
1437
- * const dispose = onClientBanned(() => {
1438
- * // ...
1439
- * })
1440
- * ```
1441
- *
1442
- * Fired when any {@link Amity.Client} have been banned from the platform
1443
- *
1444
- * @param callback The function to call when the event was fired
1445
- * @returns an {@link Amity.Unsubscriber} function to stop listening
1446
- *
1447
- * @category Client Events
1448
- */
1449
- const onClientBanned = (callback) => {
1450
- return onConnectionError(({ code }) => {
1451
- code === 400312 /* GLOBAL_BAN */ && callback();
1452
- });
1453
- };
1648
+ var SubscriptionLevels;
1649
+ (function (SubscriptionLevels) {
1650
+ SubscriptionLevels["COMMUNITY"] = "community";
1651
+ SubscriptionLevels["POST"] = "post";
1652
+ SubscriptionLevels["COMMENT"] = "comment";
1653
+ SubscriptionLevels["POST_AND_COMMENT"] = "post_and_comment";
1654
+ SubscriptionLevels["USER"] = "user";
1655
+ })(SubscriptionLevels || (SubscriptionLevels = {}));
1656
+ const getCommunityUserTopic = ({ path }, level) => {
1657
+ switch (level) {
1658
+ case 'post':
1659
+ return `${path}/post/+`;
1660
+ case 'comment':
1661
+ return `${path}/post/+/comment/+`;
1662
+ case 'post_and_comment':
1663
+ return `${path}/post/#`;
1664
+ default:
1665
+ return path;
1666
+ }
1667
+ };
1668
+ const getCommunityTopic = ({ path }, level = SubscriptionLevels.COMMUNITY) => getCommunityUserTopic({ path }, level);
1669
+ const getUserTopic = ({ path }, level = SubscriptionLevels.USER) => getCommunityUserTopic({ path }, level);
1670
+ const getPostTopic = ({ path }, level = SubscriptionLevels.POST) => {
1671
+ switch (level) {
1672
+ case 'comment':
1673
+ return `${path}/comment/+`;
1674
+ default:
1675
+ return path;
1676
+ }
1677
+ };
1678
+ const getCommentTopic = ({ path }) => {
1679
+ return path;
1680
+ };
1681
+ let mqttAccessToken;
1682
+ let mqttUserId;
1683
+ function subscribeTopic(topic, callback) {
1684
+ const { mqtt, emitter, accessToken, user } = getActiveClient();
1685
+ if (mqttAccessToken !== accessToken || mqttUserId !== user._id) {
1686
+ mqttAccessToken = accessToken;
1687
+ mqttUserId = user._id;
1688
+ mqtt.connect({ accessToken: accessToken, userId: user._id });
1689
+ proxyMqttEvents(mqtt, emitter);
1690
+ }
1691
+ return mqtt.subscribe(topic, callback);
1692
+ }
1454
1693
 
1455
1694
  /**
1456
1695
  * ```js
@@ -1652,6 +1891,16 @@ const updateUser = async (userId, patch) => {
1652
1891
  return data.users.find(user => user.userId === userId);
1653
1892
  };
1654
1893
 
1894
+ const createUserEventSubscriber = (event, callback) => {
1895
+ const client = getActiveClient();
1896
+ const filter = (payload) => {
1897
+ decoratePayload(payload);
1898
+ ingestInCache(payload);
1899
+ callback(payload.users[0]);
1900
+ };
1901
+ return createEventSubscriber(client, event, event, filter);
1902
+ };
1903
+
1655
1904
  /**
1656
1905
  * ```js
1657
1906
  * import { onUserUpdated } from '@amityco/ts-sdk'
@@ -1660,22 +1909,65 @@ const updateUser = async (userId, patch) => {
1660
1909
  * })
1661
1910
  * ```
1662
1911
  *
1663
- * Fired when any {@link Amity.User} have been updated
1912
+ * Fired when a {@link Amity.User} has been updated
1664
1913
  *
1665
1914
  * @param callback The function to call when the event was fired
1666
1915
  * @returns an {@link Amity.Unsubscriber} function to stop listening
1667
1916
  *
1668
1917
  * @category User Events
1669
1918
  */
1670
- const onUserUpdated = (callback) => {
1671
- const client = getActiveClient();
1672
- const filter = (payload) => {
1673
- decoratePayload(payload);
1674
- ingestInCache(payload);
1675
- callback(payload.users[0]);
1676
- };
1677
- return createEventSubscriber(client, 'user/onUserUpdate', 'v3.user.didUpdate', filter);
1678
- };
1919
+ const onUserUpdated = (callback) => createUserEventSubscriber('user.updated', callback);
1920
+
1921
+ /**
1922
+ * ```js
1923
+ * import { onUserFlagged } from '@amityco/ts-sdk'
1924
+ * const dispose = onUserFlagged(user => {
1925
+ * // ...
1926
+ * })
1927
+ * ```
1928
+ *
1929
+ * Fired when a {@link Amity.User} has been flagged
1930
+ *
1931
+ * @param callback The function to call when the event was fired
1932
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
1933
+ *
1934
+ * @category User Events
1935
+ */
1936
+ const onUserFlagged = (callback) => createUserEventSubscriber('user.flagged', callback);
1937
+
1938
+ /**
1939
+ * ```js
1940
+ * import { onUserUnflagged } from '@amityco/ts-sdk'
1941
+ * const dispose = onUserUnflagged(user => {
1942
+ * // ...
1943
+ * })
1944
+ * ```
1945
+ *
1946
+ * Fired when a flag has been removed from a {@link Amity.User}
1947
+ *
1948
+ * @param callback The function to call when the event was fired
1949
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
1950
+ *
1951
+ * @category User Events
1952
+ */
1953
+ const onUserUnflagged = (callback) => createUserEventSubscriber('user.unflagged', callback);
1954
+
1955
+ /**
1956
+ * ```js
1957
+ * import { onUserFlagCleared } from '@amityco/ts-sdk'
1958
+ * const dispose = onUserFlagCleared(user => {
1959
+ * // ...
1960
+ * })
1961
+ * ```
1962
+ *
1963
+ * Fired when flags have been cleared for a {@link Amity.User}
1964
+ *
1965
+ * @param callback The function to call when the event was fired
1966
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
1967
+ *
1968
+ * @category User Events
1969
+ */
1970
+ const onUserFlagCleared = (callback) => createUserEventSubscriber('user.flagCleared', callback);
1679
1971
 
1680
1972
  /**
1681
1973
  * ```js
@@ -1709,7 +2001,7 @@ const observeUser = (userId, callback) => {
1709
2001
  (_c = callback[action]) === null || _c === void 0 ? void 0 : _c.call(callback, result);
1710
2002
  };
1711
2003
  const disposers = [];
1712
- disposers.push(onUserUpdated(data => router({ data }, 'onUpdate')));
2004
+ disposers.push(onUserUpdated(data => router({ data }, 'onUpdate')), onUserFlagged(data => router({ data }, 'onFlagged')), onUserUnflagged(data => router({ data }, 'onUnflagged')), onUserFlagCleared(data => router({ data }, 'onFlagCleared')));
1713
2005
  runQuery(createQuery(getUser, userId), (result) => result.data && router(result, 'onFetch'));
1714
2006
  return () => {
1715
2007
  log(`observeUser(tmpid: ${timestamp}) > dispose`);
@@ -1973,10 +2265,10 @@ const dispatchReactable = (referenceType, model) => {
1973
2265
  fireEvent('v3.message.didUpdate', { messages: [model] });
1974
2266
  else if (referenceType === 'post')
1975
2267
  // @ts-ignore: refactor later
1976
- fireEvent('v3.post.didUpdate', { posts: [model] });
2268
+ fireEvent('post.updated', { posts: [model] });
1977
2269
  else if (referenceType === 'comment')
1978
2270
  // @ts-ignore: refactor later
1979
- fireEvent('v3.comment.didUpdate', { comments: [model] });
2271
+ fireEvent('comment.updated', { comments: [model] });
1980
2272
  };
1981
2273
 
1982
2274
  /**
@@ -2509,8 +2801,8 @@ const createPost = async (bundle) => {
2509
2801
  const { data } = await client.http.post('/api/v3/posts', bundle);
2510
2802
  decoratePayload(data);
2511
2803
  ingestInCache(data);
2512
- fireEvent('v3.community.didUpdate', { communities: data.communities });
2513
- fireEvent('v3.post.didCreate', data);
2804
+ fireEvent('community.updated', { communities: data.communities });
2805
+ fireEvent('post.created', data);
2514
2806
  const { posts } = data;
2515
2807
  return posts[0];
2516
2808
  };
@@ -2538,7 +2830,7 @@ const updatePost = async (postId, patch) => {
2538
2830
  const { data } = await client.http.put(`/api/v3/posts/${postId}`, patch);
2539
2831
  decoratePayload(data);
2540
2832
  ingestInCache(data);
2541
- fireEvent('v3.post.didUpdate', data);
2833
+ fireEvent('post.updated', data);
2542
2834
  const { posts } = data;
2543
2835
  return posts.find(post => post.postId === postId);
2544
2836
  };
@@ -2708,7 +3000,7 @@ const createCommunity = async (bundle) => {
2708
3000
  const { data } = await client.http.post('/api/v3/communities/', bundle);
2709
3001
  decoratePayload(data);
2710
3002
  ingestInCache(data);
2711
- fireEvent('v3.community.didCreate', data);
3003
+ fireEvent('community.created', data);
2712
3004
  const { communities } = data;
2713
3005
  return communities[0];
2714
3006
  };
@@ -2734,7 +3026,7 @@ const updateCommunity = async (communityId, patch) => {
2734
3026
  const { data } = await client.http.put(`/api/v3/communities/${communityId}`, patch);
2735
3027
  decoratePayload(data);
2736
3028
  ingestInCache(data);
2737
- fireEvent('v3.community.didUpdate', data);
3029
+ fireEvent('community.updated', data);
2738
3030
  const { communities } = data;
2739
3031
  return communities.find(community => community.communityId === communityId);
2740
3032
  };
@@ -2759,7 +3051,7 @@ const deleteCommunity = async (communityId) => {
2759
3051
  // API-FIX: This endpoint has not been implemented yet.
2760
3052
  await client.http.delete(`/api/v3/communities/${communityId}`);
2761
3053
  const deleted = await getCommunity(communityId);
2762
- fireEvent('v3.community.didDelete', { communities: [deleted] });
3054
+ fireEvent('community.deleted', { communities: [deleted] });
2763
3055
  return deleted;
2764
3056
  };
2765
3057
 
@@ -2783,7 +3075,7 @@ const joinCommunity = async (communityId) => {
2783
3075
  const { data } = await client.http.post(`/api/v3/communities/${communityId}/join`);
2784
3076
  decoratePayload(data);
2785
3077
  ingestInCache(data);
2786
- fireEvent('v3.community.didJoin', {
3078
+ fireEvent('community.joined', {
2787
3079
  communities: data.communities
2788
3080
  });
2789
3081
  const { communityUsers } = data;
@@ -2811,7 +3103,7 @@ const leaveCommunity = async (communityId) => {
2811
3103
  const { data } = await client.http.delete(`/api/v3/communities/${communityId}/leave`);
2812
3104
  decoratePayload(data);
2813
3105
  ingestInCache(data);
2814
- fireEvent('v3.community.didJoin', {
3106
+ fireEvent('community.left', {
2815
3107
  communities: data.communities,
2816
3108
  });
2817
3109
  const { communityUsers } = data;
@@ -2890,7 +3182,7 @@ const addCommunityMembers = async (communityId, userIds) => {
2890
3182
  const { data } = await client.http.post(`/api/v3/communities/${communityId}/users`, { communityId, userIds });
2891
3183
  decoratePayload(data);
2892
3184
  ingestInCache(data);
2893
- fireEvent('v3.community.didAddUsers', {
3185
+ fireEvent('community.userAdded', {
2894
3186
  communities: data.communities,
2895
3187
  });
2896
3188
  const { communityUsers } = data;
@@ -2919,7 +3211,7 @@ const removeCommunityMembers = async (communityId, userIds) => {
2919
3211
  const { data } = await client.http.delete(`/api/v3/communities/${communityId}/users`, { data: { communityId, userIds } });
2920
3212
  decoratePayload(data);
2921
3213
  ingestInCache(data);
2922
- fireEvent('v3.community.didRemoveUsers', {
3214
+ fireEvent('community.userRemoved', {
2923
3215
  communities: data.communities,
2924
3216
  });
2925
3217
  const { communityUsers } = data;
@@ -3010,11 +3302,11 @@ const deletePost = async (postId, permanent = false) => {
3010
3302
  // later when realtime events covers that for us.
3011
3303
  if (post.targetType === 'community') {
3012
3304
  const community = await getCommunity(post.targetId);
3013
- fireEvent('v3.community.didUpdate', { communities: [community] });
3305
+ fireEvent('community.updated', { communities: [community] });
3014
3306
  }
3015
3307
  // to support hard deletion
3016
3308
  const deleted = Object.assign(Object.assign({}, post), { isDeleted: true });
3017
- fireEvent('v3.post.didDelete', { posts: [deleted] });
3309
+ fireEvent('post.deleted', { posts: [deleted] });
3018
3310
  if (permanent) {
3019
3311
  setTimeout(() => {
3020
3312
  dropFromCache('post', { postId });
@@ -3262,8 +3554,8 @@ const createComment = async (bundle) => {
3262
3554
  decoratePayload(data);
3263
3555
  ingestInCache(data);
3264
3556
  const post = await getPost(bundle.referenceId);
3265
- fireEvent('v3.post.didUpdate', { posts: [post] });
3266
- fireEvent('v3.comment.didCreate', data);
3557
+ fireEvent('post.updated', { posts: [post] });
3558
+ fireEvent('comment.created', data);
3267
3559
  const { comments } = data;
3268
3560
  return comments[0];
3269
3561
  };
@@ -3291,7 +3583,7 @@ const updateComment = async (commentId, patch) => {
3291
3583
  const { data } = await client.http.put(`/api/v3/comments/${commentId}`, patch);
3292
3584
  decoratePayload(data);
3293
3585
  ingestInCache(data);
3294
- fireEvent('v3.comment.didUpdate', data);
3586
+ fireEvent('comment.updated', data);
3295
3587
  const { comments } = data;
3296
3588
  return comments.find(comment => comment.commentId === commentId);
3297
3589
  };
@@ -3324,8 +3616,8 @@ const deleteComment = async (commentId, permanent = false) => {
3324
3616
  // to support hard deletion
3325
3617
  const deleted = Object.assign(Object.assign({}, comment), { isDeleted: true });
3326
3618
  const post = await getPost(comment.referenceId);
3327
- fireEvent('v3.post.didUpdate', { posts: [post] });
3328
- fireEvent('v3.comment.didDelete', { comments: [deleted] });
3619
+ fireEvent('post.updated', { posts: [post] });
3620
+ fireEvent('comment.deleted', { comments: [deleted] });
3329
3621
  if (permanent) {
3330
3622
  setTimeout(() => {
3331
3623
  dropFromCache('comment', { commentId });
@@ -3348,6 +3640,42 @@ const fetchReference = async (referenceType, referenceId) => {
3348
3640
  throw new Error(`Incorrect referenceType: ${referenceType}`);
3349
3641
  };
3350
3642
 
3643
+ /** @hidden */
3644
+ const preparePayloadForCache = (event, payload) => {
3645
+ var _a, _b;
3646
+ const client = getActiveClient();
3647
+ if (client.userId !== payload.reactor.userId) {
3648
+ return;
3649
+ }
3650
+ let model;
3651
+ let cached;
3652
+ if (event === 'post.addReaction' || event === 'post.removeReaction') {
3653
+ const post = payload.posts[0];
3654
+ cached = ((_a = pullFromCache('post', post.postId)) !== null && _a !== void 0 ? _a : [])[0];
3655
+ model = post;
3656
+ }
3657
+ else {
3658
+ const comment = payload.comments[0];
3659
+ cached = ((_b = pullFromCache('comment', comment.commentId)) !== null && _b !== void 0 ? _b : [])[0];
3660
+ model = comment;
3661
+ }
3662
+ if (!cached || !cached.myReactions) {
3663
+ return;
3664
+ }
3665
+ if (event === 'post.addReaction' || event === 'comment.addReaction') {
3666
+ if (cached.myReactions.includes(payload.reactor.reactionName)) {
3667
+ return;
3668
+ }
3669
+ Object.assign(model, { myReactions: [...cached.myReactions, payload.reactor.reactionName] });
3670
+ }
3671
+ else {
3672
+ if (!cached.myReactions.includes(payload.reactor.reactionName)) {
3673
+ return;
3674
+ }
3675
+ Object.assign(model, { myReactions: cached.myReactions.filter(x => x !== payload.reactor.reactionName) });
3676
+ }
3677
+ };
3678
+
3351
3679
  /**
3352
3680
  * ```js
3353
3681
  * import { addReaction } from '@amityco/ts-sdk'
@@ -3460,75 +3788,468 @@ removeReaction.optimistically = (referenceType, referenceId, reactionName) => {
3460
3788
  return (_b = !((_a = model === null || model === void 0 ? void 0 : model.myReactions) === null || _a === void 0 ? void 0 : _a.includes(reactionName))) !== null && _b !== void 0 ? _b : false;
3461
3789
  };
3462
3790
 
3791
+ const createPostEventSubscriber = (event, callback) => {
3792
+ const client = getActiveClient();
3793
+ const filter = (payload) => {
3794
+ var _a, _b;
3795
+ const [cached] = (_a = pullFromCache('post', payload.posts[0].postId)) !== null && _a !== void 0 ? _a : [];
3796
+ const { communities } = payload, others = __rest(payload, ["communities"]);
3797
+ decoratePayload(others);
3798
+ ingestInCache(others);
3799
+ if (communities === null || communities === void 0 ? void 0 : communities[0]) {
3800
+ fireEvent('community.updated', { communities });
3801
+ }
3802
+ const [post] = (_b = pullFromCache('post', others.posts[0].postId)) !== null && _b !== void 0 ? _b : [];
3803
+ if (cached && isMatch(cached, post)) {
3804
+ return;
3805
+ }
3806
+ callback(post);
3807
+ };
3808
+ return createEventSubscriber(client, event, event, filter);
3809
+ };
3810
+
3463
3811
  /**
3464
3812
  * ```js
3465
- * import { onReactionRemoved } from '@amityco/ts-sdk'
3466
- * const dispose = onReactionRemoved(message => {
3813
+ * import { onPostCreated } from '@amityco/ts-sdk'
3814
+ * const dispose = onPostCreated(post => {
3467
3815
  * // ...
3468
3816
  * })
3469
3817
  * ```
3470
3818
  *
3471
- * Fired when an {@link Amity.Reaction} has been removed
3819
+ * Fired when {@link Amity.Post} has been created
3472
3820
  *
3473
3821
  * @param callback The function to call when the event was fired
3474
3822
  * @returns an {@link Amity.Unsubscriber} function to stop listening
3475
3823
  *
3476
- * @category Message Events
3477
- **/
3478
- const onReactionRemoved = (referenceType, referenceId, callback) => {
3479
- const client = getActiveClient();
3480
- const filter = (payload) => {
3481
- // TODO: lol
3482
- decoratePayload(payload);
3483
- ingestInCache(payload);
3484
- };
3485
- return createEventSubscriber(client, 'reaction/onReactionRemoved', 'v3.message.didUpdate', filter);
3486
- };
3487
-
3488
- var REFERENCE_TYPES = {
3489
- post: {
3490
- domainName: 'posts',
3491
- eventName: 'v3/post.isflagbyme',
3492
- primaryKey: 'postId',
3493
- },
3494
- comment: {
3495
- domainName: 'comments',
3496
- eventName: 'v3/comment.isflagbyme',
3497
- primaryKey: 'commentId',
3498
- },
3499
- message: {
3500
- domainName: 'messages',
3501
- eventName: 'v3/message.isFlaggedByMe',
3502
- primaryKey: 'messageId',
3503
- },
3504
- user: {
3505
- domainName: 'users',
3506
- eventName: 'user.isFlagByMe',
3507
- primaryKey: 'userId',
3508
- },
3509
- };
3824
+ * @category Post Events
3825
+ */
3826
+ const onPostCreated = (callback) => createPostEventSubscriber('post.created', callback);
3510
3827
 
3511
3828
  /**
3512
3829
  * ```js
3513
- * import { createReport } from '@amityco/ts-sdk'
3514
- * const flagged = await createReport('post', postId)
3830
+ * import { onPostUpdated } from '@amityco/ts-sdk'
3831
+ * const dispose = onPostUpdated(post => {
3832
+ * // ...
3833
+ * })
3515
3834
  * ```
3516
3835
  *
3517
- * @param referenceType The type of thing to add a report to, such as a post or a comment.
3518
- * @param referenceId The ID of the thing to add a new report to.
3519
- * @returns the created report result
3836
+ * Fired when a {@link Amity.Post} has been updated
3520
3837
  *
3521
- * @category Report API
3522
- * @async
3523
- **/
3524
- const createReport = async (referenceType, referenceId) => {
3525
- const client = getActiveClient();
3526
- client.log('report/createReport', { referenceType, referenceId });
3527
- const { domainName } = REFERENCE_TYPES[referenceType];
3838
+ * @param callback The function to call when the event was fired
3839
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
3840
+ *
3841
+ * @category Post Events
3842
+ */
3843
+ const onPostUpdated = (callback) => createPostEventSubscriber('post.updated', callback);
3844
+
3845
+ /**
3846
+ * ```js
3847
+ * import { onPostDeleted } from '@amityco/ts-sdk'
3848
+ * const dispose = onPostDeleted(post => {
3849
+ * // ...
3850
+ * })
3851
+ * ```
3852
+ *
3853
+ * Fired when a {@link Amity.Post} has been deleted
3854
+ *
3855
+ * @param callback The function to call when the event was fired
3856
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
3857
+ *
3858
+ * @category Post Events
3859
+ */
3860
+ const onPostDeleted = (callback) => createPostEventSubscriber('post.deleted', callback);
3861
+
3862
+ /**
3863
+ * ```js
3864
+ * import { onPostApproved } from '@amityco/ts-sdk'
3865
+ * const dispose = onPostApproved(post => {
3866
+ * // ...
3867
+ * })
3868
+ * ```
3869
+ *
3870
+ * Fired when a {@link Amity.Post} has been updated
3871
+ *
3872
+ * @param callback The function to call when the event was fired
3873
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
3874
+ *
3875
+ * @category Post Events
3876
+ */
3877
+ const onPostApproved = (callback) => createPostEventSubscriber('post.approved', callback);
3878
+
3879
+ /**
3880
+ * ```js
3881
+ * import { onPostDeclined } from '@amityco/ts-sdk'
3882
+ * const dispose = onPostDeclined(post => {
3883
+ * // ...
3884
+ * })
3885
+ * ```
3886
+ *
3887
+ * Fired when a {@link Amity.Post} has been updated
3888
+ *
3889
+ * @param callback The function to call when the event was fired
3890
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
3891
+ *
3892
+ * @category Post Events
3893
+ */
3894
+ const onPostDeclined = (callback) => createPostEventSubscriber('post.declined', callback);
3895
+
3896
+ /**
3897
+ * ```js
3898
+ * import { onPostFlagged } from '@amityco/ts-sdk'
3899
+ * const dispose = onPostFlagged(post => {
3900
+ * // ...
3901
+ * })
3902
+ * ```
3903
+ *
3904
+ * Fired when a {@link Amity.Post} has been flagged
3905
+ *
3906
+ * @param callback The function to call when the event was fired
3907
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
3908
+ *
3909
+ * @category Post Events
3910
+ */
3911
+ const onPostFlagged = (callback) => createPostEventSubscriber('post.flagged', callback);
3912
+
3913
+ /**
3914
+ * ```js
3915
+ * import { onPostUnflagged } from '@amityco/ts-sdk'
3916
+ * const dispose = onPostUnflagged(post => {
3917
+ * // ...
3918
+ * })
3919
+ * ```
3920
+ *
3921
+ * Fired when a flag has been removed from a {@link Amity.Post}
3922
+ *
3923
+ * @param callback The function to call when the event was fired
3924
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
3925
+ *
3926
+ * @category Post Events
3927
+ */
3928
+ const onPostUnflagged = (callback) => createPostEventSubscriber('post.unflagged', callback);
3929
+
3930
+ /**
3931
+ * ```js
3932
+ * import { onPostReactionAdded } from '@amityco/ts-sdk'
3933
+ * const dispose = onPostReactionAdded(post => {
3934
+ * // ...
3935
+ * })
3936
+ * ```
3937
+ *
3938
+ * Fired when a {@link Amity.Post} has been reacted
3939
+ *
3940
+ * @param callback The function to call when the event was fired
3941
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
3942
+ *
3943
+ * @category Post Events
3944
+ */
3945
+ const onPostReactionAdded = (callback) => {
3946
+ const client = getActiveClient();
3947
+ const filter = (payload) => {
3948
+ var _a, _b;
3949
+ const [cached] = (_a = pullFromCache('post', payload.posts[0].postId)) !== null && _a !== void 0 ? _a : [];
3950
+ const postPayload = __rest(payload, ["reactor"]);
3951
+ decoratePayload(postPayload);
3952
+ preparePayloadForCache('post.addReaction', payload);
3953
+ ingestInCache(postPayload);
3954
+ const [post] = (_b = pullFromCache('post', payload.posts[0].postId)) !== null && _b !== void 0 ? _b : [];
3955
+ if (cached && isMatch(cached, post)) {
3956
+ return;
3957
+ }
3958
+ callback(post);
3959
+ };
3960
+ return createEventSubscriber(client, 'post.addReaction', 'post.addReaction', filter);
3961
+ };
3962
+
3963
+ /**
3964
+ * ```js
3965
+ * import { onPostReactionRemoved } from '@amityco/ts-sdk'
3966
+ * const dispose = onPostReactionRemoved(post => {
3967
+ * // ...
3968
+ * })
3969
+ * ```
3970
+ *
3971
+ * Fired when a reaction has been removed from a {@link Amity.Post}
3972
+ *
3973
+ * @param callback The function to call when the event was fired
3974
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
3975
+ *
3976
+ * @category Post Events
3977
+ */
3978
+ const onPostReactionRemoved = (callback) => {
3979
+ const client = getActiveClient();
3980
+ const filter = (payload) => {
3981
+ var _a, _b;
3982
+ const [cached] = (_a = pullFromCache('post', payload.posts[0].postId)) !== null && _a !== void 0 ? _a : [];
3983
+ const postPayload = __rest(payload, ["reactor"]);
3984
+ decoratePayload(postPayload);
3985
+ preparePayloadForCache('post.removeReaction', payload);
3986
+ ingestInCache(postPayload);
3987
+ const [post] = (_b = pullFromCache('post', payload.posts[0].postId)) !== null && _b !== void 0 ? _b : [];
3988
+ if (cached && isMatch(cached, post)) {
3989
+ return;
3990
+ }
3991
+ callback(post);
3992
+ };
3993
+ return createEventSubscriber(client, 'post.removeReaction', 'post.removeReaction', filter);
3994
+ };
3995
+
3996
+ const createCommentEventSubscriber = (event, callback) => {
3997
+ const client = getActiveClient();
3998
+ const filter = (payload) => {
3999
+ var _a, _b;
4000
+ const [cached] = (_a = pullFromCache('comment', payload.comments[0].commentId)) !== null && _a !== void 0 ? _a : [];
4001
+ decoratePayload(payload);
4002
+ ingestInCache(payload);
4003
+ const [comment] = (_b = pullFromCache('comment', payload.comments[0].commentId)) !== null && _b !== void 0 ? _b : [];
4004
+ if (cached && isMatch(cached, comment)) {
4005
+ return;
4006
+ }
4007
+ callback(comment);
4008
+ };
4009
+ return createEventSubscriber(client, event, event, filter);
4010
+ };
4011
+
4012
+ /**
4013
+ * ```js
4014
+ * import { onCommentCreated } from '@amityco/ts-sdk'
4015
+ * const dispose = onCommentCreated(comment => {
4016
+ * // ...
4017
+ * })
4018
+ * ```
4019
+ *
4020
+ * Fired when {@link Amity.Comment} has been created
4021
+ *
4022
+ * @param callback The function to call when the event was fired
4023
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
4024
+ *
4025
+ * @category Comment Events
4026
+ */
4027
+ const onCommentCreated = (callback) => createCommentEventSubscriber('comment.created', callback);
4028
+
4029
+ /**
4030
+ * ```js
4031
+ * import { onCommentUpdated } from '@amityco/ts-sdk'
4032
+ * const dispose = onCommentUpdated(comment => {
4033
+ * // ...
4034
+ * })
4035
+ * ```
4036
+ *
4037
+ * Fired when a {@link Amity.Comment} has been updated
4038
+ *
4039
+ * @param callback The function to call when the event was fired
4040
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
4041
+ *
4042
+ * @category Comment Events
4043
+ */
4044
+ const onCommentUpdated = (callback) => createCommentEventSubscriber('comment.updated', callback);
4045
+
4046
+ /**
4047
+ * ```js
4048
+ * import { onCommentDeleted } from '@amityco/ts-sdk'
4049
+ * const dispose = onCommentDeleted(comment => {
4050
+ * // ...
4051
+ * })
4052
+ * ```
4053
+ *
4054
+ * Fired when a {@link Amity.Comment} has been deleted
4055
+ *
4056
+ * @param callback The function to call when the event was fired
4057
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
4058
+ *
4059
+ * @category Comment Events
4060
+ */
4061
+ const onCommentDeleted = (callback) => createCommentEventSubscriber('comment.deleted', callback);
4062
+
4063
+ /**
4064
+ * ```js
4065
+ * import { onCommentFlagged } from '@amityco/ts-sdk'
4066
+ * const dispose = onCommentFlagged(comment => {
4067
+ * // ...
4068
+ * })
4069
+ * ```
4070
+ *
4071
+ * Fired when a {@link Amity.Comment} has been flagged
4072
+ *
4073
+ * @param callback The function to call when the event was fired
4074
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
4075
+ *
4076
+ * @category Comment Events
4077
+ */
4078
+ const onCommentFlagged = (callback) => createCommentEventSubscriber('comment.flagged', callback);
4079
+
4080
+ /**
4081
+ * ```js
4082
+ * import { onCommentUnflagged } from '@amityco/ts-sdk'
4083
+ * const dispose = onCommentUnflagged(comment => {
4084
+ * // ...
4085
+ * })
4086
+ * ```
4087
+ *
4088
+ * Fired when a flag has been removed from a {@link Amity.Comment}
4089
+ *
4090
+ * @param callback The function to call when the event was fired
4091
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
4092
+ *
4093
+ * @category Comment Events
4094
+ */
4095
+ const onCommentUnflagged = (callback) => createCommentEventSubscriber('comment.unflagged', callback);
4096
+
4097
+ /**
4098
+ * ```js
4099
+ * import { onCommentReactionAdded } from '@amityco/ts-sdk'
4100
+ * const dispose = onCommentReactionAdded(comment => {
4101
+ * // ...
4102
+ * })
4103
+ * ```
4104
+ *
4105
+ * Fired when a {@link Amity.Comment} has been reacted
4106
+ *
4107
+ * @param callback The function to call when the event was fired
4108
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
4109
+ *
4110
+ * @category Comment Events
4111
+ */
4112
+ const onCommentReactionAdded = (callback) => {
4113
+ const client = getActiveClient();
4114
+ const filter = (payload) => {
4115
+ var _a, _b;
4116
+ const [cached] = (_a = pullFromCache('comment', payload.comments[0].commentId)) !== null && _a !== void 0 ? _a : [];
4117
+ const commentPayload = __rest(payload, ["reactor"]);
4118
+ decoratePayload(commentPayload);
4119
+ preparePayloadForCache('comment.addReaction', payload);
4120
+ ingestInCache(commentPayload);
4121
+ const [comment] = (_b = pullFromCache('comment', payload.comments[0].commentId)) !== null && _b !== void 0 ? _b : [];
4122
+ if (cached && isMatch(cached, comment)) {
4123
+ return;
4124
+ }
4125
+ callback(comment);
4126
+ };
4127
+ return createEventSubscriber(client, 'comment.addReaction', 'comment.addReaction', filter);
4128
+ };
4129
+
4130
+ /**
4131
+ * ```js
4132
+ * import { onCommentReactionRemoved } from '@amityco/ts-sdk'
4133
+ * const dispose = onCommentReactionRemoved(comment => {
4134
+ * // ...
4135
+ * })
4136
+ * ```
4137
+ *
4138
+ * Fired when a reaction has been removed from a {@link Amity.Comment}
4139
+ *
4140
+ * @param callback The function to call when the event was fired
4141
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
4142
+ *
4143
+ * @category Comment Events
4144
+ */
4145
+ const onCommentReactionRemoved = (callback) => {
4146
+ const client = getActiveClient();
4147
+ const filter = (payload) => {
4148
+ var _a, _b;
4149
+ const [cached] = (_a = pullFromCache('comment', payload.comments[0].commentId)) !== null && _a !== void 0 ? _a : [];
4150
+ const commentPayload = __rest(payload, ["reactor"]);
4151
+ decoratePayload(commentPayload);
4152
+ preparePayloadForCache('comment.removeReaction', payload);
4153
+ ingestInCache(commentPayload);
4154
+ const [comment] = (_b = pullFromCache('comment', payload.comments[0].commentId)) !== null && _b !== void 0 ? _b : [];
4155
+ if (cached && isMatch(cached, comment)) {
4156
+ return;
4157
+ }
4158
+ callback(comment);
4159
+ };
4160
+ return createEventSubscriber(client, 'comment.removeReaction', 'comment.removeReaction', filter);
4161
+ };
4162
+
4163
+ /**
4164
+ * ```js
4165
+ * import { onReactionRemoved } from '@amityco/ts-sdk'
4166
+ * const dispose = onReactionRemoved('post', postId, post => {
4167
+ * // ...
4168
+ * })
4169
+ * ```
4170
+ *
4171
+ * Fired when an {@link Amity.Reaction} has been removed
4172
+ *
4173
+ * @param {@link Amity.ReactableType} referenceType
4174
+ * @param {string} referenceId
4175
+ * @param callback The function to call when the event was fired
4176
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
4177
+ *
4178
+ * @category Message Events
4179
+ **/
4180
+ const onReactionRemoved = (referenceType, referenceId, callback) => {
4181
+ const callbackWrapper = (model) => {
4182
+ if (getResolver(referenceType)(model) === referenceId) {
4183
+ callback(model);
4184
+ }
4185
+ };
4186
+ if (referenceType === 'message') {
4187
+ const client = getActiveClient();
4188
+ const filter = (payload) => {
4189
+ var _a, _b;
4190
+ const reactionsCountInCache = (_b = ((_a = pullFromCache('message', payload.messages[0].messageId)) !== null && _a !== void 0 ? _a : [])[0]) === null || _b === void 0 ? void 0 : _b.reactionsCount;
4191
+ const isReactionEvent = reactionsCountInCache !== payload.messages[0].reactionsCount;
4192
+ decoratePayload(payload);
4193
+ ingestInCache(payload);
4194
+ if (isReactionEvent) {
4195
+ callbackWrapper(payload.messages[0]);
4196
+ }
4197
+ };
4198
+ return createEventSubscriber(client, 'reaction/onReactionRemoved', 'v3.message.didUpdate', filter);
4199
+ }
4200
+ if (referenceType === 'post') {
4201
+ return onPostReactionRemoved(callbackWrapper);
4202
+ }
4203
+ return onCommentReactionRemoved(callbackWrapper);
4204
+ };
4205
+
4206
+ var REFERENCE_TYPES = {
4207
+ post: {
4208
+ domainName: 'posts',
4209
+ eventName: 'v3/post.isflagbyme',
4210
+ primaryKey: 'postId',
4211
+ },
4212
+ comment: {
4213
+ domainName: 'comments',
4214
+ eventName: 'v3/comment.isflagbyme',
4215
+ primaryKey: 'commentId',
4216
+ },
4217
+ message: {
4218
+ domainName: 'messages',
4219
+ eventName: 'v3/message.isFlaggedByMe',
4220
+ primaryKey: 'messageId',
4221
+ },
4222
+ user: {
4223
+ domainName: 'users',
4224
+ eventName: 'user.isFlagByMe',
4225
+ primaryKey: 'userId',
4226
+ },
4227
+ };
4228
+
4229
+ /**
4230
+ * ```js
4231
+ * import { createReport } from '@amityco/ts-sdk'
4232
+ * const flagged = await createReport('post', postId)
4233
+ * ```
4234
+ *
4235
+ * @param referenceType The type of thing to add a report to, such as a post or a comment.
4236
+ * @param referenceId The ID of the thing to add a new report to.
4237
+ * @returns the created report result
4238
+ *
4239
+ * @category Report API
4240
+ * @async
4241
+ **/
4242
+ const createReport = async (referenceType, referenceId) => {
4243
+ const client = getActiveClient();
4244
+ client.log('report/createReport', { referenceType, referenceId });
4245
+ const { domainName } = REFERENCE_TYPES[referenceType];
3528
4246
  const { data } = await client.http.post(`/api/v3/${domainName}/${referenceId}/flag`);
4247
+ const event = referenceType === 'message'
4248
+ ? 'v3.message.didUpdate'
4249
+ : `${referenceType}.updated`;
3529
4250
  decoratePayload(data);
3530
4251
  ingestInCache(data);
3531
- fireEvent(`v3.${referenceType}.didUpdate`, data);
4252
+ fireEvent(event, data);
3532
4253
  return !!data;
3533
4254
  };
3534
4255
 
@@ -3550,9 +4271,12 @@ const deleteReport = async (referenceType, referenceId) => {
3550
4271
  client.log('report/deleteReport', { referenceType, referenceId });
3551
4272
  const { domainName } = REFERENCE_TYPES[referenceType];
3552
4273
  const { data } = await client.http.delete(`/api/v3/${domainName}/${referenceId}/unflag`);
4274
+ const event = referenceType === 'message'
4275
+ ? 'v3.message.didUpdate'
4276
+ : `${referenceType}.updated`;
3553
4277
  decoratePayload(data);
3554
4278
  ingestInCache(data);
3555
- fireEvent(`v3.${referenceType}.didUpdate`, data);
4279
+ fireEvent(event, data);
3556
4280
  return !!data;
3557
4281
  };
3558
4282
 
@@ -4322,166 +5046,253 @@ const observeMessage = (messageId, callback, policy = 'cache_then_server') => {
4322
5046
 
4323
5047
  /**
4324
5048
  * ```js
4325
- * import { observeMessages } from '@amityco/ts-sdk'
5049
+ * import { observeMessages } from '@amityco/ts-sdk'
5050
+ *
5051
+ * let messages = []
5052
+ * const unsub = observeMessages(channelId, message => merge(messages, message))
5053
+ * ```
5054
+ *
5055
+ * Observe all mutations on a list of {@link Amity.Message} for a given {@link Amity.Channel} object
5056
+ *
5057
+ * @param client the client to observe the message with
5058
+ * @param channelId the ID of the channel where to observe the messages
5059
+ * @param callback the function to call when new data are available
5060
+ * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the messages
5061
+ *
5062
+ * @category Message Observer
5063
+ */
5064
+ const observeMessages = (channelId, callback) => {
5065
+ const { log } = getActiveClient();
5066
+ const timestamp = Date.now();
5067
+ log(`observeMessages(tmpid: ${timestamp}) > listen`);
5068
+ const disposers = [];
5069
+ const router = (message, action) => {
5070
+ var _a, _b;
5071
+ if (message.channelId !== channelId)
5072
+ return;
5073
+ if (callback instanceof Function)
5074
+ return callback(message);
5075
+ (_a = callback.onEvent) === null || _a === void 0 ? void 0 : _a.call(callback, action, message);
5076
+ (_b = callback[action]) === null || _b === void 0 ? void 0 : _b.call(callback, message);
5077
+ };
5078
+ disposers.push(onMessageCreated(message => router(message, 'onCreate')), onMessageUpdated(message => router(message, 'onUpdate')), onMessageDeleted(message => router(message, 'onDelete')));
5079
+ return () => {
5080
+ log(`observeMessages(tmpid: ${timestamp}) > dispose`);
5081
+ disposers.forEach(fn => fn());
5082
+ };
5083
+ };
5084
+
5085
+ const createCommunityEventSubscriber = (event, callback) => {
5086
+ const client = getActiveClient();
5087
+ const filter = (payload) => {
5088
+ var _a, _b;
5089
+ const [cached] = (_a = pullFromCache('community', payload.communities[0].communityId)) !== null && _a !== void 0 ? _a : [];
5090
+ decoratePayload(payload);
5091
+ ingestInCache(payload);
5092
+ const [community] = (_b = pullFromCache('community', payload.communities[0].communityId)) !== null && _b !== void 0 ? _b : [];
5093
+ if (cached && isMatch(cached, community)) {
5094
+ return;
5095
+ }
5096
+ callback(community);
5097
+ };
5098
+ return createEventSubscriber(client, event, event, filter);
5099
+ };
5100
+ function hasPermission(member, payload, permission) {
5101
+ if (member.permissions.some(x => x === permission)) {
5102
+ return true;
5103
+ }
5104
+ return payload.users
5105
+ .find(user => user.userId === member.userId)
5106
+ .permissions.some(x => x === permission);
5107
+ }
5108
+ function getEventRelatedMember(event, payload) {
5109
+ if (event === 'community.joined' || event === 'community.left') {
5110
+ return payload.communityUsers[0];
5111
+ }
5112
+ // NOTE: backend returns the one who took the action and the one on whom
5113
+ // the action was taken. We need the 2nd one
5114
+ if (event === 'community.userRemoved') {
5115
+ return payload.communityUsers.filter(x => x.communityMembership === 'none')[0];
5116
+ }
5117
+ if (event === 'community.userBanned') {
5118
+ return payload.communityUsers.filter(x => x.communityMembership === 'banned')[0];
5119
+ }
5120
+ // NOTE: it might be that in certain edge cases permission check won't be enough
5121
+ if (event === 'community.userUnbanned') {
5122
+ return payload.communityUsers.filter(x => !hasPermission(x, payload, 'BAN_COMMUNITY_USER'))[0];
5123
+ }
5124
+ return payload.communityUsers.filter(x => !hasPermission(x, payload, 'ADD_COMMUNITY_USER'))[0];
5125
+ }
5126
+ const createCommunityMemberEventSubscriber = (event, callback) => {
5127
+ const client = getActiveClient();
5128
+ const filter = (payload) => {
5129
+ var _a, _b, _c, _d;
5130
+ const [cachedCommunity] = (_a = pullFromCache('community', payload.communities[0].communityId)) !== null && _a !== void 0 ? _a : [];
5131
+ const [cachedMember] = (_b = pullFromCache('communityUsers', getResolver('communityUsers')(getEventRelatedMember(event, payload)))) !== null && _b !== void 0 ? _b : [];
5132
+ decoratePayload(payload);
5133
+ ingestInCache(payload);
5134
+ const [community] = (_c = pullFromCache('community', payload.communities[0].communityId)) !== null && _c !== void 0 ? _c : [];
5135
+ const [member] = (_d = pullFromCache('communityUsers', getResolver('communityUsers')(getEventRelatedMember(event, payload)))) !== null && _d !== void 0 ? _d : [];
5136
+ if (cachedCommunity && isMatch(cachedCommunity, community) && cachedMember && isMatch(cachedMember, member)) {
5137
+ return;
5138
+ }
5139
+ callback(community, member);
5140
+ };
5141
+ return createEventSubscriber(client, event, event, filter);
5142
+ };
5143
+
5144
+ /**
5145
+ * ```js
5146
+ * import { onCommunityCreated } from '@amityco/ts-sdk'
5147
+ * const dispose = onCommunityCreated(community => {
5148
+ * // ...
5149
+ * })
5150
+ * ```
5151
+ *
5152
+ * Fired when {@link Amity.Community} have been created
5153
+ *
5154
+ * @param callback The function to call when the event was fired
5155
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
5156
+ *
5157
+ * @category Community Events
5158
+ */
5159
+ const onCommunityCreated = (callback) => createCommunityEventSubscriber('community.created', callback);
5160
+
5161
+ /**
5162
+ * ```js
5163
+ * import { onCommunityUpdated } from '@amityco/ts-sdk'
5164
+ * const dispose = onCommunityUpdated(community => {
5165
+ * // ...
5166
+ * })
5167
+ * ```
5168
+ *
5169
+ * Fired when a {@link Amity.Community} has been updated
5170
+ *
5171
+ * @param callback The function to call when the event was fired
5172
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
5173
+ *
5174
+ * @category Community Events
5175
+ */
5176
+ const onCommunityUpdated = (callback) => createCommunityEventSubscriber('community.updated', callback);
5177
+
5178
+ /**
5179
+ * ```js
5180
+ * import { onCommunityDeleted } from '@amityco/ts-sdk'
5181
+ * const dispose = onCommunityDeleted(community => {
5182
+ * // ...
5183
+ * })
5184
+ * ```
4326
5185
  *
4327
- * let messages = []
4328
- * const unsub = observeMessages(channelId, message => merge(messages, message))
5186
+ * Fired when a {@link Amity.Community} has been deleted
5187
+ *
5188
+ * @param callback The function to call when the event was fired
5189
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
5190
+ *
5191
+ * @category Community Events
5192
+ */
5193
+ const onCommunityDeleted = (callback) => createCommunityEventSubscriber('community.deleted', callback);
5194
+
5195
+ /**
5196
+ * ```js
5197
+ * import { onCommunityJoined } from '@amityco/ts-sdk'
5198
+ * const dispose = onCommunityJoined((community, member) => {
5199
+ * // ...
5200
+ * })
4329
5201
  * ```
4330
5202
  *
4331
- * Observe all mutations on a list of {@link Amity.Message} for a given {@link Amity.Channel} object
5203
+ * Fired when a {@link Amity.Community} has been joined
4332
5204
  *
4333
- * @param client the client to observe the message with
4334
- * @param channelId the ID of the channel where to observe the messages
4335
- * @param callback the function to call when new data are available
4336
- * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the messages
5205
+ * @param callback The function to call when the event was fired
5206
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
4337
5207
  *
4338
- * @category Message Observer
5208
+ * @category Community Events
4339
5209
  */
4340
- const observeMessages = (channelId, callback) => {
4341
- const { log } = getActiveClient();
4342
- const timestamp = Date.now();
4343
- log(`observeMessages(tmpid: ${timestamp}) > listen`);
4344
- const disposers = [];
4345
- const router = (message, action) => {
4346
- var _a, _b;
4347
- if (message.channelId !== channelId)
4348
- return;
4349
- if (callback instanceof Function)
4350
- return callback(message);
4351
- (_a = callback.onEvent) === null || _a === void 0 ? void 0 : _a.call(callback, action, message);
4352
- (_b = callback[action]) === null || _b === void 0 ? void 0 : _b.call(callback, message);
4353
- };
4354
- disposers.push(onMessageCreated(message => router(message, 'onCreate')), onMessageUpdated(message => router(message, 'onUpdate')), onMessageDeleted(message => router(message, 'onDelete')));
4355
- return () => {
4356
- log(`observeMessages(tmpid: ${timestamp}) > dispose`);
4357
- disposers.forEach(fn => fn());
4358
- };
4359
- };
5210
+ const onCommunityJoined = (callback) => createCommunityMemberEventSubscriber('community.joined', callback);
4360
5211
 
4361
5212
  /**
4362
5213
  * ```js
4363
- * import { onCommunityCreated } from '@amityco/ts-sdk'
4364
- * const dispose = onCommunityCreated(channel => {
5214
+ * import { onCommunityLeft } from '@amityco/ts-sdk'
5215
+ * const dispose = onCommunityLeft((community, member) => {
4365
5216
  * // ...
4366
5217
  * })
4367
5218
  * ```
4368
5219
  *
4369
- * Fired when any {@link Amity.Community} have been created
5220
+ * Fired when a {@link Amity.Community} has been left
4370
5221
  *
4371
5222
  * @param callback The function to call when the event was fired
4372
5223
  * @returns an {@link Amity.Unsubscriber} function to stop listening
4373
5224
  *
4374
5225
  * @category Community Events
4375
5226
  */
4376
- const onCommunityCreated = (callback) => {
4377
- const client = getActiveClient();
4378
- const filter = (payload) => {
4379
- decoratePayload(payload);
4380
- ingestInCache(payload);
4381
- callback(payload.communities[0]);
4382
- };
4383
- return createEventSubscriber(client, 'onCommunityCreated', 'v3.community.didCreate', filter);
4384
- };
5227
+ const onCommunityLeft = (callback) => createCommunityMemberEventSubscriber('community.left', callback);
4385
5228
 
4386
5229
  /**
4387
5230
  * ```js
4388
- * import { onCommunityUpdated } from '@amityco/ts-sdk'
4389
- * const dispose = onCommunityUpdated(channel => {
5231
+ * import { onCommunityUserAdded } from '@amityco/ts-sdk'
5232
+ * const dispose = onCommunityUserAdded((community, member) => {
4390
5233
  * // ...
4391
5234
  * })
4392
5235
  * ```
4393
5236
  *
4394
- * Fired when any {@link Amity.Community} have been updated
5237
+ * Fired when a user has been added to a {@link Amity.Community}
4395
5238
  *
4396
5239
  * @param callback The function to call when the event was fired
4397
5240
  * @returns an {@link Amity.Unsubscriber} function to stop listening
4398
5241
  *
4399
5242
  * @category Community Events
4400
5243
  */
4401
- const onCommunityUpdated = (callback) => {
4402
- const client = getActiveClient();
4403
- const filter = (payload) => {
4404
- decoratePayload(payload);
4405
- ingestInCache(payload);
4406
- callback(payload.communities[0]);
4407
- };
4408
- return createEventSubscriber(client, 'onCommunityUpdated', 'v3.community.didUpdate', filter);
4409
- };
5244
+ const onCommunityUserAdded = (callback) => createCommunityMemberEventSubscriber('community.userAdded', callback);
4410
5245
 
4411
5246
  /**
4412
5247
  * ```js
4413
- * import { onCommunityDeleted } from '@amityco/ts-sdk'
4414
- * const dispose = onCommunityDeleted(channel => {
5248
+ * import { onCommunityUserRemoved } from '@amityco/ts-sdk'
5249
+ * const dispose = onCommunityUserRemoved((community, member) => {
4415
5250
  * // ...
4416
5251
  * })
4417
5252
  * ```
4418
5253
  *
4419
- * Fired when any {@link Amity.Community} have been deleted
5254
+ * Fired when a user has been removed from a {@link Amity.Community}
4420
5255
  *
4421
5256
  * @param callback The function to call when the event was fired
4422
5257
  * @returns an {@link Amity.Unsubscriber} function to stop listening
4423
5258
  *
4424
5259
  * @category Community Events
4425
5260
  */
4426
- const onCommunityDeleted = (callback) => {
4427
- const client = getActiveClient();
4428
- const filter = (payload) => {
4429
- decoratePayload(payload);
4430
- ingestInCache(payload);
4431
- callback(payload.communities[0]);
4432
- };
4433
- return createEventSubscriber(client, 'onCommunityDeleted', 'v3.community.didDelete', filter);
4434
- };
5261
+ const onCommunityUserRemoved = (callback) => createCommunityMemberEventSubscriber('community.userRemoved', callback);
4435
5262
 
4436
5263
  /**
4437
5264
  * ```js
4438
- * import { onCommunityJoined } from '@amityco/ts-sdk'
4439
- * const dispose = onCommunityJoined(channel => {
5265
+ * import { onCommunityUserBanned } from '@amityco/ts-sdk'
5266
+ * const dispose = onCommunityUserBanned((community, member) => {
4440
5267
  * // ...
4441
5268
  * })
4442
5269
  * ```
4443
5270
  *
4444
- * Fired when any {@link Amity.Community} was joined
5271
+ * Fired when a user has been banned in a {@link Amity.Community}
4445
5272
  *
4446
5273
  * @param callback The function to call when the event was fired
4447
5274
  * @returns an {@link Amity.Unsubscriber} function to stop listening
4448
5275
  *
4449
5276
  * @category Community Events
4450
5277
  */
4451
- const onCommunityJoined = (callback) => {
4452
- const client = getActiveClient();
4453
- const filter = (payload) => {
4454
- decoratePayload(payload);
4455
- ingestInCache(payload);
4456
- callback(payload.communities[0]);
4457
- };
4458
- return createEventSubscriber(client, 'onCommunityJoined', 'v3.community.didJoin', filter);
4459
- };
5278
+ const onCommunityUserBanned = (callback) => createCommunityMemberEventSubscriber('community.userBanned', callback);
4460
5279
 
4461
5280
  /**
4462
5281
  * ```js
4463
- * import { onCommunityLeft } from '@amityco/ts-sdk'
4464
- * const dispose = onCommunityLeft(channel => {
5282
+ * import { onCommunityUserUnbanned } from '@amityco/ts-sdk'
5283
+ * const dispose = onCommunityUserUnbanned((community, member) => {
4465
5284
  * // ...
4466
5285
  * })
4467
5286
  * ```
4468
5287
  *
4469
- * Fired when any {@link Amity.Community} was left
5288
+ * Fired when a user has been unbanned in a {@link Amity.Community}
4470
5289
  *
4471
5290
  * @param callback The function to call when the event was fired
4472
5291
  * @returns an {@link Amity.Unsubscriber} function to stop listening
4473
5292
  *
4474
5293
  * @category Community Events
4475
5294
  */
4476
- const onCommunityLeft = (callback) => {
4477
- const client = getActiveClient();
4478
- const filter = (payload) => {
4479
- decoratePayload(payload);
4480
- ingestInCache(payload);
4481
- callback(payload.communities[0]);
4482
- };
4483
- return createEventSubscriber(client, 'onCommunityLeft', 'v3.community.didLeave', filter);
4484
- };
5295
+ const onCommunityUserUnbanned = (callback) => createCommunityMemberEventSubscriber('community.userUnbanned', callback);
4485
5296
 
4486
5297
  /**
4487
5298
  * ```js
@@ -4505,19 +5316,22 @@ const observeCommunity = (communityId, callback) => {
4505
5316
  log(`observeCommunity(tmpid: ${timestamp}) > listen`);
4506
5317
  // wrapper function to make sure
4507
5318
  const router = (result, action) => {
4508
- var _a, _b, _c;
4509
- // filter function
4510
- if (((_a = result.data) === null || _a === void 0 ? void 0 : _a.communityId) !== communityId)
4511
- return;
5319
+ var _a, _b;
4512
5320
  if (callback instanceof Function)
4513
5321
  return callback(result);
4514
5322
  if (action !== 'onFetch')
4515
- (_b = callback.onEvent) === null || _b === void 0 ? void 0 : _b.call(callback, action, result);
4516
- (_c = callback[action]) === null || _c === void 0 ? void 0 : _c.call(callback, result);
5323
+ (_a = callback.onEvent) === null || _a === void 0 ? void 0 : _a.call(callback, action, result);
5324
+ (_b = callback[action]) === null || _b === void 0 ? void 0 : _b.call(callback, result);
5325
+ };
5326
+ const realtimeRouter = (result, action) => {
5327
+ var _a;
5328
+ if (((_a = result.data) === null || _a === void 0 ? void 0 : _a.communityId) !== communityId)
5329
+ return;
5330
+ router(result, action);
4517
5331
  };
4518
5332
  const disposers = [];
4519
- disposers.push(onCommunityUpdated(data => router({ data }, 'onUpdate')), onCommunityDeleted(data => router({ data }, 'onDelete')), onCommunityJoined(data => router({ data }, 'onJoin')), onCommunityLeft(data => router({ data }, 'onLeft')));
4520
- runQuery(createQuery(getCommunity, communityId), result => result.data && router(result, 'onFetch'));
5333
+ disposers.push(onCommunityUpdated(data => realtimeRouter({ data }, 'onUpdate')), onCommunityDeleted(data => realtimeRouter({ data }, 'onDelete')), onCommunityJoined(data => realtimeRouter({ data }, 'onJoin')), onCommunityLeft(data => realtimeRouter({ data }, 'onLeft')), onCommunityUserAdded(data => realtimeRouter({ data }, 'onUserAdded')), onCommunityUserRemoved(data => realtimeRouter({ data }, 'onUserRemoved')), onCommunityUserBanned(data => realtimeRouter({ data }, 'onUserBanned')), onCommunityUserUnbanned(data => realtimeRouter({ data }, 'onUserUnbanned')));
5334
+ runQuery(createQuery(getCommunity, communityId), result => router(result, 'onFetch'));
4521
5335
  return () => {
4522
5336
  log(`observeCommunity(tmpid: ${timestamp}) > dispose`);
4523
5337
  disposers.forEach(fn => fn());
@@ -4554,81 +5368,6 @@ const queryGlobalFeed = async (query) => {
4554
5368
  return { data: toRecord(posts), nextPage, prevPage };
4555
5369
  };
4556
5370
 
4557
- /**
4558
- * ```js
4559
- * import { onPostCreated } from '@amityco/ts-sdk'
4560
- * const dispose = onPostCreated(post => {
4561
- * // ...
4562
- * })
4563
- * ```
4564
- *
4565
- * Fired when an {@link Amity.Post} has been created
4566
- *
4567
- * @param callback The function to call when the event was fired
4568
- * @returns an {@link Amity.Unsubscriber} function to stop listening
4569
- *
4570
- * @category Post Events
4571
- */
4572
- const onPostCreated = (callback) => {
4573
- const client = getActiveClient();
4574
- const filter = (payload) => {
4575
- decoratePayload(payload);
4576
- ingestInCache(payload);
4577
- callback(payload.posts[0]);
4578
- };
4579
- return createEventSubscriber(client, 'message/onPostCreated', 'v3.post.didCreate', filter);
4580
- };
4581
-
4582
- /**
4583
- * ```js
4584
- * import { onPostUpdated } from '@amityco/ts-sdk'
4585
- * const dispose = onPostUpdated(post => {
4586
- * // ...
4587
- * })
4588
- * ```
4589
- *
4590
- * Fired when an {@link Amity.Post} has been updated
4591
- *
4592
- * @param callback The function to call when the event was fired
4593
- * @returns an {@link Amity.Unsubscriber} function to stop listening
4594
- *
4595
- * @category Post Events
4596
- */
4597
- const onPostUpdated = (callback) => {
4598
- const client = getActiveClient();
4599
- const filter = (payload) => {
4600
- decoratePayload(payload);
4601
- ingestInCache(payload);
4602
- callback(payload.posts[0]);
4603
- };
4604
- return createEventSubscriber(client, 'message/onPostUpdated', 'v3.post.didUpdate', filter);
4605
- };
4606
-
4607
- /**
4608
- * ```js
4609
- * import { onPostDeleted } from '@amityco/ts-sdk'
4610
- * const dispose = onPostDeleted(post => {
4611
- * // ...
4612
- * })
4613
- * ```
4614
- *
4615
- * Fired when an {@link Amity.Post} has been deleted
4616
- *
4617
- * @param callback The function to call when the event was fired
4618
- * @returns an {@link Amity.Unsubscriber} function to stop listening
4619
- *
4620
- * @category Post Events
4621
- */
4622
- const onPostDeleted = (callback) => {
4623
- const client = getActiveClient();
4624
- const filter = (payload) => {
4625
- decoratePayload(payload);
4626
- ingestInCache(payload);
4627
- callback(payload.posts[0]);
4628
- };
4629
- return createEventSubscriber(client, 'message/onPostDeleted', 'v3.post.didDelete', filter);
4630
- };
4631
-
4632
5371
  /**
4633
5372
  * ```js
4634
5373
  * import { observePosts } from '@amityco/ts-sdk'
@@ -4664,7 +5403,7 @@ const observePosts = (params, callback) => {
4664
5403
  (_a = callback.onEvent) === null || _a === void 0 ? void 0 : _a.call(callback, action, post);
4665
5404
  (_b = callback[action]) === null || _b === void 0 ? void 0 : _b.call(callback, post);
4666
5405
  };
4667
- disposers.push(onPostCreated(post => router(post, 'onCreate')), onPostUpdated(post => router(post, 'onUpdate')), onPostDeleted(post => router(post, 'onDelete')));
5406
+ disposers.push(onPostCreated(post => router(post, 'onCreate')), onPostUpdated(post => router(post, 'onUpdate')), onPostDeleted(post => router(post, 'onDelete')), onPostApproved(post => router(post, 'onApproved')), onPostDeclined(post => router(post, 'onDeclined')), onPostFlagged(post => router(post, 'onFlagged')), onPostUnflagged(post => router(post, 'onUnflagged')), onPostReactionAdded(post => router(post, 'onReactionAdded')), onPostReactionRemoved(post => router(post, 'onReactionRemoved')));
4668
5407
  return () => {
4669
5408
  log(`observePosts(tmpid: ${timestamp}) > dispose`);
4670
5409
  disposers.forEach(fn => fn());
@@ -4693,100 +5432,28 @@ const observePost = (postId, callback, policy = 'cache_then_server') => {
4693
5432
  log(`observePost(tmpid: ${timestamp}) > listen`);
4694
5433
  // wrapper function to make sure
4695
5434
  const router = (result, action) => {
4696
- var _a, _b, _c;
4697
- // filter function
4698
- if (((_a = result.data) === null || _a === void 0 ? void 0 : _a.postId) !== postId)
4699
- return;
5435
+ var _a, _b;
4700
5436
  if (callback instanceof Function)
4701
5437
  return callback(result);
4702
5438
  if (action !== 'onFetch')
4703
- (_b = callback.onEvent) === null || _b === void 0 ? void 0 : _b.call(callback, action, result);
4704
- (_c = callback[action]) === null || _c === void 0 ? void 0 : _c.call(callback, result);
5439
+ (_a = callback.onEvent) === null || _a === void 0 ? void 0 : _a.call(callback, action, result);
5440
+ (_b = callback[action]) === null || _b === void 0 ? void 0 : _b.call(callback, result);
5441
+ };
5442
+ const realtimeRouter = (result, action) => {
5443
+ var _a;
5444
+ if (((_a = result.data) === null || _a === void 0 ? void 0 : _a.postId) !== postId)
5445
+ return;
5446
+ router(result, action);
4705
5447
  };
4706
5448
  const disposers = [];
4707
- disposers.push(onPostUpdated(data => router({ data }, 'onUpdate')), onPostDeleted(data => router({ data }, 'onDelete')));
4708
- runQuery(createQuery(getPost, postId), (result) => result.data && router(result, 'onFetch'), queryOptions(policy));
5449
+ disposers.push(onPostUpdated(data => realtimeRouter({ data }, 'onUpdate')), onPostDeleted(data => realtimeRouter({ data }, 'onDelete')), onPostApproved(data => realtimeRouter({ data }, 'onApproved')), onPostDeclined(data => realtimeRouter({ data }, 'onDeclined')), onPostFlagged(data => realtimeRouter({ data }, 'onFlagged')), onPostUnflagged(data => realtimeRouter({ data }, 'onUnflagged')), onPostReactionAdded(data => realtimeRouter({ data }, 'onReactionAdded')), onPostReactionRemoved(data => realtimeRouter({ data }, 'onReactionRemoved')));
5450
+ runQuery(createQuery(getPost, postId), (result) => router(result, 'onFetch'), queryOptions(policy));
4709
5451
  return () => {
4710
5452
  log(`observePosts(tmpid: ${timestamp}) > dispose`);
4711
5453
  disposers.forEach(fn => fn());
4712
5454
  };
4713
5455
  };
4714
5456
 
4715
- /**
4716
- * ```js
4717
- * import { onCommentCreated } from '@amityco/ts-sdk'
4718
- * const dispose = onCommentCreated(comment => {
4719
- * // ...
4720
- * })
4721
- * ```
4722
- *
4723
- * Fired when an {@link Amity.Comment} has been created
4724
- *
4725
- * @param callback The function to call when the event was fired
4726
- * @returns an {@link Amity.Unsubscriber} function to stop listening
4727
- *
4728
- * @category Comment Events
4729
- */
4730
- const onCommentCreated = (callback) => {
4731
- const client = getActiveClient();
4732
- const filter = (payload) => {
4733
- decoratePayload(payload);
4734
- ingestInCache(payload);
4735
- callback(payload.comments[0]);
4736
- };
4737
- return createEventSubscriber(client, 'message/onCommentCreated', 'v3.comment.didCreate', filter);
4738
- };
4739
-
4740
- /**
4741
- * ```js
4742
- * import { onCommentUpdated } from '@amityco/ts-sdk'
4743
- * const dispose = onCommentUpdated(comment => {
4744
- * // ...
4745
- * })
4746
- * ```
4747
- *
4748
- * Fired when an {@link Amity.Comment} has been updated
4749
- *
4750
- * @param callback The function to call when the event was fired
4751
- * @returns an {@link Amity.Unsubscriber} function to stop listening
4752
- *
4753
- * @category Comment Events
4754
- */
4755
- const onCommentUpdated = (callback) => {
4756
- const client = getActiveClient();
4757
- const filter = (payload) => {
4758
- decoratePayload(payload);
4759
- ingestInCache(payload);
4760
- callback(payload.comments[0]);
4761
- };
4762
- return createEventSubscriber(client, 'message/onCommentUpdated', 'v3.comment.didUpdate', filter);
4763
- };
4764
-
4765
- /**
4766
- * ```js
4767
- * import { onCommentDeleted } from '@amityco/ts-sdk'
4768
- * const dispose = onCommentDeleted(comment => {
4769
- * // ...
4770
- * })
4771
- * ```
4772
- *
4773
- * Fired when an {@link Amity.Comment} has been deleted
4774
- *
4775
- * @param callback The function to call when the event was fired
4776
- * @returns an {@link Amity.Unsubscriber} function to stop listening
4777
- *
4778
- * @category Comment Events
4779
- */
4780
- const onCommentDeleted = (callback) => {
4781
- const client = getActiveClient();
4782
- const filter = (payload) => {
4783
- decoratePayload(payload);
4784
- ingestInCache(payload);
4785
- callback(payload.comments[0]);
4786
- };
4787
- return createEventSubscriber(client, 'message/onCommentDeleted', 'v3.comment.didDelete', filter);
4788
- };
4789
-
4790
5457
  /**
4791
5458
  * ```js
4792
5459
  * import { observeComments } from '@amityco/ts-sdk'
@@ -4817,7 +5484,7 @@ const observeComments = (postId, callback) => {
4817
5484
  (_a = callback.onEvent) === null || _a === void 0 ? void 0 : _a.call(callback, action, comment);
4818
5485
  (_b = callback[action]) === null || _b === void 0 ? void 0 : _b.call(callback, comment);
4819
5486
  };
4820
- disposers.push(onCommentCreated(comment => router(comment, 'onCreate')), onCommentUpdated(comment => router(comment, 'onUpdate')), onCommentDeleted(comment => router(comment, 'onDelete')));
5487
+ disposers.push(onCommentCreated(comment => router(comment, 'onCreate')), onCommentUpdated(comment => router(comment, 'onUpdate')), onCommentDeleted(comment => router(comment, 'onDelete')), onCommentFlagged(comment => router(comment, 'onFlagged')), onCommentUnflagged(comment => router(comment, 'onUnflagged')), onCommentReactionAdded(comment => router(comment, 'onReactionAdded')), onCommentReactionRemoved(comment => router(comment, 'onReactionRemoved')));
4821
5488
  return () => {
4822
5489
  log(`observeComments(tmpid: ${timestamp}) > dispose`);
4823
5490
  disposers.forEach(fn => fn());
@@ -4846,19 +5513,22 @@ const observeComment = (commentId, callback, policy = 'cache_then_server') => {
4846
5513
  log(`observeComment(tmpid: ${timestamp}) > listen`);
4847
5514
  // wrapper function to make sure
4848
5515
  const router = (result, action) => {
4849
- var _a, _b, _c;
4850
- // filter function
4851
- if (((_a = result.data) === null || _a === void 0 ? void 0 : _a.commentId) !== commentId)
4852
- return;
5516
+ var _a, _b;
4853
5517
  if (callback instanceof Function)
4854
5518
  return callback(result);
4855
5519
  if (action !== 'onFetch')
4856
- (_b = callback.onEvent) === null || _b === void 0 ? void 0 : _b.call(callback, action, result);
4857
- (_c = callback[action]) === null || _c === void 0 ? void 0 : _c.call(callback, result);
5520
+ (_a = callback.onEvent) === null || _a === void 0 ? void 0 : _a.call(callback, action, result);
5521
+ (_b = callback[action]) === null || _b === void 0 ? void 0 : _b.call(callback, result);
5522
+ };
5523
+ const realtimeRouter = (result, action) => {
5524
+ var _a;
5525
+ if (((_a = result.data) === null || _a === void 0 ? void 0 : _a.commentId) !== commentId)
5526
+ return;
5527
+ router(result, action);
4858
5528
  };
4859
5529
  const disposers = [];
4860
- disposers.push(onCommentUpdated(data => router({ data }, 'onUpdate')), onCommentDeleted(data => router({ data }, 'onDelete')));
4861
- runQuery(createQuery(getComment, commentId), result => result.data && router(result, 'onFetch'), queryOptions(policy));
5530
+ disposers.push(onCommentUpdated(data => realtimeRouter({ data }, 'onUpdate')), onCommentDeleted(data => realtimeRouter({ data }, 'onDelete')), onCommentFlagged(data => realtimeRouter({ data }, 'onFlagged')), onCommentUnflagged(data => realtimeRouter({ data }, 'onUnflagged')), onCommentReactionAdded(data => realtimeRouter({ data }, 'onReactionAdded')), onCommentReactionRemoved(data => realtimeRouter({ data }, 'onReactionRemoved')));
5531
+ runQuery(createQuery(getComment, commentId), result => router(result, 'onFetch'), queryOptions(policy));
4862
5532
  return () => {
4863
5533
  log(`observeComment(tmpid: ${timestamp}) > dispose`);
4864
5534
  disposers.forEach(fn => fn());
@@ -5058,4 +5728,4 @@ const disposeStream = async (streamId) => {
5058
5728
  return videoStreamings.find(stream => stream.streamId === streamId);
5059
5729
  };
5060
5730
 
5061
- export { VERSION$1 as VERSION, addChannelMembers, addChannelMembersRole, addCommunityMembers, addCommunityMembersRole, addReaction, clearCache, connectClient, createCache, createChannel, createClient, createComment, createCommunity, createFile, createMessage, createPost, createQuery, createReport, createStream, decorateModel, decorateModels, decoratePayload, deleteChannel, deleteComment, deleteCommunity, deleteFile, deleteMessage, deletePost, deleteReport, deleteStream, disconnectClient, disposeStream, dropFromCache, enableCache, fileUrlWithSize, filterByPropEquality, getActiveClient, getChannel, getChannels, getComment, getComments, getCommunities, getCommunity, getFile, getMessage, getMessages, getPost, getPosts, getRole, getStream, getUser, getUsers, ingestInCache, isAfterBefore, isConnected, isFetcher, isFresh, isLocal, isMutator, isOffline, isPaged, isReportedByMe, isSkipLimit, isSyncable, isSynced, joinChannel, joinCommunity, leaveChannel, leaveCommunity, memoryStore, memoryStores, mergeInCache, mutateCache, observeChannel, observeComment, observeComments, observeCommunity, observeFile, observeMessage, observeMessages, observePost, observePosts, observeUser, onChannelDeleted, onChannelJoined, onChannelLeft, onChannelUpdated, onClientBanned, onClientDisconnected, onCommentCreated, onCommentDeleted, onCommentUpdated, onCommunityCreated, onCommunityDeleted, onCommunityJoined, onCommunityLeft, onCommunityUpdated, onConnectionError, onMemberAdded, onMemberRemoved, onMessageCreated, onMessageDeleted, onMessageUpdated, onPostCreated, onPostDeleted, onPostUpdated, onReactionRemoved, onUserUpdated, persistentStore, pullFromCache, pushToCache, queryChannelMembers, queryChannels, queryComments, queryCommunities, queryCommunityMembers, queryGlobalFeed, queryMessages, queryOptions, queryPosts, queryRoles, queryStreams, queryUsers, removeChannelMembers, removeChannelMembersRole, removeCommunityMembers, removeCommunityMembersRole, removeReaction, runQuery, sliceByPaging, sortByChannelSegment, sortByDisplayName, sortByFirstCreated, sortByLastActivity, sortByLastCreated, sortBySegmentNumber, syncInCache, toPage, toToken, updateChannel, updateComment, updateCommunity, updateMessage, updatePost, updateStream, updateUser };
5731
+ export { SubscriptionLevels, VERSION$1 as VERSION, addChannelMembers, addChannelMembersRole, addCommunityMembers, addCommunityMembersRole, addReaction, clearCache, connectClient, createCache, createChannel, createClient, createComment, createCommunity, createFile, createMessage, createPost, createQuery, createReport, createStream, decorateModel, decorateModels, decoratePayload, deleteChannel, deleteComment, deleteCommunity, deleteFile, deleteMessage, deletePost, deleteReport, deleteStream, disconnectClient, disposeStream, dropFromCache, enableCache, fileUrlWithSize, filterByPropEquality, getActiveClient, getChannel, getChannels, getComment, getCommentTopic, getComments, getCommunities, getCommunity, getCommunityTopic, getFile, getMessage, getMessages, getPost, getPostTopic, getPosts, getRole, getStream, getUser, getUserTopic, getUsers, ingestInCache, isAfterBefore, isConnected, isFetcher, isFresh, isLocal, isMutator, isOffline, isPaged, isReportedByMe, isSkipLimit, isSyncable, isSynced, joinChannel, joinCommunity, leaveChannel, leaveCommunity, memoryStore, memoryStores, mergeInCache, mutateCache, observeChannel, observeComment, observeComments, observeCommunity, observeFile, observeMessage, observeMessages, observePost, observePosts, observeUser, onChannelDeleted, onChannelJoined, onChannelLeft, onChannelUpdated, onClientBanned, onClientDisconnected, onCommentCreated, onCommentDeleted, onCommentFlagged, onCommentReactionAdded, onCommentReactionRemoved, onCommentUnflagged, onCommentUpdated, onCommunityCreated, onCommunityDeleted, onCommunityJoined, onCommunityLeft, onCommunityUpdated, onCommunityUserAdded, onCommunityUserBanned, onCommunityUserRemoved, onCommunityUserUnbanned, onConnectionError, onMemberAdded, onMemberRemoved, onMessageCreated, onMessageDeleted, onMessageUpdated, onPostApproved, onPostCreated, onPostDeclined, onPostDeleted, onPostFlagged, onPostReactionAdded, onPostReactionRemoved, onPostUnflagged, onPostUpdated, onReactionRemoved, onUserFlagCleared, onUserFlagged, onUserUnflagged, onUserUpdated, persistentStore, pullFromCache, pushToCache, queryChannelMembers, queryChannels, queryComments, queryCommunities, queryCommunityMembers, queryGlobalFeed, queryMessages, queryOptions, queryPosts, queryRoles, queryStreams, queryUsers, removeChannelMembers, removeChannelMembersRole, removeCommunityMembers, removeCommunityMembersRole, removeReaction, runQuery, sliceByPaging, sortByChannelSegment, sortByDisplayName, sortByFirstCreated, sortByLastActivity, sortByLastCreated, sortBySegmentNumber, subscribeTopic, syncInCache, toPage, toToken, updateChannel, updateComment, updateCommunity, updateMessage, updatePost, updateStream, updateUser };