@amityco/ts-sdk 7.1.1-207e990f.0 → 7.1.1-295c780.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 (40) hide show
  1. package/dist/@types/domains/channel.d.ts +2 -2
  2. package/dist/@types/domains/channel.d.ts.map +1 -1
  3. package/dist/@types/domains/client.d.ts +1 -0
  4. package/dist/@types/domains/client.d.ts.map +1 -1
  5. package/dist/channelRepository/internalApi/getTotalChannelsUnread.d.ts +11 -0
  6. package/dist/channelRepository/internalApi/getTotalChannelsUnread.d.ts.map +1 -0
  7. package/dist/channelRepository/observers/getTotalChannelsUnread.d.ts +20 -0
  8. package/dist/channelRepository/observers/getTotalChannelsUnread.d.ts.map +1 -0
  9. package/dist/channelRepository/observers/index.d.ts +1 -0
  10. package/dist/channelRepository/observers/index.d.ts.map +1 -1
  11. package/dist/channelRepository/utils/prepareChannelPayload.d.ts.map +1 -1
  12. package/dist/client/api/createClient.d.ts +1 -0
  13. package/dist/client/api/createClient.d.ts.map +1 -1
  14. package/dist/client/utils/ReadReceiptSync/readReceiptSyncEngine.d.ts.map +1 -1
  15. package/dist/client/utils/endpoints.d.ts +1 -0
  16. package/dist/client/utils/endpoints.d.ts.map +1 -1
  17. package/dist/client/utils/setClientToken.d.ts.map +1 -1
  18. package/dist/commentRepository/events/utils.d.ts.map +1 -1
  19. package/dist/index.cjs.js +216 -21
  20. package/dist/index.esm.js +216 -21
  21. package/dist/index.umd.js +4 -4
  22. package/dist/messageRepository/events/onMessageCreated.d.ts.map +1 -1
  23. package/dist/messageRepository/observers/getMessage.d.ts.map +1 -1
  24. package/package.json +1 -1
  25. package/src/@types/domains/channel.ts +2 -2
  26. package/src/@types/domains/client.ts +1 -0
  27. package/src/channelRepository/internalApi/getTotalChannelsUnread.ts +38 -0
  28. package/src/channelRepository/observers/getTotalChannelsUnread.ts +129 -0
  29. package/src/channelRepository/observers/index.ts +1 -0
  30. package/src/channelRepository/utils/prepareChannelPayload.ts +21 -10
  31. package/src/client/api/createClient.ts +4 -1
  32. package/src/client/utils/ReadReceiptSync/readReceiptSyncEngine.ts +5 -1
  33. package/src/client/utils/endpoints.ts +1 -0
  34. package/src/client/utils/setClientToken.ts +8 -0
  35. package/src/commentRepository/events/utils.ts +73 -0
  36. package/src/fileRepository/api/uploadFile.ts +1 -1
  37. package/src/fileRepository/api/uploadImage.ts +1 -1
  38. package/src/fileRepository/api/uploadVideo.ts +1 -1
  39. package/src/messageRepository/events/onMessageCreated.ts +19 -9
  40. package/src/messageRepository/observers/getMessage.ts +0 -1
package/dist/index.esm.js CHANGED
@@ -1547,6 +1547,7 @@ const API_REGIONS = {
1547
1547
  };
1548
1548
  const URLS = {
1549
1549
  http: 'https://apix.{region}.amity.co',
1550
+ upload: 'https://upload.{region}.amity.co',
1550
1551
  mqtt: 'wss://sse.{region}.amity.co:443/mqtt',
1551
1552
  };
