@amityco/ts-sdk 0.0.1-02f0fa3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (611) hide show
  1. package/LICENSE +390 -0
  2. package/README.md +137 -0
  3. package/dist/@types/core/cache.d.ts +21 -0
  4. package/dist/@types/core/cache.d.ts.map +1 -0
  5. package/dist/@types/core/errors.d.ts +32 -0
  6. package/dist/@types/core/errors.d.ts.map +1 -0
  7. package/dist/@types/core/events.d.ts +46 -0
  8. package/dist/@types/core/events.d.ts.map +1 -0
  9. package/dist/@types/core/model.d.ts +41 -0
  10. package/dist/@types/core/model.d.ts.map +1 -0
  11. package/dist/@types/core/payload.d.ts +88 -0
  12. package/dist/@types/core/payload.d.ts.map +1 -0
  13. package/dist/@types/core/permissions.d.ts +71 -0
  14. package/dist/@types/core/permissions.d.ts.map +1 -0
  15. package/dist/@types/core/query.d.ts +72 -0
  16. package/dist/@types/core/query.d.ts.map +1 -0
  17. package/dist/@types/core/store.d.ts +46 -0
  18. package/dist/@types/core/store.d.ts.map +1 -0
  19. package/dist/@types/core/transport.d.ts +27 -0
  20. package/dist/@types/core/transport.d.ts.map +1 -0
  21. package/dist/@types/domains/category.d.ts +11 -0
  22. package/dist/@types/domains/category.d.ts.map +1 -0
  23. package/dist/@types/domains/channel.d.ts +26 -0
  24. package/dist/@types/domains/channel.d.ts.map +1 -0
  25. package/dist/@types/domains/client.d.ts +31 -0
  26. package/dist/@types/domains/client.d.ts.map +1 -0
  27. package/dist/@types/domains/comment.d.ts +17 -0
  28. package/dist/@types/domains/comment.d.ts.map +1 -0
  29. package/dist/@types/domains/community.d.ts +24 -0
  30. package/dist/@types/domains/community.d.ts.map +1 -0
  31. package/dist/@types/domains/content.d.ts +26 -0
  32. package/dist/@types/domains/content.d.ts.map +1 -0
  33. package/dist/@types/domains/feed.d.ts +14 -0
  34. package/dist/@types/domains/feed.d.ts.map +1 -0
  35. package/dist/@types/domains/file.d.ts +29 -0
  36. package/dist/@types/domains/file.d.ts.map +1 -0
  37. package/dist/@types/domains/group.d.ts +26 -0
  38. package/dist/@types/domains/group.d.ts.map +1 -0
  39. package/dist/@types/domains/message.d.ts +16 -0
  40. package/dist/@types/domains/message.d.ts.map +1 -0
  41. package/dist/@types/domains/partials.d.ts +42 -0
  42. package/dist/@types/domains/partials.d.ts.map +1 -0
  43. package/dist/@types/domains/post.d.ts +22 -0
  44. package/dist/@types/domains/post.d.ts.map +1 -0
  45. package/dist/@types/domains/reaction.d.ts +24 -0
  46. package/dist/@types/domains/reaction.d.ts.map +1 -0
  47. package/dist/@types/domains/stream.d.ts +47 -0
  48. package/dist/@types/domains/stream.d.ts.map +1 -0
  49. package/dist/@types/domains/user.d.ts +12 -0
  50. package/dist/@types/domains/user.d.ts.map +1 -0
  51. package/dist/@types/global.d.ts +13 -0
  52. package/dist/@types/global.d.ts.map +1 -0
  53. package/dist/@types/index.d.ts +23 -0
  54. package/dist/@types/index.d.ts.map +1 -0
  55. package/dist/category/api/getCategory.d.ts +16 -0
  56. package/dist/category/api/getCategory.d.ts.map +1 -0
  57. package/dist/category/api/index.d.ts +3 -0
  58. package/dist/category/api/index.d.ts.map +1 -0
  59. package/dist/category/api/queryCategories.d.ts +23 -0
  60. package/dist/category/api/queryCategories.d.ts.map +1 -0
  61. package/dist/channel/api/addChannelMembers.d.ts +17 -0
  62. package/dist/channel/api/addChannelMembers.d.ts.map +1 -0
  63. package/dist/channel/api/addChannelMembersRole.d.ts +18 -0
  64. package/dist/channel/api/addChannelMembersRole.d.ts.map +1 -0
  65. package/dist/channel/api/createChannel.d.ts +19 -0
  66. package/dist/channel/api/createChannel.d.ts.map +1 -0
  67. package/dist/channel/api/deleteChannel.d.ts +16 -0
  68. package/dist/channel/api/deleteChannel.d.ts.map +1 -0
  69. package/dist/channel/api/getChannel.d.ts +32 -0
  70. package/dist/channel/api/getChannel.d.ts.map +1 -0
  71. package/dist/channel/api/getChannels.d.ts +32 -0
  72. package/dist/channel/api/getChannels.d.ts.map +1 -0
  73. package/dist/channel/api/index.d.ts +14 -0
  74. package/dist/channel/api/index.d.ts.map +1 -0
  75. package/dist/channel/api/joinChannel.d.ts +16 -0
  76. package/dist/channel/api/joinChannel.d.ts.map +1 -0
  77. package/dist/channel/api/leaveChannel.d.ts +16 -0
  78. package/dist/channel/api/leaveChannel.d.ts.map +1 -0
  79. package/dist/channel/api/queryChannelMembers.d.ts +42 -0
  80. package/dist/channel/api/queryChannelMembers.d.ts.map +1 -0
  81. package/dist/channel/api/queryChannels.d.ts +43 -0
  82. package/dist/channel/api/queryChannels.d.ts.map +1 -0
  83. package/dist/channel/api/removeChannelMembers.d.ts +17 -0
  84. package/dist/channel/api/removeChannelMembers.d.ts.map +1 -0
  85. package/dist/channel/api/removeChannelMembersRole.d.ts +18 -0
  86. package/dist/channel/api/removeChannelMembersRole.d.ts.map +1 -0
  87. package/dist/channel/api/updateChannel.d.ts +17 -0
  88. package/dist/channel/api/updateChannel.d.ts.map +1 -0
  89. package/dist/channel/events/index.d.ts +7 -0
  90. package/dist/channel/events/index.d.ts.map +1 -0
  91. package/dist/channel/events/onChannelCreated.d.ts +17 -0
  92. package/dist/channel/events/onChannelCreated.d.ts.map +1 -0
  93. package/dist/channel/events/onChannelDeleted.d.ts +17 -0
  94. package/dist/channel/events/onChannelDeleted.d.ts.map +1 -0
  95. package/dist/channel/events/onChannelJoined.d.ts +17 -0
  96. package/dist/channel/events/onChannelJoined.d.ts.map +1 -0
  97. package/dist/channel/events/onChannelLeft.d.ts +17 -0
  98. package/dist/channel/events/onChannelLeft.d.ts.map +1 -0
  99. package/dist/channel/events/onChannelUpdated.d.ts +17 -0
  100. package/dist/channel/events/onChannelUpdated.d.ts.map +1 -0
  101. package/dist/channel/events/onMemberAdded.d.ts +17 -0
  102. package/dist/channel/events/onMemberAdded.d.ts.map +1 -0
  103. package/dist/channel/events/onMemberRemoved.d.ts +17 -0
  104. package/dist/channel/events/onMemberRemoved.d.ts.map +1 -0
  105. package/dist/channel/observers/index.d.ts +2 -0
  106. package/dist/channel/observers/index.d.ts.map +1 -0
  107. package/dist/channel/observers/observeChannel.d.ts +20 -0
  108. package/dist/channel/observers/observeChannel.d.ts.map +1 -0
  109. package/dist/client/api/activeClient.d.ts +17 -0
  110. package/dist/client/api/activeClient.d.ts.map +1 -0
  111. package/dist/client/api/clearCache.d.ts +15 -0
  112. package/dist/client/api/clearCache.d.ts.map +1 -0
  113. package/dist/client/api/connectClient.d.ts +26 -0
  114. package/dist/client/api/connectClient.d.ts.map +1 -0
  115. package/dist/client/api/createClient.d.ts +17 -0
  116. package/dist/client/api/createClient.d.ts.map +1 -0
  117. package/dist/client/api/disconnectClient.d.ts +16 -0
  118. package/dist/client/api/disconnectClient.d.ts.map +1 -0
  119. package/dist/client/api/enableCache.d.ts +15 -0
  120. package/dist/client/api/enableCache.d.ts.map +1 -0
  121. package/dist/client/api/getToken.d.ts +19 -0
  122. package/dist/client/api/getToken.d.ts.map +1 -0
  123. package/dist/client/api/index.d.ts +8 -0
  124. package/dist/client/api/index.d.ts.map +1 -0
  125. package/dist/client/api/isConnected.d.ts +14 -0
  126. package/dist/client/api/isConnected.d.ts.map +1 -0
  127. package/dist/client/events/index.d.ts +2 -0
  128. package/dist/client/events/index.d.ts.map +1 -0
  129. package/dist/client/events/onClientDisconnected.d.ts +17 -0
  130. package/dist/client/events/onClientDisconnected.d.ts.map +1 -0
  131. package/dist/comment/api/createComment.d.ts +16 -0
  132. package/dist/comment/api/createComment.d.ts.map +1 -0
  133. package/dist/comment/api/deleteComment.d.ts +16 -0
  134. package/dist/comment/api/deleteComment.d.ts.map +1 -0
  135. package/dist/comment/api/getComment.d.ts +32 -0
  136. package/dist/comment/api/getComment.d.ts.map +1 -0
  137. package/dist/comment/api/getComments.d.ts +32 -0
  138. package/dist/comment/api/getComments.d.ts.map +1 -0
  139. package/dist/comment/api/index.d.ts +7 -0
  140. package/dist/comment/api/index.d.ts.map +1 -0
  141. package/dist/comment/api/queryComments.d.ts +53 -0
  142. package/dist/comment/api/queryComments.d.ts.map +1 -0
  143. package/dist/comment/api/updateComment.d.ts +19 -0
  144. package/dist/comment/api/updateComment.d.ts.map +1 -0
  145. package/dist/comment/events/index.d.ts +4 -0
  146. package/dist/comment/events/index.d.ts.map +1 -0
  147. package/dist/comment/events/onCommentCreated.d.ts +17 -0
  148. package/dist/comment/events/onCommentCreated.d.ts.map +1 -0
  149. package/dist/comment/events/onCommentDeleted.d.ts +17 -0
  150. package/dist/comment/events/onCommentDeleted.d.ts.map +1 -0
  151. package/dist/comment/events/onCommentUpdated.d.ts +17 -0
  152. package/dist/comment/events/onCommentUpdated.d.ts.map +1 -0
  153. package/dist/comment/observers/index.d.ts +3 -0
  154. package/dist/comment/observers/index.d.ts.map +1 -0
  155. package/dist/comment/observers/observeComment.d.ts +20 -0
  156. package/dist/comment/observers/observeComment.d.ts.map +1 -0
  157. package/dist/comment/observers/observeComments.d.ts +22 -0
  158. package/dist/comment/observers/observeComments.d.ts.map +1 -0
  159. package/dist/community/api/addCommunityMembers.d.ts +17 -0
  160. package/dist/community/api/addCommunityMembers.d.ts.map +1 -0
  161. package/dist/community/api/addCommunityMembersRole.d.ts +18 -0
  162. package/dist/community/api/addCommunityMembersRole.d.ts.map +1 -0
  163. package/dist/community/api/createCommunity.d.ts +20 -0
  164. package/dist/community/api/createCommunity.d.ts.map +1 -0
  165. package/dist/community/api/deleteCommunity.d.ts +16 -0
  166. package/dist/community/api/deleteCommunity.d.ts.map +1 -0
  167. package/dist/community/api/getCommunities.d.ts +32 -0
  168. package/dist/community/api/getCommunities.d.ts.map +1 -0
  169. package/dist/community/api/getCommunity.d.ts +32 -0
  170. package/dist/community/api/getCommunity.d.ts.map +1 -0
  171. package/dist/community/api/index.d.ts +14 -0
  172. package/dist/community/api/index.d.ts.map +1 -0
  173. package/dist/community/api/joinCommunity.d.ts +16 -0
  174. package/dist/community/api/joinCommunity.d.ts.map +1 -0
  175. package/dist/community/api/leaveCommunity.d.ts +16 -0
  176. package/dist/community/api/leaveCommunity.d.ts.map +1 -0
  177. package/dist/community/api/queryCommunities.d.ts +46 -0
  178. package/dist/community/api/queryCommunities.d.ts.map +1 -0
  179. package/dist/community/api/queryCommunityMembers.d.ts +42 -0
  180. package/dist/community/api/queryCommunityMembers.d.ts.map +1 -0
  181. package/dist/community/api/removeCommunityMembers.d.ts +17 -0
  182. package/dist/community/api/removeCommunityMembers.d.ts.map +1 -0
  183. package/dist/community/api/removeCommunityMembersRole.d.ts +18 -0
  184. package/dist/community/api/removeCommunityMembersRole.d.ts.map +1 -0
  185. package/dist/community/api/updateCommunity.d.ts +17 -0
  186. package/dist/community/api/updateCommunity.d.ts.map +1 -0
  187. package/dist/community/events/index.d.ts +6 -0
  188. package/dist/community/events/index.d.ts.map +1 -0
  189. package/dist/community/events/onCommunityCreated.d.ts +17 -0
  190. package/dist/community/events/onCommunityCreated.d.ts.map +1 -0
  191. package/dist/community/events/onCommunityDeleted.d.ts +17 -0
  192. package/dist/community/events/onCommunityDeleted.d.ts.map +1 -0
  193. package/dist/community/events/onCommunityJoined.d.ts +17 -0
  194. package/dist/community/events/onCommunityJoined.d.ts.map +1 -0
  195. package/dist/community/events/onCommunityLeft.d.ts +17 -0
  196. package/dist/community/events/onCommunityLeft.d.ts.map +1 -0
  197. package/dist/community/events/onCommunityUpdated.d.ts +17 -0
  198. package/dist/community/events/onCommunityUpdated.d.ts.map +1 -0
  199. package/dist/community/observers/index.d.ts +2 -0
  200. package/dist/community/observers/index.d.ts.map +1 -0
  201. package/dist/community/observers/observeCommunity.d.ts +20 -0
  202. package/dist/community/observers/observeCommunity.d.ts.map +1 -0
  203. package/dist/core/cache/drop.d.ts +11 -0
  204. package/dist/core/cache/drop.d.ts.map +1 -0
  205. package/dist/core/cache/index.d.ts +19 -0
  206. package/dist/core/cache/index.d.ts.map +1 -0
  207. package/dist/core/cache/ingest.d.ts +10 -0
  208. package/dist/core/cache/ingest.d.ts.map +1 -0
  209. package/dist/core/cache/merge.d.ts +10 -0
  210. package/dist/core/cache/merge.d.ts.map +1 -0
  211. package/dist/core/cache/mutate.d.ts +10 -0
  212. package/dist/core/cache/mutate.d.ts.map +1 -0
  213. package/dist/core/cache/pull.d.ts +11 -0
  214. package/dist/core/cache/pull.d.ts.map +1 -0
  215. package/dist/core/cache/push.d.ts +10 -0
  216. package/dist/core/cache/push.d.ts.map +1 -0
  217. package/dist/core/cache/sync.d.ts +10 -0
  218. package/dist/core/cache/sync.d.ts.map +1 -0
  219. package/dist/core/debug.d.ts +15 -0
  220. package/dist/core/debug.d.ts.map +1 -0
  221. package/dist/core/device.d.ts +7 -0
  222. package/dist/core/device.d.ts.map +1 -0
  223. package/dist/core/errors.d.ts +59 -0
  224. package/dist/core/errors.d.ts.map +1 -0
  225. package/dist/core/events.d.ts +33 -0
  226. package/dist/core/events.d.ts.map +1 -0
  227. package/dist/core/model/idResolvers.d.ts +20 -0
  228. package/dist/core/model/idResolvers.d.ts.map +1 -0
  229. package/dist/core/model/identifyModel.d.ts +8 -0
  230. package/dist/core/model/identifyModel.d.ts.map +1 -0
  231. package/dist/core/model/index.d.ts +4 -0
  232. package/dist/core/model/index.d.ts.map +1 -0
  233. package/dist/core/model/toRecord.d.ts +10 -0
  234. package/dist/core/model/toRecord.d.ts.map +1 -0
  235. package/dist/core/query/decorate.d.ts +23 -0
  236. package/dist/core/query/decorate.d.ts.map +1 -0
  237. package/dist/core/query/filtering.d.ts +12 -0
  238. package/dist/core/query/filtering.d.ts.map +1 -0
  239. package/dist/core/query/index.d.ts +6 -0
  240. package/dist/core/query/index.d.ts.map +1 -0
  241. package/dist/core/query/paging.d.ts +58 -0
  242. package/dist/core/query/paging.d.ts.map +1 -0
  243. package/dist/core/query/query.d.ts +121 -0
  244. package/dist/core/query/query.d.ts.map +1 -0
  245. package/dist/core/query/sorting.d.ts +39 -0
  246. package/dist/core/query/sorting.d.ts.map +1 -0
  247. package/dist/core/stores/index.d.ts +3 -0
  248. package/dist/core/stores/index.d.ts.map +1 -0
  249. package/dist/core/stores/memory.d.ts +30 -0
  250. package/dist/core/stores/memory.d.ts.map +1 -0
  251. package/dist/core/stores/persistent.d.ts +13 -0
  252. package/dist/core/stores/persistent.d.ts.map +1 -0
  253. package/dist/core/transports.d.ts +49 -0
  254. package/dist/core/transports.d.ts.map +1 -0
  255. package/dist/core/uuid.d.ts +2 -0
  256. package/dist/core/uuid.d.ts.map +1 -0
  257. package/dist/feed/api/index.d.ts +2 -0
  258. package/dist/feed/api/index.d.ts.map +1 -0
  259. package/dist/feed/api/queryGlobalFeed.d.ts +23 -0
  260. package/dist/feed/api/queryGlobalFeed.d.ts.map +1 -0
  261. package/dist/file/api/createFile.d.ts +16 -0
  262. package/dist/file/api/createFile.d.ts.map +1 -0
  263. package/dist/file/api/deleteFile.d.ts +16 -0
  264. package/dist/file/api/deleteFile.d.ts.map +1 -0
  265. package/dist/file/api/fileUrlWithSize.d.ts +9 -0
  266. package/dist/file/api/fileUrlWithSize.d.ts.map +1 -0
  267. package/dist/file/api/getFile.d.ts +32 -0
  268. package/dist/file/api/getFile.d.ts.map +1 -0
  269. package/dist/file/api/index.d.ts +5 -0
  270. package/dist/file/api/index.d.ts.map +1 -0
  271. package/dist/file/observers/index.d.ts +2 -0
  272. package/dist/file/observers/index.d.ts.map +1 -0
  273. package/dist/file/observers/observeFile.d.ts +20 -0
  274. package/dist/file/observers/observeFile.d.ts.map +1 -0
  275. package/dist/index.cjs.js +4884 -0
  276. package/dist/index.d.ts +32 -0
  277. package/dist/index.d.ts.map +1 -0
  278. package/dist/index.esm.js +4734 -0
  279. package/dist/index.umd.js +4880 -0
  280. package/dist/message/api/createMessage.d.ts +38 -0
  281. package/dist/message/api/createMessage.d.ts.map +1 -0
  282. package/dist/message/api/deleteMessage.d.ts +32 -0
  283. package/dist/message/api/deleteMessage.d.ts.map +1 -0
  284. package/dist/message/api/getMessage.d.ts +32 -0
  285. package/dist/message/api/getMessage.d.ts.map +1 -0
  286. package/dist/message/api/getMessages.d.ts +32 -0
  287. package/dist/message/api/getMessages.d.ts.map +1 -0
  288. package/dist/message/api/index.d.ts +7 -0
  289. package/dist/message/api/index.d.ts.map +1 -0
  290. package/dist/message/api/queryMessages.d.ts +55 -0
  291. package/dist/message/api/queryMessages.d.ts.map +1 -0
  292. package/dist/message/api/updateMessage.d.ts +38 -0
  293. package/dist/message/api/updateMessage.d.ts.map +1 -0
  294. package/dist/message/events/index.d.ts +4 -0
  295. package/dist/message/events/index.d.ts.map +1 -0
  296. package/dist/message/events/onMessageCreated.d.ts +17 -0
  297. package/dist/message/events/onMessageCreated.d.ts.map +1 -0
  298. package/dist/message/events/onMessageDeleted.d.ts +17 -0
  299. package/dist/message/events/onMessageDeleted.d.ts.map +1 -0
  300. package/dist/message/events/onMessageUpdated.d.ts +17 -0
  301. package/dist/message/events/onMessageUpdated.d.ts.map +1 -0
  302. package/dist/message/observers/index.d.ts +3 -0
  303. package/dist/message/observers/index.d.ts.map +1 -0
  304. package/dist/message/observers/observeMessage.d.ts +22 -0
  305. package/dist/message/observers/observeMessage.d.ts.map +1 -0
  306. package/dist/message/observers/observeMessages.d.ts +19 -0
  307. package/dist/message/observers/observeMessages.d.ts.map +1 -0
  308. package/dist/post/api/createPost.d.ts +21 -0
  309. package/dist/post/api/createPost.d.ts.map +1 -0
  310. package/dist/post/api/deletePost.d.ts +16 -0
  311. package/dist/post/api/deletePost.d.ts.map +1 -0
  312. package/dist/post/api/getPost.d.ts +32 -0
  313. package/dist/post/api/getPost.d.ts.map +1 -0
  314. package/dist/post/api/getPosts.d.ts +32 -0
  315. package/dist/post/api/getPosts.d.ts.map +1 -0
  316. package/dist/post/api/index.d.ts +7 -0
  317. package/dist/post/api/index.d.ts.map +1 -0
  318. package/dist/post/api/queryPosts.d.ts +45 -0
  319. package/dist/post/api/queryPosts.d.ts.map +1 -0
  320. package/dist/post/api/updatePost.d.ts +19 -0
  321. package/dist/post/api/updatePost.d.ts.map +1 -0
  322. package/dist/post/events/index.d.ts +4 -0
  323. package/dist/post/events/index.d.ts.map +1 -0
  324. package/dist/post/events/onPostCreated.d.ts +17 -0
  325. package/dist/post/events/onPostCreated.d.ts.map +1 -0
  326. package/dist/post/events/onPostDeleted.d.ts +17 -0
  327. package/dist/post/events/onPostDeleted.d.ts.map +1 -0
  328. package/dist/post/events/onPostUpdated.d.ts +17 -0
  329. package/dist/post/events/onPostUpdated.d.ts.map +1 -0
  330. package/dist/post/observers/index.d.ts +3 -0
  331. package/dist/post/observers/index.d.ts.map +1 -0
  332. package/dist/post/observers/observePost.d.ts +20 -0
  333. package/dist/post/observers/observePost.d.ts.map +1 -0
  334. package/dist/post/observers/observePosts.d.ts +25 -0
  335. package/dist/post/observers/observePosts.d.ts.map +1 -0
  336. package/dist/reaction/api/addReaction.d.ts +36 -0
  337. package/dist/reaction/api/addReaction.d.ts.map +1 -0
  338. package/dist/reaction/api/index.d.ts +3 -0
  339. package/dist/reaction/api/index.d.ts.map +1 -0
  340. package/dist/reaction/api/removeReaction.d.ts +36 -0
  341. package/dist/reaction/api/removeReaction.d.ts.map +1 -0
  342. package/dist/reaction/events/index.d.ts +2 -0
  343. package/dist/reaction/events/index.d.ts.map +1 -0
  344. package/dist/reaction/events/onReactionAdded.d.ts +17 -0
  345. package/dist/reaction/events/onReactionAdded.d.ts.map +1 -0
  346. package/dist/reaction/events/onReactionRemoved.d.ts +17 -0
  347. package/dist/reaction/events/onReactionRemoved.d.ts.map +1 -0
  348. package/dist/reaction/utils/dispatchReactable.d.ts +3 -0
  349. package/dist/reaction/utils/dispatchReactable.d.ts.map +1 -0
  350. package/dist/reaction/utils/fetchReference.d.ts +3 -0
  351. package/dist/reaction/utils/fetchReference.d.ts.map +1 -0
  352. package/dist/reaction/utils/index.d.ts +3 -0
  353. package/dist/reaction/utils/index.d.ts.map +1 -0
  354. package/dist/report/api/createReport.d.ts +16 -0
  355. package/dist/report/api/createReport.d.ts.map +1 -0
  356. package/dist/report/api/deleteReport.d.ts +16 -0
  357. package/dist/report/api/deleteReport.d.ts.map +1 -0
  358. package/dist/report/api/index.d.ts +4 -0
  359. package/dist/report/api/index.d.ts.map +1 -0
  360. package/dist/report/api/isReportedByMe.d.ts +16 -0
  361. package/dist/report/api/isReportedByMe.d.ts.map +1 -0
  362. package/dist/report/constants/referenceTypes.d.ts +24 -0
  363. package/dist/report/constants/referenceTypes.d.ts.map +1 -0
  364. package/dist/role/api/getRole.d.ts +32 -0
  365. package/dist/role/api/getRole.d.ts.map +1 -0
  366. package/dist/role/api/index.d.ts +3 -0
  367. package/dist/role/api/index.d.ts.map +1 -0
  368. package/dist/role/api/queryRoles.d.ts +42 -0
  369. package/dist/role/api/queryRoles.d.ts.map +1 -0
  370. package/dist/stream/api/createStream.d.ts +18 -0
  371. package/dist/stream/api/createStream.d.ts.map +1 -0
  372. package/dist/stream/api/deleteStream.d.ts +16 -0
  373. package/dist/stream/api/deleteStream.d.ts.map +1 -0
  374. package/dist/stream/api/getStream.d.ts +12 -0
  375. package/dist/stream/api/getStream.d.ts.map +1 -0
  376. package/dist/stream/api/index.d.ts +6 -0
  377. package/dist/stream/api/index.d.ts.map +1 -0
  378. package/dist/stream/api/queryStreams.d.ts +23 -0
  379. package/dist/stream/api/queryStreams.d.ts.map +1 -0
  380. package/dist/stream/api/updateStream.d.ts +17 -0
  381. package/dist/stream/api/updateStream.d.ts.map +1 -0
  382. package/dist/stream/events/index.d.ts +4 -0
  383. package/dist/stream/events/index.d.ts.map +1 -0
  384. package/dist/stream/events/onStreamRecorded.d.ts +17 -0
  385. package/dist/stream/events/onStreamRecorded.d.ts.map +1 -0
  386. package/dist/stream/events/onStreamStarted.d.ts +17 -0
  387. package/dist/stream/events/onStreamStarted.d.ts.map +1 -0
  388. package/dist/stream/events/onStreamStopped.d.ts +17 -0
  389. package/dist/stream/events/onStreamStopped.d.ts.map +1 -0
  390. package/dist/user/api/getUser.d.ts +32 -0
  391. package/dist/user/api/getUser.d.ts.map +1 -0
  392. package/dist/user/api/getUsers.d.ts +32 -0
  393. package/dist/user/api/getUsers.d.ts.map +1 -0
  394. package/dist/user/api/index.d.ts +5 -0
  395. package/dist/user/api/index.d.ts.map +1 -0
  396. package/dist/user/api/queryUsers.d.ts +43 -0
  397. package/dist/user/api/queryUsers.d.ts.map +1 -0
  398. package/dist/user/api/updateUser.d.ts +17 -0
  399. package/dist/user/api/updateUser.d.ts.map +1 -0
  400. package/dist/user/events/index.d.ts +2 -0
  401. package/dist/user/events/index.d.ts.map +1 -0
  402. package/dist/user/events/onUserUpdated.d.ts +17 -0
  403. package/dist/user/events/onUserUpdated.d.ts.map +1 -0
  404. package/dist/user/observers/index.d.ts +2 -0
  405. package/dist/user/observers/index.d.ts.map +1 -0
  406. package/dist/user/observers/observeUser.d.ts +19 -0
  407. package/dist/user/observers/observeUser.d.ts.map +1 -0
  408. package/package.json +59 -0
  409. package/rollup.config.js +41 -0
  410. package/src/@types/core/cache.ts +22 -0
  411. package/src/@types/core/errors.ts +34 -0
  412. package/src/@types/core/events.ts +60 -0
  413. package/src/@types/core/model.ts +51 -0
  414. package/src/@types/core/payload.ts +102 -0
  415. package/src/@types/core/permissions.ts +76 -0
  416. package/src/@types/core/query.ts +95 -0
  417. package/src/@types/core/store.ts +52 -0
  418. package/src/@types/core/transport.ts +32 -0
  419. package/src/@types/domains/category.ts +15 -0
  420. package/src/@types/domains/channel.ts +38 -0
  421. package/src/@types/domains/client.ts +36 -0
  422. package/src/@types/domains/comment.ts +26 -0
  423. package/src/@types/domains/community.ts +35 -0
  424. package/src/@types/domains/content.ts +35 -0
  425. package/src/@types/domains/feed.ts +16 -0
  426. package/src/@types/domains/file.ts +41 -0
  427. package/src/@types/domains/group.ts +38 -0
  428. package/src/@types/domains/message.ts +27 -0
  429. package/src/@types/domains/partials.ts +52 -0
  430. package/src/@types/domains/post.ts +31 -0
  431. package/src/@types/domains/reaction.ts +30 -0
  432. package/src/@types/domains/stream.ts +57 -0
  433. package/src/@types/domains/user.ts +18 -0
  434. package/src/@types/global.ts +25 -0
  435. package/src/@types/index.ts +31 -0
  436. package/src/category/api/getCategory.ts +35 -0
  437. package/src/category/api/index.ts +2 -0
  438. package/src/category/api/queryCategories.ts +49 -0
  439. package/src/channel/api/addChannelMembers.ts +45 -0
  440. package/src/channel/api/addChannelMembersRole.ts +43 -0
  441. package/src/channel/api/createChannel.ts +37 -0
  442. package/src/channel/api/deleteChannel.ts +34 -0
  443. package/src/channel/api/getChannel.ts +59 -0
  444. package/src/channel/api/getChannels.ts +63 -0
  445. package/src/channel/api/index.ts +18 -0
  446. package/src/channel/api/joinChannel.ts +38 -0
  447. package/src/channel/api/leaveChannel.ts +38 -0
  448. package/src/channel/api/queryChannelMembers.ts +79 -0
  449. package/src/channel/api/queryChannels.ts +89 -0
  450. package/src/channel/api/removeChannelMembers.ts +45 -0
  451. package/src/channel/api/removeChannelMembersRole.ts +43 -0
  452. package/src/channel/api/updateChannel.ts +38 -0
  453. package/src/channel/events/index.ts +6 -0
  454. package/src/channel/events/onChannelCreated.ts +37 -0
  455. package/src/channel/events/onChannelDeleted.ts +37 -0
  456. package/src/channel/events/onChannelJoined.ts +37 -0
  457. package/src/channel/events/onChannelLeft.ts +37 -0
  458. package/src/channel/events/onChannelUpdated.ts +37 -0
  459. package/src/channel/events/onMemberAdded.ts +37 -0
  460. package/src/channel/events/onMemberRemoved.ts +37 -0
  461. package/src/channel/observers/index.ts +1 -0
  462. package/src/channel/observers/observeChannel.ts +80 -0
  463. package/src/client/api/activeClient.ts +33 -0
  464. package/src/client/api/clearCache.ts +23 -0
  465. package/src/client/api/connectClient.ts +63 -0
  466. package/src/client/api/createClient.ts +56 -0
  467. package/src/client/api/disconnectClient.ts +31 -0
  468. package/src/client/api/enableCache.ts +35 -0
  469. package/src/client/api/getToken.ts +35 -0
  470. package/src/client/api/index.ts +7 -0
  471. package/src/client/api/isConnected.ts +24 -0
  472. package/src/client/events/index.ts +1 -0
  473. package/src/client/events/onClientDisconnected.ts +29 -0
  474. package/src/comment/api/createComment.ts +43 -0
  475. package/src/comment/api/deleteComment.ts +40 -0
  476. package/src/comment/api/getComment.ts +59 -0
  477. package/src/comment/api/getComments.ts +63 -0
  478. package/src/comment/api/index.ts +7 -0
  479. package/src/comment/api/queryComments.ts +169 -0
  480. package/src/comment/api/updateComment.ts +41 -0
  481. package/src/comment/events/index.ts +3 -0
  482. package/src/comment/events/onCommentCreated.ts +39 -0
  483. package/src/comment/events/onCommentDeleted.ts +39 -0
  484. package/src/comment/events/onCommentUpdated.ts +39 -0
  485. package/src/comment/observers/index.ts +2 -0
  486. package/src/comment/observers/observeComment.ts +73 -0
  487. package/src/comment/observers/observeComments.ts +61 -0
  488. package/src/community/api/addCommunityMembers.ts +46 -0
  489. package/src/community/api/addCommunityMembersRole.ts +43 -0
  490. package/src/community/api/createCommunity.ts +43 -0
  491. package/src/community/api/deleteCommunity.ts +35 -0
  492. package/src/community/api/getCommunities.ts +63 -0
  493. package/src/community/api/getCommunity.ts +58 -0
  494. package/src/community/api/index.ts +17 -0
  495. package/src/community/api/joinCommunity.ts +41 -0
  496. package/src/community/api/leaveCommunity.ts +41 -0
  497. package/src/community/api/queryCommunities.ts +92 -0
  498. package/src/community/api/queryCommunityMembers.ts +78 -0
  499. package/src/community/api/removeCommunityMembers.ts +46 -0
  500. package/src/community/api/removeCommunityMembersRole.ts +43 -0
  501. package/src/community/api/updateCommunity.ts +40 -0
  502. package/src/community/events/index.ts +6 -0
  503. package/src/community/events/onCommunityCreated.ts +37 -0
  504. package/src/community/events/onCommunityDeleted.ts +37 -0
  505. package/src/community/events/onCommunityJoined.ts +37 -0
  506. package/src/community/events/onCommunityLeft.ts +37 -0
  507. package/src/community/events/onCommunityUpdated.ts +37 -0
  508. package/src/community/observers/index.ts +1 -0
  509. package/src/community/observers/observeCommunity.ts +74 -0
  510. package/src/core/cache/drop.ts +24 -0
  511. package/src/core/cache/index.ts +24 -0
  512. package/src/core/cache/ingest.ts +24 -0
  513. package/src/core/cache/merge.ts +19 -0
  514. package/src/core/cache/mutate.ts +25 -0
  515. package/src/core/cache/pull.ts +31 -0
  516. package/src/core/cache/push.ts +41 -0
  517. package/src/core/cache/sync.ts +41 -0
  518. package/src/core/debug.ts +26 -0
  519. package/src/core/device.ts +38 -0
  520. package/src/core/errors.ts +85 -0
  521. package/src/core/events.ts +93 -0
  522. package/src/core/model/idResolvers.ts +66 -0
  523. package/src/core/model/identifyModel.ts +32 -0
  524. package/src/core/model/index.ts +3 -0
  525. package/src/core/model/toRecord.ts +11 -0
  526. package/src/core/query/decorate.ts +64 -0
  527. package/src/core/query/filtering.ts +17 -0
  528. package/src/core/query/index.ts +5 -0
  529. package/src/core/query/paging.ts +166 -0
  530. package/src/core/query/query.ts +300 -0
  531. package/src/core/query/sorting.ts +50 -0
  532. package/src/core/stores/index.ts +2 -0
  533. package/src/core/stores/memory.ts +59 -0
  534. package/src/core/stores/persistent.ts +63 -0
  535. package/src/core/transports.ts +157 -0
  536. package/src/core/uuid.ts +2 -0
  537. package/src/feed/api/index.ts +1 -0
  538. package/src/feed/api/queryGlobalFeed.ts +50 -0
  539. package/src/file/api/createFile.ts +51 -0
  540. package/src/file/api/deleteFile.ts +35 -0
  541. package/src/file/api/fileUrlWithSize.ts +13 -0
  542. package/src/file/api/getFile.ts +60 -0
  543. package/src/file/api/index.ts +4 -0
  544. package/src/file/observers/index.ts +1 -0
  545. package/src/file/observers/observeFile.ts +57 -0
  546. package/src/index.ts +55 -0
  547. package/src/message/api/createMessage.ts +90 -0
  548. package/src/message/api/deleteMessage.ts +75 -0
  549. package/src/message/api/getMessage.ts +60 -0
  550. package/src/message/api/getMessages.ts +63 -0
  551. package/src/message/api/index.ts +6 -0
  552. package/src/message/api/queryMessages.ts +145 -0
  553. package/src/message/api/updateMessage.ts +79 -0
  554. package/src/message/events/index.ts +3 -0
  555. package/src/message/events/onMessageCreated.ts +39 -0
  556. package/src/message/events/onMessageDeleted.ts +39 -0
  557. package/src/message/events/onMessageUpdated.ts +39 -0
  558. package/src/message/observers/index.ts +2 -0
  559. package/src/message/observers/observeMessage.ts +76 -0
  560. package/src/message/observers/observeMessages.ts +60 -0
  561. package/src/post/api/createPost.ts +45 -0
  562. package/src/post/api/deletePost.ts +43 -0
  563. package/src/post/api/getPost.ts +60 -0
  564. package/src/post/api/getPosts.ts +63 -0
  565. package/src/post/api/index.ts +7 -0
  566. package/src/post/api/queryPosts.ts +86 -0
  567. package/src/post/api/updatePost.ts +42 -0
  568. package/src/post/events/index.ts +3 -0
  569. package/src/post/events/onPostCreated.ts +39 -0
  570. package/src/post/events/onPostDeleted.ts +39 -0
  571. package/src/post/events/onPostUpdated.ts +39 -0
  572. package/src/post/observers/index.ts +2 -0
  573. package/src/post/observers/observePost.ts +72 -0
  574. package/src/post/observers/observePosts.ts +66 -0
  575. package/src/reaction/api/addReaction.ts +84 -0
  576. package/src/reaction/api/index.ts +2 -0
  577. package/src/reaction/api/removeReaction.ts +84 -0
  578. package/src/reaction/events/index.ts +1 -0
  579. package/src/reaction/events/onReactionAdded.ts +43 -0
  580. package/src/reaction/events/onReactionRemoved.ts +41 -0
  581. package/src/reaction/utils/dispatchReactable.ts +19 -0
  582. package/src/reaction/utils/fetchReference.ts +18 -0
  583. package/src/reaction/utils/index.ts +2 -0
  584. package/src/report/api/createReport.ts +40 -0
  585. package/src/report/api/deleteReport.ts +40 -0
  586. package/src/report/api/index.ts +4 -0
  587. package/src/report/api/isReportedByMe.ts +37 -0
  588. package/src/report/constants/referenceTypes.ts +22 -0
  589. package/src/role/api/getRole.ts +53 -0
  590. package/src/role/api/index.ts +2 -0
  591. package/src/role/api/queryRoles.ts +79 -0
  592. package/src/stream/api/createStream.ts +33 -0
  593. package/src/stream/api/deleteStream.ts +38 -0
  594. package/src/stream/api/getStream.ts +29 -0
  595. package/src/stream/api/index.ts +7 -0
  596. package/src/stream/api/queryStreams.ts +44 -0
  597. package/src/stream/api/updateStream.ts +36 -0
  598. package/src/stream/events/index.ts +3 -0
  599. package/src/stream/events/onStreamRecorded.ts +39 -0
  600. package/src/stream/events/onStreamStarted.ts +39 -0
  601. package/src/stream/events/onStreamStopped.ts +39 -0
  602. package/src/user/api/getUser.ts +59 -0
  603. package/src/user/api/getUsers.ts +60 -0
  604. package/src/user/api/index.ts +5 -0
  605. package/src/user/api/queryUsers.ts +88 -0
  606. package/src/user/api/updateUser.ts +44 -0
  607. package/src/user/events/index.ts +1 -0
  608. package/src/user/events/onUserUpdated.ts +39 -0
  609. package/src/user/observers/index.ts +1 -0
  610. package/src/user/observers/observeUser.ts +64 -0
  611. package/tsconfig.json +28 -0
