stream-chat 9.54.0 → 9.54.2

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.
@@ -1048,7 +1048,11 @@ var messagePaginationLinear = ({
1048
1048
  newPagination.hasNext = hasNext;
1049
1049
  return newPagination;
1050
1050
  };
1051
+ var hasMessagePaginationCursor = (options) => !!(options?.id_lt || options?.id_lte || options?.id_gt || options?.id_gte || options?.id_around || options?.created_at_before || options?.created_at_before_or_equal || options?.created_at_after || options?.created_at_after_or_equal || options?.created_at_around || options?.offset);
1051
1052
  var messageSetPagination = (params) => {
1053
+ if (params.requestedPageSize === 0 && params.parentSet.messages.length > 0) {
1054
+ return params.parentSet.pagination;
1055
+ }
1052
1056
  if (params.parentSet.messages.length + (params.returnedPage.length - params.filteredReturnedPage.length) < params.returnedPage.length) {
1053
1057
  params.logger?.(
1054
1058
  "error",
@@ -1224,6 +1228,7 @@ var aOverlapsB = (a, b) => {
1224
1228
  return oldestMessageA < oldestMessageB && oldestMessageB < newestMessageA && newestMessageA < newestMessageB;
1225
1229
  };
1226
1230
  var messageSetsOverlapByTimestamp = (a, b) => aContainsOrEqualsB(a, b) || aContainsOrEqualsB(b, a) || aOverlapsB(a, b) || aOverlapsB(b, a);
1231
+ var isLocalOnlyMessage = (message) => message.status === "sending" || message.status === "failed" || message.type === "error" || message.type === "ephemeral";
1227
1232
  var ChannelState = class {
1228
1233
  constructor(channel) {
1229
1234
  /**
@@ -1883,6 +1888,22 @@ var ChannelState = class {
1883
1888
  currentMessages.isCurrent = false;
1884
1889
  this.messageSets[index].isCurrent = true;
1885
1890
  }
1891
+ /**
1892
+ * Empties the latest message set if the newest page is newer than it and shares no messages
1893
+ * with it. Merging them would hide the messages in between from pagination.
1894
+ * Skipped while the set holds local-only messages, so they are not lost.
1895
+ */
1896
+ _dropLatestMessagesDisjointFrom(newestPage) {
1897
+ const latestSet = this.messageSets.find((s) => s.isLatest);
1898
+ const newestLoaded = latestSet?.messages.slice(-1)[0];
1899
+ const oldestReturned = newestPage.find((m) => !m.parent_id || m.show_in_channel);
1900
+ if (!latestSet || !newestLoaded || !oldestReturned?.created_at) return;
1901
+ if (new Date(oldestReturned.created_at).getTime() <= newestLoaded.created_at.getTime() || this.areMessageSetsOverlap(latestSet.messages, newestPage) || latestSet.messages.some(isLocalOnlyMessage)) {
1902
+ return;
1903
+ }
1904
+ latestSet.messages = [];
1905
+ latestSet.pagination = { ...DEFAULT_MESSAGE_SET_PAGINATION };
1906
+ }
1886
1907
  areMessageSetsOverlap(messages1, messages2) {
1887
1908
  return messages1.some((m1) => messages2.find((m2) => m1.id === m2.id));
1888
1909
  }
@@ -3865,13 +3886,14 @@ var localAttachmentToAttachment = (localAttachment) => {
3865
3886
  const { localMetadata, ...attachment } = localAttachment;
3866
3887
  return attachment;
3867
3888
  };
3889
+ var isSendable = (attachment) => isFinishedUpload(attachment) || !isLocalUploadAttachment(attachment);
3868
3890
  var composeWithPendingUploads = ({
3869
3891
  composer,
3870
3892
  state
3871
3893
  }) => {
3872
3894
  const composerIsKeptAsDraft = !!composer.pollId;
3873
3895
  const relevantAttachments = composer.attachmentManager.attachments.filter(
3874
- (attachment) => isFinishedUpload(attachment) || !composerIsKeptAsDraft && isPendingUpload(attachment)
3896
+ (attachment) => isSendable(attachment) || !composerIsKeptAsDraft && isPendingUpload(attachment)
3875
3897
  );
3876
3898
  const localAttachments = (state.localMessage.attachments ?? []).concat(
3877
3899
  relevantAttachments.map(
@@ -3879,7 +3901,7 @@ var composeWithPendingUploads = ({
3879
3901
  )
3880
3902
  );
3881
3903
  const messageAttachments = (state.message.attachments ?? []).concat(
3882
- relevantAttachments.filter(isFinishedUpload).map(localAttachmentToAttachment)
3904
+ relevantAttachments.filter(isSendable).map(localAttachmentToAttachment)
3883
3905
  );
3884
3906
  if (!localAttachments.length && !messageAttachments.length) return state;
3885
3907
  return {
@@ -3934,7 +3956,7 @@ var createAttachmentsCompositionMiddleware = (composer) => ({
3934
3956
  return discard();
3935
3957
  }
3936
3958
  const attachments = (state.message.attachments ?? []).concat(
3937
- attachmentManager.successfulUploads.map(localAttachmentToAttachment)
3959
+ attachmentManager.attachments.filter(isSendable).map(localAttachmentToAttachment)
3938
3960
  );
3939
3961
  if (!attachments.length) return forward();
3940
3962
  return next({
@@ -3961,9 +3983,9 @@ var createDraftAttachmentsCompositionMiddleware = (composer) => ({
3961
3983
  }) => {
3962
3984
  const { attachmentManager } = composer;
3963
3985
  if (!attachmentManager) return forward();
3964
- const successfulUploads = attachmentManager.successfulUploads;
3965
- const attachments = successfulUploads.length ? (state.draft.attachments ?? []).concat(
3966
- successfulUploads.map(localAttachmentToAttachment)
3986
+ const sendableAttachments = attachmentManager.attachments.filter(isSendable);
3987
+ const attachments = sendableAttachments.length ? (state.draft.attachments ?? []).concat(
3988
+ sendableAttachments.map(localAttachmentToAttachment)
3967
3989
  ) : void 0;
3968
3990
  return next({
3969
3991
  ...state,
@@ -8088,10 +8110,13 @@ var Thread = class extends WithSubscriptions {
8088
8110
  }));
8089
8111
  }
8090
8112
  };
8091
- const channel = client.channel(threadData.channel.type, threadData.channel.id, {
8092
- // @ts-expect-error name is a "custom" property
8093
- name: threadData.channel.name
8094
- });
8113
+ const channelResponse = threadData.channel;
8114
+ const channelData = { name: channelResponse.name };
8115
+ const channel = client.channel(
8116
+ threadData.channel.type,
8117
+ threadData.channel.id,
8118
+ channelData
8119
+ );
8095
8120
  channel._hydrateMembers({
8096
8121
  members: threadData.channel.members ?? [],
8097
8122
  overrideCurrentState: false
@@ -10598,7 +10623,8 @@ var Channel = class {
10598
10623
  }
10599
10624
  const { messageSet, filteredMessageIds } = this._initializeState(
10600
10625
  state,
10601
- messageSetToAddToIfDoesNotExist
10626
+ messageSetToAddToIfDoesNotExist,
10627
+ !hasMessagePaginationCursor(options?.messages)
10602
10628
  );
10603
10629
  messageSet.pagination = {
10604
10630
  ...messageSet.pagination,
@@ -11216,7 +11242,7 @@ var Channel = class {
11216
11242
  );
11217
11243
  }
11218
11244
  }
11219
- _initializeState(state, messageSetToAddToIfDoesNotExist = "latest") {
11245
+ _initializeState(state, messageSetToAddToIfDoesNotExist = "latest", isNewestPage = true) {
11220
11246
  const { state: clientState, user, userID } = this.getClient();
11221
11247
  if (state.members) {
11222
11248
  this._hydrateMembers({ members: state.members });
@@ -11231,6 +11257,9 @@ var Channel = class {
11231
11257
  if (!this.state.messages) {
11232
11258
  this.state.initMessages();
11233
11259
  }
11260
+ if (messageSetToAddToIfDoesNotExist === "latest" && isNewestPage) {
11261
+ this.state._dropLatestMessagesDisjointFrom(messages);
11262
+ }
11234
11263
  const { messageSet, filteredMessageIds } = this.state.addMessagesSorted(
11235
11264
  messages,
11236
11265
  false,
@@ -11491,6 +11520,10 @@ var StableWSConnection = class {
11491
11520
  if (data.type === "health.check") {
11492
11521
  this.scheduleNextPing();
11493
11522
  }
11523
+ if (data?.type === "connection.error" && data?.error?.code === chatCodes.TOKEN_EXPIRED) {
11524
+ this._log("onmessage() - server reported that the token expired", { wsID });
11525
+ this.tokenExpiredByServer = true;
11526
+ }
11494
11527
  this.client.dispatchEvent(data);
11495
11528
  this.scheduleConnectionCheck();
11496
11529
  };
@@ -11514,7 +11547,7 @@ var StableWSConnection = class {
11514
11547
  this.isConnecting = false;
11515
11548
  this.rejectPromise?.(this._errorFromWSEvent(event));
11516
11549
  this._log(`onclose() - WS connection closed. Calling reconnect ...`, { event });
11517
- this._reconnect();
11550
+ this._reconnectAfterFailure();
11518
11551
  }
11519
11552
  };
11520
11553
  this.onerror = (wsID, event) => {
@@ -11525,7 +11558,7 @@ var StableWSConnection = class {
11525
11558
  this.isConnecting = false;
11526
11559
  this.rejectPromise?.(this._errorFromWSEvent(event));
11527
11560
  this._log(`onerror() - WS connection resulted into error`, { event });
11528
- this._reconnect();
11561
+ this._reconnectAfterFailure();
11529
11562
  };
11530
11563
  /**
11531
11564
  * _setHealth - Sets the connection to healthy or unhealthy.
@@ -11578,6 +11611,7 @@ var StableWSConnection = class {
11578
11611
  */
11579
11612
  this._setupConnectionPromise = () => {
11580
11613
  this.isResolved = false;
11614
+ this.tokenExpiredByServer = false;
11581
11615
  this.connectionOpen = new Promise((resolve, reject) => {
11582
11616
  this.resolvePromise = resolve;
11583
11617
  this.rejectPromise = reject;
@@ -11625,6 +11659,7 @@ var StableWSConnection = class {
11625
11659
  this.isHealthy = false;
11626
11660
  this.wsID = 1;
11627
11661
  this.lastEvent = null;
11662
+ this.tokenExpiredByServer = false;
11628
11663
  this.pingInterval = 25 * 1e3;
11629
11664
  this.connectionCheckTimeout = this.pingInterval + 10 * 1e3;
11630
11665
  addConnectionEventListeners(this.onlineStatusChanged);
@@ -11723,6 +11758,7 @@ var StableWSConnection = class {
11723
11758
  this.wsID += 1;
11724
11759
  this.isConnecting = false;
11725
11760
  this.isDisconnected = true;
11761
+ this.tokenExpiredByServer = false;
11726
11762
  if (this.healthCheckTimeoutRef) {
11727
11763
  clearInterval(this.healthCheckTimeoutRef);
11728
11764
  }
@@ -11855,6 +11891,10 @@ var StableWSConnection = class {
11855
11891
  this._destroyCurrentWSConnection();
11856
11892
  if (options.refreshToken) {
11857
11893
  await this.client.tokenManager.loadToken();
11894
+ if (this.isConnecting || this.isHealthy) {
11895
+ this._log("_reconnect() - Abort (4) since already connecting or healthy");
11896
+ return;
11897
+ }
11858
11898
  }
11859
11899
  try {
11860
11900
  await this._connect();
@@ -11878,6 +11918,21 @@ var StableWSConnection = class {
11878
11918
  }
11879
11919
  this._log("_reconnect() - == END ==");
11880
11920
  }
11921
+ /**
11922
+ * _reconnectAfterFailure - Reconnects after the socket closed or failed. If the server
11923
+ * reported that the token expired, the token is refreshed before reconnecting.
11924
+ * Static tokens cannot be refreshed and reconnect as before.
11925
+ */
11926
+ _reconnectAfterFailure() {
11927
+ if (this.tokenExpiredByServer && !this.client.tokenManager.isStatic()) {
11928
+ this._log(
11929
+ "_reconnectAfterFailure() - token expired, so going to reload token and reconnect"
11930
+ );
11931
+ this._reconnect({ refreshToken: true });
11932
+ return;
11933
+ }
11934
+ this._reconnect();
11935
+ }
11881
11936
  /**
11882
11937
  * _destroyCurrentWSConnection - Removes the current WS connection
11883
11938
  *
@@ -13134,9 +13189,14 @@ function applyOwnVoteDelta(state, { add = [], remove = [] }) {
13134
13189
  }
13135
13190
  voteCount = Math.max(voteCount - 1, 0);
13136
13191
  if (latestVotesByOption?.[optionId]) {
13137
- latestVotesByOption[optionId] = latestVotesByOption[optionId].filter(
13192
+ const latestVotes = latestVotesByOption[optionId].filter(
13138
13193
  (latestVote) => latestVote.id !== vote.id
13139
13194
  );
13195
+ if (latestVotes.length) {
13196
+ latestVotesByOption[optionId] = latestVotes;
13197
+ } else {
13198
+ delete latestVotesByOption[optionId];
13199
+ }
13140
13200
  }
13141
13201
  }
13142
13202
  for (const vote of add) {
@@ -13240,7 +13300,15 @@ var Poll = class {
13240
13300
  if (!isPollUpdatedEvent(event)) return;
13241
13301
  const { id, ...pollData } = extractPollData(event.poll);
13242
13302
  if (pollData.is_closed) this.closeConfirmed = true;
13243
- this.state.partialNext({ ...pollData, lastActivityAt: new Date(event.created_at) });
13303
+ this.state.partialNext({
13304
+ ...pollData,
13305
+ // Server-owned translations, which `extractPollData` (an update request) leaves out. Copied
13306
+ // even when absent: the event carries the whole poll, and a change made under channel-only
13307
+ // translation drops the stale ones.
13308
+ description_i18n: event.poll.description_i18n,
13309
+ lastActivityAt: new Date(event.created_at),
13310
+ name_i18n: event.poll.name_i18n
13311
+ });
13244
13312
  this.upsertOfflineDb();
13245
13313
  };
13246
13314
  this.handlePollClosed = (event) => {
@@ -15233,7 +15301,7 @@ var StreamChat = class _StreamChat {
15233
15301
  return this.userAgent;
15234
15302
  }
15235
15303
  if (!this.cachedUserAgent) {
15236
- const version = "9.54.0";
15304
+ const version = "9.54.2";
15237
15305
  const { name: sdkName, version: sdkVersion } = this.sdkIdentifier ?? {};
15238
15306
  const { name: appName, version: appVersion } = this.appIdentifier ?? {};
15239
15307
  const { os, model: deviceModel } = this.deviceIdentifier ?? {};
@@ -16163,7 +16231,7 @@ var StreamChat = class _StreamChat {
16163
16231
  ...updatedMessagesSet.pagination,
16164
16232
  ...messageSetPagination({
16165
16233
  parentSet: updatedMessagesSet,
16166
- requestedPageSize: queryChannelsOptions?.message_limit || DEFAULT_QUERY_CHANNELS_MESSAGE_LIST_PAGE_SIZE,
16234
+ requestedPageSize: queryChannelsOptions?.message_limit ?? DEFAULT_QUERY_CHANNELS_MESSAGE_LIST_PAGE_SIZE,
16167
16235
  returnedPage: channelState.messages,
16168
16236
  filteredReturnedPage: channelState.messages.filter(
16169
16237
  (m) => !filteredMessageIds.includes(m.id)
@@ -16822,7 +16890,7 @@ var StreamChat = class _StreamChat {
16822
16890
  * @param {string} messageId
16823
16891
  * @param {string} language
16824
16892
  *
16825
- * @return {MessageResponse} Response that includes the message
16893
+ * @return {APIResponse & { message: MessageResponse }} Response that includes the translated message
16826
16894
  */
16827
16895
  async translateMessage(messageId, language) {
16828
16896
  return await this.post(