1552
1553
  function computeUrl(type, region) {
@@ -21820,7 +21821,9 @@ class MessageReadReceiptSyncEngine {
21820
21821
  // Step 1: Optimistic update of channelUnread.readToSegment to message.segment and update unreadCount value
21821
21822
  const cacheKey = ['channelUnread', 'get', channelId];
21822
21823
  const channelUnread = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
21823
- if (channelUnread && segment > channelUnread.readToSegment) {
21824
+ if (typeof (channelUnread === null || channelUnread === void 0 ? void 0 : channelUnread.readToSegment) === 'number' &&
21825
+ channelUnread &&
21826
+ segment > channelUnread.readToSegment) {
21824
21827
  channelUnread.readToSegment = segment;
21825
21828
  channelUnread.unreadCount = Math.max(channelUnread.lastSegment - segment, 0);
21826
21829
  pushToCache(cacheKey, channelUnread);
@@ -23153,19 +23156,27 @@ const preUpdateChannelCache = (rawPayload, options = { isMessagePreviewUpdated:
23153
23156
  const updateChannelUnread = ({ currentUserId, channels, channelUsers, }) => {
23154
23157
  for (let i = 0; i < channels.length; i += 1) {
23155
23158
  const cacheKey = ['channelUnread', 'get', channels[i].channelId];
23156
- const { readToSegment, lastMentionedSegment } = channelUsers.find(channelUser => channelUser.channelId === channels[i].channelId && channelUser.userId === currentUserId) || {
23157
- readToSegment: 0,
23158
- lastMentionedSegment: 0,
23159
- };
23160
- pushToCache(cacheKey, {
23159
+ const channelUser = channelUsers.find(channelUser => channelUser.channelId === channels[i].channelId && channelUser.userId === currentUserId);
23160
+ let unreadCount = 0;
23161
+ let readToSegment = null;
23162
+ let lastMentionedSegment = null;
23163
+ let isMentioned = false;
23164
+ if (channelUser) {
23165
+ readToSegment = channelUser.readToSegment;
23166
+ lastMentionedSegment = channelUser.lastMentionedSegment;
23167
+ unreadCount = Math.max(channels[i].messageCount - readToSegment, 0);
23168
+ isMentioned = lastMentionedSegment > readToSegment;
23169
+ }
23170
+ const cacheChannelUnread = {
23161
23171
  channelId: channels[i].channelId,
23162
23172
  lastSegment: channels[i].messageCount,
23163
23173
  readToSegment,
23164
23174
  lastMentionedSegment,
23165
- unreadCount: channels[i].messageCount - readToSegment,
23166
- isMentioned: lastMentionedSegment > readToSegment,
23167
- isDeleted: channels[i].isDeleted,
23168
- });
23175
+ unreadCount,
23176
+ isMentioned,
23177
+ isDeleted: channels[i].isDeleted || false,
23178
+ };
23179
+ pushToCache(cacheKey, cacheChannelUnread);
23169
23180
  }
23170
23181
  };
23171
23182
  const prepareChannelPayload = async (rawPayload, options = { isMessagePreviewUpdated: true }) => {
@@ -23965,6 +23976,12 @@ const setClientToken = async (params) => {
23965
23976
  isGlobalBanned: false,
23966
23977
  isUserDeleted: false,
23967
23978
  };
23979
+ client.upload.defaults.headers.common.Authorization = `Bearer ${accessToken}`;
23980
+ client.upload.defaults.metadata = {
23981
+ tokenExpiry: expiresAt,
23982
+ isGlobalBanned: false,
23983
+ isUserDeleted: false,
23984
+ };
23968
23985
  // manually setup the token for ws transport
23969
23986
  if (client.ws)
23970
23987
  client.ws.io.opts.query = { token: accessToken };
@@ -25008,7 +25025,10 @@ const onMessageCreatedMqtt = (callback) => {
25008
25025
  'get',
25009
25026
  message.channelId,
25010
25027
  ])) === null || _a === void 0 ? void 0 : _a.data;
25011
- if (!channelUnread || channelUnread.lastSegment >= message.segment)
25028
+ if (!channelUnread ||
25029
+ channelUnread.lastSegment >= message.segment ||
25030
+ typeof channelUnread.readToSegment !== 'number' ||
25031
+ typeof channelUnread.lastMentionedSegment !== 'number')
25012
25032
  return;
25013
25033
  const lastSegment = message.segment;
25014
25034
  const isMentionedInMessage = (_b = message.mentionedUsers) === null || _b === void 0 ? void 0 : _b.some(mention => {
@@ -25017,10 +25037,12 @@ const onMessageCreatedMqtt = (callback) => {
25017
25037
  client.userId &&
25018
25038
  mention.userPublicIds.includes(client.userId)));
25019
25039
  });
25020
- const lastMentionSegment = isMentionedInMessage
25040
+ const lastMentionedSegment = isMentionedInMessage
25021
25041
  ? message.segment
25022
- : channelUnread.lastMentionSegment;
25023
- pushToCache(['channelUnread', 'get', message.channelId], Object.assign(Object.assign({}, channelUnread), { lastSegment, unreadCount: lastSegment - channelUnread.readToSegment, lastMentionSegment, isMentioned: !(channelUnread.readToSegment >= lastMentionSegment) }));
25042
+ : channelUnread.lastMentionedSegment;
25043
+ const updatedChannelUnread = Object.assign(Object.assign({}, channelUnread), { lastSegment, unreadCount: Math.max(lastSegment - channelUnread.readToSegment, 0), lastMentionedSegment, isMentioned: !(channelUnread.readToSegment >= lastMentionedSegment) });
25044
+ pushToCache(['channelUnread', 'get', message.channelId], updatedChannelUnread);
25045
+ fireEvent('local.channelUnread.updated', updatedChannelUnread);
25024
25046
  });
25025
25047
  }
25026
25048
  // Update in cache
@@ -25677,15 +25699,17 @@ const DEFAULT_DEBUG_SESSION = 'amity';
25677
25699
  * @category Client API
25678
25700
  * */
25679
25701
  const createClient = (apiKey, apiRegion = API_REGIONS.SG, { debugSession = DEFAULT_DEBUG_SESSION, apiEndpoint, prefixDeviceIdKey, rteEnabled = true, } = {}) => {
25680
- var _a, _b;
25702
+ var _a, _b, _c;
25681
25703
  const log = createLogger(debugSession);
25682
25704
  log('client/api/createClient', {
25683
25705
  apiKey: apiKey.replace(/.{5}$/g, 'xxxxx'),
25684
25706
  apiRegion,
25685
25707
  });
25686
25708
  const httpEndpoint = (_a = apiEndpoint === null || apiEndpoint === void 0 ? void 0 : apiEndpoint.http) !== null && _a !== void 0 ? _a : computeUrl('http', apiRegion);
25687
- const mqttEndpoint = (_b = apiEndpoint === null || apiEndpoint === void 0 ? void 0 : apiEndpoint.mqtt) !== null && _b !== void 0 ? _b : computeUrl('mqtt', apiRegion);
25709
+ const uploadEndpoint = (_b = apiEndpoint === null || apiEndpoint === void 0 ? void 0 : apiEndpoint.upload) !== null && _b !== void 0 ? _b : computeUrl('upload', apiRegion);
25710
+ const mqttEndpoint = (_c = apiEndpoint === null || apiEndpoint === void 0 ? void 0 : apiEndpoint.mqtt) !== null && _c !== void 0 ? _c : computeUrl('mqtt', apiRegion);
25688
25711
  const http = createHttpTransport(httpEndpoint);
25712
+ const upload = createHttpTransport(uploadEndpoint);
25689
25713
  let ws;
25690
25714
  let mqtt;
25691
25715
  if (rteEnabled) {
@@ -25716,6 +25740,7 @@ const createClient = (apiKey, apiRegion = API_REGIONS.SG, { debugSession = DEFAU
25716
25740
  http,
25717
25741
  ws,
25718
25742
  mqtt,
25743
+ upload,
25719
25744
  emitter,
25720
25745
  /*
25721
25746
  * Session Components
@@ -25745,7 +25770,7 @@ const createClient = (apiKey, apiRegion = API_REGIONS.SG, { debugSession = DEFAU
25745
25770
  return activeClient;
25746
25771
  setActiveClient(client);
25747
25772
  }
25748
- catch (_c) {
25773
+ catch (_d) {
25749
25774
  setActiveClient(client);
25750
25775
  }
25751
25776
  return client;
@@ -28534,7 +28559,7 @@ const uploadFile = async (formData, onProgress) => {
28534
28559
  const headers = 'getHeaders' in formData
28535
28560
  ? formData.getHeaders()
28536
28561
  : { 'content-type': 'multipart/form-data' };
28537
- const { data } = await client.http.post('/api/v4/files', formData, {
28562
+ const { data } = await client.upload.post('/api/v4/files', formData, {
28538
28563
  headers,
28539
28564
  onUploadProgress({ loaded, total = 100 }) {
28540
28565
  onProgress && onProgress(Math.round((loaded * 100) / total));
@@ -28624,7 +28649,7 @@ const uploadVideo = async (formData, feedType, onProgress) => {
28624
28649
  const headers = 'getHeaders' in formData
28625
28650
  ? formData.getHeaders()
28626
28651
  : { 'content-type': 'multipart/form-data' };
28627
- const { data } = await client.http.post('/api/v4/videos', formData, {
28652
+ const { data } = await client.upload.post('/api/v4/videos', formData, {
28628
28653
  headers,
28629
28654
  onUploadProgress({ loaded, total = 100 }) {
28630
28655
  onProgress && onProgress(Math.round((loaded * 100) / total));
@@ -28672,7 +28697,7 @@ const uploadImage = async (formData, onProgress) => {
28672
28697
  const headers = 'getHeaders' in formData
28673
28698
  ? formData.getHeaders()
28674
28699
  : { 'content-type': 'multipart/form-data' };
28675
- const { data } = await client.http.post('/api/v4/images', formData, {
28700
+ const { data } = await client.upload.post('/api/v4/images', formData, {
28676
28701
  headers,
28677
28702
  onUploadProgress({ loaded, total = 100 }) {
28678
28703
  onProgress && onProgress(Math.round((loaded * 100) / total));
@@ -29757,6 +29782,29 @@ const createCommentEventSubscriber = (event, callback) => {
29757
29782
  }
29758
29783
  }
29759
29784
  }
29785
+ }
29786
+ if (['comment.deleted'].includes(event)) {
29787
+ // NOTE: skip deleting comment to parent comment children if it's the same user since we use the local event to update instead.
29788
+ if (event === 'comment.deleted' && comment.data.userId === client.userId)
29789
+ return;
29790
+ if (comments[0].parentId) {
29791
+ const parentComment = pullFromCache([
29792
+ 'comment',
29793
+ 'get',
29794
+ comments[0].parentId,
29795
+ ]);
29796
+ if (parentComment === null || parentComment === void 0 ? void 0 : parentComment.data) {
29797
+ // Remove deleted comment in parent childComment if still exists
29798
+ if (parentComment.data.children.includes(comments[0].commentId)) {
29799
+ const newParentComment = Object.assign(Object.assign({}, parentComment.data), { childrenNumber: parentComment.data.childrenNumber - 1, children: [
29800
+ ...new Set([
29801
+ ...parentComment.data.children.filter(id => id !== comments[0].commentId),
29802
+ ]),
29803
+ ] });
29804
+ pushToCache(['comment', 'get', comments[0].parentId], newParentComment);
29805
+ }
29806
+ }
29807
+ }
29760
29808
  const queries = (_a = queryCache(['comment', 'query'])) === null || _a === void 0 ? void 0 : _a.filter(({ key }) => { var _a; return ((_a = key[2]) === null || _a === void 0 ? void 0 : _a.referenceId) === comment.data.referenceId; });
29761
29809
  queries === null || queries === void 0 ? void 0 : queries.map(({ key, data }) => upsertInCache(key, data, { cachedAt: -1 }));
29762
29810
  }
@@ -29769,7 +29817,7 @@ const createCommentEventSubscriber = (event, callback) => {
29769
29817
  const createLocalCommentEventSubscriber = (event, callback) => {
29770
29818
  const client = getActiveClient();
29771
29819
  const filter = (payload) => {
29772
- var _a;
29820
+ var _a, _b;
29773
29821
  if (!client.cache) {
29774
29822
  // TODO: here we are missing specific properties here!
29775
29823
  callback(LinkedObject.comment(payload.comments[0]));
@@ -29812,6 +29860,38 @@ const createLocalCommentEventSubscriber = (event, callback) => {
29812
29860
  const queries = (_a = queryCache(['comment', 'query'])) === null || _a === void 0 ? void 0 : _a.filter(({ key }) => { var _a; return ((_a = key[2]) === null || _a === void 0 ? void 0 : _a.referenceId) === comment.data.referenceId; });
29813
29861
  queries === null || queries === void 0 ? void 0 : queries.map(({ key, data }) => upsertInCache(key, data, { cachedAt: -1 }));
29814
29862
  }
29863
+ if (['local.comment.deleted'].includes(event)) {
29864
+ if (comments[0].parentId) {
29865
+ const parentComment = pullFromCache([
29866
+ 'comment',
29867
+ 'get',
29868
+ comments[0].parentId,
29869
+ ]);
29870
+ if (parentComment === null || parentComment === void 0 ? void 0 : parentComment.data) {
29871
+ // Remove deleted comment in parent childComment if still exists
29872
+ if (parentComment.data.children.includes(comments[0].commentId)) {
29873
+ const newParentComment = Object.assign(Object.assign({}, parentComment.data), { childrenNumber: parentComment.data.childrenNumber - 1, children: [
29874
+ ...new Set([
29875
+ ...parentComment.data.children.filter(id => id !== comments[0].commentId),
29876
+ ]),
29877
+ ] });
29878
+ pushToCache(['comment', 'get', comments[0].parentId], newParentComment);
29879
+ setTimeout(() => {
29880
+ // NOTE: This is workaround solution for emitting event not work properly.
29881
+ fireEvent('comment.updated', {
29882
+ comments: [newParentComment],
29883
+ commentChildren: [],
29884
+ files: [],
29885
+ users: [],
29886
+ communityUsers: [],
29887
+ });
29888
+ }, 200);
29889
+ }
29890
+ }
29891
+ }
29892
+ const queries = (_b = queryCache(['comment', 'query'])) === null || _b === void 0 ? void 0 : _b.filter(({ key }) => { var _a; return ((_a = key[2]) === null || _a === void 0 ? void 0 : _a.referenceId) === comment.data.referenceId; });
29893
+ queries === null || queries === void 0 ? void 0 : queries.map(({ key, data }) => upsertInCache(key, data, { cachedAt: -1 }));
29894
+ }
29815
29895
  callback(LinkedObject.comment(comment.data));
29816
29896
  }
29817
29897
  }
@@ -33680,6 +33760,120 @@ const getChannels = (params, callback, config) => {
33680
33760
  };
33681
33761
  /* end_public_function */
33682
33762
 
33763
+ /**
33764
+ *
33765
+ * Calculate user unread from {@link Amity.ChannelUnread} objects
33766
+ *
33767
+ * @returns the {@link Amity.UserUnread} objects
33768
+ *
33769
+ * @category Channel API
33770
+ * @async
33771
+ */
33772
+ const getTotalChannelsUnread$1 = () => {
33773
+ var _a;
33774
+ const client = getActiveClient();
33775
+ client.log('channel/getTotalChannelsUnread.locally');
33776
+ const cachedChannelsUnread = ((_a = queryCache(['channelUnread', 'get'])) === null || _a === void 0 ? void 0 : _a.filter(({ data }) => {
33777
+ return !data.isDeleted;
33778
+ })) || [];
33779
+ const totalChannelsUnread = (cachedChannelsUnread === null || cachedChannelsUnread === void 0 ? void 0 : cachedChannelsUnread.reduce((acc, { data }) => {
33780
+ acc.unreadCount += data.unreadCount;
33781
+ acc.isMentioned = acc.isMentioned || data.isMentioned;
33782
+ return acc;
33783
+ }, { unreadCount: 0, isMentioned: false })) || { unreadCount: 0, isMentioned: false };
33784
+ const cachedAt = client.cache && Date.now();
33785
+ return {
33786
+ data: totalChannelsUnread,
33787
+ cachedAt,
33788
+ };
33789
+ };
33790
+
33791
+ /* begin_public_function
33792
+ id: totalChannelsUnread.get
33793
+ */
33794
+ /**
33795
+ * ```js
33796
+ * import { ChannelRepository } from '@amityco/ts-sdk';
33797
+ *
33798
+ * let totalChannelsUnread;
33799
+ *
33800
+ * const unsubscribe = ChannelRepository.getTotalChannelsUnread(response => {
33801
+ * unread = response.data;
33802
+ * });
33803
+ * ```
33804
+ *
33805
+ * Observe all mutation on a given {@link Amity.UserUnread}
33806
+ *
33807
+ * @returns An {@link Amity.UserUnread} function to run when willing to stop observing the message
33808
+ *
33809
+ * @category User Unread Live Object
33810
+ *
33811
+ */
33812
+ const getTotalChannelsUnread = (callback) => {
33813
+ const { _id: userId } = getActiveUser();
33814
+ if (!userId)
33815
+ throw new ASCError('The _id has not been defined in ActiveUser', 800000 /* Amity.ClientError.UNKNOWN_ERROR */, "error" /* Amity.ErrorLevel.ERROR */);
33816
+ const { log, cache } = getActiveClient();
33817
+ if (!cache) {
33818
+ console.log('For using Live Object feature you need to enable Cache!');
33819
+ }
33820
+ const timestamp = Date.now();
33821
+ log(`liveTotalChannelsUnread(tmpid: ${timestamp}) > listen`);
33822
+ const disposers = [];
33823
+ let isUnsyncedModel = false; // for messages
33824
+ let model;
33825
+ const dispatcher = (data) => {
33826
+ const { data: userUnread } = data;
33827
+ const callbackModel = userUnread
33828
+ ? {
33829
+ unreadCount: userUnread.unreadCount,
33830
+ isMentioned: userUnread.isMentioned,
33831
+ }
33832
+ : undefined;
33833
+ model = callbackModel ? convertGetterPropsToStatic(callbackModel) : callbackModel;
33834
+ callback({
33835
+ data: callbackModel
33836
+ ? Object.assign(Object.assign({}, callbackModel), { isMentioned: callbackModel.isMentioned }) : callbackModel,
33837
+ loading: data.loading,
33838
+ error: data.error,
33839
+ });
33840
+ };
33841
+ const realtimeRouter = (userUnread) => {
33842
+ if (isEqual(model, userUnread))
33843
+ return;
33844
+ dispatcher({
33845
+ loading: false,
33846
+ data: userUnread,
33847
+ });
33848
+ };
33849
+ const onFetch = () => {
33850
+ const query = createQuery(async () => getTotalChannelsUnread$1());
33851
+ runQuery(query, ({ error, data, loading, origin, cachedAt }) => {
33852
+ if (cachedAt === UNSYNCED_OBJECT_CACHED_AT_VALUE) {
33853
+ dispatcher({
33854
+ data,
33855
+ origin,
33856
+ loading: false,
33857
+ error: new ASCApiError(UNSYNCED_OBJECT_CACHED_AT_MESSAGE, 800800 /* Amity.ClientError.DISALOOW_UNSYNCED_OBJECT */, "error" /* Amity.ErrorLevel.ERROR */),
33858
+ });
33859
+ isUnsyncedModel = true;
33860
+ disposers.forEach(fn => fn());
33861
+ }
33862
+ else if (!isUnsyncedModel) {
33863
+ dispatcher({ loading, data, origin, error });
33864
+ }
33865
+ if (error) {
33866
+ disposers.forEach(fn => fn());
33867
+ }
33868
+ });
33869
+ };
33870
+ disposers.push(onChannelUnreadUpdatedLocal(realtimeRouter));
33871
+ onFetch();
33872
+ return () => {
33873
+ disposers.forEach(fn => fn());
33874
+ };
33875
+ };
33876
+
33683
33877
  /* begin_public_function
33684
33878
  id: channel.member.add
33685
33879
  */
@@ -34283,6 +34477,7 @@ var index$c = /*#__PURE__*/Object.freeze({
34283
34477
  onChannelMemberRoleRemoved: onChannelMemberRoleRemoved,
34284
34478
  getChannel: getChannel,
34285
34479
  getChannels: getChannels,
34480
+ getTotalChannelsUnread: getTotalChannelsUnread,
34286
34481
  MARKER_INCLUDED_CHANNEL_TYPE: MARKER_INCLUDED_CHANNEL_TYPE,
34287
34482
  isUnreadCountSupport: isUnreadCountSupport,
34288
34483
  convertFromRaw: convertFromRaw,