@@ -0,0 +1,4880 @@
1
+ var Amity = (function (exports, jsBase64, nativeIdGenerator, debug, axios, HttpAgent, io, mitt, AsyncStorage) {
2
+ 'use strict';
3
+
4
+ function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
5
+
6
+ var nativeIdGenerator__default = /*#__PURE__*/_interopDefaultLegacy(nativeIdGenerator);
7
+ var debug__default = /*#__PURE__*/_interopDefaultLegacy(debug);
8
+ var axios__default = /*#__PURE__*/_interopDefaultLegacy(axios);
9
+ var HttpAgent__default = /*#__PURE__*/_interopDefaultLegacy(HttpAgent);
10
+ var io__default = /*#__PURE__*/_interopDefaultLegacy(io);
11
+ var mitt__default = /*#__PURE__*/_interopDefaultLegacy(mitt);
12
+ var AsyncStorage__default = /*#__PURE__*/_interopDefaultLegacy(AsyncStorage);
13
+
14
+ /**
15
+ * Generic ASC error
16
+ * @category Errors
17
+ */
18
+ class ASCError extends Error {
19
+ /**
20
+ * @param message A custom error message
21
+ * @param code A normalized error code
22
+ * @param level A normalized failure level descriptor
23
+ */
24
+ constructor(message, code, level) {
25
+ super(`Amity SDK (${code}): ${message}`);
26
+ this.code = code;
27
+ this.level = level;
28
+ this.type = 'ASC';
29
+ this.timestamp = Date.now();
30
+ if (Error.captureStackTrace)
31
+ Error.captureStackTrace(this, ASCError);
32
+ }
33
+ }
34
+ /**
35
+ * API level error
36
+ * @category Errors
37
+ */
38
+ class ASCApiError extends ASCError {
39
+ /**
40
+ * @param code A normalized error code
41
+ * @param level A normalized failure level descriptor
42
+ */
43
+ constructor(message, code, level) {
44
+ super(message, code, level);
45
+ }
46
+ }
47
+ /**
48
+ * Unexpected error
49
+ * @category Errors
50
+ */
51
+ class ASCUnknownError extends ASCError {
52
+ /**
53
+ * @param code A normalized error code
54
+ * @param level A normalized failure level descriptor
55
+ */
56
+ constructor(code = 800000 /* UNKNOWN_ERROR */, level = "fatal" /* FATAL */) {
57
+ super('Unexpected error', code, level);
58
+ }
59
+ }
60
+ /**
61
+ * Network related error
62
+ * @category Errors
63
+ */
64
+ class ASCConnectionError extends ASCError {
65
+ /**
66
+ * @param message A custom error message
67
+ */
68
+ constructor(message = 'SDK client is having connection issues') {
69
+ super(message, 800210 /* CONNECTION_ERROR */, "error" /* ERROR */);
70
+ }
71
+ }
72
+
73
+ let activeClient = null;
74
+ /**
75
+ * Get the active client
76
+ *
77
+ * @returns the active client instance
78
+ *
79
+ * @hidden
80
+ */
81
+ const getActiveClient = () => {
82
+ if (!activeClient) {
83
+ throw new ASCError('There is no active client', 800000 /* UNKNOWN_ERROR */, "fatal" /* FATAL */);
84
+ }
85
+ return activeClient;
86
+ };
87
+ /**
88
+ * Sets the active client
89
+ *
90
+ * @param client the client to assume as currently active client
91
+ *
92
+ * @hidden
93
+ */
94
+ const setActiveClient = (client) => {
95
+ activeClient = client;
96
+ };
97
+
98
+ /**
99
+ * Pull objects from the cache layer
100
+ *
101
+ * @param name The name of the store to query
102
+ * @param keys A collection of unique keys for the store
103
+ * @returns The collection of objects matching the keys. Keys which don't match object will be omitted
104
+ *
105
+ * @category Cache
106
+ */
107
+ const pullFromCache = (name, ...keys) => {
108
+ var _a;
109
+ const { cache } = getActiveClient();
110
+ const store = cache === null || cache === void 0 ? void 0 : cache[name];
111
+ if (!cache || !store)
112
+ return;
113
+ const state = (_a = store.read()) !== null && _a !== void 0 ? _a : {};
114
+ // return all
115
+ if (!(keys === null || keys === void 0 ? void 0 : keys.length))
116
+ return Object.values(state);
117
+ // return some
118
+ return keys
119
+ .map(key => {
120
+ const localId = cache.lookup[`${name}#${key}`];
121
+ return state[localId];
122
+ })
123
+ .filter(Boolean);
124
+ };
125
+
126
+ /**
127
+ * Dictionary of resolver functions for each model
128
+ * @hidden
129
+ */
130
+ const idResolvers = {
131
+ user: ({ userId }) => userId,
132
+ file: ({ fileId }) => fileId,
133
+ role: ({ roleId }) => roleId,
134
+ channel: ({ channelId }) => channelId,
135
+ channelUsers: ({ channelId, userId }) => `${channelId}#${userId}`,
136
+ message: ({ messageId }) => messageId,
137
+ community: ({ communityId }) => communityId,
138
+ communityUsers: ({ communityId, userId }) => `${communityId}#${userId}`,
139
+ post: ({ postId }) => postId,
140
+ comment: ({ commentId }) => commentId,
141
+ stream: ({ streamId }) => streamId,
142
+ };
143
+ /**
144
+ * Retrieve the id resolver matching a domain name
145
+ *
146
+ * @param name the domain name for the resolve
147
+ * @returns an idResolver for the given domain name
148
+ */
149
+ const getResolver = (name) => idResolvers[name];
150
+ /**
151
+ * A map of v3 response keys to a store name.
152
+ * @hidden
153
+ */
154
+ const storeInterests = {
155
+ users: 'user',
156
+ files: 'file',
157
+ roles: 'role',
158
+ channels: 'channel',
159
+ channelUsers: 'channelUsers',
160
+ messages: 'message',
161
+ communities: 'community',
162
+ communityUsers: 'communityUsers',
163
+ posts: 'post',
164
+ postChildren: 'post',
165
+ comments: 'comment',
166
+ };
167
+
168
+ /**
169
+ * Pull objects from the cache layer
170
+ *
171
+ * @param name The name of the store to query
172
+ * @param models A collection of models t store
173
+ *
174
+ * @category Cache
175
+ */
176
+ const pushToCache = (name, ...models) => {
177
+ const { cache } = getActiveClient();
178
+ const store = cache === null || cache === void 0 ? void 0 : cache[name];
179
+ if (!cache || !store)
180
+ return;
181
+ const filtered = models.filter(Boolean);
182
+ if (!filtered.length)
183
+ return;
184
+ const synced = Object.fromEntries(filtered.map(model => {
185
+ var _a;
186
+ var _b, _c;
187
+ const modelId = getResolver(name)(model);
188
+ const localId = ((_a = (_b = cache.lookup)[_c = `${name}#${modelId}`]) !== null && _a !== void 0 ? _a : (_b[_c] = model.localId));
189
+ // WARNING: shallow immutable
190
+ return [localId, Object.assign(Object.assign({
191
+ // @ts-ignore: syncedAt is before "...model" so it can be manually overridden
192
+ syncedAt: Date.now() }, model), { localId })];
193
+ }));
194
+ store.write(synced);
195
+ };
196
+
197
+ /**
198
+ * Pull objects from the cache layer
199
+ *
200
+ * @param name The name of the store to query
201
+ * @param keys A collection of unique keys for the store
202
+ * @returns The collection of objects matching the keys. Keys which don't match object will be omitted
203
+ *
204
+ * @category Cache
205
+ */
206
+ const dropFromCache = (name, partial) => {
207
+ const { cache } = getActiveClient();
208
+ const store = cache === null || cache === void 0 ? void 0 : cache[name];
209
+ if (!cache || !store)
210
+ return [];
211
+ const modelId = getResolver(name)(partial);
212
+ const localId = cache.lookup[`${name}#${modelId}`];
213
+ delete cache.lookup[`${name}#${modelId}`];
214
+ store.erase(localId);
215
+ };
216
+
217
+ /** hidden */
218
+ /** @hidden */
219
+ const CRITERIAS = {
220
+ 'file': ['fileId', 'attributes'],
221
+ 'user': ['userId', 'avatarFileId'],
222
+ 'role': ['roleId'],
223
+ 'channel': ['channelId', 'rateLimit'],
224
+ 'channelUsers': ['channelId', 'userId', 'membership'],
225
+ 'message': ['messageId'],
226
+ 'community': ['communityId', 'onlyAdminCanPost'],
227
+ 'communityUsers': ['userId', 'communityId', 'communityMembership'],
228
+ 'post': ['postId', 'feedId'],
229
+ 'comment': ['commentId', 'referenceId'],
230
+ 'stream': ['streamId'],
231
+ };
232
+ /** @hidden */
233
+ const hasKeys = (object, needles) => {
234
+ const haystack = Object.keys(object);
235
+ return needles.every(needle => haystack.includes(needle));
236
+ };
237
+ /**
238
+ * Finds the name of the store for a given unknown model
239
+ *
240
+ * @param model one of the {@link Amity.Model} to identify
241
+ * @returns the name of the corresponding store
242
+ */
243
+ const identifyModel = (model) => {
244
+ var _a;
245
+ const criterias = Object.entries(CRITERIAS);
246
+ return (_a = criterias.find(([_, keys]) => hasKeys(model, keys))) === null || _a === void 0 ? void 0 : _a[0];
247
+ };
248
+
249
+ /**
250
+ * Sync-up local ids of objects in the cache
251
+ *
252
+ * @param original The object holding the localId to keep
253
+ * @param replacement The object holding the localId to discard
254
+ *
255
+ * @category Cache
256
+ */
257
+ const syncInCache = (original, replacement) => {
258
+ var _a;
259
+ const { cache, log } = getActiveClient();
260
+ const name = (_a = identifyModel(original)) !== null && _a !== void 0 ? _a : identifyModel(replacement);
261
+ if (!name) {
262
+ log('syncInCache', 'could not identify the models', { original, replacement });
263
+ return;
264
+ }
265
+ const store = cache === null || cache === void 0 ? void 0 : cache[name];
266
+ if (!cache || !store)
267
+ return;
268
+ // remove the object from cache (it's cleaner this way)
269
+ dropFromCache(name, original);
270
+ dropFromCache(name, replacement);
271
+ // glue the localIds together
272
+ replacement.localId = original.localId;
273
+ // put back the replacement after (again, it's cleaner this way)
274
+ pushToCache(name, replacement);
275
+ };
276
+
277
+ /**
278
+ * Ingest a payload (v3) into the cache
279
+ *
280
+ * @param payload a "backend v3" payload object
281
+ * @param order the order of the keys to process (in case of need)
282
+ *
283
+ * @category Cache
284
+ */
285
+ const ingestInCache = (payload = {}, order = Object.keys(payload)) => {
286
+ order
287
+ .forEach(key => {
288
+ const name = storeInterests[key];
289
+ if (!name)
290
+ return;
291
+ pushToCache(name, ...payload[key]);
292
+ });
293
+ };
294
+
295
+ /**
296
+ * Apply partial mutation to objects in the cache
297
+ *
298
+ * @param name The name of the store to query
299
+ * @param mutation A partial view of the object to update
300
+ *
301
+ * @category Cache
302
+ */
303
+ const mutateCache = (name, key, mutator) => {
304
+ var _a;
305
+ const [model] = (_a = pullFromCache(name, key)) !== null && _a !== void 0 ? _a : [];
306
+ if (!model)
307
+ return;
308
+ const mutation = mutator(model);
309
+ mutation && pushToCache(name, Object.assign(Object.assign({}, model), mutation));
310
+ return mutation;
311
+ };
312
+
313
+ /**
314
+ * Apply partial mutation to objects in the cache
315
+ *
316
+ * @param name The name of the store to query
317
+ * @param mutation A partial view of the object to update
318
+ *
319
+ * @category Cache
320
+ */
321
+ const mergeInCache = (name, mutation) => {
322
+ const key = getResolver(name)(mutation);
323
+ mutateCache(name, key, model => (Object.assign(Object.assign({}, model), mutation)));
324
+ };
325
+
326
+ /**
327
+ * Creates a cache instance. The cache instance will handle stores
328
+ * given to it as input, and will be used as the first source of cached data
329
+ * in the SDK.
330
+ *
331
+ * @param stores A partial collection of stores
332
+ * @returns A cache instance
333
+ *
334
+ * @category Cache
335
+ */
336
+ const createCache = (stores) => {
337
+ const lookup = {};
338
+ return Object.assign({ lookup }, stores);
339
+ };
340
+
341
+ // @ts-ignore
342
+ /**
343
+ * Type guard to find if the a given decoded backend token uses "skip/limit" pagination style
344
+ *
345
+ * @param json any json object as extracted from the backend
346
+ * @returns success boolean if the token has either "skip" or "limit" props
347
+ *
348
+ * @hidden
349
+ */
350
+ const isSkipLimit = (json) => (['skip', 'limit'].some(prop => prop in json));
351
+ /**
352
+ * Type guard to find if the a given decoded backend token uses "after/before" pagination style
353
+ *
354
+ * @param json any json object as extracted from the backend
355
+ * @returns success boolean if the token has either "after" or "before" props
356
+ *
357
+ * @hidden
358
+ */
359
+ const isAfterBefore = (json) => (['after', 'before', 'first', 'last'].some(prop => prop in json));
360
+ /**
361
+ * Type guard to find if the a given object is wrapped around Amity.Paged<>
362
+ *
363
+ * @param payload any object as passed from query functions
364
+ * @returns success boolean if the object is an array shaped as [Record<string, Amity.Syncable>, Amity.Pages]
365
+ *
366
+ * @hidden
367
+ */
368
+ const isPaged = (payload) => {
369
+ return ((payload === null || payload === void 0 ? void 0 : payload.hasOwnProperty('data'))
370
+ && (payload === null || payload === void 0 ? void 0 : payload.hasOwnProperty('nextPage'))
371
+ && (payload === null || payload === void 0 ? void 0 : payload.hasOwnProperty('prevPage')));
372
+ };
373
+ /**
374
+ * Converts a paging object into a b64 string token
375
+ *
376
+ * @param paging the sdk-friendly paging object
377
+ * @param style the style of token to produce
378
+ * @returns a backend's b64 encoded token
379
+ *
380
+ * @hidden
381
+ */
382
+ const toToken = (paging, style) => {
383
+ var _a;
384
+ if (!paging || !Object.keys(paging).length)
385
+ return;
386
+ let payload = {};
387
+ // TODO: refactor this clean
388
+ if (style === 'skiplimit') {
389
+ payload = {
390
+ skip: (_a = paging.after) !== null && _a !== void 0 ? _a : 0,
391
+ limit: paging.limit,
392
+ };
393
+ }
394
+ else if (style === 'afterbefore') {
395
+ /*
396
+ Caution: this testing style is only valid because
397
+ our backend expects nothing else than a number as
398
+ "before" or "after" value. if that would change,
399
+ we'd need to move toward a more simple: `!paging.before`
400
+ */
401
+ if (!isNaN(paging === null || paging === void 0 ? void 0 : paging.before)) {
402
+ payload = {
403
+ before: paging.before,
404
+ last: paging.limit,
405
+ };
406
+ }
407
+ else if (!isNaN(paging === null || paging === void 0 ? void 0 : paging.after)) {
408
+ payload = {
409
+ after: paging.after,
410
+ first: paging.limit,
411
+ };
412
+ }
413
+ }
414
+ // avoid sending {} as it seems backend flips when we do
415
+ if (!Object.keys(payload).length)
416
+ return;
417
+ // don't try catch, let it throw
418
+ return jsBase64.encode(JSON.stringify(payload));
419
+ };
420
+ /**
421
+ * Converts a b64 string token into a paging object
422
+ *
423
+ * @param token the backend's b64 encoded token
424
+ * @returns a sdk-friendly paging object
425
+ *
426
+ * @hidden
427
+ */
428
+ const toPage = (token) => {
429
+ if (!token)
430
+ return null;
431
+ // don't try catch, let it throw
432
+ const json = JSON.parse(jsBase64.decode(token));
433
+ if (isSkipLimit(json)) {
434
+ return {
435
+ after: json.skip,
436
+ limit: json.limit,
437
+ };
438
+ }
439
+ else if (isAfterBefore(json)) {
440
+ if ('before' in json) {
441
+ return {
442
+ before: json.before,
443
+ limit: json.last,
444
+ };
445
+ }
446
+ else if ('after' in json) {
447
+ return {
448
+ after: json.after,
449
+ limit: json.first,
450
+ };
451
+ }
452
+ }
453
+ return null;
454
+ };
455
+ /**
456
+ * Slices a collection according to its paging
457
+ *
458
+ * @param type the type of collection (for unique id identification with after/before)
459
+ * @param collection the collection to slice
460
+ * @param paging the paging object
461
+ * @returns the sliced collection according to the paging definition
462
+ *
463
+ * @hidden
464
+ */
465
+ const sliceByPaging = (type, collection, page) => {
466
+ console.log('slice by paging', page);
467
+ if (!page)
468
+ return collection.slice();
469
+ let start = 0;
470
+ let end = undefined;
471
+ // next page behavior
472
+ if (page.after) {
473
+ start = page.after;
474
+ end = start + page.limit;
475
+ // prev page behavior
476
+ }
477
+ else if (page.before) {
478
+ end = page.before + 1;
479
+ start = end > page.limit ? end - page.limit : 0;
480
+ }
481
+ const paged = collection.slice(start, end);
482
+ return paged.length === page.limit ? paged : undefined;
483
+ };
484
+
485
+ /**
486
+ * Type guard to check and cast that a given async function is has the ".locally" property
487
+ *
488
+ * @param func any SDK APi function
489
+ * @returns success boolean if the function has a 'locally' twin
490
+ *
491
+ * @hidden
492
+ */
493
+ const isFetcher = (func) => ('locally' in func);
494
+ /**
495
+ * Type guard to check and cast that a given async function is has the ".optimistically" property
496
+ *
497
+ * @param func any SDK APi function
498
+ * @returns success boolean if the function has an 'optimistically' twin
499
+ *
500
+ * @hidden
501
+ */
502
+ const isMutator = (func) => ('optimistically' in func);
503
+ /**
504
+ * Type guard to check and cast that a given async function is has
505
+ * the ".locally" or ".optimistically" property
506
+ *
507
+ * @param func any SDK APi function
508
+ * @returns success boolean if the function has an offline twin
509
+ *
510
+ * @hidden
511
+ */
512
+ const isOffline = (func) => isFetcher(func) || isMutator(func);
513
+ /**
514
+ * Type guard to check and cast that a given object has the "syncedAt" property
515
+ *
516
+ * @param model any object to check on
517
+ * @returns success boolean if the object has property "syncedAt"
518
+ *
519
+ * @hidden
520
+ */
521
+ const isSyncable = (model) => (model === null || model === void 0 ? void 0 : model.hasOwnProperty('syncedAt'));
522
+ /**
523
+ * Checks if a model is considered local (syncedAt === -1)
524
+ *
525
+ * @param model any syncable object to check
526
+ * @returns success boolean if the object is marked as local
527
+ *
528
+ * @hidden
529
+ */
530
+ const isLocal = (model) => {
531
+ return isSyncable(model) && (model === null || model === void 0 ? void 0 : model.syncedAt) === -1;
532
+ };
533
+ /**
534
+ * Checks if a model is considered fresh
535
+ *
536
+ * @param model any syncable object to check
537
+ * @param lifeSpan the supposedly duration for which the object is considered synced
538
+ * @returns success boolean if the object is below the given lifespan
539
+ *
540
+ * @hidden
541
+ */
542
+ const isFresh = (model, lifeSpan = 0) => {
543
+ var _a;
544
+ return Date.now() - ((_a = model === null || model === void 0 ? void 0 : model.syncedAt) !== null && _a !== void 0 ? _a : 0) <= lifeSpan;
545
+ };
546
+ /**
547
+ * Checks if a model is considered synced
548
+ *
549
+ * @param model any syncable object to check
550
+ * @param lifeSpan the supposedly duration for which the object is considered synced
551
+ * @returns success boolean if the object is local or below the given lifespan
552
+ *
553
+ * @hidden
554
+ */
555
+ const isSynced = (model, lifeSpan = 0) => {
556
+ return isLocal(model) || isFresh(model, lifeSpan);
557
+ };
558
+ /**
559
+ * ```js
560
+ * import { createQuery, getUser } from '@amityco/ts-sdk'
561
+ * const query = createQuery(getUser, 'foobar')
562
+ * ```
563
+ *
564
+ * Creates a wrapper for the API call you wish to call.
565
+ * This wrapper is necessary to create for optimistically calls
566
+ *
567
+ *
568
+ * @param fn A compatible API function from the ts sdk
569
+ * @param args The arguments to pass to the function passed as `fn`
570
+ * @returns A wrapper containing both the function and its future arguments
571
+ *
572
+ * @category Query
573
+ */
574
+ const createQuery = (func, ...args) => ({ func, args });
575
+ /**
576
+ * ```js
577
+ * import { queryOptions } from '@amityco/ts-sdk'
578
+ * const options = queryOptions('no_fetch', lifeSpan)
579
+ * ```
580
+ *
581
+ * Creates a query options object based on the query policy passed
582
+ *
583
+ * @param policy The policy to apply to a query
584
+ * @returns A properly set query options object
585
+ *
586
+ * @category Query
587
+ */
588
+ const queryOptions = (policy, lifeSpan = 2 * 60 * 1000) => {
589
+ if (policy === 'cache_only')
590
+ return { lifeSpan: Infinity };
591
+ else if (policy === 'server_only')
592
+ return { lifeSpan: 0 };
593
+ return { lifeSpan };
594
+ };
595
+ /**
596
+ * Checks if an unknown shaped payload is considered empty or not.
597
+ * Since the payload can be wrapped around [] or {} (query or get many),
598
+ * we need a smarter definition of what's considered "empty".
599
+ *
600
+ * @param local the unknown object to check for emptiness
601
+ * @returns true if the mixed-shape "local" content is considered empty
602
+ *
603
+ * @hidden
604
+ */
605
+ const isEmpty = (local) => {
606
+ // if it's supposed to be a single object, it'd be undefined
607
+ if (!local)
608
+ return true;
609
+ // it's a paged query, the 1st cell of the array would be empty
610
+ else if (isPaged(local) && isEmpty(local.data)) {
611
+ return true;
612
+ }
613
+ // if it's a item collection, it'd have no keys
614
+ else if (!Object.keys(local).length)
615
+ return true;
616
+ return false;
617
+ };
618
+ /**
619
+ * Checks if an unknown shaped payload is considered synced or not.
620
+ * The object will first be identified by 3 types of shapes:
621
+ *
622
+ * 1. Amity.Paged<Amity.Syncable>
623
+ * 2. Amity.Syncable
624
+ * 3. Record<string, Amity.Syncable>
625
+ *
626
+ * then the "Syncable" component will be extracted and evaluated against
627
+ * the query options' lifeSpan value.
628
+ *
629
+ * @param local the unknown object to check for freshness
630
+ * @param options query options (for lifeSpan checking)
631
+ * @returns true if the mixed-shape "local" content is considered fresh
632
+ *
633
+ * @hidden
634
+ */
635
+ const shouldAbort = (local, options) => {
636
+ // it's a paged query
637
+ if (isPaged(local) && shouldAbort(local.data, options)) {
638
+ return true;
639
+ }
640
+ // if it's object let's try to see if it's Amity.Syncable first
641
+ else if (isSynced(local, options.lifeSpan)) {
642
+ return true;
643
+ }
644
+ // otherwise consider as Record<string, Amity.Syncable>
645
+ else if (Object.values(local).length > 0 &&
646
+ Object.values(local).every(item => isSynced(item, options.lifeSpan))) {
647
+ return true;
648
+ }
649
+ return false;
650
+ };
651
+ /**
652
+ * ```js
653
+ * import { createQuery, getUser, runQuery } from '@amityco/ts-sdk'
654
+ * const query = createQuery(getUser, client, 'foobar')
655
+ * runQuery(query, user => console.log(user))
656
+ * ```
657
+ *
658
+ * Calls an API function wrapped around a Amity.Query, and executes the callback whenever
659
+ * a value is available. The value can be picked either from the local cache and/or
660
+ * from the server afterwards depending on the query options passed
661
+ *
662
+ * @param query A query object wrapping the call to be made
663
+ * @param callback A function to execute when a value is available
664
+ * @param options the query options
665
+ *
666
+ * @category Query
667
+ */
668
+ const runQuery = ({ func, args }, callback, options = queryOptions('cache_then_server')) => {
669
+ if (!isOffline(func) || options.lifeSpan === 0) {
670
+ callback === null || callback === void 0 ? void 0 : callback(wrap(undefined, {
671
+ origin: 'server',
672
+ loading: true
673
+ }));
674
+ func(...args)
675
+ .then(fresh => {
676
+ callback === null || callback === void 0 ? void 0 : callback(wrap(fresh, {
677
+ origin: 'server',
678
+ loading: false,
679
+ }));
680
+ })
681
+ .catch(error => {
682
+ callback === null || callback === void 0 ? void 0 : callback(wrap(undefined, {
683
+ error,
684
+ loading: false,
685
+ }));
686
+ });
687
+ return;
688
+ }
689
+ const local = isMutator(func)
690
+ ? func.optimistically(...args)
691
+ : func.locally(...args);
692
+ if (!isEmpty(local)) {
693
+ callback === null || callback === void 0 ? void 0 : callback(wrap(local, { origin: 'local' }));
694
+ }
695
+ if (local && isFetcher(func) && shouldAbort(local, options))
696
+ return;
697
+ callback === null || callback === void 0 ? void 0 : callback(wrap(local, {
698
+ origin: 'local',
699
+ loading: true,
700
+ }));
701
+ func(...args)
702
+ .then(fresh => {
703
+ // @ts-ignore i know.
704
+ isLocal(local) && syncInCache(local, fresh);
705
+ callback === null || callback === void 0 ? void 0 : callback(wrap(fresh, {
706
+ origin: 'server',
707
+ loading: false
708
+ }));
709
+ })
710
+ .catch(error => {
711
+ callback === null || callback === void 0 ? void 0 : callback(wrap(local, {
712
+ error,
713
+ loading: false,
714
+ }));
715
+ });
716
+ };
717
+ /**
718
+ *
719
+ * @param data
720
+ * @param meta
721
+ * @returns
722
+ */
723
+ const wrap = (data, meta = {}) => {
724
+ if (isPaged(data))
725
+ return Object.assign(Object.assign({}, meta), data);
726
+ return Object.assign(Object.assign({}, meta), { data });
727
+ };
728
+
729
+ const uuid = () => nativeIdGenerator__default['default'].v4().toString();
730
+
731
+ /**
732
+ * Creates a pre-configured logger instance
733
+ *
734
+ * @param session The name of the debug session
735
+ * @returns A pre-configured logger function
736
+ *
737
+ * @category Debug
738
+ * @hidden
739
+ */
740
+ const createLogger = (session) => {
741
+ const active = (`${session === null || session === void 0 ? void 0 : session.trim()}`.length > 0
742
+ && process.env.NODE_ENV !== 'production');
743
+ const logger = debug__default['default'](session);
744
+ const print = (topic, ...args) => {
745
+ active && logger(topic, args);
746
+ };
747
+ print.__instance__ = logger;
748
+ return print;
749
+ };
750
+
751
+ /**
752
+ * Axios param serializer (for querystring)
753
+ * @hidden
754
+ */
755
+ const stringify = (params, prefix) => {
756
+ return Object.entries(params)
757
+ .filter(([, value]) => value !== undefined)
758
+ .map(([name, value]) => {
759
+ const key = prefix ? `${prefix}[${name}]` : name;
760
+ if (Array.isArray(value)) {
761
+ return value.map(item => `${key}[]=${item}`).join('&');
762
+ }
763
+ else if (typeof value !== 'object') {
764
+ return `${key}=${value}`;
765
+ }
766
+ return stringify(value, prefix !== null && prefix !== void 0 ? prefix : name);
767
+ })
768
+ .join('&');
769
+ };
770
+ /**
771
+ * Creates a pre-configured axios instance
772
+ *
773
+ * @param endpoint The ASC rest api server's URL
774
+ * @returns A pre-configured axios instance
775
+ *
776
+ * @category Transport
777
+ * @hidden
778
+ */
779
+ const createHttpTransport = (endpoint = 'https://api.amity.co') => {
780
+ const options = {
781
+ maxSockets: 100,
782
+ maxFreeSockets: 10,
783
+ timeout: 60000,
784
+ freeSocketTimeout: 30000,
785
+ };
786
+ const instance = axios__default['default'].create({
787
+ baseURL: endpoint,
788
+ httpAgent: new HttpAgent__default['default'](options),
789
+ httpsAgent: new HttpAgent.HttpsAgent(options),
790
+ paramsSerializer: stringify,
791
+ });
792
+ instance.interceptors.response.use((response) => response, (error) => {
793
+ var _a;
794
+ const { response } = error;
795
+ console.error((_a = response === null || response === void 0 ? void 0 : response.data) !== null && _a !== void 0 ? _a : error);
796
+ if (response)
797
+ unwrapPayload(response.data);
798
+ });
799
+ return instance;
800
+ };
801
+ /**
802
+ * Creates a pre-configured socket.io instance
803
+ *
804
+ * @param endpoint The socket.io server's URL
805
+ * @returns A pre-configured (non-connected) socket.io client instance
806
+ *
807
+ * @category Transport
808
+ * @hidden
809
+ */
810
+ const createWebsocketTransport = (endpoint = 'https://api.ekomedia.technology') => {
811
+ const socket = io__default['default'](endpoint, {
812
+ autoConnect: false,
813
+ reconnectionDelay: 2000,
814
+ transports: ['websocket'],
815
+ });
816
+ socket.on('disconnect', (reason) => {
817
+ if (reason === 'io server disconnect')
818
+ socket.connect();
819
+ });
820
+ ['error', 'connect_error', 'connect_timeout', 'reconnect_error', 'reconnect_failed'].forEach(event => {
821
+ socket.on(event, (error) => {
822
+ throw new ASCConnectionError(`socket.io(${event}): ${error.message}`);
823
+ });
824
+ });
825
+ return socket;
826
+ };
827
+ /**
828
+ * Unwraps v3 server payload (for error handling and type extraction)
829
+ *
830
+ * @param response A typical "v3" response (related to backend's service strategy)
831
+ *
832
+ * @returns The data returned by the backend
833
+ * @throws An error related to backend's rejection
834
+ *
835
+ * @category Transport
836
+ * @hidden
837
+ */
838
+ const unwrapPayload = (response) => {
839
+ if (response.status === 'success') {
840
+ return response.data;
841
+ }
842
+ else if (response.status === 'fail') {
843
+ throw new ASCUnknownError(response.code);
844
+ }
845
+ else if (response.status === 'error') {
846
+ throw new ASCApiError(response.message, response.code, "error" /* ERROR */);
847
+ }
848
+ // unjust, but helps force uncast "T | undefined" to allow deconstruction without warnings
849
+ return undefined;
850
+ };
851
+ /**
852
+ * Promisify a websocket event emission - resulting in a synchronous http-like XHR (ws legacy)
853
+ *
854
+ * @param client The current client for which to send the event with
855
+ * @param event The websocket event name
856
+ * @param data The event's payload
857
+ *
858
+ * @returns The data returned by the backend
859
+ * @throws An error related to backend's rejection
860
+ *
861
+ * @category Transport
862
+ * @async
863
+ * @hidden
864
+ */
865
+ const synchronousWSCall = async (client, event, data) => {
866
+ const { ws } = client;
867
+ const value = await new Promise((resolve, reject) => {
868
+ ws.emit(event, data, (response) => {
869
+ try {
870
+ resolve(unwrapPayload(response));
871
+ }
872
+ catch (error) {
873
+ reject(error);
874
+ }
875
+ });
876
+ });
877
+ return value;
878
+ };
879
+
880
+ // need to sync up the list
881
+ const EVENTS = [
882
+ 'disconnected',
883
+ 'v3.user.didUpdate',
884
+ 'v3.channel.didUpdate',
885
+ 'v3.channel.didUpdate',
886
+ 'v3.channel.didJoin',
887
+ 'v3.channel.didLeave',
888
+ 'v3.channel.didAddUsers',
889
+ 'v3.channel.didRemoveUsers',
890
+ 'v3.channel.didBan',
891
+ 'v3.channel.didUnban',
892
+ 'v3.message.didCreate',
893
+ 'v3.message.didUpdate',
894
+ 'v3.message.didDelete',
895
+ ];
896
+ /** @hidden */
897
+ const createEventEmitter = () => {
898
+ return mitt__default['default']();
899
+ };
900
+ /**
901
+ * Wraps the websocket events into the client's event emitter for
902
+ * abstraction of transport.
903
+ *
904
+ * @param ws A websocket connection to listen from
905
+ * @param emitter An event emitter to wire the events to
906
+ *
907
+ * @category Transport
908
+ * @hidden
909
+ */
910
+ const proxyWebsocketEvents = (ws, emitter) => {
911
+ EVENTS.forEach(event => {
912
+ ws.on(event, (param) => emitter.emit(event, param));
913
+ });
914
+ };
915
+ /**
916
+ * Standardize the subscription of SSE through web sockets
917
+ *
918
+ * @param client The current client for which to subscribe the event to
919
+ * @param namespace A unique name for the logger
920
+ * @param event The websocket event name
921
+ * @param fn A wrapper for the callback.
922
+ * @returns A dispose function to unsubscribe to the event
923
+ *
924
+ * @category Transport
925
+ * @hidden
926
+ */
927
+ const createEventSubscriber = (client, namespace, event, fn) => {
928
+ const { log, emitter } = client;
929
+ const timestamp = Date.now();
930
+ log(`${namespace}(tmpid: ${timestamp}) > listen`);
931
+ const handler = (...payload) => {
932
+ log(`${namespace}(tmpid: ${timestamp}) > trigger`, payload);
933
+ fn(...payload);
934
+ };
935
+ emitter.on(event, handler);
936
+ return () => {
937
+ log(`${namespace}(tmpid: ${timestamp}) > dispose`);
938
+ emitter.off(event, handler);
939
+ };
940
+ };
941
+ /**
942
+ * Wrapper around dispatch event
943
+ *
944
+ * @hidden
945
+ */
946
+ const fireEvent = (event, payload) => {
947
+ const { emitter } = getActiveClient();
948
+ setTimeout(() => { emitter.emit(event, payload); }, 0);
949
+ };
950
+
951
+ /**
952
+ * ```js
953
+ * import { createClient } from '@amityco/ts-sdk'
954
+ * const client = createClient(apiKey, 'https://asc.server/', 'myClient')
955
+ * ```
956
+ *
957
+ * Creates a new {@link Amity.Client} instance
958
+ *
959
+ * @param apiKey for the {@link Amity.Client} instance
960
+ * @param apiEndpoint endpoint to connect to
961
+ * @param debugSession session's identifier for the client's logger instance
962
+ * @returns A {@link Amity.Client} instance
963
+ *
964
+ * @category Client API
965
+ **/
966
+ const createClient = (apiKey, apiEndpoint = 'https://api.amity.co', debugSession = 'amity') => {
967
+ const log = createLogger(debugSession);
968
+ log('client/api/createClient', {
969
+ apiKey: apiKey.replace(/.{5}$/g, 'xxxxx'),
970
+ apiEndpoint,
971
+ });
972
+ const http = createHttpTransport(apiEndpoint);
973
+ const ws = createWebsocketTransport(apiEndpoint);
974
+ const emitter = createEventEmitter();
975
+ const client = {
976
+ apiKey, log, http, ws, emitter,
977
+ use: () => setActiveClient(client),
978
+ };
979
+ try {
980
+ getActiveClient();
981
+ }
982
+ catch (_a) {
983
+ setActiveClient(client);
984
+ }
985
+ return client;
986
+ };
987
+
988
+ // TODO: find a way to uniquely identify the device
989
+ // import { getStorage } from './storage'
990
+ /** @hidden */
991
+ const VERSION = '11.0.0';
992
+ /** @hidden */
993
+ const getDeviceId = () => {
994
+ // here maybe put some auto detection of the device id based on if it's react or not?
995
+ // anyhow we let consumer branch out if they want, but it doesn't mean we shouldn't try to be nice
996
+ // and do things automatically
997
+ // https://www.npmjs.com/package/react-native-device-info#getuniqueid
998
+ // how to make sure that the react native package will not be included when build is for web
999
+ return `ascWebSdk#${Math.random().toString(16)}`;
1000
+ };
1001
+ /** @hidden */
1002
+ const getDeviceModel = () => {
1003
+ var _a, _b;
1004
+ if ((_a = process === null || process === void 0 ? void 0 : process.versions) === null || _a === void 0 ? void 0 : _a.node)
1005
+ return process.versions.node;
1006
+ if (navigator)
1007
+ return `${navigator.product.toLowerCase()}#${(_b = navigator.userAgent) !== null && _b !== void 0 ? _b : 'unknown_agent'}`;
1008
+ return 'unknown_model';
1009
+ };
1010
+ /** @hidden */
1011
+ const getDeviceInfo = () => {
1012
+ const model = getDeviceModel();
1013
+ return {
1014
+ version: VERSION,
1015
+ // TODO: replace with: kind: process.versions ? 'node' : 'web', when backend has fixed this
1016
+ kind: 'web',
1017
+ model,
1018
+ };
1019
+ };
1020
+
1021
+ /**
1022
+ * Retrieves a pair of {@link Amity.Tokens} necessary for connection
1023
+ *
1024
+ * @param userId The userId to use to issue a token
1025
+ * @param displayName The user's displayName
1026
+ * @param deviceId The user's device Id (can be manually set for native users)
1027
+ * @param authToken The authentication token - necessary when network option is set to secure
1028
+ * @return The accessToken for the given userId
1029
+ *
1030
+ * @category Client API
1031
+ * @hidden
1032
+ */
1033
+ const getToken = async (params) => {
1034
+ const client = getActiveClient();
1035
+ client.log('client/api/getToken', params);
1036
+ const deviceInfo = await getDeviceInfo();
1037
+ const { data } = await client.http.post('/v1/device', Object.assign(Object.assign({}, params), { deviceInfo }), {
1038
+ headers: { 'X-API-Key': client.apiKey }
1039
+ });
1040
+ return data;
1041
+ };
1042
+
1043
+ /**
1044
+ * ```js
1045
+ * import { connectClient } from '@amityco/ts-sdk/client/api'
1046
+ * const success = await connectClient({
1047
+ * userId: 'XYZ123456789',
1048
+ * })
1049
+ * ```
1050
+ *
1051
+ * Connects an {@link Amity.Client} instance to ASC servers
1052
+ *
1053
+ * @param userId the user ID for the current session
1054
+ * @param displayName the user's displayName for the current session
1055
+ * @param deviceId Manual override of the user's device id (for device management)
1056
+ * @param authToken The authentication token - necessary when network option is set to secure
1057
+ * @returns a success boolean if connected
1058
+ *
1059
+ * @category Client API
1060
+ * @async
1061
+ */
1062
+ const connectClient = async (params) => {
1063
+ var _a, _b;
1064
+ const client = getActiveClient();
1065
+ client.log('client/api/connectClient', Object.assign({ apiKey: client.apiKey }, params));
1066
+ // default values
1067
+ (_a = params.displayName) !== null && _a !== void 0 ? _a : (params.displayName = params.userId);
1068
+ (_b = params.deviceId) !== null && _b !== void 0 ? _b : (params.deviceId = getDeviceId());
1069
+ // @ts-ignore: in that particular case, typing can be
1070
+ // ignored since we enforce default values just before.
1071
+ const { accessToken } = await getToken(params);
1072
+ // manually setup the token for http transport
1073
+ client.http.defaults.headers.common['Authorization'] = `Bearer ${accessToken}`;
1074
+ // manually setup the token for ws transport
1075
+ client.ws.io.opts.query = { token: accessToken };
1076
+ // wire websocket events to our event emitter
1077
+ proxyWebsocketEvents(client.ws, client.emitter);
1078
+ // TODO: in phase 2, this should not be necessary. we should have WS
1079
+ // to be connected "on demand" rather than "by default"
1080
+ await new Promise(resolve => {
1081
+ client.ws.once('connect', resolve);
1082
+ client.ws.open();
1083
+ });
1084
+ client.userId = params.userId;
1085
+ return client.ws.connected;
1086
+ };
1087
+
1088
+ /**
1089
+ * ```js
1090
+ * import { disconnectClient } from '@amityco/ts-sdk'
1091
+ * const success = await disconnectClient()
1092
+ * ```
1093
+ *
1094
+ * Disconnects an {@link Amity.Client} instance from ASC servers
1095
+ *
1096
+ * @param client The {@link Amity.Client} instance to disconnect
1097
+ * @returns a success boolean if disconnected
1098
+ *
1099
+ * @category Client API
1100
+ * @async
1101
+ */
1102
+ const disconnectClient = async () => {
1103
+ const client = getActiveClient();
1104
+ client.log('client/api/disconnectClient');
1105
+ await new Promise(resolve => {
1106
+ client.ws.once('disconnect', resolve);
1107
+ client.ws.disconnect();
1108
+ });
1109
+ client.emitter.all.clear();
1110
+ client.ws.removeAllListeners();
1111
+ client.userId = undefined;
1112
+ return !client.ws.connected;
1113
+ };
1114
+
1115
+ /**
1116
+ * ```js
1117
+ * import { isConnected } from '@amityco/ts-sdk'
1118
+ * const connected = isConnected()
1119
+ * ```
1120
+ *
1121
+ * Checks if a {@link Amity.Client} instance is connected to ASC servers
1122
+ *
1123
+ * @returns a success boolean if connected
1124
+ *
1125
+ * @category Client API
1126
+ */
1127
+ const isConnected = () => {
1128
+ var _a, _b;
1129
+ const client = getActiveClient();
1130
+ client.log('client/api/isConnected', client);
1131
+ return !!(client.userId
1132
+ && ((_b = (_a = client.http.defaults.headers.common) === null || _a === void 0 ? void 0 : _a['Authorization']) === null || _b === void 0 ? void 0 : _b.length)
1133
+ && client.ws.connected);
1134
+ };
1135
+
1136
+ /**
1137
+ * Minimal store implementation.
1138
+ *
1139
+ * Beware, the state is mutable! it is your responsibility
1140
+ * handle the state's mutations correctly. We do so in
1141
+ * order for users with mutable/observable stacks to be able
1142
+ * to decorate the state with their favorite libraries.
1143
+ *
1144
+ * @param defaultValue the hydration state value of the store
1145
+ * @returns A store instance with an "in memory" storage strategy
1146
+ *
1147
+ * @category Storage
1148
+ * @hidden
1149
+ */
1150
+ const memoryStore = (defaultValue = {}) => {
1151
+ const state = defaultValue;
1152
+ /* default read operation is just to return the state */
1153
+ const read = () => state;
1154
+ /* default write operation is just to mutate the state */
1155
+ const write = (payload) => {
1156
+ Object.assign(state, payload);
1157
+ };
1158
+ /* default write operation is just to mutate the state */
1159
+ const erase = (...keys) => {
1160
+ if (!keys.length)
1161
+ keys = Object.keys(state);
1162
+ keys.forEach(key => delete state[key]);
1163
+ };
1164
+ return { read, write, erase };
1165
+ };
1166
+ /**
1167
+ * ```js
1168
+ * import { memoryStores } from '@amityco/core/cache/store/volatile'
1169
+ * const stores = imemoryStores('user', 'file')
1170
+ * ```
1171
+ *
1172
+ * Builds a collection of in memory stores based on the available store names
1173
+ *
1174
+ * @param names collection of store names
1175
+ * @returns a dictionary of { storeName: storeInstance } according to the given names
1176
+ *
1177
+ * @category Storage
1178
+ */
1179
+ const memoryStores = (...names) => {
1180
+ return names.reduce((acc, name) => {
1181
+ const store = memoryStore();
1182
+ return Object.assign(Object.assign({}, acc), { [name]: store });
1183
+ }, {});
1184
+ };
1185
+
1186
+ const DEFAULT_DEBOUNCE_TIME = 250;
1187
+ /**
1188
+ * Persistent store implementation.
1189
+ *
1190
+ * @param persistentKey the name of the store in persistent storage
1191
+ * @param defaultValue the hydration state value of the store
1192
+ * @param debounceTime a delay to avoid spamming the persistent storage while writing,
1193
+ * @returns A store instance with an "persistent" storage strategy
1194
+ *
1195
+ * @category Storage
1196
+ * @hidden
1197
+ */
1198
+ const persistentStore = async (persistentKey, defaultValue = {}, debounceTime = DEFAULT_DEBOUNCE_TIME) => {
1199
+ let initialValue = defaultValue;
1200
+ const serializedBackup = await AsyncStorage__default['default'].getItem(persistentKey);
1201
+ if (serializedBackup) {
1202
+ try {
1203
+ initialValue = JSON.parse(serializedBackup);
1204
+ }
1205
+ catch (err) { }
1206
+ }
1207
+ // create a store
1208
+ const store = memoryStore(initialValue);
1209
+ let timer;
1210
+ let job = null;
1211
+ const backup = () => {
1212
+ if (job) {
1213
+ job.then(() => backup());
1214
+ return;
1215
+ }
1216
+ clearTimeout(timer);
1217
+ setTimeout(async () => {
1218
+ job = Promise.resolve()
1219
+ .then(() => AsyncStorage__default['default'].setItem(persistentKey, JSON.stringify(store.read())))
1220
+ .then(() => job = null);
1221
+ }, debounceTime);
1222
+ };
1223
+ const write = (payload) => {
1224
+ store.write(payload);
1225
+ backup();
1226
+ };
1227
+ const erase = (...keys) => {
1228
+ store.erase(...keys);
1229
+ backup();
1230
+ };
1231
+ return { read: store.read, write, erase };
1232
+ };
1233
+
1234
+ /**
1235
+ * ```js
1236
+ * import { enableCache } from '@amityco/ts-sdk'
1237
+ * enableCache()
1238
+ * ```
1239
+ *
1240
+ * Adds a new {@link Amity.Cache} object to an {@link Amity.Client} instance
1241
+ *
1242
+ * @param stores a partial dictionary of stores to be used for caching
1243
+ *
1244
+ * @category Client API
1245
+ */
1246
+ const enableCache = (stores = memoryStores('user', 'file', 'channel', 'message', 'community', 'post', 'comment', 'communityUsers', 'channelUsers')) => {
1247
+ const client = getActiveClient();
1248
+ client.log('client/api/enableCache');
1249
+ client.cache = createCache(stores);
1250
+ };
1251
+
1252
+ /**
1253
+ * ```js
1254
+ * import { clearCache } from '@amityco/ts-sdk'
1255
+ * clearCache()
1256
+ * ```
1257
+ *
1258
+ * Resets the state of the given {@link Amity.Store} names within
1259
+ * the {@link Amity.Cache} object of a {@link Amity.Client} instance
1260
+ *
1261
+ * @param stores an array of the stores names to be wiped
1262
+ *
1263
+ * @category Client API
1264
+ */
1265
+ const clearCache = (stores = ['user', 'file', 'channel', 'message', 'community', 'post', 'comment']) => {
1266
+ const client = getActiveClient();
1267
+ client.log('client/api/enableCache');
1268
+ 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(); });
1269
+ };
1270
+
1271
+ /**
1272
+ * converts an array looking collection to an object collection, grouped by localId
1273
+ *
1274
+ * @param array array of {@link Amity.Syncable}
1275
+ * @returns array converted to object, grouped by localId
1276
+ *
1277
+ * @hidden
1278
+ */
1279
+ const toRecord = (array) => (array.reduce((acc, item) => (Object.assign(Object.assign({}, acc), { [item.localId]: item })), {}));
1280
+
1281
+ /**
1282
+ * Set the model's syncedAt property and localId
1283
+ *
1284
+ * @param model the model to decorate
1285
+ * @param timestamp the given timestamp
1286
+ */
1287
+ const decoratePayload = (payload, timestamp = Date.now(), keyMapping = storeInterests) => {
1288
+ Object.fromEntries(Object.entries(payload)
1289
+ .map(([key, models]) => ([
1290
+ key, decorateModels(models, timestamp, keyMapping[key])
1291
+ ])));
1292
+ };
1293
+ /**
1294
+ * Set the model's syncedAt property and localId
1295
+ *
1296
+ * @param model the model to decorate
1297
+ * @param timestamp the given timestamp
1298
+ */
1299
+ const decorateModels = (models, timestamp = Date.now(), type) => {
1300
+ models.forEach(model => decorateModel(model, timestamp, type));
1301
+ };
1302
+ /**
1303
+ * Set the model's syncedAt property and localId
1304
+ *
1305
+ * @param model the model to decorate
1306
+ * @param syncedAt the given timestamp
1307
+ * @param type An opportunity to manually pass the type. If undefined, it will be smartly computed
1308
+ */
1309
+ const decorateModel = (model, timestamp = Date.now(), type = identifyModel(model)) => {
1310
+ var _a, _b;
1311
+ (_a = model.syncedAt) !== null && _a !== void 0 ? _a : (model.syncedAt = timestamp);
1312
+ const { cache } = getActiveClient();
1313
+ if (type) {
1314
+ const modelId = getResolver(type)(model);
1315
+ model.localId = (_b = cache === null || cache === void 0 ? void 0 : cache.lookup[`${type}#${modelId}`]) !== null && _b !== void 0 ? _b : uuid();
1316
+ }
1317
+ };
1318
+
1319
+ // Note:
1320
+ // this file should contain a suite of filtering utilities to help the
1321
+ // local version of the query functions.
1322
+ /**
1323
+ * Filter a given collection with strict equality against a param
1324
+ *
1325
+ * @param collection the collection to filter
1326
+ * @param key the key of the collection's items to challenge
1327
+ * @param value the expected value
1328
+ * @returns a filtered collection with items only matching the criteria
1329
+ *
1330
+ * @hidden
1331
+ */
1332
+ const filterByPropEquality = (collection, key, value) => (value !== undefined ? collection.filter(item => item[key] === value) : collection);
1333
+
1334
+ // Note:
1335
+ // this file should contain a suite of sorting utilities to help the
1336
+ // local version of the query functions.
1337
+ /**
1338
+ * Alphabetic sorting of objects having a displayName
1339
+ */
1340
+ const sortByDisplayName = ({ displayName: a }, { displayName: b }) => {
1341
+ if (a === b)
1342
+ return 0;
1343
+ return a < b ? -1 : 1;
1344
+ };
1345
+ /**
1346
+ * Sorting a collection by their apparition order (oldest first)
1347
+ */
1348
+ const sortByChannelSegment = ({ channelSegment: a }, { channelSegment: b }) => a - b;
1349
+ /**
1350
+ * Sorting a collection by their apparition order (oldest first)
1351
+ */
1352
+ const sortBySegmentNumber = ({ segmentNumber: a }, { segmentNumber: b }) => a - b;
1353
+ /**
1354
+ * Sorting a collection by its oldest items
1355
+ */
1356
+ const sortByFirstCreated = ({ createdAt: a }, { createdAt: b }) => new Date(a).valueOf() - new Date(b).valueOf();
1357
+ /**
1358
+ * Sorting a collection by its newest items
1359
+ */
1360
+ const sortByLastCreated = ({ createdAt: a }, { createdAt: b }) => new Date(b).valueOf() - new Date(a).valueOf();
1361
+ /**
1362
+ * Sorting a collection by the items with most recent activity
1363
+ */
1364
+ const sortByLastActivity = ({ lastActivity: a }, { lastActivity: b }) => new Date(b).valueOf() - new Date(a).valueOf();
1365
+
1366
+ /**
1367
+ * ```js
1368
+ * import { onClientDisconnected } from '@amityco/ts-sdk'
1369
+ * const dispose = onClientDisconnected(reason => {
1370
+ * // ...
1371
+ * })
1372
+ * ```
1373
+ *
1374
+ * Fired when any {@link Amity.Client} have been disconnected
1375
+ *
1376
+ * @param callback The function to call when the event was fired
1377
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
1378
+ *
1379
+ * @category Client Events
1380
+ */
1381
+ const onClientDisconnected = (callback) => {
1382
+ return createEventSubscriber(getActiveClient(), 'client/onClientDisconnected', 'disconnected', () => callback());
1383
+ };
1384
+
1385
+ /**
1386
+ * ```js
1387
+ * import { getUser } from '@amityco/ts-sdk'
1388
+ * const user = await getUser('foobar')
1389
+ * ```
1390
+ *
1391
+ * Fetches a {@link Amity.User} object
1392
+ *
1393
+ * @param userId the ID of the {@link Amity.User} to fetch
1394
+ * @returns the associated {@link Amity.User} object
1395
+ *
1396
+ * @category User API
1397
+ * @async
1398
+ */
1399
+ const getUser = async (userId) => {
1400
+ const client = getActiveClient();
1401
+ client.log('user/getUser', userId);
1402
+ // API-FIX: endpoint should not be /list, parameters should be querystring.
1403
+ const { data } = await client.http.get(`/api/v3/users/${userId}`);
1404
+ decoratePayload(data);
1405
+ ingestInCache(data);
1406
+ const { users } = data;
1407
+ return users.find(user => user.userId === userId);
1408
+ };
1409
+ /**
1410
+ * ```js
1411
+ * import { getUser } from '@amityco/ts-sdk'
1412
+ * const user = getUser.locally('foobar')
1413
+ * ```
1414
+ *
1415
+ * Fetches a {@link Amity.User} object from cache
1416
+ *
1417
+ * @param userId the ID of the {@link Amity.User} to fetch
1418
+ * @returns the associated {@link Amity.User} object
1419
+ *
1420
+ * @category User API
1421
+ */
1422
+ getUser.locally = (userId) => {
1423
+ var _a;
1424
+ const client = getActiveClient();
1425
+ client.log('user/getUser.locally', userId);
1426
+ const [user] = (_a = pullFromCache('user', userId)) !== null && _a !== void 0 ? _a : [];
1427
+ return user;
1428
+ };
1429
+
1430
+ /**
1431
+ * ```js
1432
+ * import { getUsers } from '@amityco/ts-sdk'
1433
+ * const users = await getUsers(['foo', 'bar'])
1434
+ * ```
1435
+ *
1436
+ * Fetches a collection of {@link Amity.User} objects
1437
+ *
1438
+ * @param userIds the IDs of the {@link Amity.User} to fetch
1439
+ * @returns the associated collection of {@link Amity.User} objects
1440
+ *
1441
+ * @category User API
1442
+ * @async
1443
+ */
1444
+ const getUsers = async (userIds) => {
1445
+ const client = getActiveClient();
1446
+ client.log('user/getUsers', userIds);
1447
+ // API-FIX: endpoint should not be /list, parameters should be querystring.
1448
+ const { data } = await client.http.get(`/api/v3/users/list`, { params: { userIds } });
1449
+ decoratePayload(data);
1450
+ ingestInCache(data);
1451
+ const { users } = data;
1452
+ return toRecord(users);
1453
+ };
1454
+ /**
1455
+ * ```js
1456
+ * import { getUsers } from '@amityco/ts-sdk'
1457
+ * const users = getUsers.locally!(['foo', 'bar'])
1458
+ * ```
1459
+ *
1460
+ * Fetches a collection of {@link Amity.User} objects from cache
1461
+ *
1462
+ * @param userIds the IDs of the {@link Amity.User} to fetch
1463
+ * @returns the associated collection of {@link Amity.User} objects
1464
+ *
1465
+ * @category User API
1466
+ */
1467
+ getUsers.locally = (userIds) => {
1468
+ var _a;
1469
+ const cached = (_a = pullFromCache('user', ...userIds)) !== null && _a !== void 0 ? _a : [];
1470
+ if ((cached === null || cached === void 0 ? void 0 : cached.length) === userIds.length)
1471
+ return toRecord(cached);
1472
+ };
1473
+
1474
+ /*! *****************************************************************************
1475
+ Copyright (c) Microsoft Corporation.
1476
+
1477
+ Permission to use, copy, modify, and/or distribute this software for any
1478
+ purpose with or without fee is hereby granted.
1479
+
1480
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
1481
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
1482
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
1483
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
1484
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
1485
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
1486
+ PERFORMANCE OF THIS SOFTWARE.
1487
+ ***************************************************************************** */
1488
+
1489
+ function __rest(s, e) {
1490
+ var t = {};
1491
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
1492
+ t[p] = s[p];
1493
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
1494
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
1495
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
1496
+ t[p[i]] = s[p[i]];
1497
+ }
1498
+ return t;
1499
+ }
1500
+
1501
+ /**
1502
+ * ```js
1503
+ * import { queryUsers } from '@amityco/ts-sdk'
1504
+ * const { users, previous, next } = await queryUsers({ keyword: 'foo' })
1505
+ * ```
1506
+ *
1507
+ * Queries a paginable list of {@link Amity.User} objects
1508
+ * Search is performed by displayName such as `.startsWith(search)`
1509
+ *
1510
+ * @param query The query parameters
1511
+ * @returns A page of {@link Amity.User} objects
1512
+ *
1513
+ * @category User API
1514
+ * @async
1515
+ */
1516
+ const queryUsers = async (query) => {
1517
+ const client = getActiveClient();
1518
+ client.log('user/queryUsers', query);
1519
+ const _a = query !== null && query !== void 0 ? query : {}, { page, displayName, filter = 'all', sortBy = 'displayName' } = _a, params = __rest(_a, ["page", "displayName", "filter", "sortBy"]);
1520
+ // API-FIX: parameters should be querystring.
1521
+ const { data } = await client.http.get(`/api/v3/users`, { params: Object.assign(Object.assign({}, params), { keyword: displayName, filter,
1522
+ sortBy, options: {
1523
+ token: toToken(page, 'skiplimit'),
1524
+ } }) });
1525
+ // unpacking
1526
+ const { paging } = data, response = __rest(data, ["paging"]);
1527
+ decoratePayload(response);
1528
+ ingestInCache(response);
1529
+ const prevPage = toPage(paging.previous);
1530
+ const nextPage = toPage(paging.next);
1531
+ const { users } = response;
1532
+ return { data: toRecord(users), prevPage, nextPage };
1533
+ };
1534
+ /**
1535
+ * ```js
1536
+ * import { queryUsers } from '@amityco/ts-sdk'
1537
+ * const users = queryUsers.locally({ keyword: 'foo' })
1538
+ * ```
1539
+ *
1540
+ * Queries a paginable list of {@link Amity.User} objects from cache
1541
+ * Search is performed by displayName such as `.startsWith(search)`
1542
+ *
1543
+ * @param query The query parameters
1544
+ * @returns A page of {@link Amity.User} objects
1545
+ *
1546
+ * @category User API
1547
+ */
1548
+ queryUsers.locally = (query) => {
1549
+ const client = getActiveClient();
1550
+ client.log('user/queryUsers.locally', query);
1551
+ // TODO
1552
+ };
1553
+
1554
+ /**
1555
+ * ```js
1556
+ * import { updateUser } from '@amityco/ts-sdk'
1557
+ * const updated = await updateUser(userId, { displayName: 'foobar' })
1558
+ * ```
1559
+ *
1560
+ * Updates an {@link Amity.User}
1561
+ *
1562
+ * @param userId The ID of the {@link Amity.User} to update
1563
+ * @param patch The patch data to apply
1564
+ * @returns the updated {@link Amity.User} object
1565
+ *
1566
+ * @category User API
1567
+ * @async
1568
+ */
1569
+ const updateUser = async (userId, patch) => {
1570
+ const client = getActiveClient();
1571
+ client.log('user/updateUser', userId, patch);
1572
+ // API-FIX: Endpoint is malformed, userId should be a url param.
1573
+ /*
1574
+ const { data } = await client.http.put<Amity.Response<UserPayload>>(
1575
+ `/api/v3/users/${userId}`, patch,
1576
+ )
1577
+ */
1578
+ const { data } = await client.http.put(`/api/v3/users/`, Object.assign(Object.assign({ userId }, patch), { createNewUserWhenNotFound: false }));
1579
+ decoratePayload(data);
1580
+ ingestInCache(data);
1581
+ // no need for event, fired by server
1582
+ return data.users.find(user => user.userId === userId);
1583
+ };
1584
+
1585
+ /**
1586
+ * ```js
1587
+ * import { onUserUpdated } from '@amityco/ts-sdk'
1588
+ * const dispose = onUserUpdated(user => {
1589
+ * // ...
1590
+ * })
1591
+ * ```
1592
+ *
1593
+ * Fired when any {@link Amity.User} have been updated
1594
+ *
1595
+ * @param callback The function to call when the event was fired
1596
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
1597
+ *
1598
+ * @category User Events
1599
+ */
1600
+ const onUserUpdated = (callback) => {
1601
+ const client = getActiveClient();
1602
+ const filter = (payload) => {
1603
+ decoratePayload(payload);
1604
+ ingestInCache(payload);
1605
+ callback(payload.users[0]);
1606
+ };
1607
+ return createEventSubscriber(client, 'user/onUserUpdate', 'v3.user.didUpdate', filter);
1608
+ };
1609
+
1610
+ /**
1611
+ * ```js
1612
+ * import { observeUser } from '@amityco/ts-sdk'
1613
+ *
1614
+ * let user = {}
1615
+ * const dispose = observeUser(userId, updated => user = updated)
1616
+ * ```
1617
+ *
1618
+ * @param userId the ID of the user to observe
1619
+ * @param callback the function to call when new data are available
1620
+ * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the user
1621
+ *
1622
+ * Observe all mutation on a given {@link Amity.User}
1623
+ * @category User Observer
1624
+ */
1625
+ const observeUser = (userId, callback) => {
1626
+ const { log } = getActiveClient();
1627
+ const timestamp = Date.now();
1628
+ log(`observeUser(tmpid: ${timestamp}) > listen`);
1629
+ // wrapper function to make sure
1630
+ const router = (result, action) => {
1631
+ var _a, _b, _c;
1632
+ // filter function
1633
+ if (((_a = result.data) === null || _a === void 0 ? void 0 : _a.userId) !== userId)
1634
+ return;
1635
+ if (callback instanceof Function)
1636
+ return callback(result);
1637
+ if (action !== 'onFetch')
1638
+ (_b = callback.onEvent) === null || _b === void 0 ? void 0 : _b.call(callback, action, result);
1639
+ (_c = callback[action]) === null || _c === void 0 ? void 0 : _c.call(callback, result);
1640
+ };
1641
+ const disposers = [];
1642
+ disposers.push(onUserUpdated(data => router({ data }, 'onUpdate')));
1643
+ runQuery(createQuery(getUser, userId), (result) => result.data && router(result, 'onFetch'));
1644
+ return () => {
1645
+ log(`observeUser(tmpid: ${timestamp}) > dispose`);
1646
+ disposers.forEach(fn => fn());
1647
+ };
1648
+ };
1649
+
1650
+ /**
1651
+ * ```js
1652
+ * import { getFile } from '@amityco/ts-sdk'
1653
+ * const file = await getFile('foo')
1654
+ * ```
1655
+ *
1656
+ * Fetches a {@link Amity.File} object
1657
+ *
1658
+ * @param filelId the ID of the {@link Amity.File} to fetch
1659
+ * @returns the associated {@link Amity.File} object
1660
+ *
1661
+ * @category File API
1662
+ * @async
1663
+ */
1664
+ const getFile = async (fileId) => {
1665
+ const client = getActiveClient();
1666
+ client.log('file/getFile', fileId);
1667
+ const { data } = await client.http.get(`/api/v3/files/${fileId}`);
1668
+ // API-FIX: backend bad serializer issue. it should be:
1669
+ // const { files } = data
1670
+ decorateModel(data);
1671
+ ingestInCache({ files: [data] });
1672
+ return data;
1673
+ };
1674
+ /**
1675
+ * ```js
1676
+ * import { getFile } from '@amityco/ts-sdk'
1677
+ * const file = getFile.locally('foo')
1678
+ * ```
1679
+ *
1680
+ * Fetches a {@link Amity.File} object from cache
1681
+ *
1682
+ * @param fileId the ID of the {@link Amity.File} to fetch
1683
+ * @returns the associated {@link Amity.File} object
1684
+ *
1685
+ * @category File API
1686
+ */
1687
+ getFile.locally = (fileId) => {
1688
+ var _a;
1689
+ const client = getActiveClient();
1690
+ client.log('file/getFile.locally', fileId);
1691
+ const [file] = (_a = pullFromCache('file', fileId)) !== null && _a !== void 0 ? _a : [];
1692
+ return file;
1693
+ };
1694
+
1695
+ /**
1696
+ * ```js
1697
+ * import { createFile } from '@amityco/ts-sdk'
1698
+ * const created = await createFile(formData)
1699
+ * ```
1700
+ *
1701
+ * Creates an {@link Amity.File}
1702
+ *
1703
+ * @param formData The data necessary to create a new {@link Amity.File}
1704
+ * @returns The newly created {@link Amity.File}
1705
+ *
1706
+ * @category File API
1707
+ * @async
1708
+ */
1709
+ const createFile = async (formData, onProgress) => {
1710
+ const client = getActiveClient();
1711
+ client.log('file/createFile', formData);
1712
+ if (!formData.getAll('file').length)
1713
+ throw new Error('The formData object must have a `file` key.');
1714
+ const headers = 'getHeaders' in formData
1715
+ ? formData.getHeaders()
1716
+ : { 'content-type': 'multipart/form-data' };
1717
+ const { data } = await client.http.post('/api/v3/files', formData, {
1718
+ headers, onUploadProgress({ loaded, total }) {
1719
+ onProgress && onProgress(Math.round((loaded * 100) / total));
1720
+ }
1721
+ });
1722
+ // API-FIX: payload should be serialized properly
1723
+ // const { files } = data
1724
+ decorateModels(data);
1725
+ ingestInCache({ files: data });
1726
+ return data[0];
1727
+ };
1728
+ // TODO: consider doing local creation with URL.createObjectURL()
1729
+
1730
+ /**
1731
+ * ```js
1732
+ * import { deleteFile } from '@amityco/ts-sdk'
1733
+ * const success = await deleteFile('foo')
1734
+ * ```
1735
+ *
1736
+ * Deletes a {@link Amity.File}
1737
+ *
1738
+ * @param fileId The {@link Amity.File} ID to delete
1739
+ * @return A success boolean if the {@link Amity.File} was deleted
1740
+ *
1741
+ * @category File API
1742
+ * @async
1743
+ */
1744
+ const deleteFile = async (fileId) => {
1745
+ const client = getActiveClient();
1746
+ client.log('file/deleteFile', fileId);
1747
+ const { data } = await client.http.delete(`/api/v3/files/${fileId}`);
1748
+ const { success } = data;
1749
+ if (success)
1750
+ mergeInCache('file', { fileId, isDeleted: true });
1751
+ return success;
1752
+ };
1753
+
1754
+ /**
1755
+ * Allow to query a file url with a selected size
1756
+ *
1757
+ * @param fileUrl the file Url to decorate
1758
+ * @param size one of the selected sizes
1759
+ * @returns the computed url for the selected size
1760
+ */
1761
+ const fileUrlWithSize = (fileUrl, size) => {
1762
+ return `${fileUrl}?size=${size}`;
1763
+ };
1764
+
1765
+ /**
1766
+ * ```js
1767
+ * import { observeFile } from '@amityco/ts-sdk'
1768
+ *
1769
+ * let file = {}
1770
+ * const dispose = observeFile(fileId, updated => file = updated)
1771
+ * ```
1772
+ *
1773
+ * Observe all mutation on a given {@link Amity.File}
1774
+ *
1775
+ * @param fileId the ID of the file to observe
1776
+ * @param callback the function to call when new data are available
1777
+ * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the file
1778
+ *
1779
+ * @category File Observer
1780
+ */
1781
+ const observeFile = (fileId, callback) => {
1782
+ const { log } = getActiveClient();
1783
+ const timestamp = Date.now();
1784
+ log(`observeFile(tmpid: ${timestamp}) > listen`);
1785
+ // wrapper function to make sure
1786
+ const router = (result, action) => {
1787
+ var _a, _b, _c;
1788
+ // filter function
1789
+ if (((_a = result.data) === null || _a === void 0 ? void 0 : _a.fileId) !== fileId)
1790
+ return;
1791
+ if (callback instanceof Function)
1792
+ return callback(result);
1793
+ if (action !== 'onFetch')
1794
+ (_b = callback.onEvent) === null || _b === void 0 ? void 0 : _b.call(callback, action, result);
1795
+ (_c = callback[action]) === null || _c === void 0 ? void 0 : _c.call(callback, result);
1796
+ };
1797
+ runQuery(createQuery(getFile, fileId), (result) => result.data && router(result, 'onFetch'));
1798
+ return () => {
1799
+ log(`observeFile(tmpid: ${timestamp}) > dispose`);
1800
+ };
1801
+ };
1802
+
1803
+ /**
1804
+ * ```js
1805
+ * import { queryRoles } from '@amityco/ts-sdk'
1806
+ * const roles = await queryRoles()
1807
+ * ```
1808
+ *
1809
+ * Queries a paginable list of {@link Amity.Role} objects
1810
+ * Search is performed by displayName such as `.startsWith(search)`
1811
+ *
1812
+ * @param query The query parameters
1813
+ * @returns A page of {@link Amity.Role} objects
1814
+ *
1815
+ * @category Role API
1816
+ * @async
1817
+ */
1818
+ const queryRoles = async (query) => {
1819
+ const client = getActiveClient();
1820
+ client.log('role/queryRoles', query);
1821
+ const _a = query !== null && query !== void 0 ? query : {}, { page, displayName, sortBy } = _a, params = __rest(_a, ["page", "displayName", "sortBy"]);
1822
+ // API-FIX: parameters should be querystring.
1823
+ const { data } = await client.http.get(`/api/v3/roles`, {
1824
+ params: Object.assign(Object.assign({}, params), { keyword: displayName, sortBy, options: {
1825
+ token: toToken(page, 'skiplimit'),
1826
+ } }),
1827
+ });
1828
+ // unpacking
1829
+ const { paging } = data, response = __rest(data, ["paging"]);
1830
+ decoratePayload(response);
1831
+ ingestInCache(response);
1832
+ const prevPage = toPage(paging.previous);
1833
+ const nextPage = toPage(paging.next);
1834
+ const { roles } = response;
1835
+ return { data: toRecord(roles), prevPage, nextPage };
1836
+ };
1837
+ /**
1838
+ * ```js
1839
+ * import { queryRoles } from '@amityco/ts-sdk'
1840
+ * const roles = queryRoles.locally({ keyword: 'foo' })
1841
+ * ```
1842
+ *
1843
+ * Queries a paginable list of {@link Amity.Role} objects from cache
1844
+ * Search is performed by displayName such as `.startsWith(search)`
1845
+ *
1846
+ * @param query The query parameters
1847
+ * @returns A page of {@link Amity.Role} objects
1848
+ *
1849
+ * @category Role API
1850
+ */
1851
+ queryRoles.locally = (query) => {
1852
+ const client = getActiveClient();
1853
+ client.log('role/queryRoles.locally', query);
1854
+ // TODO
1855
+ };
1856
+
1857
+ /**
1858
+ * ```js
1859
+ * import { getRole } from '@amityco/ts-sdk'
1860
+ * const role = await getRole('foobar')
1861
+ * ```
1862
+ *
1863
+ * Fetches a {@link Amity.Role} object
1864
+ *
1865
+ * @param roleId the ID of the {@link Amity.Role} to fetch
1866
+ * @returns the associated {@link Amity.Role} object
1867
+ *
1868
+ * @category Role API
1869
+ * @async
1870
+ */
1871
+ const getRole = async (roleId) => {
1872
+ const client = getActiveClient();
1873
+ client.log('role/getRole', roleId);
1874
+ const { data } = await client.http.get(`/api/v3/roles/${roleId}`);
1875
+ decorateModels(data);
1876
+ ingestInCache({ roles: data });
1877
+ return data.find(role => role.roleId === roleId);
1878
+ };
1879
+ /**
1880
+ * ```js
1881
+ * import { getRole } from '@amityco/ts-sdk'
1882
+ * const role = getRole.locally('foobar')
1883
+ * ```
1884
+ *
1885
+ * Fetches a {@link Amity.Role} object from cache
1886
+ *
1887
+ * @param roleId the ID of the {@link Amity.Role} to fetch
1888
+ * @returns the associated {@link Amity.Role} object
1889
+ *
1890
+ * @category Role API
1891
+ */
1892
+ getRole.locally = (roleId) => {
1893
+ var _a;
1894
+ const client = getActiveClient();
1895
+ client.log('role/getRole.locally', roleId);
1896
+ const [role] = (_a = pullFromCache('role', roleId)) !== null && _a !== void 0 ? _a : [];
1897
+ return role;
1898
+ };
1899
+
1900
+ /** @hidden */
1901
+ const dispatchReactable = (referenceType, model) => {
1902
+ if (referenceType === 'message')
1903
+ // @ts-ignore: refactor later
1904
+ fireEvent('v3.message.didUpdate', { messages: [model] });
1905
+ else if (referenceType === 'post')
1906
+ // @ts-ignore: refactor later
1907
+ fireEvent('v3.post.didUpdate', { posts: [model] });
1908
+ else if (referenceType === 'comment')
1909
+ // @ts-ignore: refactor later
1910
+ fireEvent('v3.comment.didUpdate', { comments: [model] });
1911
+ };
1912
+
1913
+ /**
1914
+ * ```js
1915
+ * import { getMessage } from '@amityco/ts-sdk'
1916
+ * const message = await getMessage('foobar')
1917
+ * ```
1918
+ *
1919
+ * Fetches a {@link Amity.Message} object
1920
+ *
1921
+ * @param messageId the ID of the {@link Amity.Message} to fetch
1922
+ * @returns the associated {@link Amity.Message} object
1923
+ *
1924
+ * @category Message API
1925
+ * @async
1926
+ */
1927
+ const getMessage = async (messageId) => {
1928
+ const client = getActiveClient();
1929
+ client.log('message/getMessage', messageId);
1930
+ // API-FIX: endpoint should not be /list, parameters should be querystring.
1931
+ const { data } = await client.http.get(`/api/v3/messages/${messageId}`);
1932
+ decoratePayload(data);
1933
+ ingestInCache(data);
1934
+ const { messages } = data;
1935
+ return messages.find(message => message.messageId === messageId);
1936
+ };
1937
+ /**
1938
+ * ```js
1939
+ * import { getMessage } from '@amityco/ts-sdk'
1940
+ * const message = getMessage.locally('foobar')
1941
+ * ```
1942
+ *
1943
+ * Fetches a {@link Amity.Message} object
1944
+ *
1945
+ * @param messageId the ID of the {@link Amity.Message} to fetch
1946
+ * @returns the associated {@link Amity.Message} object
1947
+ *
1948
+ * @category Message API
1949
+ */
1950
+ getMessage.locally = (messageId) => {
1951
+ var _a;
1952
+ const client = getActiveClient();
1953
+ client.log('message/getMessage.locally', messageId);
1954
+ const [message] = (_a = pullFromCache('message', messageId)) !== null && _a !== void 0 ? _a : [];
1955
+ return message;
1956
+ };
1957
+
1958
+ /**
1959
+ * ```js
1960
+ * import { getMessages } from '@amityco/ts-sdk'
1961
+ * const messages = await getMessages(['foo', 'bar'])
1962
+ * ```
1963
+ *
1964
+ * Fetches a collection of {@link Amity.Message} objects
1965
+ *
1966
+ * @param messageIds the IDs of the {@link Amity.Message} to fetch
1967
+ * @returns the associated collection of {@link Amity.Message} objects
1968
+ *
1969
+ * @category Message API
1970
+ * @async
1971
+ */
1972
+ const getMessages = async (messageIds) => {
1973
+ const client = getActiveClient();
1974
+ client.log('message/getMessages', messageIds);
1975
+ // API-FIX: endpoint should not be /list, parameters should be querystring.
1976
+ const { data } = await client.http.get(`/api/v3/messages/list`, { params: { messageIds } });
1977
+ decoratePayload(data);
1978
+ ingestInCache(data);
1979
+ const { messages } = data;
1980
+ return toRecord(messages);
1981
+ };
1982
+ /**
1983
+ * ```js
1984
+ * import { getMessages } from '@amityco/ts-sdk'
1985
+ * const messages = getMessages.locally(['foo', 'bar']) ?? []
1986
+ * ```
1987
+ *
1988
+ * Fetches a collection of {@link Amity.Message} objects from cache
1989
+ *
1990
+ * @param messageIds the IDs of the {@link Amity.Message} to fetch
1991
+ * @returns the associated collection of {@link Amity.Message} objects
1992
+ *
1993
+ * @category Message API
1994
+ */
1995
+ getMessages.locally = (messageIds) => {
1996
+ var _a;
1997
+ const client = getActiveClient();
1998
+ client.log('message/getMessages.locally', messageIds);
1999
+ const cached = (_a = pullFromCache('message', ...messageIds)) !== null && _a !== void 0 ? _a : [];
2000
+ if ((cached === null || cached === void 0 ? void 0 : cached.length) === messageIds.length)
2001
+ return toRecord(cached);
2002
+ };
2003
+
2004
+ /**
2005
+ * ```js
2006
+ * import { queryMessages } from '@amityco/ts-sdk'
2007
+ * const messages = await queryMessages({ channelId })
2008
+ * ```
2009
+ *
2010
+ * Queries a paginable list of {@link Amity.Message} objects
2011
+ *
2012
+ * @param query The query parameters
2013
+ * @returns A page of {@link Amity.Message} objects
2014
+ *
2015
+ * @category Message API
2016
+ * @async
2017
+ */
2018
+ const queryMessages = async (query) => {
2019
+ const client = getActiveClient();
2020
+ client.log('message/queryMessages', query);
2021
+ const _a = query !== null && query !== void 0 ? query : {}, { page } = _a, params = __rest(_a, ["page"]);
2022
+ // API-FIX: parameters should be querystring. (1)
2023
+ // API-FIX: backend should answer Amity.Response (2)
2024
+ // API-FIX: pagination should not be indexed on channelSegment (3)
2025
+ // const { data } = await client.http.get<Amity.Response<Amity.Paged<Amity.MessagePayload>>>(
2026
+ const { data } = await client.http.get(`/api/v3/messages`, { params: Object.assign(Object.assign({}, params), { options: {
2027
+ token: toToken(page, 'afterbefore'),
2028
+ } }), });
2029
+ // API-FIX: backend should answer Amity.Response (2)
2030
+ // const { paging, messages } = unwrapPayload(data)
2031
+ const { paging } = data, response = __rest(data, ["paging"]);
2032
+ decoratePayload(response);
2033
+ ingestInCache(response);
2034
+ const { messages } = response;
2035
+ const nextPage = toPage(paging.next);
2036
+ const prevPage = toPage(paging.previous);
2037
+ return { data: toRecord(messages), nextPage, prevPage };
2038
+ };
2039
+ /**
2040
+ * ```js
2041
+ * import { queryMessages } from '@amityco/ts-sdk'
2042
+ * const messages = queryMessages.locally!({ channelId })
2043
+ * ```
2044
+ *
2045
+ * Queries a paginable list of {@link Amity.Message} objects from cache
2046
+ *
2047
+ * @param query The query parameters
2048
+ * @returns A page of {@link Amity.Message} objects
2049
+ *
2050
+ * @category Message API
2051
+ */
2052
+ queryMessages.locally = (query) => {
2053
+ var _a, _b, _c, _d, _e;
2054
+ const client = getActiveClient();
2055
+ client.log('message/queryMessages.locally', query);
2056
+ const { channelId, page } = query;
2057
+ const [channel] = (_a = pullFromCache('channel', channelId)) !== null && _a !== void 0 ? _a : [];
2058
+ let messages = (_b = pullFromCache('message')) !== null && _b !== void 0 ? _b : [];
2059
+ // filter
2060
+ messages = filterByPropEquality(messages, 'channelId', channelId);
2061
+ // API-FIX filter by isDeleted doesn't work in backend... srsly wtf... how do they test things???
2062
+ // messages = filterByPropEquality(messages, 'isDeleted', query?.isDeleted)
2063
+ // sort
2064
+ messages = messages.sort(sortByChannelSegment);
2065
+ // paging
2066
+ if (page) {
2067
+ // slice
2068
+ // API-FIX we can't reuse proper page because the message page is done
2069
+ // by channelSegment which is sadly unique to the entire platform.
2070
+ // this part is copied and adapted from sliceByPaging function
2071
+ let start = 0;
2072
+ let end = undefined;
2073
+ // next page behavior
2074
+ if ('after' in page) {
2075
+ start = page.after !== 0
2076
+ ? messages.findIndex(message => message.channelSegment === (page === null || page === void 0 ? void 0 : page.after)) + 1
2077
+ : 0;
2078
+ end = start + page.limit;
2079
+ // prev page behavior
2080
+ }
2081
+ else if ('before' in page) {
2082
+ end = page.before !== 0
2083
+ ? messages.findIndex(message => message.channelSegment === (page === null || page === void 0 ? void 0 : page.before)) + 1
2084
+ : messages.length - 1;
2085
+ start = end > page.limit ? end - page.limit : 0;
2086
+ }
2087
+ const paged = messages.slice(start, end);
2088
+ messages = paged.length === page.limit ? paged : [];
2089
+ }
2090
+ const prevPage = ((_c = messages[0]) === null || _c === void 0 ? void 0 : _c.channelSegment) > 0
2091
+ ? { before: messages[0].channelSegment, limit: page === null || page === void 0 ? void 0 : page.limit }
2092
+ : undefined;
2093
+ const nextPage = ((_d = messages[messages.length - 1]) === null || _d === void 0 ? void 0 : _d.channelSegment) < ((_e = channel === null || channel === void 0 ? void 0 : channel.messageCount) !== null && _e !== void 0 ? _e : 0)
2094
+ ? { after: messages[messages.length - 1].channelSegment, limit: page === null || page === void 0 ? void 0 : page.limit }
2095
+ : undefined;
2096
+ return { data: toRecord(messages), nextPage, prevPage };
2097
+ };
2098
+
2099
+ /**
2100
+ * ```js
2101
+ * import { createMessage } from '@amityco/ts-sdk'
2102
+ * const created = await createMessage({
2103
+ * channelId: 'foobar',
2104
+ * data: { text: 'hello world' }
2105
+ * })
2106
+ * ```
2107
+ *
2108
+ * Creates an {@link Amity.Message}
2109
+ *
2110
+ * @param bundle The data necessary to create a new {@link Amity.Message}
2111
+ * @returns The newly created {@link Amity.Message}
2112
+ *
2113
+ * @category Message API
2114
+ * @async
2115
+ */
2116
+ const createMessage = async (bundle) => {
2117
+ const client = getActiveClient();
2118
+ client.log('user/createMessage', bundle);
2119
+ const { data } = await client.http.post('/api/v3/messages', bundle);
2120
+ decoratePayload(data);
2121
+ ingestInCache(data);
2122
+ // no need for event, fired by server
2123
+ const { messages } = data;
2124
+ return messages[0];
2125
+ };
2126
+ /**
2127
+ * ```js
2128
+ * import { createMessage } from '@amityco/ts-sdk'
2129
+ * const created = createMessage.locally({
2130
+ * channelId: 'foobar',
2131
+ * data: { text: 'hello world' }
2132
+ * })
2133
+ * ```
2134
+ *
2135
+ * Creates an {@link Amity.Message} in cache
2136
+ *
2137
+ * @param bundle The data necessary to create a new {@link Amity.Message}
2138
+ * @returns The newly created {@link Amity.Message}
2139
+ *
2140
+ * @category Message API
2141
+ */
2142
+ createMessage.optimistically = (bundle) => {
2143
+ var _a, _b, _c;
2144
+ const client = getActiveClient();
2145
+ client.log('user/createMessage.locally', bundle);
2146
+ // should we do this?
2147
+ if (!client.cache)
2148
+ return;
2149
+ const [channel] = (_a = pullFromCache('channel', bundle.channelId)) !== null && _a !== void 0 ? _a : [];
2150
+ pushToCache('channel', Object.assign(Object.assign({}, channel), { messageCount: ((_b = channel.messageCount) !== null && _b !== void 0 ? _b : 0) + 1 }));
2151
+ const message = Object.assign(Object.assign({ localId: uuid(), messageId: Math.random().toString(16), userId: client.userId, channelSegment: ((_c = channel === null || channel === void 0 ? void 0 : channel.messageCount) !== null && _c !== void 0 ? _c : 0) + 1, createdAt: new Date().toISOString() }, bundle), { syncedAt: -1 });
2152
+ pushToCache('message', message);
2153
+ fireEvent('v3.message.didCreate', { messages: [message] });
2154
+ return message;
2155
+ };
2156
+
2157
+ /**
2158
+ * ```js
2159
+ * import { updateMessage } from '@amityco/ts-sdk'
2160
+ * const updated = await updateMessage(messageId, {
2161
+ * data: { text: 'hello world' }
2162
+ * })
2163
+ * ```
2164
+ *
2165
+ * Updates an {@link Amity.Message}
2166
+ *
2167
+ * @param messageId The ID of the {@link Amity.Message} to edit
2168
+ * @param patch The patch data to apply
2169
+ * @returns the updated {@link Amity.Message} object
2170
+ *
2171
+ * @category Message API
2172
+ * @async
2173
+ */
2174
+ const updateMessage = async (messageId, patch) => {
2175
+ const client = getActiveClient();
2176
+ client.log('user/updateMessage', patch);
2177
+ const { data } = await client.http.put(`/api/v3/messages/${messageId}`, patch);
2178
+ decoratePayload(data);
2179
+ ingestInCache(data);
2180
+ // no need for event, fired by server
2181
+ return data.messages.find(message => message.messageId === messageId);
2182
+ };
2183
+ /**
2184
+ * ```js
2185
+ * import { updateMessage } from '@amityco/ts-sdk'
2186
+ * const updated = updateMessage.locally('foobar', {
2187
+ * data: { text: 'hello world' }
2188
+ * })
2189
+ * ```
2190
+ *
2191
+ * Updates an {@link Amity.Message} in cache
2192
+ *
2193
+ * @param messageId The ID of the {@link Amity.Message} to edit
2194
+ * @param patch The patch data to apply
2195
+ * @returns the updated {@link Amity.Message} object
2196
+ *
2197
+ * @category Message API
2198
+ */
2199
+ updateMessage.optimistically = (messageId, patch) => {
2200
+ var _a;
2201
+ const client = getActiveClient();
2202
+ client.log('user/updateMessage', patch);
2203
+ const [message] = (_a = pullFromCache('message', messageId)) !== null && _a !== void 0 ? _a : [];
2204
+ if (!message)
2205
+ return;
2206
+ const updated = Object.assign(Object.assign(Object.assign({}, message), patch), { updatedAt: new Date().toISOString() });
2207
+ pushToCache('message', updated);
2208
+ fireEvent('v3.message.didUpdate', { messages: [updated] });
2209
+ return updated;
2210
+ };
2211
+
2212
+ /**
2213
+ * ```js
2214
+ * import { deleteMessage } from '@amityco/ts-sdk'
2215
+ * const success = await deleteMessage('foobar')
2216
+ * ```
2217
+ *
2218
+ * Delete a {@link Amity.Message}
2219
+ *
2220
+ * @param The ID of the {@link Amity.Message} to delete
2221
+ * @return A success boolean if the {@link Amity.Message} was deleted
2222
+ *
2223
+ * @category Message API
2224
+ * @async
2225
+ */
2226
+ const deleteMessage = async (messageId) => {
2227
+ const client = getActiveClient();
2228
+ client.log('message/deleteMessage', messageId);
2229
+ // API-FIX: This endpoint has not been implemented yet.
2230
+ await client.http.delete(`/api/v3/messages/${messageId}`);
2231
+ const deleted = await getMessage(messageId);
2232
+ // no need for event, fired by server
2233
+ return deleted;
2234
+ };
2235
+ /**
2236
+ * ```js
2237
+ * import { deleteMessage } from '@amityco/ts-sdk'
2238
+ * const success = deleteMessage.locally('foobar')
2239
+ * ```
2240
+ *
2241
+ * Deletes a {@link Amity.Message}
2242
+ *
2243
+ * @param messageId The {@link Amity.Message} ID to delete
2244
+ * @return A success boolean if the {@link Amity.Message} was deleted
2245
+ *
2246
+ * @category Message API
2247
+ */
2248
+ deleteMessage.optimistically = (messageId) => {
2249
+ var _a;
2250
+ const client = getActiveClient();
2251
+ client.log('message/deleteMessage', messageId);
2252
+ const [message] = (_a = pullFromCache('message', messageId)) !== null && _a !== void 0 ? _a : [];
2253
+ if (!message)
2254
+ return;
2255
+ const deleted = Object.assign(Object.assign({}, message), { isDeleted: true, updatedAt: new Date().toISOString() });
2256
+ pushToCache('message', deleted);
2257
+ fireEvent('v3.message.didDelete', { messages: [deleted] });
2258
+ return deleted;
2259
+ };
2260
+
2261
+ /**
2262
+ * ```js
2263
+ * import { queryPosts } from '@amityco/ts-sdk'
2264
+ * const posts = await queryPosts({ targetId, targetType })
2265
+ * ```
2266
+ *
2267
+ * Queries a paginable list of {@link Amity.Post} objects
2268
+ *
2269
+ * @param query The query parameters
2270
+ * @returns posts
2271
+ *
2272
+ * @category Post API
2273
+ * @async
2274
+ */
2275
+ const queryPosts = async (query) => {
2276
+ const client = getActiveClient();
2277
+ client.log('post/queryPosts', query);
2278
+ const _a = query !== null && query !== void 0 ? query : {}, { page } = _a, params = __rest(_a, ["page"]);
2279
+ // API-FIX: parameters should be querystring. (1)
2280
+ // API-FIX: backend should answer Amity.Response (2)
2281
+ // const { data } = await client.http.get<Amity.Response<Amity.PagedResponse<Amity.PostPayload>>>(
2282
+ const { data } = await client.http.get(`/api/v3/posts`, { params: Object.assign(Object.assign({}, params), { options: {
2283
+ token: toToken(page, 'skiplimit'),
2284
+ } }), });
2285
+ // API-FIX: backend should answer Amity.Response (2)
2286
+ // const { paging, posts } = unwrapPayload(data)
2287
+ const { paging } = data, response = __rest(data, ["paging"]);
2288
+ decoratePayload(response);
2289
+ ingestInCache(response);
2290
+ const { posts } = response;
2291
+ const nextPage = toPage(paging.next);
2292
+ const prevPage = toPage(paging.previous);
2293
+ return { data: toRecord(posts), nextPage, prevPage };
2294
+ };
2295
+ /**
2296
+ * ```js
2297
+ * import { queryPosts } from '@amityco/ts-sdk'
2298
+ * const posts = queryPosts.locally({ targetId, targetType })
2299
+ * ```
2300
+ *
2301
+ * Queries a paginable list of {@link Amity.Post} objects from cache
2302
+ *
2303
+ * @param query The query parameters
2304
+ * @returns posts
2305
+ *
2306
+ * @category Post API
2307
+ */
2308
+ queryPosts.locally = (query) => {
2309
+ const client = getActiveClient();
2310
+ client.log('post/queryPosts.locally', query);
2311
+ // TODO
2312
+ };
2313
+
2314
+ /**
2315
+ * ```js
2316
+ * import { getPosts } from '@amityco/ts-sdk'
2317
+ * const posts = await getPosts(['foo', 'bar'])
2318
+ * ```
2319
+ *
2320
+ * Fetches a collection of {@link Amity.Post} objects
2321
+ *
2322
+ * @param postIds the IDs of the {@link Amity.Post} to fetch
2323
+ * @returns the associated collection of {@link Amity.Post} objects
2324
+ *
2325
+ * @category Post API
2326
+ * @async
2327
+ */
2328
+ const getPosts = async (postIds) => {
2329
+ const client = getActiveClient();
2330
+ client.log('post/getPosts', postIds);
2331
+ // API-FIX: endpoint should not be /list, parameters should be querystring.
2332
+ const { data } = await client.http.get(`/api/v3/posts/list`, { params: { postIds } });
2333
+ decoratePayload(data);
2334
+ ingestInCache(data);
2335
+ const { posts } = data;
2336
+ return posts;
2337
+ };
2338
+ /**
2339
+ * ```js
2340
+ * import { getPosts } from '@amityco/ts-sdk'
2341
+ * const posts = getPosts.locally(['foo', 'bar'])
2342
+ * ```
2343
+ *
2344
+ * Fetches a collection of {@link Amity.Post} objects from cache
2345
+ *
2346
+ * @param postIds the IDs of the {@link Amity.Post} to fetch
2347
+ * @returns the associated collection of {@link Amity.Post} objects
2348
+ *
2349
+ * @category Post API
2350
+ */
2351
+ getPosts.locally = (postIds) => {
2352
+ var _a;
2353
+ const client = getActiveClient();
2354
+ client.log('post/getPosts.locally', postIds);
2355
+ const cached = (_a = pullFromCache('post', ...postIds)) !== null && _a !== void 0 ? _a : [];
2356
+ if ((cached === null || cached === void 0 ? void 0 : cached.length) === postIds.length)
2357
+ return toRecord(cached);
2358
+ };
2359
+
2360
+ /**
2361
+ * ```js
2362
+ * import { getPost } from '@amityco/ts-sdk'
2363
+ * const post = await getPost('foobar')
2364
+ * ```
2365
+ *
2366
+ * Fetches a {@link Amity.Post} object
2367
+ *
2368
+ * @param postId the ID of the {@link Amity.Post} to fetch
2369
+ * @returns the associated {@link Amity.Post} object
2370
+ *
2371
+ * @category Post API
2372
+ * @async
2373
+ */
2374
+ const getPost = async (postId) => {
2375
+ const client = getActiveClient();
2376
+ client.log('post/getPost', postId);
2377
+ // API-FIX: endpoint should not be /list, parameters should be querystring.
2378
+ const { data } = await client.http.get(`/api/v3/posts/${postId}`);
2379
+ decoratePayload(data);
2380
+ ingestInCache(data);
2381
+ const { posts } = data;
2382
+ return posts.find(post => post.postId === postId);
2383
+ };
2384
+ /**
2385
+ * ```js
2386
+ * import { getPost } from '@amityco/ts-sdk'
2387
+ * const post = getPost.locally('foobar')
2388
+ * ```
2389
+ *
2390
+ * Fetches a {@link Amity.Post} object
2391
+ *
2392
+ * @param postId the ID of the {@link Amity.Post} to fetch
2393
+ * @returns the associated {@link Amity.Post} object
2394
+ *
2395
+ * @category Post API
2396
+ */
2397
+ getPost.locally = (postId) => {
2398
+ var _a;
2399
+ const client = getActiveClient();
2400
+ client.log('post/getPost.locally', postId);
2401
+ const [post] = (_a = pullFromCache('post', postId)) !== null && _a !== void 0 ? _a : [];
2402
+ return post;
2403
+ };
2404
+
2405
+ /**
2406
+ * ```js
2407
+ * import { createPost } from '@amityco/ts-sdk'
2408
+ * const newPost = await createPost(bundle)
2409
+ * ```
2410
+ *
2411
+ * Creates an {@link Amity.Post}
2412
+ *
2413
+ * @param bundle The data necessary to create a new {@link Amity.Post}
2414
+ * @returns The newly created {@link Amity.Post}
2415
+ *
2416
+ * @category Post API
2417
+ * @async
2418
+ */
2419
+ const createPost = async (bundle) => {
2420
+ const client = getActiveClient();
2421
+ client.log('post/createPost', bundle);
2422
+ // API-FIX: backend rejects that we pass the dataType manually T_T
2423
+ if (!bundle.dataType || ['text', 'image', 'file'].includes(bundle.dataType))
2424
+ delete bundle.dataType;
2425
+ const { data } = await client.http.post('/api/v3/posts', bundle);
2426
+ decoratePayload(data);
2427
+ ingestInCache(data);
2428
+ fireEvent('v3.community.didUpdate', { communities: data.communities });
2429
+ fireEvent('v3.post.didCreate', data);
2430
+ const { posts } = data;
2431
+ return posts[0];
2432
+ };
2433
+
2434
+ /**
2435
+ * ```js
2436
+ * import { updatePost } from '@amityco/ts-sdk'
2437
+ * const updated = await updatePost(postId, {
2438
+ * data: { text: 'hello world' }
2439
+ * })
2440
+ * ```
2441
+ *
2442
+ * Updates an {@link Amity.Post}
2443
+ *
2444
+ * @param postId The ID of the {@link Amity.Post} to edit
2445
+ * @param patch The patch data to apply
2446
+ * @returns the updated {@link Amity.Post} object
2447
+ *
2448
+ * @category Post API
2449
+ * @async
2450
+ */
2451
+ const updatePost = async (postId, patch) => {
2452
+ const client = getActiveClient();
2453
+ client.log('user/updatePost', patch);
2454
+ const { data } = await client.http.put(`/api/v3/posts/${postId}`, patch);
2455
+ decoratePayload(data);
2456
+ ingestInCache(data);
2457
+ fireEvent('v3.post.didUpdate', data);
2458
+ const { posts } = data;
2459
+ return posts.find(post => post.postId === postId);
2460
+ };
2461
+
2462
+ /**
2463
+ * ```js
2464
+ * import { queryCommunities } from '@amityco/ts-sdk'
2465
+ * const communities = await queryCommunities()
2466
+ * ```
2467
+ *
2468
+ * Queries a paginable list of {@link Amity.Community} objects
2469
+ * Search is performed by displayName such as `.startsWith(search)`
2470
+ *
2471
+ * @param query The query parameters
2472
+ * @returns A page of {@link Amity.Community} objects
2473
+ *
2474
+ * @category Community API
2475
+ * @async
2476
+ */
2477
+ const queryCommunities = async (query) => {
2478
+ const client = getActiveClient();
2479
+ client.log('channel/queryCommunities', query);
2480
+ // safe decapsulation
2481
+ const _a = query !== null && query !== void 0 ? query : {}, { page, displayName, membership } = _a, params = __rest(_a, ["page", "displayName", "membership"]);
2482
+ // API-FIX: parameters should be querystring.
2483
+ // API-FIX: backend doesnt answer Amity.Response
2484
+ // const { data } = await client.http.get<Amity.Response<Amity.PagedResponse<CommunityPayload>>>(
2485
+ const { data } = await client.http.get(`/api/v3/communities`, { params: Object.assign(Object.assign({}, params), { keyword: displayName, filter: membership, options: {
2486
+ token: toToken(page, 'skiplimit')
2487
+ } }) });
2488
+ // API-FIX: backend to response Amity.Response: const { paging, communities } = unwrapPayload(data)
2489
+ const { paging } = data, response = __rest(data, ["paging"]);
2490
+ decoratePayload(response);
2491
+ ingestInCache(response);
2492
+ const prevPage = toPage(paging === null || paging === void 0 ? void 0 : paging.previous);
2493
+ const nextPage = toPage(paging === null || paging === void 0 ? void 0 : paging.next);
2494
+ const { communities } = response;
2495
+ return { data: toRecord(communities), prevPage, nextPage };
2496
+ };
2497
+ /**
2498
+ * ```js
2499
+ * import { queryCommunities } from '@amityco/ts-sdk'
2500
+ * const communities = queryCommunities.locally()
2501
+ * ```
2502
+ *
2503
+ * Queries a paginable list of {@link Amity.Community} objects from cache
2504
+ *
2505
+ * @param query The query parameters
2506
+ * @returns communities
2507
+ *
2508
+ * @category Community API
2509
+ */
2510
+ queryCommunities.locally = (query) => {
2511
+ const client = getActiveClient();
2512
+ client.log('community/queryCommunities.locally', query);
2513
+ // TODO
2514
+ };
2515
+
2516
+ /**
2517
+ * ```js
2518
+ * import { getCommunities } from '@amityco/ts-sdk'
2519
+ * const communities = await getCommunities(['foo', 'bar'])
2520
+ * ```
2521
+ *
2522
+ * Fetches a collection of {@link Amity.Community} objects
2523
+ *
2524
+ * @param communityIds the IDs of the {@link Amity.Community} to fetch
2525
+ * @returns the associated collection of {@link Amity.Community} objects
2526
+ *
2527
+ * @category Community API
2528
+ * @async
2529
+ */
2530
+ const getCommunities = async (communityIds) => {
2531
+ const client = getActiveClient();
2532
+ client.log('community/getCommunities', communityIds);
2533
+ // API-FIX: endpoint should not be /list, parameters should be querystring.
2534
+ const { data } = await client.http.get(`/api/v3/communities/list`, { params: { communityIds } });
2535
+ decoratePayload(data);
2536
+ ingestInCache(data);
2537
+ const { communities } = data;
2538
+ return toRecord(communities);
2539
+ };
2540
+ /**
2541
+ * ```js
2542
+ * import { getCommunities } from '@amityco/ts-sdk'
2543
+ * const communities = getCommunities.locally(['foo', 'bar']) ?? []
2544
+ * ```
2545
+ *
2546
+ * Fetches a collection of {@link Amity.Community} objects from cache
2547
+ *
2548
+ * @param communityIds the IDs of the {@link Amity.Community} to fetch
2549
+ * @returns the associated collection of {@link Amity.Community} objects
2550
+ *
2551
+ * @category Community API
2552
+ */
2553
+ getCommunities.locally = (communityIds) => {
2554
+ var _a;
2555
+ const client = getActiveClient();
2556
+ client.log('community/getCommunities.locally', communityIds);
2557
+ const cached = (_a = pullFromCache('community', ...communityIds)) !== null && _a !== void 0 ? _a : [];
2558
+ if ((cached === null || cached === void 0 ? void 0 : cached.length) === communityIds.length)
2559
+ return toRecord(cached);
2560
+ };
2561
+
2562
+ /**
2563
+ * ```js
2564
+ * import { getCommunity } from '@amityco/ts-sdk'
2565
+ * const community = await getCommunity('foobar')
2566
+ * ```
2567
+ *
2568
+ * Fetches a {@link Amity.Community} object
2569
+ *
2570
+ * @param communityId the ID of the {@link Amity.Community} to fetch
2571
+ * @returns the associated {@link Amity.Community} object
2572
+ *
2573
+ * @category Community API
2574
+ * @async
2575
+ */
2576
+ const getCommunity = async (communityId) => {
2577
+ const client = getActiveClient();
2578
+ client.log('community/getCommunity', communityId);
2579
+ // API-FIX: endpoint should not be /list, parameters should be querystring.
2580
+ const { data } = await client.http.get(`/api/v3/communities/${communityId}`);
2581
+ decoratePayload(data);
2582
+ ingestInCache(data);
2583
+ const { communities } = data;
2584
+ return communities.find(community => community.communityId === communityId);
2585
+ };
2586
+ /**
2587
+ * ```js
2588
+ * import { getCommunity } from '@amityco/ts-sdk'
2589
+ * const community = getCommunity.locally('foobar')
2590
+ * ```
2591
+ *
2592
+ * Fetches a {@link Amity.Community} object from cache
2593
+ *
2594
+ * @param communityId the ID of the {@link Amity.Community} to fetch
2595
+ * @returns the associated {@link Amity.Community} object
2596
+ *
2597
+ * @category Community API
2598
+ */
2599
+ getCommunity.locally = (communityId) => {
2600
+ var _a;
2601
+ const client = getActiveClient();
2602
+ client.log('community/getCommunity.locally', communityId);
2603
+ const [community] = (_a = pullFromCache('community', communityId)) !== null && _a !== void 0 ? _a : [];
2604
+ return community;
2605
+ };
2606
+
2607
+ /**
2608
+ * ```js
2609
+ * import { createCommunity } from '@amityco/ts-sdk'
2610
+ * const created = await createCommunity({ communityId: 'foobar', displayName: 'foobar' })
2611
+ * ```
2612
+ *
2613
+ * Creates an {@link Amity.Community}
2614
+ *
2615
+ * @param bundle The data necessary to create a new {@link Amity.Community}
2616
+ * @returns The newly created {@link Amity.Community}
2617
+ *
2618
+ * @category Community API
2619
+ * @async
2620
+ */
2621
+ const createCommunity = async (bundle) => {
2622
+ const client = getActiveClient();
2623
+ client.log('user/createCommunity', bundle);
2624
+ const { data } = await client.http.post('/api/v3/communities/', bundle);
2625
+ decoratePayload(data);
2626
+ ingestInCache(data);
2627
+ fireEvent('v3.community.didCreate', data);
2628
+ const { communities } = data;
2629
+ return communities[0];
2630
+ };
2631
+
2632
+ /**
2633
+ * ```js
2634
+ * import { updateCommunity } from '@amityco/ts-sdk'
2635
+ * const updated = await updateCommunity(communityId, { displayName: 'foobar' })
2636
+ * ```
2637
+ *
2638
+ * Updates an {@link Amity.Community}
2639
+ *
2640
+ * @param communityId The ID of the {@link Amity.Community} to edit
2641
+ * @param patch The patch data to apply
2642
+ * @returns the updated {@link Amity.Community} object
2643
+ *
2644
+ * @category Community API
2645
+ * @async
2646
+ */
2647
+ const updateCommunity = async (communityId, patch) => {
2648
+ const client = getActiveClient();
2649
+ client.log('community/updateCommunity', communityId, patch);
2650
+ const { data } = await client.http.put(`/api/v3/communities/${communityId}`, patch);
2651
+ decoratePayload(data);
2652
+ ingestInCache(data);
2653
+ fireEvent('v3.community.didUpdate', data);
2654
+ const { communities } = data;
2655
+ return communities.find(community => community.communityId === communityId);
2656
+ };
2657
+
2658
+ /**
2659
+ * ```js
2660
+ * import { deleteCommunity } from '@amityco/ts-sdk'
2661
+ * const success = await deleteCommunity('foobar')
2662
+ * ```
2663
+ *
2664
+ * Deletes a {@link Amity.Community}
2665
+ *
2666
+ * @param communityId The {@link Amity.Community} ID to delete
2667
+ * @return A success boolean if the {@link Amity.Community} was deleted
2668
+ *
2669
+ * @category Community API
2670
+ * @async
2671
+ */
2672
+ const deleteCommunity = async (communityId) => {
2673
+ const client = getActiveClient();
2674
+ client.log('community/deleteCommunity', communityId);
2675
+ // API-FIX: This endpoint has not been implemented yet.
2676
+ await client.http.delete(`/api/v3/communities/${communityId}`);
2677
+ const deleted = await getCommunity(communityId);
2678
+ fireEvent('v3.community.didDelete', { communities: [deleted] });
2679
+ return deleted;
2680
+ };
2681
+
2682
+ /**
2683
+ * ```js
2684
+ * import { joinCommunity } from '@amityco/ts-sdk'
2685
+ * const isJoined = await joinCommunity('foobar')
2686
+ * ```
2687
+ *
2688
+ * Joins a {@link Amity.Community} object
2689
+ *
2690
+ * @param communityId the {@link Amity.Community} to join
2691
+ * @returns A success boolean if the {@link Amity.Community} was joined
2692
+ *
2693
+ * @category Community API
2694
+ * @async
2695
+ */
2696
+ const joinCommunity = async (communityId) => {
2697
+ const client = getActiveClient();
2698
+ client.log('community/joinCommunity', communityId);
2699
+ const { data } = await client.http.post(`/api/v3/communities/${communityId}/join`);
2700
+ decoratePayload(data);
2701
+ ingestInCache(data);
2702
+ fireEvent('v3.community.didJoin', {
2703
+ communities: data.communities
2704
+ });
2705
+ const { communityUsers } = data;
2706
+ return !!communityUsers.find(communityUser => (communityUser.communityId === communityId
2707
+ && communityUser.communityMembership === 'member'));
2708
+ };
2709
+
2710
+ /**
2711
+ * ```js
2712
+ * import { leaveCommunity } from '@amityco/ts-sdk'
2713
+ * const isLeft = await leaveCommunity('foobar')
2714
+ * ```
2715
+ *
2716
+ * Leaves a {@link Amity.Community} object
2717
+ *
2718
+ * @param communityId the {@link Amity.Community} to leave
2719
+ * @returns A success boolean if {@link Amity.Community} was left
2720
+ *
2721
+ * @category Community API
2722
+ * @async
2723
+ */
2724
+ const leaveCommunity = async (communityId) => {
2725
+ const client = getActiveClient();
2726
+ client.log('community/leaveCommunity', communityId);
2727
+ const { data } = await client.http.delete(`/api/v3/communities/${communityId}/leave`);
2728
+ decoratePayload(data);
2729
+ ingestInCache(data);
2730
+ fireEvent('v3.community.didJoin', {
2731
+ communities: data.communities,
2732
+ });
2733
+ const { communityUsers } = data;
2734
+ return !!communityUsers.find(communityUser => (communityUser.communityId === communityId
2735
+ && communityUser.communityMembership !== 'member'));
2736
+ };
2737
+
2738
+ /**
2739
+ * ```js
2740
+ * import { queryCommunityMembers } from '@amityco/ts-sdk'
2741
+ * const communityMembers = await queryCommunityMembers({ communityId: 'foo' })
2742
+ * ```
2743
+ *
2744
+ * Queries a paginable list of {@link Amity.CommunityUser} objects
2745
+ *
2746
+ * @param query The query parameters
2747
+ * @returns A page of {@link Amity.CommunityUser} objects
2748
+ *
2749
+ * @category Community API
2750
+ * @async
2751
+ **/
2752
+ const queryCommunityMembers = async (query) => {
2753
+ const client = getActiveClient();
2754
+ client.log('community/queryCommunityMembers', query);
2755
+ const _a = query !== null && query !== void 0 ? query : {}, { page, communityId } = _a, params = __rest(_a, ["page", "communityId"]);
2756
+ const { data } = await client.http.get(`/api/v3/communities/${communityId}/users`, {
2757
+ params: Object.assign(Object.assign({}, params), { options: {
2758
+ token: toToken(page, 'skiplimit'),
2759
+ } }),
2760
+ });
2761
+ const { paging } = data, response = __rest(data, ["paging"]);
2762
+ decoratePayload(response);
2763
+ ingestInCache(response);
2764
+ const { communityUsers } = response;
2765
+ const nextPage = toPage(paging.next);
2766
+ const prevPage = toPage(paging.previous);
2767
+ return { data: toRecord(communityUsers), nextPage, prevPage };
2768
+ };
2769
+ /**
2770
+ * ```js
2771
+ * import { queryCommunityMembers } from '@amityco/ts-sdk'
2772
+ * const communityMembers = await queryCommunityMembers(query)
2773
+ * ```
2774
+ *
2775
+ * Queries a paginable list of {@link Amity.Post} objects from cache
2776
+ *
2777
+ * @param query The query parameters
2778
+ * @returns posts
2779
+ *
2780
+ * @category Post API
2781
+ */
2782
+ queryCommunityMembers.locally = (query) => {
2783
+ const client = getActiveClient();
2784
+ client.log('community/queryCommunityMembers', query);
2785
+ // TODO
2786
+ };
2787
+
2788
+ /**
2789
+ * ```js
2790
+ * import { addCommunityMembers } from '@amityco/ts-sdk'
2791
+ * const updated = await addCommunityMembers(communityId, ['foo', 'bar'])
2792
+ * ```
2793
+ *
2794
+ * Adds a list of {@link Amity.User} to a {@link Amity.Community} to add users to
2795
+ *
2796
+ * @param communityId The ID of the {@link Amity.Community} to perform
2797
+ * @param userIds The list of IDs {@link Amity.User} to add
2798
+ * @returns A success boolean if the {@link Amity.User} were added to the {@link Amity.Community}
2799
+ *
2800
+ * @category Community API
2801
+ * @async
2802
+ */
2803
+ const addCommunityMembers = async (communityId, userIds) => {
2804
+ const client = getActiveClient();
2805
+ client.log('community/addCommunityMembers', communityId, userIds);
2806
+ const { data } = await client.http.post(`/api/v3/communities/${communityId}/users`, { communityId, userIds });
2807
+ decoratePayload(data);
2808
+ ingestInCache(data);
2809
+ fireEvent('v3.community.didAddUsers', {
2810
+ communities: data.communities,
2811
+ });
2812
+ const { communityUsers } = data;
2813
+ return !!communityUsers.find(communityUser => communityUser.communityId === communityId &&
2814
+ communityUser.communityMembership === 'member');
2815
+ };
2816
+
2817
+ /**
2818
+ * ```js
2819
+ * import { removeCommunityMembers } from '@amityco/ts-sdk'
2820
+ * const updated = await removeCommunityMembers(communityId, ['foo', 'bar'])
2821
+ * ```
2822
+ *
2823
+ * Removes a list of {@link Amity.User} from a {@link Amity.Channel}
2824
+ *
2825
+ * @param communityId The ID of the {@link Amity.Community} to edit
2826
+ * @param userIds The list of IDs {@link Amity.User} to remove
2827
+ * @returns A success boolean if the list of {@link Amity.User} were removed from the {@link Amity.Community}
2828
+ *
2829
+ * @category Community API
2830
+ * @async
2831
+ */
2832
+ const removeCommunityMembers = async (communityId, userIds) => {
2833
+ const client = getActiveClient();
2834
+ client.log('community/removeCommunityMembers', communityId, userIds);
2835
+ const { data } = await client.http.delete(`/api/v3/communities/${communityId}/users`, { data: { communityId, userIds } });
2836
+ decoratePayload(data);
2837
+ ingestInCache(data);
2838
+ fireEvent('v3.community.didRemoveUsers', {
2839
+ communities: data.communities,
2840
+ });
2841
+ const { communityUsers } = data;
2842
+ return !!communityUsers.find(communityUser => communityUser.communityId === communityId &&
2843
+ communityUser.communityMembership !== 'member');
2844
+ };
2845
+
2846
+ /**
2847
+ * ```js
2848
+ * import { addCommunityMembersRole } from '@amityco/ts-sdk'
2849
+ * const updated = await addCommunityMembersRole(communityId, 'foo', ['bar'])
2850
+ * ```
2851
+ *
2852
+ * Adds an {@link Amity.Role} to a list of {@link Amity.User} on a {@link Amity.Community}
2853
+ *
2854
+ * @param communityId The ID of the {@link Amity.Community} to perform
2855
+ * @param roleId The ID of the {@link Amity.Role} to apply
2856
+ * @param userId Array of IDs of the {@link Amity.User} to perform
2857
+ * @returns A success boolean if the {@link Amity.Role} were added to list of {@link Amity.User} in the {@link Amity.Community}
2858
+ *
2859
+ * @category Community API
2860
+ * @async
2861
+ */
2862
+ const addCommunityMembersRole = async (communityId, roleId, userIds) => {
2863
+ const client = getActiveClient();
2864
+ client.log('community/addCommunityMembersRole', communityId, roleId, userIds);
2865
+ const { data } = await client.http.post(`/api/v3/communities/${communityId}/users/roles`, { communityId, role: roleId, userIds });
2866
+ decoratePayload(data);
2867
+ ingestInCache(data);
2868
+ const { communityUsers } = data;
2869
+ return !!communityUsers.find(communityUser => communityUser.communityId === communityId && communityUser.roles.includes(roleId));
2870
+ };
2871
+
2872
+ /**
2873
+ * ```js
2874
+ * import { removeCommunityMembersRole } from '@amityco/ts-sdk'
2875
+ * const updated = await removeCommunityMembersRole(communityId, 'foo', ['bar'])
2876
+ * ```
2877
+ *
2878
+ * Removes an {@link Amity.Role} from a list of {@link Amity.User} on a {@link Amity.Community}
2879
+ *
2880
+ * @param communityId The ID of the {@link Amity.Community} to perform
2881
+ * @param role The ID of the {@link Amity.Role} to apply
2882
+ * @param userId Array of IDs of the {@link Amity.User} to perform
2883
+ * @returns A success boolean if the {@link Amity.Role} were removed from list of {@link Amity.User} in the {@link Amity.Community}
2884
+ *
2885
+ * @category Community API
2886
+ * @async
2887
+ */
2888
+ const removeCommunityMembersRole = async (communityId, roleId, userIds) => {
2889
+ const client = getActiveClient();
2890
+ client.log('community/removeCommunityMembersRole', communityId, roleId, userIds);
2891
+ const { data } = await client.http.delete(`/api/v3/communities/${communityId}/users/roles`, { data: { communityId, role: roleId, userIds } });
2892
+ decoratePayload(data);
2893
+ ingestInCache(data);
2894
+ const { communityUsers } = data;
2895
+ return !!communityUsers.find(communityUser => communityUser.communityId === communityId && !communityUser.roles.includes(roleId));
2896
+ };
2897
+
2898
+ /**
2899
+ * ```js
2900
+ * import { deletePost } from '@amityco/ts-sdk'
2901
+ * const success = await deletePost('foobar')
2902
+ * ```
2903
+ *
2904
+ * Deletes a {@link Amity.Post}
2905
+ *
2906
+ * @param postId The {@link Amity.Post} ID to delete
2907
+ * @return A success boolean if the {@link Amity.Post} was deleted
2908
+ *
2909
+ * @category Post API
2910
+ * @async
2911
+ */
2912
+ const deletePost = async (postId) => {
2913
+ const client = getActiveClient();
2914
+ client.log('post/deletePost', postId);
2915
+ // API-FIX: This endpoint has not been implemented yet.
2916
+ await client.http.delete(`/api/v3/posts/${postId}`);
2917
+ // API-FIX: as for now we have no choice but to refetch
2918
+ const deleted = await getPost(postId);
2919
+ if (deleted.targetType === 'community') {
2920
+ const community = await getCommunity(deleted.targetId);
2921
+ fireEvent('v3.community.didUpdate', { communities: [community] });
2922
+ }
2923
+ fireEvent('v3.post.didDelete', { posts: [deleted] });
2924
+ return deleted;
2925
+ };
2926
+
2927
+ /**
2928
+ * ```js
2929
+ * import { queryComments } from '@amityco/ts-sdk'
2930
+ * const comments = await queryComments({ postId })
2931
+ * ```
2932
+ *
2933
+ * Queries a paginable list of {@link Amity.Comment} objects
2934
+ *
2935
+ * @param query The query parameters
2936
+ * @returns A page of {@link Amity.Comment} objects
2937
+ *
2938
+ * @category Comment API
2939
+ * @async
2940
+ */
2941
+ const queryComments = async (query) => {
2942
+ const client = getActiveClient();
2943
+ client.log('comment/queryComments', query);
2944
+ const { page } = query, params = __rest(query, ["page"]);
2945
+ query.parentId !== undefined;
2946
+ // API-FIX: parameters should be querystring. (1)
2947
+ // API-FIX: backend should answer Amity.Response (2)
2948
+ // const { data } = await client.http.get<Amity.Response<Amity.PagedResponse<Amity.CommentPayload>>>(
2949
+ const { data } = await client.http.get(`/api/v3/comments`, {
2950
+ params: Object.assign(Object.assign({}, params), {
2951
+ // filterByParentId, API-FIX: backend does not support this boolean LOL. what the hell seriously.
2952
+ options: {
2953
+ token: toToken(page, 'afterbefore'),
2954
+ } }),
2955
+ });
2956
+ // API-FIX: backend should answer Amity.Response (2)
2957
+ // const { paging, comments } = unwrapPayload(data)
2958
+ const { paging } = data, response = __rest(data, ["paging"]);
2959
+ decoratePayload(response);
2960
+ ingestInCache(response);
2961
+ const prevPage = toPage(paging.previous);
2962
+ const nextPage = toPage(paging.next);
2963
+ const { comments } = response;
2964
+ return { data: toRecord(comments), prevPage, nextPage };
2965
+ };
2966
+ /**
2967
+ * ```js
2968
+ * import { queryComments } from '@amityco/ts-sdk'
2969
+ * const comments = queryComments.locally({ postId })
2970
+ * ```
2971
+ *
2972
+ * Queries a paginable list of {@link Amity.Comment} objects from cache
2973
+ *
2974
+ * @param query The query parameters
2975
+ * @returns comments
2976
+ *
2977
+ * @category Comment API
2978
+ */
2979
+ queryComments.locally = (query) => {
2980
+ var _a;
2981
+ const client = getActiveClient();
2982
+ client.log('post/queryComments.locally', query);
2983
+ const { referenceId, referenceType, parentId, isDeleted, page = { before: 0, limit: 5 }, } = query;
2984
+ if (isNaN(page.after) && isNaN(page.before))
2985
+ page.before = 0;
2986
+ if (isNaN(page.limit))
2987
+ page.limit = 5;
2988
+ let comments = (_a = pullFromCache('comment')) !== null && _a !== void 0 ? _a : [];
2989
+ // no cache
2990
+ if (!comments.length)
2991
+ return;
2992
+ // filter
2993
+ comments = filterByPropEquality(comments, 'referenceId', referenceId);
2994
+ comments = filterByPropEquality(comments, 'referenceType', referenceType);
2995
+ comments = filterByPropEquality(comments, 'parentId', parentId);
2996
+ comments = filterByPropEquality(comments, 'isDeleted', isDeleted);
2997
+ // no interesting cache
2998
+ if (!comments.length)
2999
+ return;
3000
+ // sort
3001
+ comments = comments.sort(sortBySegmentNumber);
3002
+ // paging
3003
+ // API-FIX we can't reuse proper page because the message page is done
3004
+ // by segmentNumber which is sadly unique to the entire platform.
3005
+ // this part is copied and adapted from sliceByPaging function
3006
+ const afterIndex = !isNaN(page.after)
3007
+ ? comments.findIndex(({ segmentNumber }) => segmentNumber === page.after + 1)
3008
+ : 0;
3009
+ const beforeIndex = !isNaN(page.before) && page.before !== 0
3010
+ ? comments.findIndex(({ segmentNumber }) => segmentNumber === page.before - 1) + 1
3011
+ : comments.length;
3012
+ if (afterIndex < 0 || beforeIndex < 0)
3013
+ return;
3014
+ let slice = comments.slice(afterIndex !== -1 ? afterIndex : 0, beforeIndex !== -1 ? beforeIndex : undefined);
3015
+ // nothing left after slicing
3016
+ if (!slice.length)
3017
+ return;
3018
+ if (!isNaN(page.after) && !isNaN(page.before)) ;
3019
+ else if (!isNaN(page.after)) {
3020
+ slice = slice.slice(0, page.limit);
3021
+ }
3022
+ else if (!isNaN(page.before)) {
3023
+ slice = slice.slice(-page.limit);
3024
+ }
3025
+ for (let i = 0; i < slice.length - 1; i++)
3026
+ if (slice[i].segmentNumber !== slice[i + 1].segmentNumber - 1)
3027
+ return;
3028
+ const prevPage = slice[0].segmentNumber > 1
3029
+ ? { before: slice[0].segmentNumber, limit: page.limit }
3030
+ : undefined;
3031
+ const nextPage = {
3032
+ after: slice[slice.length - 1].segmentNumber,
3033
+ limit: page.limit,
3034
+ };
3035
+ return { data: toRecord(slice), nextPage, prevPage };
3036
+ };
3037
+
3038
+ /**
3039
+ * ```js
3040
+ * import { getComments } from '@amityco/ts-sdk'
3041
+ * const comments = await getComments(['foo', 'bar'])
3042
+ * ```
3043
+ *
3044
+ * Fetches a collection of {@link Amity.Comment} objects
3045
+ *
3046
+ * @param commentIds the IDs of the {@link Amity.Comment} to fetch
3047
+ * @returns the associated collection of {@link Amity.Comment} objects
3048
+ *
3049
+ * @category Comment API
3050
+ * @async
3051
+ */
3052
+ const getComments = async (commentIds) => {
3053
+ const client = getActiveClient();
3054
+ client.log('comment/getComments', commentIds);
3055
+ // API-FIX: endpoint should not be /list, parameters should be querystring.
3056
+ const { data } = await client.http.get(`/api/v3/comments/list`, { params: { commentIds } });
3057
+ decoratePayload(data);
3058
+ ingestInCache(data);
3059
+ const { comments } = data;
3060
+ return toRecord(comments);
3061
+ };
3062
+ /**
3063
+ * ```js
3064
+ * import { getComments } from '@amityco/ts-sdk'
3065
+ * const comments = getComments.locally(['foo', 'bar'])
3066
+ * ```
3067
+ *
3068
+ * Fetches a collection of {@link Amity.Comment} objects from cache
3069
+ *
3070
+ * @param commentIds the IDs of the {@link Amity.Comment} to fetch
3071
+ * @returns the associated collection of {@link Amity.Comment} objects
3072
+ *
3073
+ * @category Comment API
3074
+ */
3075
+ getComments.locally = (commentIds) => {
3076
+ var _a;
3077
+ const client = getActiveClient();
3078
+ client.log('comment/getComments.locally', commentIds);
3079
+ const cached = (_a = pullFromCache('comment', ...commentIds)) !== null && _a !== void 0 ? _a : [];
3080
+ if ((cached === null || cached === void 0 ? void 0 : cached.length) === commentIds.length)
3081
+ return toRecord(cached);
3082
+ };
3083
+
3084
+ /**
3085
+ * ```js
3086
+ * import { getComment } from '@amityco/ts-sdk'
3087
+ * const comment = await getComment('foobar')
3088
+ * ```
3089
+ *
3090
+ * Fetches a {@link Amity.Comment} object
3091
+ *
3092
+ * @param commentId the ID of the {@link Amity.Comment} to fetch
3093
+ * @returns the associated {@link Amity.Comment} object
3094
+ *
3095
+ * @category Comment API
3096
+ * @async
3097
+ */
3098
+ const getComment = async (commentId) => {
3099
+ const client = getActiveClient();
3100
+ client.log('comment/getComment', commentId);
3101
+ // API-FIX: endpoint should not be /list, parameters should be querystring.
3102
+ const { data } = await client.http.get(`/api/v3/comments/${commentId}`);
3103
+ decoratePayload(data);
3104
+ ingestInCache(data);
3105
+ const { comments } = data;
3106
+ return comments.find(comment => comment.commentId === commentId);
3107
+ };
3108
+ /**
3109
+ * ```js
3110
+ * import { getComment } from '@amityco/ts-sdk'
3111
+ * const comment = getComment.locally('foobar')
3112
+ * ```
3113
+ *
3114
+ * Fetches a {@link Amity.Comment} object
3115
+ *
3116
+ * @param commentId the ID of the {@link Amity.Comment} to fetch
3117
+ * @returns the associated {@link Amity.Comment} object
3118
+ *
3119
+ * @category Comment API
3120
+ */
3121
+ getComment.locally = (commentId) => {
3122
+ var _a;
3123
+ const client = getActiveClient();
3124
+ client.log('comment/getComment.locally', commentId);
3125
+ const [comment] = (_a = pullFromCache('comment', commentId)) !== null && _a !== void 0 ? _a : [];
3126
+ return comment;
3127
+ };
3128
+
3129
+ /**
3130
+ * ```js
3131
+ * import { createComment } from '@amityco/ts-sdk'
3132
+ * const newComment = await createComment(bundle)
3133
+ * ```
3134
+ *
3135
+ * Creates an {@link Amity.Comment}
3136
+ *
3137
+ * @param bundle The data necessary to create a new {@link Amity.Comment}
3138
+ * @returns The newly created {@link Amity.Comment}
3139
+ *
3140
+ * @category Comment API
3141
+ * @async
3142
+ */
3143
+ const createComment = async (bundle) => {
3144
+ const client = getActiveClient();
3145
+ client.log('comment/createComment', bundle);
3146
+ const { data } = await client.http.post('/api/v3/comments', bundle);
3147
+ decoratePayload(data);
3148
+ ingestInCache(data);
3149
+ const post = await getPost(bundle.referenceId);
3150
+ fireEvent('v3.post.didUpdate', { posts: [post] });
3151
+ fireEvent('v3.comment.didCreate', data);
3152
+ const { comments } = data;
3153
+ return comments[0];
3154
+ };
3155
+
3156
+ /**
3157
+ * ```js
3158
+ * import { updateComment } from '@amityco/ts-sdk'
3159
+ * const updated = await updateComment(commentId, {
3160
+ * data: { text: 'hello world' }
3161
+ * })
3162
+ * ```
3163
+ *
3164
+ * Updates an {@link Amity.Comment}
3165
+ *
3166
+ * @param commentId The ID of the {@link Amity.Comment} to edit
3167
+ * @param patch The patch data to apply
3168
+ * @returns the updated {@link Amity.Comment} object
3169
+ *
3170
+ * @category Comment API
3171
+ * @async
3172
+ */
3173
+ const updateComment = async (commentId, patch) => {
3174
+ const client = getActiveClient();
3175
+ client.log('user/updateComment', patch);
3176
+ const { data } = await client.http.put(`/api/v3/comments/${commentId}`, patch);
3177
+ decoratePayload(data);
3178
+ ingestInCache(data);
3179
+ fireEvent('v3.comment.didUpdate', data);
3180
+ const { comments } = data;
3181
+ return comments.find(comment => comment.commentId === commentId);
3182
+ };
3183
+
3184
+ /**
3185
+ * ```js
3186
+ * import { deleteComment } from '@amityco/ts-sdk'
3187
+ * const success = await deleteComment('foobar')
3188
+ * ```
3189
+ *
3190
+ * Deletes a {@link Amity.Comment}
3191
+ *
3192
+ * @param commentId The {@link Amity.Comment} ID to delete
3193
+ * @return A success boolean if the {@link Amity.Comment} was deleted
3194
+ *
3195
+ * @category Comment API
3196
+ * @async
3197
+ */
3198
+ const deleteComment = async (commentId) => {
3199
+ const client = getActiveClient();
3200
+ client.log('comment/deleteComment', commentId);
3201
+ // API-FIX: This endpoint has not been implemented yet.
3202
+ await client.http.delete(`/api/v3/comments/${commentId}`);
3203
+ const deleted = await getComment(commentId);
3204
+ const post = await getPost(deleted.referenceId);
3205
+ fireEvent('v3.post.didUpdate', { posts: [post] });
3206
+ fireEvent('v3.comment.didDelete', { comments: [deleted] });
3207
+ return deleted;
3208
+ };
3209
+
3210
+ /** @hidden */
3211
+ const fetchReference = async (referenceType, referenceId) => {
3212
+ if (referenceType === 'message')
3213
+ return getMessage(referenceId);
3214
+ else if (referenceType === 'post')
3215
+ return getPost(referenceId);
3216
+ else if (referenceType === 'comment')
3217
+ return getComment(referenceId);
3218
+ throw new Error(`Incorrect referenceType: ${referenceType}`);
3219
+ };
3220
+
3221
+ /**
3222
+ * ```js
3223
+ * import { addReaction } from '@amityco/ts-sdk'
3224
+ * const success = await addReaction('post', postId, 'like')
3225
+ * ```
3226
+ *
3227
+ * Creates an {@link Amity.Reaction}
3228
+ *
3229
+ * @param referenceType The type of thing to add a {@link Amity.Reaction} to, such as a post or a comment.
3230
+ * @param referenceId The ID of the thing to add a new {@link Amity.Reaction} to.
3231
+ * @param reactionName Reaction name, such as a `like` or `love`.
3232
+ * @returns The added result.
3233
+ *
3234
+ * @category Reaction API
3235
+ * @async
3236
+ **/
3237
+ const addReaction = async (referenceType, referenceId, reactionName) => {
3238
+ var _a, _b;
3239
+ const client = getActiveClient();
3240
+ client.log('reaction/createReaction', {
3241
+ referenceId,
3242
+ referenceType,
3243
+ reactionName,
3244
+ });
3245
+ await client.http.post('/api/v2/reactions', { referenceId, referenceType, reactionName });
3246
+ const model = await fetchReference(referenceType, referenceId);
3247
+ dispatchReactable(referenceType, model);
3248
+ return (_b = (_a = model.myReactions) === null || _a === void 0 ? void 0 : _a.includes(reactionName)) !== null && _b !== void 0 ? _b : false;
3249
+ };
3250
+ /**
3251
+ * ```js
3252
+ * import { addReaction } from '@amityco/ts-sdk'
3253
+ * const success = addReaction.optimistically('post', postId, 'like')
3254
+ * ```
3255
+ *
3256
+ * Creates an {@link Amity.Reaction} optimistically
3257
+ *
3258
+ * @param referenceType The type of thing to add a {@link Amity.Reaction} to, such as a post or a comment.
3259
+ * @param referenceId The ID of the thing to add a new {@link Amity.Reaction} to.
3260
+ * @param reactionName Reaction name, such as a `like` or `love`.
3261
+ * @returns The added result.
3262
+ *
3263
+ * @category Reaction API
3264
+ **/
3265
+ addReaction.optimistically = (referenceType, referenceId, reactionName) => {
3266
+ var _a, _b;
3267
+ const model = mutateCache(referenceType, referenceId, model => {
3268
+ var _a, _b, _c;
3269
+ if ((_a = model.myReactions) === null || _a === void 0 ? void 0 : _a.includes(reactionName))
3270
+ return;
3271
+ return Object.assign(Object.assign({}, model), { syncedAt: -1, reactionsCount: model.reactionsCount + 1, myReactions: [...((_b = model.myReactions) !== null && _b !== void 0 ? _b : []), reactionName], reactions: Object.assign(Object.assign({}, model.reactions), { [reactionName]: ((_c = model.reactions[reactionName]) !== null && _c !== void 0 ? _c : 0) + 1 }) });
3272
+ });
3273
+ model && dispatchReactable(referenceType, model);
3274
+ 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;
3275
+ };
3276
+
3277
+ /**
3278
+ * ```js
3279
+ * import { deleteReaction } from '@amityco/ts-sdk'
3280
+ * const success = await deleteReaction('post', 'foobar', 'like')
3281
+ * ```
3282
+ *
3283
+ * Removes a {@link Amity.Reaction} from a {@link Amity.Reactable} object
3284
+ *
3285
+ * @param referenceType The type of thing to add a {@link Amity.Reaction} to, such as a post or a comment.
3286
+ * @param referenceId The ID of the thing to add a new {@link Amity.Reaction} to.
3287
+ * @param reactionName Reaction name, such as a `like` or `love`.
3288
+ * @returns The removed result.
3289
+ *
3290
+ * @category Reaction API
3291
+ * @async
3292
+ **/
3293
+ const removeReaction = async (referenceType, referenceId, reactionName) => {
3294
+ var _a, _b;
3295
+ const client = getActiveClient();
3296
+ client.log('reaction/removeReaction', {
3297
+ referenceId,
3298
+ referenceType,
3299
+ reactionName,
3300
+ });
3301
+ await client.http.delete(`/api/v2/reactions`, { data: { referenceId, referenceType, reactionName } });
3302
+ const model = await fetchReference(referenceType, referenceId);
3303
+ dispatchReactable(referenceType, model);
3304
+ return (_b = !((_a = model.myReactions) === null || _a === void 0 ? void 0 : _a.includes(reactionName))) !== null && _b !== void 0 ? _b : false;
3305
+ };
3306
+ /**
3307
+ * ```js
3308
+ * import { removeReaction } from '@amityco/ts-sdk'
3309
+ * const success = removeReaction.optimistically('post', postId, 'like')
3310
+ * ```
3311
+ *
3312
+ * Removes a {@link Amity.Reaction} from a {@link Amity.Reactable} object optimistically
3313
+ *
3314
+ * @param referenceType The type of thing to add a {@link Amity.Reaction} to, such as a post or a comment.
3315
+ * @param referenceId The ID of the thing to add a new {@link Amity.Reaction} to.
3316
+ * @param reactionName Reaction name, such as a `like` or `love`.
3317
+ * @returns The added result.
3318
+ *
3319
+ * @category Reaction API
3320
+ **/
3321
+ removeReaction.optimistically = (referenceType, referenceId, reactionName) => {
3322
+ var _a, _b;
3323
+ const model = mutateCache(referenceType, referenceId, model => {
3324
+ var _a, _b, _c;
3325
+ if (!((_a = model.myReactions) === null || _a === void 0 ? void 0 : _a.includes(reactionName)))
3326
+ return;
3327
+ return Object.assign(Object.assign({}, model), { syncedAt: -1, reactionsCount: Math.max(0, model.reactionsCount - 1), myReactions: ((_b = model.myReactions) !== null && _b !== void 0 ? _b : []).filter(item => item !== reactionName), reactions: Object.assign(Object.assign({}, model.reactions), { [reactionName]: Math.max(0, ((_c = model.reactions[reactionName]) !== null && _c !== void 0 ? _c : 0) - 1) }) });
3328
+ });
3329
+ model && dispatchReactable(referenceType, model);
3330
+ 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;
3331
+ };
3332
+
3333
+ /**
3334
+ * ```js
3335
+ * import { onReactionRemoved } from '@amityco/ts-sdk'
3336
+ * const dispose = onReactionRemoved(message => {
3337
+ * // ...
3338
+ * })
3339
+ * ```
3340
+ *
3341
+ * Fired when an {@link Amity.Reaction} has been removed
3342
+ *
3343
+ * @param callback The function to call when the event was fired
3344
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
3345
+ *
3346
+ * @category Message Events
3347
+ **/
3348
+ const onReactionRemoved = (referenceType, referenceId, callback) => {
3349
+ const client = getActiveClient();
3350
+ const filter = (payload) => {
3351
+ // TODO: lol
3352
+ decoratePayload(payload);
3353
+ ingestInCache(payload);
3354
+ };
3355
+ return createEventSubscriber(client, 'reaction/onReactionRemoved', 'v3.message.didUpdate', filter);
3356
+ };
3357
+
3358
+ var REFERENCE_TYPES = {
3359
+ post: {
3360
+ domainName: 'posts',
3361
+ eventName: 'v3/post.isflagbyme',
3362
+ primaryKey: 'postId',
3363
+ },
3364
+ comment: {
3365
+ domainName: 'comments',
3366
+ eventName: 'v3/comment.isflagbyme',
3367
+ primaryKey: 'commentId',
3368
+ },
3369
+ message: {
3370
+ domainName: 'messages',
3371
+ eventName: 'v3/message.isFlaggedByMe',
3372
+ primaryKey: 'messageId',
3373
+ },
3374
+ user: {
3375
+ domainName: 'users',
3376
+ eventName: 'user.isFlagByMe',
3377
+ primaryKey: 'userId',
3378
+ },
3379
+ };
3380
+
3381
+ /**
3382
+ * ```js
3383
+ * import { createReport } from '@amityco/ts-sdk'
3384
+ * const flagged = await createReport('post', postId)
3385
+ * ```
3386
+ *
3387
+ * @param referenceType The type of thing to add a report to, such as a post or a comment.
3388
+ * @param referenceId The ID of the thing to add a new report to.
3389
+ * @returns the created report result
3390
+ *
3391
+ * @category Report API
3392
+ * @async
3393
+ **/
3394
+ const createReport = async (referenceType, referenceId) => {
3395
+ const client = getActiveClient();
3396
+ client.log('report/createReport', { referenceType, referenceId });
3397
+ const { domainName } = REFERENCE_TYPES[referenceType];
3398
+ const { data } = await client.http.post(`/api/v3/${domainName}/${referenceId}/flag`);
3399
+ decoratePayload(data);
3400
+ ingestInCache(data);
3401
+ fireEvent(`v3.${referenceType}.didUpdate`, data);
3402
+ return !!data;
3403
+ };
3404
+
3405
+ /**
3406
+ * ```js
3407
+ * import { deleteReport } from '@amityco/ts-sdk'
3408
+ * const unflagged = await deleteReport('post', postId)
3409
+ * ```
3410
+ *
3411
+ * @param referenceType The type of thing to delete a report to, such as a post or a comment.
3412
+ * @param referenceId The ID of the thing to delete a report to.
3413
+ * @returns the deleted report result
3414
+ *
3415
+ * @category Report API
3416
+ * @async
3417
+ **/
3418
+ const deleteReport = async (referenceType, referenceId) => {
3419
+ const client = getActiveClient();
3420
+ client.log('report/deleteReport', { referenceType, referenceId });
3421
+ const { domainName } = REFERENCE_TYPES[referenceType];
3422
+ const { data } = await client.http.delete(`/api/v3/${domainName}/${referenceId}/unflag`);
3423
+ decoratePayload(data);
3424
+ ingestInCache(data);
3425
+ fireEvent(`v3.${referenceType}.didUpdate`, data);
3426
+ return !!data;
3427
+ };
3428
+
3429
+ /**
3430
+ * ```js
3431
+ * import { isReportedByMe } from '@amityco/ts-sdk'
3432
+ * const isReported = await isReportedByMe('post', postId)
3433
+ * ```
3434
+ *
3435
+ * @param referenceType The type of thing to check a report to, such as a post or a comment.
3436
+ * @param referenceId The ID of the thing to check a report to.
3437
+ * @returns `true` if the report is created by me, `false` if doesn't.
3438
+ *
3439
+ * @category Report API
3440
+ * @async
3441
+ **/
3442
+ const isReportedByMe = async (referenceType, referenceId) => {
3443
+ var _a, _b;
3444
+ const client = getActiveClient();
3445
+ client.log('report/isReportedByMe', { referenceType, referenceId });
3446
+ const { eventName, primaryKey } = REFERENCE_TYPES[referenceType];
3447
+ const { result, isFlagByMe } = (_a = (await synchronousWSCall(client, eventName, {
3448
+ [primaryKey]: referenceId,
3449
+ }))) !== null && _a !== void 0 ? _a : {};
3450
+ return (_b = result !== null && result !== void 0 ? result : isFlagByMe) !== null && _b !== void 0 ? _b : false;
3451
+ };
3452
+
3453
+ /**
3454
+ * ```js
3455
+ * import { queryChannels } from '@amityco/ts-sdk'
3456
+ * const channels = await queryChannels()
3457
+ * ```
3458
+ *
3459
+ * Queries a paginable list of {@link Amity.Channel} objects
3460
+ * Search is performed by displayName such as `.startsWith(search)`
3461
+ *
3462
+ * @param query The query parameters
3463
+ * @returns A page of {@link Amity.Channel} objects
3464
+ *
3465
+ * @category Channel API
3466
+ * @async
3467
+ */
3468
+ const queryChannels = async (query) => {
3469
+ const client = getActiveClient();
3470
+ client.log('channel/queryChannels', query);
3471
+ // safe decapsulation
3472
+ const _a = query !== null && query !== void 0 ? query : {}, { page, displayName, membership } = _a, params = __rest(_a, ["page", "displayName", "membership"]);
3473
+ // API-FIX: parameters should be querystring.
3474
+ // API-FIX: backend doesnt answer Amity.Response
3475
+ // const { data } = await client.http.get<Amity.Response<Amity.Paged<ChannelPayload>>>(
3476
+ const { data } = await client.http.get(`/api/v3/channels`, { params: Object.assign(Object.assign({}, params), { keyword: displayName, filter: membership, options: {
3477
+ token: toToken(page, 'skiplimit'),
3478
+ } }) });
3479
+ const { paging } = data, response = __rest(data, ["paging"]);
3480
+ decoratePayload(response);
3481
+ ingestInCache(response);
3482
+ const prevPage = toPage(paging === null || paging === void 0 ? void 0 : paging.previous);
3483
+ const nextPage = toPage(paging === null || paging === void 0 ? void 0 : paging.next);
3484
+ const { channels } = response;
3485
+ return { data: toRecord(channels), prevPage, nextPage };
3486
+ };
3487
+ /**
3488
+ * ```js
3489
+ * import { queryChannels } from '@amityco/ts-sdk'
3490
+ * const channels = queryChannels.locally()
3491
+ * ```
3492
+ *
3493
+ * Queries a paginable list of {@link Amity.Channel} objects from cache
3494
+ *
3495
+ * @param query The query parameters
3496
+ * @returns channels
3497
+ *
3498
+ * @category Channel API
3499
+ */
3500
+ queryChannels.locally = (query) => {
3501
+ const client = getActiveClient();
3502
+ client.log('channel/queryChannels.locally', query);
3503
+ // TODO
3504
+ };
3505
+
3506
+ /**
3507
+ * ```js
3508
+ * import { getChannels } from '@amityco/ts-sdk'
3509
+ * const channels = await getChannels(['foo', 'bar'])
3510
+ * ```
3511
+ *
3512
+ * Fetches a collection of {@link Amity.Channel} objects
3513
+ *
3514
+ * @param channelIds the IDs of the {@link Amity.Channel} to fetch
3515
+ * @returns the associated collection of {@link Amity.Channel} objects
3516
+ *
3517
+ * @category Channel API
3518
+ * @async
3519
+ */
3520
+ const getChannels = async (channelIds) => {
3521
+ const client = getActiveClient();
3522
+ client.log('channel/getChannels', channelIds);
3523
+ // API-FIX: endpoint should not be /list, parameters should be querystring.
3524
+ const { data } = await client.http.get(`/api/v3/channels/list`, { params: { channelIds } });
3525
+ decoratePayload(data);
3526
+ ingestInCache(data);
3527
+ const { channels } = data;
3528
+ return toRecord(channels);
3529
+ };
3530
+ /**
3531
+ * ```js
3532
+ * import { getChannels } from '@amityco/ts-sdk'
3533
+ * const channels = getChannels.locally(['foo', 'bar']) ?? []
3534
+ * ```
3535
+ *
3536
+ * Fetches a collection of {@link Amity.Channel} objects from cache
3537
+ *
3538
+ * @param channelIds the IDs of the {@link Amity.Channel} to fetch
3539
+ * @returns the associated collection of {@link Amity.Channel} objects
3540
+ *
3541
+ * @category Channel API
3542
+ */
3543
+ getChannels.locally = (channelIds) => {
3544
+ var _a;
3545
+ const client = getActiveClient();
3546
+ client.log('channel/getChannels.locally', channelIds);
3547
+ const cached = (_a = pullFromCache('channel', ...channelIds)) !== null && _a !== void 0 ? _a : [];
3548
+ if ((cached === null || cached === void 0 ? void 0 : cached.length) === channelIds.length)
3549
+ return toRecord(cached);
3550
+ };
3551
+
3552
+ /**
3553
+ * ```js
3554
+ * import { getChannel } from '@amityco/ts-sdk'
3555
+ * const channel = await getChannel('foobar')
3556
+ * ```
3557
+ *
3558
+ * Fetches a {@link Amity.Channel} object
3559
+ *
3560
+ * @param channelId the ID of the {@link Amity.Channel} to fetch
3561
+ * @returns the associated {@link Amity.Channel} object
3562
+ *
3563
+ * @category Channel API
3564
+ * @async
3565
+ */
3566
+ const getChannel = async (channelId) => {
3567
+ const client = getActiveClient();
3568
+ client.log('channel/getChannel', channelId);
3569
+ // API-FIX: endpoint should not be /list, parameters should be querystring.
3570
+ const { data } = await client.http.get(`/api/v3/channels/${channelId}`);
3571
+ decoratePayload(data);
3572
+ ingestInCache(data);
3573
+ const { channels } = data;
3574
+ return channels.find(channel => channel.channelId === channelId);
3575
+ };
3576
+ /**
3577
+ * ```js
3578
+ * import { getChannel } from '@amityco/ts-sdk'
3579
+ * const channel = getChannel.locally('foobar')
3580
+ * ```
3581
+ *
3582
+ * Fetches a {@link Amity.Channel} object from cache
3583
+ *
3584
+ * @param channelId the ID of the {@link Amity.Channel} to fetch
3585
+ * @returns the associated {@link Amity.Channel} object
3586
+ *
3587
+ * @category Channel API
3588
+ */
3589
+ getChannel.locally = (channelId) => {
3590
+ var _a;
3591
+ const client = getActiveClient();
3592
+ client.log('channel/getChannel.locally', channelId);
3593
+ const [channel] = (_a = pullFromCache('channel', channelId)) !== null && _a !== void 0 ? _a : [];
3594
+ return channel;
3595
+ };
3596
+
3597
+ /**
3598
+ * ```js
3599
+ * import { createChannel } from '@amityco/ts-sdk'
3600
+ * const created = await createChannel({ channelId: 'foobar', displayName: 'foobar' })
3601
+ * ```
3602
+ *
3603
+ * Creates an {@link Amity.Channel}
3604
+ *
3605
+ * @param bundle The data necessary to create a new {@link Amity.Channel}
3606
+ * @returns The newly created {@link Amity.Channel}
3607
+ *
3608
+ * @category Channel API
3609
+ * @async
3610
+ */
3611
+ const createChannel = async (bundle) => {
3612
+ const client = getActiveClient();
3613
+ client.log('user/createChannel', bundle);
3614
+ const { data } = await client.http.post('/api/v3/channels', bundle);
3615
+ decoratePayload(data);
3616
+ ingestInCache(data);
3617
+ // no need for event, fired by server
3618
+ const { channels } = data;
3619
+ return channels[0];
3620
+ };
3621
+
3622
+ /**
3623
+ * ```js
3624
+ * import { updateChannel } from '@amityco/ts-sdk'
3625
+ * const updated = await updateChannel(channelId, { displayName: 'foobar' })
3626
+ * ```
3627
+ *
3628
+ * Updates an {@link Amity.Channel}
3629
+ *
3630
+ * @param channelId The ID of the {@link Amity.Channel} to edit
3631
+ * @param patch The patch data to apply
3632
+ * @returns the updated {@link Amity.Channel} object
3633
+ *
3634
+ * @category Channel API
3635
+ * @async
3636
+ */
3637
+ const updateChannel = async (channelId, patch) => {
3638
+ const client = getActiveClient();
3639
+ client.log('channel/updateChannel', channelId, patch);
3640
+ const { data } = await client.http.put(`/api/v3/channels/${channelId}`, patch);
3641
+ decoratePayload(data);
3642
+ ingestInCache(data);
3643
+ // no need for event, fired by server
3644
+ const { channels } = data;
3645
+ return channels.find(channel => channel.channelId === channelId);
3646
+ };
3647
+
3648
+ /**
3649
+ * ```js
3650
+ * import { deleteChannel } from '@amityco/ts-sdk'
3651
+ * const success = await deleteChannel('foobar')
3652
+ * ```
3653
+ *
3654
+ * Deletes a {@link Amity.Channel}
3655
+ *
3656
+ * @param channelId The {@link Amity.Channel} ID to delete
3657
+ * @return A success boolean if the {@link Amity.Channel} was deleted
3658
+ *
3659
+ * @category Channel API
3660
+ * @async
3661
+ */
3662
+ const deleteChannel = async (channelId) => {
3663
+ const client = getActiveClient();
3664
+ client.log('channel/deleteChannel', channelId);
3665
+ // API-FIX: This endpoint has not been implemented yet.
3666
+ await client.http.delete(`/api/v3/channels/${channelId}`);
3667
+ const deleted = await getChannel(channelId);
3668
+ // no need for event, fired by server
3669
+ return deleted;
3670
+ };
3671
+
3672
+ /**
3673
+ * ```js
3674
+ * import { joinChannel } from '@amityco/ts-sdk'
3675
+ * const isJoined = await joinChannel('foobar')
3676
+ * ```
3677
+ *
3678
+ * Joins a {@link Amity.Channel} object
3679
+ *
3680
+ * @param channelId the {@link Amity.Channel} to join
3681
+ * @returns A success boolean if the {@link Amity.Channel} was joined
3682
+ *
3683
+ * @category Channel API
3684
+ * @async
3685
+ */
3686
+ const joinChannel = async (channelId) => {
3687
+ const client = getActiveClient();
3688
+ client.log('channel/joinChannel', channelId);
3689
+ const { data } = await client.http.post(`/api/v3/channels/${channelId}/join`);
3690
+ decoratePayload(data);
3691
+ ingestInCache(data);
3692
+ // no need for event, fired by server
3693
+ const { channelUsers } = data;
3694
+ return !!channelUsers.find(channelUser => (channelUser.channelId === channelId
3695
+ && channelUser.membership === 'member'));
3696
+ };
3697
+
3698
+ /**
3699
+ * ```js
3700
+ * import { leaveChannel } from '@amityco/ts-sdk'
3701
+ * const isLeft = await leaveChannel('foobar')
3702
+ * ```
3703
+ *
3704
+ * Leave a {@link Amity.Channel} object
3705
+ *
3706
+ * @param channelId the {@link Amity.Channel} to leave
3707
+ * @returns A success boolean if the {@link Amity.Channel} was left
3708
+ *
3709
+ * @category Channel API
3710
+ * @async
3711
+ */
3712
+ const leaveChannel = async (channelId) => {
3713
+ const client = getActiveClient();
3714
+ client.log('channel/leaveChannel', channelId);
3715
+ const { data } = await client.http.delete(`/api/v3/channels/${channelId}/leave`);
3716
+ decoratePayload(data);
3717
+ ingestInCache(data);
3718
+ // no need for event, fired by server
3719
+ const { channelUsers } = data;
3720
+ return !!channelUsers.find(channelUser => (channelUser.channelId === channelId
3721
+ && channelUser.membership !== 'member'));
3722
+ };
3723
+
3724
+ /**
3725
+ * ```js
3726
+ * import { queryChannelMembers } from '@amityco/ts-sdk'
3727
+ * const channelMembers = await queryChannelMembers({ channelId: 'foo' })
3728
+ * ```
3729
+ *
3730
+ * Queries a paginable list of {@link Amity.ChannelUser} objects
3731
+ *
3732
+ * @param query The query parameters
3733
+ * @returns A page of {@link Amity.ChannelUser} objects
3734
+ *
3735
+ * @category Channel API
3736
+ * @async
3737
+ **/
3738
+ const queryChannelMembers = async (query) => {
3739
+ const client = getActiveClient();
3740
+ client.log('channel/queryChannelMembers', query);
3741
+ const _a = query !== null && query !== void 0 ? query : {}, { page, channelId, membership } = _a, params = __rest(_a, ["page", "channelId", "membership"]);
3742
+ const { data } = await client.http.get(`/api/v3/channels/${channelId}/users`, {
3743
+ params: Object.assign(Object.assign({}, params), { filter: membership, options: {
3744
+ token: toToken(page, 'skiplimit'),
3745
+ } }),
3746
+ });
3747
+ const { paging } = data, response = __rest(data, ["paging"]);
3748
+ decoratePayload(response);
3749
+ ingestInCache(response);
3750
+ const { channelUsers } = response;
3751
+ const nextPage = toPage(paging.next);
3752
+ const prevPage = toPage(paging.previous);
3753
+ return { data: toRecord(channelUsers), nextPage, prevPage };
3754
+ };
3755
+ /**
3756
+ * ```js
3757
+ * import { queryChannelMembers } from '@amityco/ts-sdk'
3758
+ * const channelMembers = await queryChannelMembers(query)
3759
+ * ```
3760
+ *
3761
+ * Queries a paginable list of {@link Amity.Post} objects from cache
3762
+ *
3763
+ * @param query The query parameters
3764
+ * @returns posts
3765
+ *
3766
+ * @category Post API
3767
+ */
3768
+ queryChannelMembers.locally = (query) => {
3769
+ const client = getActiveClient();
3770
+ client.log('channel/queryChannelMembers', query);
3771
+ // TODO
3772
+ };
3773
+
3774
+ /**
3775
+ * ```js
3776
+ * import { addChannelMembers } from '@amityco/ts-sdk'
3777
+ * const updated = await addChannelMembers(channelId, ['foo', 'bar'])
3778
+ * ```
3779
+ *
3780
+ * Adds a list of {@link Amity.User} to a {@link Amity.Channel}
3781
+ *
3782
+ * @param channelId The ID of the {@link Amity.Channel} to perform
3783
+ * @param userIds The list of IDs {@link Amity.User} to add
3784
+ * @returns A success boolean if the {@link Amity.User} were added to the {@link Amity.Channel}
3785
+ *
3786
+ * @category Channel API
3787
+ * @async
3788
+ */
3789
+ const addChannelMembers = async (channelId, userIds) => {
3790
+ const client = getActiveClient();
3791
+ client.log('channel/addChannelMembers', channelId, userIds);
3792
+ const { data } = await client.http.post(`/api/v3/channels/${channelId}/users`, { channelId, userIds });
3793
+ decoratePayload(data);
3794
+ ingestInCache(data);
3795
+ fireEvent('v3.channel.didAddUsers', {
3796
+ channels: data.channels,
3797
+ });
3798
+ const { channelUsers } = data;
3799
+ return !!channelUsers.find(channelUser => channelUser.channelId === channelId && channelUser.membership === 'member');
3800
+ };
3801
+
3802
+ /**
3803
+ * ```js
3804
+ * import { removeChannelMembers } from '@amityco/ts-sdk'
3805
+ * const updated = await removeChannelMembers(channelId, ['foo', 'bar'])
3806
+ * ```
3807
+ *
3808
+ * Removes a list of {@link Amity.User} from a {@link Amity.Channel}
3809
+ *
3810
+ * @param channelId The ID of the {@link Amity.Channel} to perform
3811
+ * @param userIds The list of IDs {@link Amity.User} to remove
3812
+ * @returns A success boolean if the list of {@link Amity.User} were removed from the {@link Amity.Channel}
3813
+ *
3814
+ * @category Channel API
3815
+ * @async
3816
+ */
3817
+ const removeChannelMembers = async (channelId, userIds) => {
3818
+ const client = getActiveClient();
3819
+ client.log('channel/removeChannelMembers', channelId, userIds);
3820
+ const { data } = await client.http.delete(`/api/v3/channels/${channelId}/users`, { data: { channelId, userIds } });
3821
+ decoratePayload(data);
3822
+ ingestInCache(data);
3823
+ fireEvent('v3.channel.didRemoveUsers', {
3824
+ channels: data.channels,
3825
+ });
3826
+ const { channelUsers } = data;
3827
+ return !!channelUsers.find(channelUser => channelUser.channelId === channelId && channelUser.membership !== 'member');
3828
+ };
3829
+
3830
+ /**
3831
+ * ```js
3832
+ * import { addChannelMembersRole } from '@amityco/ts-sdk'
3833
+ * const updated = await addChannelMembersRole(channelId, 'foo', ['bar'])
3834
+ * ```
3835
+ *
3836
+ * Adds an {@link Amity.Role} to a list of {@link Amity.User} on a {@link Amity.Channel}
3837
+ *
3838
+ * @param channelId The ID of the {@link Amity.Channel} to perform
3839
+ * @param roleId The ID of the {@link Amity.Role} to apply
3840
+ * @param userId Array of IDs of the {@link Amity.User} to perform
3841
+ * @returns A success boolean if the {@link Amity.Role} were added to list of {@link Amity.User} in the {@link Amity.Channel}
3842
+ *
3843
+ * @category Channel API
3844
+ * @async
3845
+ */
3846
+ const addChannelMembersRole = async (channelId, roleId, userIds) => {
3847
+ const client = getActiveClient();
3848
+ client.log('channel/addChannelMembersRole', channelId, roleId, userIds);
3849
+ const { data } = await client.http.post(`/api/v3/channels/${channelId}/users/roles`, { channelId, role: roleId, userIds });
3850
+ decoratePayload(data);
3851
+ ingestInCache(data);
3852
+ const { channelUsers } = data;
3853
+ return !!channelUsers.find(channelUser => channelUser.channelId === channelId && channelUser.roles.includes(roleId));
3854
+ };
3855
+
3856
+ /**
3857
+ * ```js
3858
+ * import { removeChannelMembersRole } from '@amityco/ts-sdk'
3859
+ * const updated = await removeChannelMembersRole(channelId, 'foo', ['bar'])
3860
+ * ```
3861
+ *
3862
+ * Removes an {@link Amity.Role} from a list of {@link Amity.User} on a {@link Amity.Channel}
3863
+ *
3864
+ * @param channelId The ID of the {@link Amity.Channel} to perform
3865
+ * @param roleId The ID of the {@link Amity.Role} to apply
3866
+ * @param userId Array of IDs of the {@link Amity.User} to perform
3867
+ * @returns A success boolean if the {@link Amity.Role} were removed from list of {@link Amity.User} in the {@link Amity.Channel}
3868
+ *
3869
+ * @category Channel API
3870
+ * @async
3871
+ */
3872
+ const removeChannelMembersRole = async (channelId, roleId, userIds) => {
3873
+ const client = getActiveClient();
3874
+ client.log('channel/removeChannelMembersRole', channelId, roleId, userIds);
3875
+ const { data } = await client.http.delete(`/api/v3/channels/${channelId}/users/roles`, { data: { channelId, role: roleId, userIds } });
3876
+ decoratePayload(data);
3877
+ ingestInCache(data);
3878
+ const { channelUsers } = data;
3879
+ return !!channelUsers.find(channelUser => channelUser.channelId === channelId && !channelUser.roles.includes(roleId));
3880
+ };
3881
+
3882
+ /**
3883
+ * ```js
3884
+ * import { onChannelUpdated } from '@amityco/ts-sdk'
3885
+ * const dispose = onChannelUpdated(channel => {
3886
+ * // ...
3887
+ * })
3888
+ * ```
3889
+ *
3890
+ * Fired when any {@link Amity.Channel} have been updated
3891
+ *
3892
+ * @param callback The function to call when the event was fired
3893
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
3894
+ *
3895
+ * @category Channel Events
3896
+ */
3897
+ const onChannelUpdated = (callback) => {
3898
+ const client = getActiveClient();
3899
+ const filter = (payload) => {
3900
+ decoratePayload(payload);
3901
+ ingestInCache(payload);
3902
+ callback(payload.channels[0]);
3903
+ };
3904
+ return createEventSubscriber(client, 'onChannelUpdated', 'v3.channel.didUpdate', filter);
3905
+ };
3906
+
3907
+ /**
3908
+ * ```js
3909
+ * import { onChannelDeleted } from '@amityco/ts-sdk'
3910
+ * const dispose = onChannelDeleted(channel => {
3911
+ * // ...
3912
+ * })
3913
+ * ```
3914
+ *
3915
+ * Fired when any {@link Amity.Channel} have been deleted
3916
+ *
3917
+ * @param callback The function to call when the event was fired
3918
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
3919
+ *
3920
+ * @category Channel Events
3921
+ */
3922
+ const onChannelDeleted = (callback) => {
3923
+ const client = getActiveClient();
3924
+ const filter = (payload) => {
3925
+ decoratePayload(payload);
3926
+ ingestInCache(payload);
3927
+ callback(payload.channels[0]);
3928
+ };
3929
+ return createEventSubscriber(client, 'onChannelDeleted', 'v3.channel.didDelete', filter);
3930
+ };
3931
+
3932
+ /**
3933
+ * ```js
3934
+ * import { onChannelJoined } from '@amityco/ts-sdk'
3935
+ * const dispose = onChannelJoined(channel => {
3936
+ * // ...
3937
+ * })
3938
+ * ```
3939
+ *
3940
+ * Fired when any {@link Amity.Channel} was joined
3941
+ *
3942
+ * @param callback The function to call when the event was fired
3943
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
3944
+ *
3945
+ * @category Channel Events
3946
+ */
3947
+ const onChannelJoined = (callback) => {
3948
+ const client = getActiveClient();
3949
+ const filter = (payload) => {
3950
+ decoratePayload(payload);
3951
+ ingestInCache(payload);
3952
+ callback(payload.channels[0]);
3953
+ };
3954
+ return createEventSubscriber(client, 'onChannelJoined', 'v3.channel.didJoin', filter);
3955
+ };
3956
+
3957
+ /**
3958
+ * ```js
3959
+ * import { onChannelLeft } from '@amityco/ts-sdk'
3960
+ * const dispose = onChannelLeft(channel => {
3961
+ * // ...
3962
+ * })
3963
+ * ```
3964
+ *
3965
+ * Fired when any {@link Amity.Channel} was left
3966
+ *
3967
+ * @param callback The function to call when the event was fired
3968
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
3969
+ *
3970
+ * @category Channel Events
3971
+ */
3972
+ const onChannelLeft = (callback) => {
3973
+ const client = getActiveClient();
3974
+ const filter = (payload) => {
3975
+ decoratePayload(payload);
3976
+ ingestInCache(payload);
3977
+ callback(payload.channels[0]);
3978
+ };
3979
+ return createEventSubscriber(client, 'onChannelLeft', 'v3.channel.didLeave', filter);
3980
+ };
3981
+
3982
+ /**
3983
+ * ```js
3984
+ * import { onMemberAdded } from '@amityco/ts-sdk'
3985
+ * const dispose = onMemberAdded(channel => {
3986
+ * // ...
3987
+ * })
3988
+ * ```
3989
+ *
3990
+ * Fired when any {@link Amity.User} has been added to any {@link Amity.Channel}
3991
+ *
3992
+ * @param callback The function to call when the event was fired
3993
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
3994
+ *
3995
+ * @category Channel Events
3996
+ */
3997
+ const onMemberAdded = (callback) => {
3998
+ const client = getActiveClient();
3999
+ const filter = (payload) => {
4000
+ decoratePayload(payload);
4001
+ ingestInCache(payload);
4002
+ callback(payload.channels[0]);
4003
+ };
4004
+ return createEventSubscriber(client, 'onMemberAdded', 'v3.channel.didAddUsers', filter);
4005
+ };
4006
+
4007
+ /**
4008
+ * ```js
4009
+ * import { onMemberRemoved } from '@amityco/ts-sdk'
4010
+ * const dispose = onMemberRemoved(channel => {
4011
+ * // ...
4012
+ * })
4013
+ * ```
4014
+ *
4015
+ * Fired when any {@link Amity.User} has been removed from any {@link Amity.Channel}
4016
+ *
4017
+ * @param callback The function to call when the event was fired
4018
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
4019
+ *
4020
+ * @category Channel Events
4021
+ */
4022
+ const onMemberRemoved = (callback) => {
4023
+ const client = getActiveClient();
4024
+ const filter = (payload) => {
4025
+ decoratePayload(payload);
4026
+ ingestInCache(payload);
4027
+ callback(payload.channels[0]);
4028
+ };
4029
+ return createEventSubscriber(client, 'onMemberRemoved', 'v3.channel.didRemoveUsers', filter);
4030
+ };
4031
+
4032
+ /**
4033
+ * ```js
4034
+ * import { observeChannel } from '@amityco/ts-sdk'
4035
+ *
4036
+ * let channel = {}
4037
+ * const dispose = observeChannel(channelId, ({ data }) => channel = data)
4038
+ * ```
4039
+ *
4040
+ * Observe all mutation on a given {@link Amity.Channel}
4041
+ *
4042
+ * @param channelId the ID of the channel to observe
4043
+ * @param callback the function to call when new data are available
4044
+ * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the channel
4045
+ *
4046
+ * @category Channel Observer
4047
+ */
4048
+ const observeChannel = (channelId, callback) => {
4049
+ const { log } = getActiveClient();
4050
+ const timestamp = Date.now();
4051
+ log(`observeChannel(tmpid: ${timestamp}) > listen`);
4052
+ // wrapper function to make sure
4053
+ const router = (result, action) => {
4054
+ var _a, _b, _c;
4055
+ // filter function
4056
+ if (((_a = result.data) === null || _a === void 0 ? void 0 : _a.channelId) !== channelId)
4057
+ return;
4058
+ if (callback instanceof Function)
4059
+ return callback(result);
4060
+ if (action !== 'onFetch')
4061
+ (_b = callback.onEvent) === null || _b === void 0 ? void 0 : _b.call(callback, action, result);
4062
+ (_c = callback[action]) === null || _c === void 0 ? void 0 : _c.call(callback, result);
4063
+ };
4064
+ const disposers = [];
4065
+ disposers.push(onChannelUpdated(data => router({ data }, 'onUpdate')), onChannelDeleted(data => router({ data }, 'onDelete')), onChannelJoined(data => router({ data }, 'onJoin')), onChannelLeft(data => router({ data }, 'onLeft')), onMemberAdded(data => router({ data }, 'onMemberAdded')), onMemberRemoved(data => router({ data }, 'onMemberRemoved')));
4066
+ runQuery(createQuery(getChannel, channelId), result => result.data && router(result, 'onFetch'));
4067
+ return () => {
4068
+ log(`observeChannel(tmpid: ${timestamp}) > dispose`);
4069
+ disposers.forEach(fn => fn());
4070
+ };
4071
+ };
4072
+
4073
+ /**
4074
+ * ```js
4075
+ * import { onMessageCreated } from '@amityco/ts-sdk'
4076
+ * const dispose = onMessageCreated(message => {
4077
+ * // ...
4078
+ * })
4079
+ * ```
4080
+ *
4081
+ * Fired when an {@link Amity.Message} has been created
4082
+ *
4083
+ * @param callback The function to call when the event was fired
4084
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
4085
+ *
4086
+ * @category Message Events
4087
+ */
4088
+ const onMessageCreated = (callback) => {
4089
+ const client = getActiveClient();
4090
+ const filter = (payload) => {
4091
+ decoratePayload(payload);
4092
+ ingestInCache(payload);
4093
+ callback(payload.messages[0]);
4094
+ };
4095
+ return createEventSubscriber(client, 'message/onMessageCreated', 'v3.message.didCreate', filter);
4096
+ };
4097
+
4098
+ /**
4099
+ * ```js
4100
+ * import { onMessageUpdated } from '@amityco/ts-sdk'
4101
+ * const dispose = onMessageUpdated(message => {
4102
+ * // ...
4103
+ * })
4104
+ * ```
4105
+ *
4106
+ * Fired when an {@link Amity.Message} has been updated
4107
+ *
4108
+ * @param callback The function to call when the event was fired
4109
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
4110
+ *
4111
+ * @category Message Events
4112
+ */
4113
+ const onMessageUpdated = (callback) => {
4114
+ const client = getActiveClient();
4115
+ const filter = (payload) => {
4116
+ decoratePayload(payload);
4117
+ ingestInCache(payload);
4118
+ callback(payload.messages[0]);
4119
+ };
4120
+ return createEventSubscriber(client, 'message/onMessageUpdated', 'v3.message.didUpdate', filter);
4121
+ };
4122
+
4123
+ /**
4124
+ * ```js
4125
+ * import { onMessageDeleted } from '@amityco/ts-sdk'
4126
+ * const dispose = onMessageDeleted(message => {
4127
+ * // ...
4128
+ * })
4129
+ * ```
4130
+ *
4131
+ * Fired when an {@link Amity.Message} was deleted
4132
+ *
4133
+ * @param callback The function to call when the event was fired
4134
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
4135
+ *
4136
+ * @category Message Events
4137
+ */
4138
+ const onMessageDeleted = (callback) => {
4139
+ const client = getActiveClient();
4140
+ const filter = (payload) => {
4141
+ decoratePayload(payload);
4142
+ ingestInCache(payload);
4143
+ callback(payload.messages[0]);
4144
+ };
4145
+ return createEventSubscriber(client, 'message/onMessageDeleted', 'v3.message.didDelete', filter);
4146
+ };
4147
+
4148
+ /**
4149
+ * ```js
4150
+ * import { observeMessage } from '@amityco/ts-sdk'
4151
+ *
4152
+ * let message = {}
4153
+ * const unsub = observeMessage(messageId, updated => message = updated)
4154
+ * ```
4155
+ *
4156
+ * Observe all mutations on a {@link Amity.Message} given a single messageId
4157
+ *
4158
+ * @param client the client to observe the message with
4159
+ * @param messageId the ID of the message to observe
4160
+ * @param callback the function to call when new data are available
4161
+ * @param policy a query policy option for this observer
4162
+ * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the message
4163
+ *
4164
+ * @category Message Observer
4165
+ */
4166
+ const observeMessage = (messageId, callback, policy = 'cache_then_server') => {
4167
+ const { log } = getActiveClient();
4168
+ const timestamp = Date.now();
4169
+ log(`observeMessage(tmpid: ${timestamp}) > listen`);
4170
+ // wrapper function to make sure
4171
+ const router = (result, action) => {
4172
+ var _a, _b, _c;
4173
+ // filter function
4174
+ if (((_a = result.data) === null || _a === void 0 ? void 0 : _a.messageId) !== messageId)
4175
+ return;
4176
+ if (callback instanceof Function)
4177
+ return callback(result);
4178
+ if (action !== 'onFetch')
4179
+ (_b = callback.onEvent) === null || _b === void 0 ? void 0 : _b.call(callback, action, result);
4180
+ (_c = callback[action]) === null || _c === void 0 ? void 0 : _c.call(callback, result);
4181
+ };
4182
+ const disposers = [];
4183
+ disposers.push(onMessageUpdated(message => router(message, 'onUpdate')), onMessageDeleted(message => router(message, 'onDelete')));
4184
+ if (policy !== 'no_fetch') {
4185
+ runQuery(createQuery(getMessage, messageId), (result) => result.data && router(result, 'onFetch'), queryOptions(policy));
4186
+ }
4187
+ return () => {
4188
+ log(`observeMessages(tmpid: ${timestamp}) > dispose`);
4189
+ disposers.forEach(fn => fn());
4190
+ };
4191
+ };
4192
+
4193
+ /**
4194
+ * ```js
4195
+ * import { observeMessages } from '@amityco/ts-sdk'
4196
+ *
4197
+ * let messages = []
4198
+ * const unsub = observeMessages(channelId, message => merge(messages, message))
4199
+ * ```
4200
+ *
4201
+ * Observe all mutations on a list of {@link Amity.Message} for a given {@link Amity.Channel} object
4202
+ *
4203
+ * @param client the client to observe the message with
4204
+ * @param channelId the ID of the channel where to observe the messages
4205
+ * @param callback the function to call when new data are available
4206
+ * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the messages
4207
+ *
4208
+ * @category Message Observer
4209
+ */
4210
+ const observeMessages = (channelId, callback) => {
4211
+ const { log } = getActiveClient();
4212
+ const timestamp = Date.now();
4213
+ log(`observeMessages(tmpid: ${timestamp}) > listen`);
4214
+ const disposers = [];
4215
+ const router = (message, action) => {
4216
+ var _a, _b;
4217
+ if (message.channelId !== channelId)
4218
+ return;
4219
+ if (callback instanceof Function)
4220
+ return callback(message);
4221
+ (_a = callback.onEvent) === null || _a === void 0 ? void 0 : _a.call(callback, action, message);
4222
+ (_b = callback[action]) === null || _b === void 0 ? void 0 : _b.call(callback, message);
4223
+ };
4224
+ disposers.push(onMessageCreated(message => router(message, 'onCreate')), onMessageUpdated(message => router(message, 'onUpdate')), onMessageDeleted(message => router(message, 'onDelete')));
4225
+ return () => {
4226
+ log(`observeMessages(tmpid: ${timestamp}) > dispose`);
4227
+ disposers.forEach(fn => fn());
4228
+ };
4229
+ };
4230
+
4231
+ /**
4232
+ * ```js
4233
+ * import { onCommunityCreated } from '@amityco/ts-sdk'
4234
+ * const dispose = onCommunityCreated(channel => {
4235
+ * // ...
4236
+ * })
4237
+ * ```
4238
+ *
4239
+ * Fired when any {@link Amity.Community} have been created
4240
+ *
4241
+ * @param callback The function to call when the event was fired
4242
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
4243
+ *
4244
+ * @category Community Events
4245
+ */
4246
+ const onCommunityCreated = (callback) => {
4247
+ const client = getActiveClient();
4248
+ const filter = (payload) => {
4249
+ decoratePayload(payload);
4250
+ ingestInCache(payload);
4251
+ callback(payload.communities[0]);
4252
+ };
4253
+ return createEventSubscriber(client, 'onCommunityCreated', 'v3.community.didCreate', filter);
4254
+ };
4255
+
4256
+ /**
4257
+ * ```js
4258
+ * import { onCommunityUpdated } from '@amityco/ts-sdk'
4259
+ * const dispose = onCommunityUpdated(channel => {
4260
+ * // ...
4261
+ * })
4262
+ * ```
4263
+ *
4264
+ * Fired when any {@link Amity.Community} have been updated
4265
+ *
4266
+ * @param callback The function to call when the event was fired
4267
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
4268
+ *
4269
+ * @category Community Events
4270
+ */
4271
+ const onCommunityUpdated = (callback) => {
4272
+ const client = getActiveClient();
4273
+ const filter = (payload) => {
4274
+ decoratePayload(payload);
4275
+ ingestInCache(payload);
4276
+ callback(payload.communities[0]);
4277
+ };
4278
+ return createEventSubscriber(client, 'onCommunityUpdated', 'v3.community.didUpdate', filter);
4279
+ };
4280
+
4281
+ /**
4282
+ * ```js
4283
+ * import { onCommunityDeleted } from '@amityco/ts-sdk'
4284
+ * const dispose = onCommunityDeleted(channel => {
4285
+ * // ...
4286
+ * })
4287
+ * ```
4288
+ *
4289
+ * Fired when any {@link Amity.Community} have been deleted
4290
+ *
4291
+ * @param callback The function to call when the event was fired
4292
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
4293
+ *
4294
+ * @category Community Events
4295
+ */
4296
+ const onCommunityDeleted = (callback) => {
4297
+ const client = getActiveClient();
4298
+ const filter = (payload) => {
4299
+ decoratePayload(payload);
4300
+ ingestInCache(payload);
4301
+ callback(payload.communities[0]);
4302
+ };
4303
+ return createEventSubscriber(client, 'onCommunityDeleted', 'v3.community.didDelete', filter);
4304
+ };
4305
+
4306
+ /**
4307
+ * ```js
4308
+ * import { onCommunityJoined } from '@amityco/ts-sdk'
4309
+ * const dispose = onCommunityJoined(channel => {
4310
+ * // ...
4311
+ * })
4312
+ * ```
4313
+ *
4314
+ * Fired when any {@link Amity.Community} was joined
4315
+ *
4316
+ * @param callback The function to call when the event was fired
4317
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
4318
+ *
4319
+ * @category Community Events
4320
+ */
4321
+ const onCommunityJoined = (callback) => {
4322
+ const client = getActiveClient();
4323
+ const filter = (payload) => {
4324
+ decoratePayload(payload);
4325
+ ingestInCache(payload);
4326
+ callback(payload.communities[0]);
4327
+ };
4328
+ return createEventSubscriber(client, 'onCommunityJoined', 'v3.community.didJoin', filter);
4329
+ };
4330
+
4331
+ /**
4332
+ * ```js
4333
+ * import { onCommunityLeft } from '@amityco/ts-sdk'
4334
+ * const dispose = onCommunityLeft(channel => {
4335
+ * // ...
4336
+ * })
4337
+ * ```
4338
+ *
4339
+ * Fired when any {@link Amity.Community} was left
4340
+ *
4341
+ * @param callback The function to call when the event was fired
4342
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
4343
+ *
4344
+ * @category Community Events
4345
+ */
4346
+ const onCommunityLeft = (callback) => {
4347
+ const client = getActiveClient();
4348
+ const filter = (payload) => {
4349
+ decoratePayload(payload);
4350
+ ingestInCache(payload);
4351
+ callback(payload.communities[0]);
4352
+ };
4353
+ return createEventSubscriber(client, 'onCommunityLeft', 'v3.community.didLeave', filter);
4354
+ };
4355
+
4356
+ /**
4357
+ * ```js
4358
+ * import { observeCommunity } from '@amityco/ts-sdk'
4359
+ *
4360
+ * let community = {}
4361
+ * const dispose = observeCommunity(communityId, updated => community = updated)
4362
+ * ```
4363
+ *
4364
+ * Observe all mutation on a given {@link Amity.Community}
4365
+ *
4366
+ * @param communityId the ID of the community to observe
4367
+ * @param callback the function to call when new data are available
4368
+ * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the community
4369
+ *
4370
+ * @category Community Observer
4371
+ */
4372
+ const observeCommunity = (communityId, callback) => {
4373
+ const { log } = getActiveClient();
4374
+ const timestamp = Date.now();
4375
+ log(`observeCommunity(tmpid: ${timestamp}) > listen`);
4376
+ // wrapper function to make sure
4377
+ const router = (result, action) => {
4378
+ var _a, _b, _c;
4379
+ // filter function
4380
+ if (((_a = result.data) === null || _a === void 0 ? void 0 : _a.communityId) !== communityId)
4381
+ return;
4382
+ if (callback instanceof Function)
4383
+ return callback(result);
4384
+ if (action !== 'onFetch')
4385
+ (_b = callback.onEvent) === null || _b === void 0 ? void 0 : _b.call(callback, action, result);
4386
+ (_c = callback[action]) === null || _c === void 0 ? void 0 : _c.call(callback, result);
4387
+ };
4388
+ const disposers = [];
4389
+ disposers.push(onCommunityUpdated(data => router({ data }, 'onUpdate')), onCommunityDeleted(data => router({ data }, 'onDelete')), onCommunityJoined(data => router({ data }, 'onJoin')), onCommunityLeft(data => router({ data }, 'onLeft')));
4390
+ runQuery(createQuery(getCommunity, communityId), result => result.data && router(result, 'onFetch'));
4391
+ return () => {
4392
+ log(`observeCommunity(tmpid: ${timestamp}) > dispose`);
4393
+ disposers.forEach(fn => fn());
4394
+ };
4395
+ };
4396
+
4397
+ /**
4398
+ * ```js
4399
+ * import { queryGlobalFeed } from '@amityco/ts-sdk'
4400
+ * const posts = await queryGlobalFeed()
4401
+ * ```
4402
+ *
4403
+ * Queries a paginable list of {@link Amity.Post} objects
4404
+ *
4405
+ * @param query The query parameters
4406
+ * @returns A page of {@link Amity.Post} objects
4407
+ *
4408
+ * @category Feed API
4409
+ * @async
4410
+ **/
4411
+ const queryGlobalFeed = async (query) => {
4412
+ const client = getActiveClient();
4413
+ client.log('feed/queryGlobalFeed', query);
4414
+ const _a = query !== null && query !== void 0 ? query : {}, { page } = _a, params = __rest(_a, ["page"]);
4415
+ const { data } = await client.http.get(`/api/v4/me/global-feeds`, { params: Object.assign(Object.assign({}, params), { options: {
4416
+ token: toToken(page, 'skiplimit')
4417
+ } }) });
4418
+ const { paging } = data, response = __rest(data, ["paging"]);
4419
+ decoratePayload(response);
4420
+ ingestInCache(response);
4421
+ const { posts } = response;
4422
+ const nextPage = toPage(paging.next);
4423
+ const prevPage = toPage(paging.previous);
4424
+ return { data: toRecord(posts), nextPage, prevPage };
4425
+ };
4426
+
4427
+ /**
4428
+ * ```js
4429
+ * import { onPostCreated } from '@amityco/ts-sdk'
4430
+ * const dispose = onPostCreated(post => {
4431
+ * // ...
4432
+ * })
4433
+ * ```
4434
+ *
4435
+ * Fired when an {@link Amity.Post} has been created
4436
+ *
4437
+ * @param callback The function to call when the event was fired
4438
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
4439
+ *
4440
+ * @category Post Events
4441
+ */
4442
+ const onPostCreated = (callback) => {
4443
+ const client = getActiveClient();
4444
+ const filter = (payload) => {
4445
+ decoratePayload(payload);
4446
+ ingestInCache(payload);
4447
+ callback(payload.posts[0]);
4448
+ };
4449
+ return createEventSubscriber(client, 'message/onPostCreated', 'v3.post.didCreate', filter);
4450
+ };
4451
+
4452
+ /**
4453
+ * ```js
4454
+ * import { onPostUpdated } from '@amityco/ts-sdk'
4455
+ * const dispose = onPostUpdated(post => {
4456
+ * // ...
4457
+ * })
4458
+ * ```
4459
+ *
4460
+ * Fired when an {@link Amity.Post} has been updated
4461
+ *
4462
+ * @param callback The function to call when the event was fired
4463
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
4464
+ *
4465
+ * @category Post Events
4466
+ */
4467
+ const onPostUpdated = (callback) => {
4468
+ const client = getActiveClient();
4469
+ const filter = (payload) => {
4470
+ decoratePayload(payload);
4471
+ ingestInCache(payload);
4472
+ callback(payload.posts[0]);
4473
+ };
4474
+ return createEventSubscriber(client, 'message/onPostUpdated', 'v3.post.didUpdate', filter);
4475
+ };
4476
+
4477
+ /**
4478
+ * ```js
4479
+ * import { onPostDeleted } from '@amityco/ts-sdk'
4480
+ * const dispose = onPostDeleted(post => {
4481
+ * // ...
4482
+ * })
4483
+ * ```
4484
+ *
4485
+ * Fired when an {@link Amity.Post} has been deleted
4486
+ *
4487
+ * @param callback The function to call when the event was fired
4488
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
4489
+ *
4490
+ * @category Post Events
4491
+ */
4492
+ const onPostDeleted = (callback) => {
4493
+ const client = getActiveClient();
4494
+ const filter = (payload) => {
4495
+ decoratePayload(payload);
4496
+ ingestInCache(payload);
4497
+ callback(payload.posts[0]);
4498
+ };
4499
+ return createEventSubscriber(client, 'message/onPostDeleted', 'v3.post.didDelete', filter);
4500
+ };
4501
+
4502
+ /**
4503
+ * ```js
4504
+ * import { observePosts } from '@amityco/ts-sdk'
4505
+ *
4506
+ * let posts = []
4507
+ * const unsub = observePosts({
4508
+ * targetType: Amity.PostTargetType,
4509
+ * targetId: Amity.Post['targetId'],
4510
+ * }, post => merge(posts, post))
4511
+ * ```
4512
+ *
4513
+ * Observe all mutations on a list of {@link Amity.Post} for a given target object
4514
+ *
4515
+ * @param targetType the type of the target
4516
+ * @param targetId the ID of the target
4517
+ * @param callback the function to call when new data are available
4518
+ * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the messages
4519
+ *
4520
+ * @category Post Observer
4521
+ */
4522
+ const observePosts = (params, callback) => {
4523
+ const { log } = getActiveClient();
4524
+ const timestamp = Date.now();
4525
+ log(`observePosts(tmpid: ${timestamp}) > listen`);
4526
+ const disposers = [];
4527
+ const router = (post, action) => {
4528
+ var _a, _b;
4529
+ if (params.targetId !== post.targetId
4530
+ || params.targetType !== post.targetType)
4531
+ return;
4532
+ if (callback instanceof Function)
4533
+ return callback(post);
4534
+ (_a = callback.onEvent) === null || _a === void 0 ? void 0 : _a.call(callback, action, post);
4535
+ (_b = callback[action]) === null || _b === void 0 ? void 0 : _b.call(callback, post);
4536
+ };
4537
+ disposers.push(onPostCreated(post => router(post, 'onCreate')), onPostUpdated(post => router(post, 'onUpdate')), onPostDeleted(post => router(post, 'onDelete')));
4538
+ return () => {
4539
+ log(`observePosts(tmpid: ${timestamp}) > dispose`);
4540
+ disposers.forEach(fn => fn());
4541
+ };
4542
+ };
4543
+
4544
+ /**
4545
+ * ```js
4546
+ * import { observePost } from '@amityco/ts-sdk'
4547
+ *
4548
+ * let post = {}
4549
+ * const dispose = observePost(postId, updated => post = updated)
4550
+ * ```
4551
+ *
4552
+ * Observe all mutation on a given {@link Amity.Post}
4553
+ *
4554
+ * @param postId the ID of the post to observe
4555
+ * @param callback the function to call when new data are available
4556
+ * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the post
4557
+ *
4558
+ * @category Post Observer
4559
+ */
4560
+ const observePost = (postId, callback, policy = 'cache_then_server') => {
4561
+ const { log } = getActiveClient();
4562
+ const timestamp = Date.now();
4563
+ log(`observePost(tmpid: ${timestamp}) > listen`);
4564
+ // wrapper function to make sure
4565
+ const router = (result, action) => {
4566
+ var _a, _b, _c;
4567
+ // filter function
4568
+ if (((_a = result.data) === null || _a === void 0 ? void 0 : _a.postId) !== postId)
4569
+ return;
4570
+ if (callback instanceof Function)
4571
+ return callback(result);
4572
+ if (action !== 'onFetch')
4573
+ (_b = callback.onEvent) === null || _b === void 0 ? void 0 : _b.call(callback, action, result);
4574
+ (_c = callback[action]) === null || _c === void 0 ? void 0 : _c.call(callback, result);
4575
+ };
4576
+ const disposers = [];
4577
+ disposers.push(onPostUpdated(data => router({ data }, 'onUpdate')), onPostDeleted(data => router({ data }, 'onDelete')));
4578
+ runQuery(createQuery(getPost, postId), (result) => result.data && router(result, 'onFetch'), queryOptions(policy));
4579
+ return () => {
4580
+ log(`observePosts(tmpid: ${timestamp}) > dispose`);
4581
+ disposers.forEach(fn => fn());
4582
+ };
4583
+ };
4584
+
4585
+ /**
4586
+ * ```js
4587
+ * import { onCommentCreated } from '@amityco/ts-sdk'
4588
+ * const dispose = onCommentCreated(comment => {
4589
+ * // ...
4590
+ * })
4591
+ * ```
4592
+ *
4593
+ * Fired when an {@link Amity.Comment} has been created
4594
+ *
4595
+ * @param callback The function to call when the event was fired
4596
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
4597
+ *
4598
+ * @category Comment Events
4599
+ */
4600
+ const onCommentCreated = (callback) => {
4601
+ const client = getActiveClient();
4602
+ const filter = (payload) => {
4603
+ decoratePayload(payload);
4604
+ ingestInCache(payload);
4605
+ callback(payload.comments[0]);
4606
+ };
4607
+ return createEventSubscriber(client, 'message/onCommentCreated', 'v3.comment.didCreate', filter);
4608
+ };
4609
+
4610
+ /**
4611
+ * ```js
4612
+ * import { onCommentUpdated } from '@amityco/ts-sdk'
4613
+ * const dispose = onCommentUpdated(comment => {
4614
+ * // ...
4615
+ * })
4616
+ * ```
4617
+ *
4618
+ * Fired when an {@link Amity.Comment} has been updated
4619
+ *
4620
+ * @param callback The function to call when the event was fired
4621
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
4622
+ *
4623
+ * @category Comment Events
4624
+ */
4625
+ const onCommentUpdated = (callback) => {
4626
+ const client = getActiveClient();
4627
+ const filter = (payload) => {
4628
+ decoratePayload(payload);
4629
+ ingestInCache(payload);
4630
+ callback(payload.comments[0]);
4631
+ };
4632
+ return createEventSubscriber(client, 'message/onCommentUpdated', 'v3.comment.didUpdate', filter);
4633
+ };
4634
+
4635
+ /**
4636
+ * ```js
4637
+ * import { onCommentDeleted } from '@amityco/ts-sdk'
4638
+ * const dispose = onCommentDeleted(comment => {
4639
+ * // ...
4640
+ * })
4641
+ * ```
4642
+ *
4643
+ * Fired when an {@link Amity.Comment} has been deleted
4644
+ *
4645
+ * @param callback The function to call when the event was fired
4646
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
4647
+ *
4648
+ * @category Comment Events
4649
+ */
4650
+ const onCommentDeleted = (callback) => {
4651
+ const client = getActiveClient();
4652
+ const filter = (payload) => {
4653
+ decoratePayload(payload);
4654
+ ingestInCache(payload);
4655
+ callback(payload.comments[0]);
4656
+ };
4657
+ return createEventSubscriber(client, 'message/onCommentDeleted', 'v3.comment.didDelete', filter);
4658
+ };
4659
+
4660
+ /**
4661
+ * ```js
4662
+ * import { observeComments } from '@amityco/ts-sdk'
4663
+ *
4664
+ * let comments = []
4665
+ * const unsub = observeComments(postId, comment => merge(comments, comment))
4666
+ * ```
4667
+ *
4668
+ * Observe all mutations on a list of {@link Amity.Comment} for a given {@link Amity.Post} object
4669
+ *
4670
+ * @param postId the ID of the post where to observe the comments
4671
+ * @param callback the function to call when new data are available
4672
+ * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the comments
4673
+ *
4674
+ * @category Comment Observer
4675
+ */
4676
+ const observeComments = (postId, callback) => {
4677
+ const { log } = getActiveClient();
4678
+ const timestamp = Date.now();
4679
+ log(`observeComments(tmpid: ${timestamp}) > listen`);
4680
+ const disposers = [];
4681
+ const router = (comment, action) => {
4682
+ var _a, _b;
4683
+ if (comment.referenceId !== postId)
4684
+ return;
4685
+ if (callback instanceof Function)
4686
+ return callback(comment);
4687
+ (_a = callback.onEvent) === null || _a === void 0 ? void 0 : _a.call(callback, action, comment);
4688
+ (_b = callback[action]) === null || _b === void 0 ? void 0 : _b.call(callback, comment);
4689
+ };
4690
+ disposers.push(onCommentCreated(comment => router(comment, 'onCreate')), onCommentUpdated(comment => router(comment, 'onUpdate')), onCommentDeleted(comment => router(comment, 'onDelete')));
4691
+ return () => {
4692
+ log(`observeComments(tmpid: ${timestamp}) > dispose`);
4693
+ disposers.forEach(fn => fn());
4694
+ };
4695
+ };
4696
+
4697
+ /**
4698
+ * ```js
4699
+ * import { observeComment } from '@amityco/ts-sdk'
4700
+ *
4701
+ * let comment = {}
4702
+ * const dispose = observeComment(commentId, ({ data }) => comment = data)
4703
+ * ```
4704
+ *
4705
+ * Observe all mutation on a given {@link Amity.Comment}
4706
+ *
4707
+ * @param commentId the ID of the comment to observe
4708
+ * @param callback the function to call when new data are available
4709
+ * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the comment
4710
+ *
4711
+ * @category Comment Observer
4712
+ */
4713
+ const observeComment = (commentId, callback, policy = 'cache_then_server') => {
4714
+ const { log } = getActiveClient();
4715
+ const timestamp = Date.now();
4716
+ log(`observeComment(tmpid: ${timestamp}) > listen`);
4717
+ // wrapper function to make sure
4718
+ const router = (result, action) => {
4719
+ var _a, _b, _c;
4720
+ // filter function
4721
+ if (((_a = result.data) === null || _a === void 0 ? void 0 : _a.commentId) !== commentId)
4722
+ return;
4723
+ if (callback instanceof Function)
4724
+ return callback(result);
4725
+ if (action !== 'onFetch')
4726
+ (_b = callback.onEvent) === null || _b === void 0 ? void 0 : _b.call(callback, action, result);
4727
+ (_c = callback[action]) === null || _c === void 0 ? void 0 : _c.call(callback, result);
4728
+ };
4729
+ const disposers = [];
4730
+ disposers.push(onCommentUpdated(data => router({ data }, 'onUpdate')), onCommentDeleted(data => router({ data }, 'onDelete')));
4731
+ runQuery(createQuery(getComment, commentId), result => result.data && router(result, 'onFetch'), queryOptions(policy));
4732
+ return () => {
4733
+ log(`observeComment(tmpid: ${timestamp}) > dispose`);
4734
+ disposers.forEach(fn => fn());
4735
+ };
4736
+ };
4737
+
4738
+ exports.addChannelMembers = addChannelMembers;
4739
+ exports.addChannelMembersRole = addChannelMembersRole;
4740
+ exports.addCommunityMembers = addCommunityMembers;
4741
+ exports.addCommunityMembersRole = addCommunityMembersRole;
4742
+ exports.addReaction = addReaction;
4743
+ exports.clearCache = clearCache;
4744
+ exports.connectClient = connectClient;
4745
+ exports.createCache = createCache;
4746
+ exports.createChannel = createChannel;
4747
+ exports.createClient = createClient;
4748
+ exports.createComment = createComment;
4749
+ exports.createCommunity = createCommunity;
4750
+ exports.createFile = createFile;
4751
+ exports.createMessage = createMessage;
4752
+ exports.createPost = createPost;
4753
+ exports.createQuery = createQuery;
4754
+ exports.createReport = createReport;
4755
+ exports.decorateModel = decorateModel;
4756
+ exports.decorateModels = decorateModels;
4757
+ exports.decoratePayload = decoratePayload;
4758
+ exports.deleteChannel = deleteChannel;
4759
+ exports.deleteComment = deleteComment;
4760
+ exports.deleteCommunity = deleteCommunity;
4761
+ exports.deleteFile = deleteFile;
4762
+ exports.deleteMessage = deleteMessage;
4763
+ exports.deletePost = deletePost;
4764
+ exports.deleteReport = deleteReport;
4765
+ exports.disconnectClient = disconnectClient;
4766
+ exports.dropFromCache = dropFromCache;
4767
+ exports.enableCache = enableCache;
4768
+ exports.fileUrlWithSize = fileUrlWithSize;
4769
+ exports.filterByPropEquality = filterByPropEquality;
4770
+ exports.getActiveClient = getActiveClient;
4771
+ exports.getChannel = getChannel;
4772
+ exports.getChannels = getChannels;
4773
+ exports.getComment = getComment;
4774
+ exports.getComments = getComments;
4775
+ exports.getCommunities = getCommunities;
4776
+ exports.getCommunity = getCommunity;
4777
+ exports.getFile = getFile;
4778
+ exports.getMessage = getMessage;
4779
+ exports.getMessages = getMessages;
4780
+ exports.getPost = getPost;
4781
+ exports.getPosts = getPosts;
4782
+ exports.getRole = getRole;
4783
+ exports.getUser = getUser;
4784
+ exports.getUsers = getUsers;
4785
+ exports.ingestInCache = ingestInCache;
4786
+ exports.isAfterBefore = isAfterBefore;
4787
+ exports.isConnected = isConnected;
4788
+ exports.isFetcher = isFetcher;
4789
+ exports.isFresh = isFresh;
4790
+ exports.isLocal = isLocal;
4791
+ exports.isMutator = isMutator;
4792
+ exports.isOffline = isOffline;
4793
+ exports.isPaged = isPaged;
4794
+ exports.isReportedByMe = isReportedByMe;
4795
+ exports.isSkipLimit = isSkipLimit;
4796
+ exports.isSyncable = isSyncable;
4797
+ exports.isSynced = isSynced;
4798
+ exports.joinChannel = joinChannel;
4799
+ exports.joinCommunity = joinCommunity;
4800
+ exports.leaveChannel = leaveChannel;
4801
+ exports.leaveCommunity = leaveCommunity;
4802
+ exports.memoryStore = memoryStore;
4803
+ exports.memoryStores = memoryStores;
4804
+ exports.mergeInCache = mergeInCache;
4805
+ exports.mutateCache = mutateCache;
4806
+ exports.observeChannel = observeChannel;
4807
+ exports.observeComment = observeComment;
4808
+ exports.observeComments = observeComments;
4809
+ exports.observeCommunity = observeCommunity;
4810
+ exports.observeFile = observeFile;
4811
+ exports.observeMessage = observeMessage;
4812
+ exports.observeMessages = observeMessages;
4813
+ exports.observePost = observePost;
4814
+ exports.observePosts = observePosts;
4815
+ exports.observeUser = observeUser;
4816
+ exports.onChannelDeleted = onChannelDeleted;
4817
+ exports.onChannelJoined = onChannelJoined;
4818
+ exports.onChannelLeft = onChannelLeft;
4819
+ exports.onChannelUpdated = onChannelUpdated;
4820
+ exports.onClientDisconnected = onClientDisconnected;
4821
+ exports.onCommentCreated = onCommentCreated;
4822
+ exports.onCommentDeleted = onCommentDeleted;
4823
+ exports.onCommentUpdated = onCommentUpdated;
4824
+ exports.onCommunityCreated = onCommunityCreated;
4825
+ exports.onCommunityDeleted = onCommunityDeleted;
4826
+ exports.onCommunityJoined = onCommunityJoined;
4827
+ exports.onCommunityLeft = onCommunityLeft;
4828
+ exports.onCommunityUpdated = onCommunityUpdated;
4829
+ exports.onMemberAdded = onMemberAdded;
4830
+ exports.onMemberRemoved = onMemberRemoved;
4831
+ exports.onMessageCreated = onMessageCreated;
4832
+ exports.onMessageDeleted = onMessageDeleted;
4833
+ exports.onMessageUpdated = onMessageUpdated;
4834
+ exports.onPostCreated = onPostCreated;
4835
+ exports.onPostDeleted = onPostDeleted;
4836
+ exports.onPostUpdated = onPostUpdated;
4837
+ exports.onReactionRemoved = onReactionRemoved;
4838
+ exports.onUserUpdated = onUserUpdated;
4839
+ exports.persistentStore = persistentStore;
4840
+ exports.pullFromCache = pullFromCache;
4841
+ exports.pushToCache = pushToCache;
4842
+ exports.queryChannelMembers = queryChannelMembers;
4843
+ exports.queryChannels = queryChannels;
4844
+ exports.queryComments = queryComments;
4845
+ exports.queryCommunities = queryCommunities;
4846
+ exports.queryCommunityMembers = queryCommunityMembers;
4847
+ exports.queryGlobalFeed = queryGlobalFeed;
4848
+ exports.queryMessages = queryMessages;
4849
+ exports.queryOptions = queryOptions;
4850
+ exports.queryPosts = queryPosts;
4851
+ exports.queryRoles = queryRoles;
4852
+ exports.queryUsers = queryUsers;
4853
+ exports.removeChannelMembers = removeChannelMembers;
4854
+ exports.removeChannelMembersRole = removeChannelMembersRole;
4855
+ exports.removeCommunityMembers = removeCommunityMembers;
4856
+ exports.removeCommunityMembersRole = removeCommunityMembersRole;
4857
+ exports.removeReaction = removeReaction;
4858
+ exports.runQuery = runQuery;
4859
+ exports.sliceByPaging = sliceByPaging;
4860
+ exports.sortByChannelSegment = sortByChannelSegment;
4861
+ exports.sortByDisplayName = sortByDisplayName;
4862
+ exports.sortByFirstCreated = sortByFirstCreated;
4863
+ exports.sortByLastActivity = sortByLastActivity;
4864
+ exports.sortByLastCreated = sortByLastCreated;
4865
+ exports.sortBySegmentNumber = sortBySegmentNumber;
4866
+ exports.syncInCache = syncInCache;
4867
+ exports.toPage = toPage;
4868
+ exports.toToken = toToken;
4869
+ exports.updateChannel = updateChannel;
4870
+ exports.updateComment = updateComment;
4871
+ exports.updateCommunity = updateCommunity;
4872
+ exports.updateMessage = updateMessage;
4873
+ exports.updatePost = updatePost;
4874
+ exports.updateUser = updateUser;
4875
+
4876
+ Object.defineProperty(exports, '__esModule', { value: true });
4877
+
4878
+ return exports;
4879
+
4880
+ }({}, jsBase64, nativeIdGenerator, debug, axios, HttpAgent, io, mitt, AsyncStorage));