stream-chat 9.53.0 → 9.54.1

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.
@@ -5879,10 +5879,11 @@ var createLinkPreviewsCompositionMiddleware = (composer) => ({
5879
5879
  const linkPreviews = linkPreviewsManager.loadingPreviews.length > 0 ? [] : linkPreviewsManager.loadedPreviews.map(
5880
5880
  (preview) => LinkPreviewsManager.getPreviewData(preview)
5881
5881
  );
5882
- const attachments = (state.message.attachments ?? []).concat(
5882
+ const messageAttachments = (state.message.attachments ?? []).concat(
5883
5883
  linkPreviews
5884
5884
  );
5885
- if (!attachments.length) return forward();
5885
+ const localAttachments = (state.localMessage.attachments ?? []).concat(linkPreviews);
5886
+ if (!messageAttachments.length && !localAttachments.length) return forward();
5886
5887
  const sendOptions = { ...state.sendOptions };
5887
5888
  const skip_enrich_url = !someLinkPreviewsLoading && linkPreviews.length > 0 || someLinkPreviewsDismissed;
5888
5889
  if (skip_enrich_url) {
@@ -5890,14 +5891,14 @@ var createLinkPreviewsCompositionMiddleware = (composer) => ({
5890
5891
  }
5891
5892
  return next({
5892
5893
  ...state,
5893
- message: {
5894
+ message: messageAttachments.length ? {
5894
5895
  ...state.message,
5895
- attachments
5896
- },
5897
- localMessage: {
5896
+ attachments: messageAttachments
5897
+ } : state.message,
5898
+ localMessage: localAttachments.length ? {
5898
5899
  ...state.localMessage,
5899
- attachments
5900
- },
5900
+ attachments: localAttachments
5901
+ } : state.localMessage,
5901
5902
  sendOptions
5902
5903
  });
5903
5904
  }
@@ -8279,10 +8280,13 @@ var Thread = class extends WithSubscriptions {
8279
8280
  }));
8280
8281
  }
8281
8282
  };
8282
- const channel = client.channel(threadData.channel.type, threadData.channel.id, {
8283
- // @ts-expect-error name is a "custom" property
8284
- name: threadData.channel.name
8285
- });
8283
+ const channelResponse = threadData.channel;
8284
+ const channelData = { name: channelResponse.name };
8285
+ const channel = client.channel(
8286
+ threadData.channel.type,
8287
+ threadData.channel.id,
8288
+ channelData
8289
+ );
8286
8290
  channel._hydrateMembers({
8287
8291
  members: threadData.channel.members ?? [],
8288
8292
  overrideCurrentState: false
@@ -11682,6 +11686,10 @@ var StableWSConnection = class {
11682
11686
  if (data.type === "health.check") {
11683
11687
  this.scheduleNextPing();
11684
11688
  }
11689
+ if (data?.type === "connection.error" && data?.error?.code === chatCodes.TOKEN_EXPIRED) {
11690
+ this._log("onmessage() - server reported that the token expired", { wsID });
11691
+ this.tokenExpiredByServer = true;
11692
+ }
11685
11693
  this.client.dispatchEvent(data);
11686
11694
  this.scheduleConnectionCheck();
11687
11695
  };
@@ -11705,7 +11713,7 @@ var StableWSConnection = class {
11705
11713
  this.isConnecting = false;
11706
11714
  this.rejectPromise?.(this._errorFromWSEvent(event));
11707
11715
  this._log(`onclose() - WS connection closed. Calling reconnect ...`, { event });
11708
- this._reconnect();
11716
+ this._reconnectAfterFailure();
11709
11717
  }
11710
11718
  };
11711
11719
  this.onerror = (wsID, event) => {
@@ -11716,7 +11724,7 @@ var StableWSConnection = class {
11716
11724
  this.isConnecting = false;
11717
11725
  this.rejectPromise?.(this._errorFromWSEvent(event));
11718
11726
  this._log(`onerror() - WS connection resulted into error`, { event });
11719
- this._reconnect();
11727
+ this._reconnectAfterFailure();
11720
11728
  };
11721
11729
  /**
11722
11730
  * _setHealth - Sets the connection to healthy or unhealthy.
@@ -11769,6 +11777,7 @@ var StableWSConnection = class {
11769
11777
  */
11770
11778
  this._setupConnectionPromise = () => {
11771
11779
  this.isResolved = false;
11780
+ this.tokenExpiredByServer = false;
11772
11781
  this.connectionOpen = new Promise((resolve, reject) => {
11773
11782
  this.resolvePromise = resolve;
11774
11783
  this.rejectPromise = reject;
@@ -11816,6 +11825,7 @@ var StableWSConnection = class {
11816
11825
  this.isHealthy = false;
11817
11826
  this.wsID = 1;
11818
11827
  this.lastEvent = null;
11828
+ this.tokenExpiredByServer = false;
11819
11829
  this.pingInterval = 25 * 1e3;
11820
11830
  this.connectionCheckTimeout = this.pingInterval + 10 * 1e3;
11821
11831
  addConnectionEventListeners(this.onlineStatusChanged);
@@ -11914,6 +11924,7 @@ var StableWSConnection = class {
11914
11924
  this.wsID += 1;
11915
11925
  this.isConnecting = false;
11916
11926
  this.isDisconnected = true;
11927
+ this.tokenExpiredByServer = false;
11917
11928
  if (this.healthCheckTimeoutRef) {
11918
11929
  clearInterval(this.healthCheckTimeoutRef);
11919
11930
  }
@@ -12046,6 +12057,10 @@ var StableWSConnection = class {
12046
12057
  this._destroyCurrentWSConnection();
12047
12058
  if (options.refreshToken) {
12048
12059
  await this.client.tokenManager.loadToken();
12060
+ if (this.isConnecting || this.isHealthy) {
12061
+ this._log("_reconnect() - Abort (4) since already connecting or healthy");
12062
+ return;
12063
+ }
12049
12064
  }
12050
12065
  try {
12051
12066
  await this._connect();
@@ -12069,6 +12084,21 @@ var StableWSConnection = class {
12069
12084
  }
12070
12085
  this._log("_reconnect() - == END ==");
12071
12086
  }
12087
+ /**
12088
+ * _reconnectAfterFailure - Reconnects after the socket closed or failed. If the server
12089
+ * reported that the token expired, the token is refreshed before reconnecting.
12090
+ * Static tokens cannot be refreshed and reconnect as before.
12091
+ */
12092
+ _reconnectAfterFailure() {
12093
+ if (this.tokenExpiredByServer && !this.client.tokenManager.isStatic()) {
12094
+ this._log(
12095
+ "_reconnectAfterFailure() - token expired, so going to reload token and reconnect"
12096
+ );
12097
+ this._reconnect({ refreshToken: true });
12098
+ return;
12099
+ }
12100
+ this._reconnect();
12101
+ }
12072
12102
  /**
12073
12103
  * _destroyCurrentWSConnection - Removes the current WS connection
12074
12104
  *
@@ -13126,6 +13156,242 @@ var ThreadManager = class extends WithSubscriptions {
13126
13156
  }
13127
13157
  };
13128
13158
 
13159
+ // src/poll_optimistic_votes.ts
13160
+ var CATCH_UP_TIMEOUT_MS = 3e3;
13161
+ var OptimisticPollVotes = class {
13162
+ constructor({ client, poll }) {
13163
+ // Own vote changes not confirmed by a WS event yet
13164
+ this.pendingCount = 0;
13165
+ // Own vote changes whose requests succeeded since the server's vote state was last shown
13166
+ this.succeededChanges = [];
13167
+ // Vote requests with this tag are sent one after another. A symbol, so it is unique per instance.
13168
+ this.requestTag = /* @__PURE__ */ Symbol("poll-votes");
13169
+ this.withServerVotes = (pollState) => ({
13170
+ ...pollState,
13171
+ ...this.serverVoteState
13172
+ });
13173
+ /**
13174
+ * Casts a vote for an option, shown right away through a placeholder vote. In polls with unique
13175
+ * votes, it replaces the existing own votes.
13176
+ */
13177
+ this.castVote = (optionId, messageId) => {
13178
+ const sendRequest = () => this.client.castPollVote(messageId, this.poll.id, { option_id: optionId });
13179
+ const state = this.poll.data;
13180
+ if (state.ownVotesByOptionId[optionId]) return this.send(sendRequest);
13181
+ const replacedVotes = state.enforce_unique_vote ? Object.values(state.ownVotesByOptionId) : [];
13182
+ this.poll.state.partialNext(
13183
+ applyOwnVoteDelta(state, {
13184
+ add: [this.createPlaceholderVote(optionId)],
13185
+ remove: replacedVotes
13186
+ })
13187
+ );
13188
+ return this.track(sendRequest, (response) => ({
13189
+ optionId,
13190
+ vote: response.vote
13191
+ }));
13192
+ };
13193
+ // Removes a vote, right away.
13194
+ this.removeVote = (voteId, messageId) => {
13195
+ const sendRequest = (id) => this.client.removePollVote(messageId, this.poll.id, id);
13196
+ const state = this.poll.data;
13197
+ const vote = Object.values(state.ownVotesByOptionId).find(({ id }) => id === voteId);
13198
+ if (!vote?.option_id) return this.send(() => sendRequest(voteId));
13199
+ const optionId = vote.option_id;
13200
+ this.poll.state.partialNext(applyOwnVoteDelta(state, { remove: [vote] }));
13201
+ return this.track(
13202
+ // runs when the removal's turn comes, so a preceding cast of the vote has finished
13203
+ () => {
13204
+ const serverVoteId = this.getServerVoteId(vote);
13205
+ return serverVoteId ? sendRequest(serverVoteId) : Promise.resolve(void 0);
13206
+ },
13207
+ () => ({ optionId })
13208
+ );
13209
+ };
13210
+ // Sends a vote request once the previous one has finished, whether it succeeded or not.
13211
+ this.send = async (sendRequest) => {
13212
+ try {
13213
+ return await withoutConcurrency(this.requestTag, sendRequest);
13214
+ } finally {
13215
+ if (!hasPending(this.requestTag)) this.scheduleCatchUp();
13216
+ }
13217
+ };
13218
+ // Stores the vote state of a WS vote event and returns the vote fields to show, if any.
13219
+ this.handleVoteEvent = (poll, {
13220
+ confirmsOwnVote,
13221
+ ownVotesByOptionId
13222
+ }) => {
13223
+ this.serverVoteState = {
13224
+ latest_votes_by_option: poll.latest_votes_by_option,
13225
+ ownVotesByOptionId,
13226
+ vote_count: poll.vote_count,
13227
+ vote_counts_by_option: poll.vote_counts_by_option
13228
+ };
13229
+ if (confirmsOwnVote) this.pendingCount = Math.max(this.pendingCount - 1, 0);
13230
+ return this.pendingCount > 0 ? {} : this.takeServerVoteState();
13231
+ };
13232
+ // Fresh server state (e.g. a refetch) replaces everything, pending changes are dropped.
13233
+ this.reset = (pollState) => {
13234
+ this.serverVoteState = pickVoteState(pollState);
13235
+ this.pendingCount = 0;
13236
+ this.succeededChanges = [];
13237
+ clearTimeout(this.catchUpTimeout);
13238
+ };
13239
+ // Tracks an own vote change until its request settles. `sendRequest` resolves to undefined
13240
+ // when no request was needed.
13241
+ this.track = async (sendRequest, toChange) => {
13242
+ this.pendingCount += 1;
13243
+ clearTimeout(this.catchUpTimeout);
13244
+ let response;
13245
+ try {
13246
+ response = await this.send(async () => {
13247
+ const result = await sendRequest();
13248
+ if (result !== void 0) this.succeededChanges.push(toChange(result));
13249
+ return result;
13250
+ });
13251
+ } catch (error) {
13252
+ this.settleWithoutEvent();
13253
+ throw error;
13254
+ }
13255
+ if (response === void 0) this.settleWithoutEvent();
13256
+ return response;
13257
+ };
13258
+ // A failed or skipped request gets no WS event, so it counts as confirmed right away.
13259
+ this.settleWithoutEvent = () => {
13260
+ this.pendingCount = Math.max(this.pendingCount - 1, 0);
13261
+ if (this.pendingCount === 0) this.poll.state.partialNext(this.takeServerVoteState());
13262
+ };
13263
+ // The vote shown for a cast until the server's vote arrives
13264
+ this.createPlaceholderVote = (optionId) => {
13265
+ const now = (/* @__PURE__ */ new Date()).toISOString();
13266
+ return {
13267
+ created_at: now,
13268
+ id: `local-${generateUUIDv4()}`,
13269
+ option_id: optionId,
13270
+ poll_id: this.poll.id,
13271
+ updated_at: now,
13272
+ user: this.client.user,
13273
+ user_id: this.client.userID
13274
+ };
13275
+ };
13276
+ /**
13277
+ * The server id of a vote to remove, once everything sent before the removal has finished. Casts
13278
+ * and removals of an option alternate, so the option's last succeeded change tells: a cast is the
13279
+ * vote being removed (e.g. a placeholder), a removal means the cast in between failed. Without
13280
+ * one, the server's own vote of the option is the vote being removed.
13281
+ */
13282
+ this.getServerVoteId = (vote) => {
13283
+ for (let i = this.succeededChanges.length - 1; i >= 0; i--) {
13284
+ const change = this.succeededChanges[i];
13285
+ if (change.optionId === vote.option_id) return change.vote?.id;
13286
+ }
13287
+ return this.serverVoteState.ownVotesByOptionId[vote.option_id]?.id;
13288
+ };
13289
+ this.takeServerVoteState = () => {
13290
+ clearTimeout(this.catchUpTimeout);
13291
+ this.succeededChanges = [];
13292
+ return {
13293
+ ...this.serverVoteState,
13294
+ maxVotedOptionIds: getMaxVotedOptionIds(this.serverVoteState.vote_counts_by_option)
13295
+ };
13296
+ };
13297
+ this.scheduleCatchUp = () => {
13298
+ clearTimeout(this.catchUpTimeout);
13299
+ if (this.pendingCount === 0) return;
13300
+ this.catchUpTimeout = setTimeout(this.applySucceededChanges, CATCH_UP_TIMEOUT_MS);
13301
+ };
13302
+ /**
13303
+ * A WS event of an own vote change got lost, so the server's own votes are stale. All requests
13304
+ * have finished (the timeout starts once nothing is left to send and a new request cancels it),
13305
+ * so applying the succeeded changes in order gives the server's own votes (changes whose events
13306
+ * did arrive end up the same). They are shown with the vote counts of the last WS event, which
13307
+ * contain the other users' votes too.
13308
+ */
13309
+ this.applySucceededChanges = () => {
13310
+ const { enforce_unique_vote } = this.poll.data;
13311
+ let ownVotesByOptionId = { ...this.serverVoteState.ownVotesByOptionId };
13312
+ for (const { optionId, vote } of this.succeededChanges) {
13313
+ if (!vote) {
13314
+ delete ownVotesByOptionId[optionId];
13315
+ } else if (enforce_unique_vote) {
13316
+ ownVotesByOptionId = { [optionId]: vote };
13317
+ } else {
13318
+ ownVotesByOptionId[optionId] = vote;
13319
+ }
13320
+ }
13321
+ this.serverVoteState = { ...this.serverVoteState, ownVotesByOptionId };
13322
+ this.pendingCount = 0;
13323
+ this.poll.state.partialNext(this.takeServerVoteState());
13324
+ };
13325
+ this.client = client;
13326
+ this.poll = poll;
13327
+ this.serverVoteState = pickVoteState(poll.data);
13328
+ }
13329
+ get serverOwnVotes() {
13330
+ return this.serverVoteState.ownVotesByOptionId;
13331
+ }
13332
+ };
13333
+ function pickVoteState(state) {
13334
+ return {
13335
+ latest_votes_by_option: state.latest_votes_by_option,
13336
+ ownVotesByOptionId: state.ownVotesByOptionId,
13337
+ vote_count: state.vote_count,
13338
+ vote_counts_by_option: state.vote_counts_by_option
13339
+ };
13340
+ }
13341
+ function applyOwnVoteDelta(state, { add = [], remove = [] }) {
13342
+ const ownVotesByOptionId = { ...state.ownVotesByOptionId };
13343
+ const voteCountsByOption = { ...state.vote_counts_by_option };
13344
+ const latestVotesByOption = state.latest_votes_by_option ? { ...state.latest_votes_by_option } : state.latest_votes_by_option;
13345
+ let voteCount = state.vote_count ?? 0;
13346
+ for (const vote of remove) {
13347
+ const optionId = vote.option_id;
13348
+ if (!optionId) continue;
13349
+ delete ownVotesByOptionId[optionId];
13350
+ const optionVoteCount = (voteCountsByOption[optionId] ?? 0) - 1;
13351
+ if (optionVoteCount > 0) {
13352
+ voteCountsByOption[optionId] = optionVoteCount;
13353
+ } else {
13354
+ delete voteCountsByOption[optionId];
13355
+ }
13356
+ voteCount = Math.max(voteCount - 1, 0);
13357
+ if (latestVotesByOption?.[optionId]) {
13358
+ latestVotesByOption[optionId] = latestVotesByOption[optionId].filter(
13359
+ (latestVote) => latestVote.id !== vote.id
13360
+ );
13361
+ }
13362
+ }
13363
+ for (const vote of add) {
13364
+ const optionId = vote.option_id;
13365
+ if (!optionId) continue;
13366
+ ownVotesByOptionId[optionId] = vote;
13367
+ voteCountsByOption[optionId] = (voteCountsByOption[optionId] ?? 0) + 1;
13368
+ voteCount += 1;
13369
+ if (latestVotesByOption && state.voting_visibility !== "anonymous") {
13370
+ latestVotesByOption[optionId] = [vote, ...latestVotesByOption[optionId] ?? []];
13371
+ }
13372
+ }
13373
+ return {
13374
+ latest_votes_by_option: latestVotesByOption,
13375
+ maxVotedOptionIds: getMaxVotedOptionIds(voteCountsByOption),
13376
+ ownVotesByOptionId,
13377
+ vote_count: voteCount,
13378
+ vote_counts_by_option: voteCountsByOption
13379
+ };
13380
+ }
13381
+ function getMaxVotedOptionIds(voteCountsByOption) {
13382
+ let maxVotes = 0;
13383
+ let winningOptions = [];
13384
+ for (const [id, count] of Object.entries(voteCountsByOption ?? {})) {
13385
+ if (count > maxVotes) {
13386
+ winningOptions = [id];
13387
+ maxVotes = count;
13388
+ } else if (count === maxVotes) {
13389
+ winningOptions.push(id);
13390
+ }
13391
+ }
13392
+ return winningOptions;
13393
+ }
13394
+
13129
13395
  // src/poll.ts
13130
13396
  var isPollUpdatedEvent = (e) => e.type === "poll.updated";
13131
13397
  var isPollClosedEventEvent = (e) => e.type === "poll.closed";
@@ -13135,6 +13401,9 @@ var isPollVoteRemovedEvent = (e) => e.type === "poll.vote_removed";
13135
13401
  var isVoteAnswer = (vote) => !!vote?.answer_text;
13136
13402
  var Poll = class {
13137
13403
  constructor({ client, poll }) {
13404
+ // Set whenever server data (WS event or rehydration) confirms that the poll is closed,
13405
+ // so that a failed optimistic close does not reopen a poll that is actually closed.
13406
+ this.closeConfirmed = false;
13138
13407
  this.getInitialStateFromPollResponse = (poll) => {
13139
13408
  const { own_votes, id, ...pollResponseForState } = poll;
13140
13409
  const { ownAnswer, ownVotes } = own_votes?.reduce(
@@ -13158,25 +13427,55 @@ var Poll = class {
13158
13427
  ownVotesByOptionId: getOwnVotesByOptionId(ownVotes)
13159
13428
  };
13160
13429
  };
13430
+ // persists only the server's votes, never the optimistic ones
13161
13431
  this.upsertOfflineDb = () => {
13432
+ const serverState = this.optimisticVotes.withServerVotes(this.data);
13162
13433
  this.client.offlineDb?.executeQuerySafely(
13163
- (db) => db.upsertPoll({ poll: mapPollStateToResponse(this) }),
13434
+ (db) => db.upsertPoll({ poll: mapPollStateToResponse(this, serverState) }),
13164
13435
  { method: "upsertPoll" }
13165
13436
  );
13166
13437
  };
13167
13438
  this.reinitializeState = (poll) => {
13168
- this.state.partialNext(this.getInitialStateFromPollResponse(poll));
13439
+ if (poll.is_closed) this.closeConfirmed = true;
13440
+ const initialState = this.getInitialStateFromPollResponse(poll);
13441
+ this.optimisticVotes.reset(initialState);
13442
+ this.state.partialNext(initialState);
13443
+ };
13444
+ // Hands the vote state of a WS vote event to the optimistic votes, which decide whether to show it.
13445
+ this.updateFromVoteEvent = (event, ownVotesByOptionId, answerState) => {
13446
+ const isOwnVote = event.poll_vote.user_id === this.client.userID;
13447
+ const shownVoteState = this.optimisticVotes.handleVoteEvent(event.poll, {
13448
+ confirmsOwnVote: isOwnVote && !isVoteAnswer(event.poll_vote) && !!event.poll_vote.option_id,
13449
+ ownVotesByOptionId
13450
+ });
13451
+ this.state.partialNext({
13452
+ ...answerState,
13453
+ answers_count: event.poll.answers_count,
13454
+ lastActivityAt: new Date(event.created_at),
13455
+ ...shownVoteState
13456
+ });
13457
+ this.upsertOfflineDb();
13169
13458
  };
13170
13459
  this.handlePollUpdated = (event) => {
13171
13460
  if (event.poll?.id && event.poll.id !== this.id) return;
13172
13461
  if (!isPollUpdatedEvent(event)) return;
13173
13462
  const { id, ...pollData } = extractPollData(event.poll);
13174
- this.state.partialNext({ ...pollData, lastActivityAt: new Date(event.created_at) });
13463
+ if (pollData.is_closed) this.closeConfirmed = true;
13464
+ this.state.partialNext({
13465
+ ...pollData,
13466
+ // Server-owned translations, which `extractPollData` (an update request) leaves out. Copied
13467
+ // even when absent: the event carries the whole poll, and a change made under channel-only
13468
+ // translation drops the stale ones.
13469
+ description_i18n: event.poll.description_i18n,
13470
+ lastActivityAt: new Date(event.created_at),
13471
+ name_i18n: event.poll.name_i18n
13472
+ });
13175
13473
  this.upsertOfflineDb();
13176
13474
  };
13177
13475
  this.handlePollClosed = (event) => {
13178
13476
  if (event.poll?.id && event.poll.id !== this.id) return;
13179
13477
  if (!isPollClosedEventEvent(event)) return;
13478
+ this.closeConfirmed = true;
13180
13479
  this.state.partialNext({
13181
13480
  is_closed: true,
13182
13481
  lastActivityAt: new Date(event.created_at)
@@ -13190,8 +13489,7 @@ var Poll = class {
13190
13489
  const isOwnVote = event.poll_vote.user_id === this.client.userID;
13191
13490
  let latestAnswers = [...currentState.latest_answers];
13192
13491
  let ownAnswer = currentState.ownAnswer;
13193
- const ownVotesByOptionId = currentState.ownVotesByOptionId;
13194
- let maxVotedOptionIds = currentState.maxVotedOptionIds;
13492
+ const ownVotesByOptionId = { ...this.optimisticVotes.serverOwnVotes };
13195
13493
  if (isOwnVote) {
13196
13494
  if (isVoteAnswer(event.poll_vote)) {
13197
13495
  ownAnswer = event.poll_vote;
@@ -13201,19 +13499,11 @@ var Poll = class {
13201
13499
  }
13202
13500
  if (isVoteAnswer(event.poll_vote)) {
13203
13501
  latestAnswers = [event.poll_vote, ...latestAnswers];
13204
- } else {
13205
- maxVotedOptionIds = getMaxVotedOptionIds(event.poll.vote_counts_by_option);
13206
13502
  }
13207
- const pollEnrichData = extractPollEnrichedData(event.poll);
13208
- this.state.partialNext({
13209
- ...pollEnrichData,
13503
+ this.updateFromVoteEvent(event, ownVotesByOptionId, {
13210
13504
  latest_answers: latestAnswers,
13211
- lastActivityAt: new Date(event.created_at),
13212
- ownAnswer,
13213
- ownVotesByOptionId,
13214
- maxVotedOptionIds
13505
+ ownAnswer
13215
13506
  });
13216
- this.upsertOfflineDb();
13217
13507
  };
13218
13508
  this.handleVoteChanged = (event) => {
13219
13509
  if (event.poll?.id && event.poll.id !== this.id) return;
@@ -13222,8 +13512,7 @@ var Poll = class {
13222
13512
  const isOwnVote = event.poll_vote.user_id === this.client.userID;
13223
13513
  let latestAnswers = [...currentState.latest_answers];
13224
13514
  let ownAnswer = currentState.ownAnswer;
13225
- let ownVotesByOptionId = currentState.ownVotesByOptionId;
13226
- let maxVotedOptionIds = currentState.maxVotedOptionIds;
13515
+ let ownVotesByOptionId = this.optimisticVotes.serverOwnVotes;
13227
13516
  if (isOwnVote) {
13228
13517
  if (isVoteAnswer(event.poll_vote)) {
13229
13518
  latestAnswers = [
@@ -13247,23 +13536,14 @@ var Poll = class {
13247
13536
  if (ownAnswer?.id === event.poll_vote.id) {
13248
13537
  ownAnswer = void 0;
13249
13538
  }
13250
- maxVotedOptionIds = getMaxVotedOptionIds(event.poll.vote_counts_by_option);
13251
13539
  }
13252
13540
  } else if (isVoteAnswer(event.poll_vote)) {
13253
13541
  latestAnswers = [event.poll_vote, ...latestAnswers];
13254
- } else {
13255
- maxVotedOptionIds = getMaxVotedOptionIds(event.poll.vote_counts_by_option);
13256
13542
  }
13257
- const pollEnrichData = extractPollEnrichedData(event.poll);
13258
- this.state.partialNext({
13259
- ...pollEnrichData,
13543
+ this.updateFromVoteEvent(event, ownVotesByOptionId, {
13260
13544
  latest_answers: latestAnswers,
13261
- lastActivityAt: new Date(event.created_at),
13262
- ownAnswer,
13263
- ownVotesByOptionId,
13264
- maxVotedOptionIds
13545
+ ownAnswer
13265
13546
  });
13266
- this.upsertOfflineDb();
13267
13547
  };
13268
13548
  this.handleVoteRemoved = (event) => {
13269
13549
  if (event.poll?.id && event.poll.id !== this.id) return;
@@ -13272,29 +13552,19 @@ var Poll = class {
13272
13552
  const isOwnVote = event.poll_vote.user_id === this.client.userID;
13273
13553
  let latestAnswers = [...currentState.latest_answers];
13274
13554
  let ownAnswer = currentState.ownAnswer;
13275
- const ownVotesByOptionId = { ...currentState.ownVotesByOptionId };
13276
- let maxVotedOptionIds = currentState.maxVotedOptionIds;
13555
+ const ownVotesByOptionId = { ...this.optimisticVotes.serverOwnVotes };
13277
13556
  if (isVoteAnswer(event.poll_vote)) {
13278
13557
  latestAnswers = latestAnswers.filter((answer) => answer.id !== event.poll_vote.id);
13279
13558
  if (isOwnVote) {
13280
13559
  ownAnswer = void 0;
13281
13560
  }
13282
- } else {
13283
- maxVotedOptionIds = getMaxVotedOptionIds(event.poll.vote_counts_by_option);
13284
- if (isOwnVote && event.poll_vote.option_id) {
13285
- delete ownVotesByOptionId[event.poll_vote.option_id];
13286
- }
13561
+ } else if (isOwnVote && event.poll_vote.option_id) {
13562
+ delete ownVotesByOptionId[event.poll_vote.option_id];
13287
13563
  }
13288
- const pollEnrichData = extractPollEnrichedData(event.poll);
13289
- this.state.partialNext({
13290
- ...pollEnrichData,
13564
+ this.updateFromVoteEvent(event, ownVotesByOptionId, {
13291
13565
  latest_answers: latestAnswers,
13292
- lastActivityAt: new Date(event.created_at),
13293
- ownAnswer,
13294
- ownVotesByOptionId,
13295
- maxVotedOptionIds
13566
+ ownAnswer
13296
13567
  });
13297
- this.upsertOfflineDb();
13298
13568
  };
13299
13569
  this.query = async (id) => {
13300
13570
  const { poll } = await this.client.getPoll(id);
@@ -13303,11 +13573,33 @@ var Poll = class {
13303
13573
  };
13304
13574
  this.update = async (data) => await this.client.updatePoll({ ...data, id: this.id });
13305
13575
  this.partialUpdate = async (partialPollObject) => await this.client.partialUpdatePoll(this.id, partialPollObject);
13306
- this.close = async () => await this.client.closePoll(this.id);
13576
+ /**
13577
+ * Closes the poll. The poll is marked as closed optimistically and the change is
13578
+ * reverted if the request fails, unless the server confirmed the close meanwhile.
13579
+ * Does nothing if the poll is already closed.
13580
+ */
13581
+ this.close = async () => {
13582
+ if (this.data.is_closed) return;
13583
+ this.closeConfirmed = false;
13584
+ this.state.partialNext({ is_closed: true });
13585
+ try {
13586
+ return await this.client.closePoll(this.id);
13587
+ } catch (error) {
13588
+ if (!this.closeConfirmed) {
13589
+ this.state.partialNext({ is_closed: false });
13590
+ }
13591
+ throw error;
13592
+ }
13593
+ };
13307
13594
  this.delete = async () => await this.client.deletePoll(this.id);
13308
13595
  this.createOption = async (option) => await this.client.createPollOption(this.id, option);
13309
13596
  this.updateOption = async (option) => await this.client.updatePollOption(this.id, option);
13310
13597
  this.deleteOption = async (optionId) => await this.client.deletePollOption(this.id, optionId);
13598
+ /**
13599
+ * Casts a vote for an option. The vote is shown right away through a local placeholder vote,
13600
+ * which the server's vote replaces once the WS events of all pending vote changes arrived.
13601
+ * If the request fails, the change is reverted.
13602
+ */
13311
13603
  this.castVote = async (optionId, messageId) => {
13312
13604
  const { max_votes_allowed, ownVotesByOptionId } = this.data;
13313
13605
  const reachedVoteLimit = max_votes_allowed && max_votes_allowed === Object.keys(ownVotesByOptionId).length;
@@ -13324,11 +13616,14 @@ var Poll = class {
13324
13616
  });
13325
13617
  return;
13326
13618
  }
13327
- return await this.client.castPollVote(messageId, this.id, {
13328
- option_id: optionId
13329
- });
13619
+ return await this.optimisticVotes.castVote(optionId, messageId);
13330
13620
  };
13331
- this.removeVote = async (voteId, messageId) => await this.client.removePollVote(messageId, this.id, voteId);
13621
+ /**
13622
+ * Removes a vote. The vote is removed right away and restored if the request fails. Vote
13623
+ * requests are sent in order, so removing a vote whose cast is not confirmed yet uses the vote
13624
+ * id from the cast's response; if that cast failed, there is nothing to remove.
13625
+ */
13626
+ this.removeVote = async (voteId, messageId) => await this.optimisticVotes.removeVote(voteId, messageId);
13332
13627
  this.addAnswer = async (answerText, messageId) => await this.client.addPollAnswer(messageId, this.id, answerText);
13333
13628
  this.removeAnswer = async (answerId, messageId) => await this.client.removePollVote(messageId, this.id, answerId);
13334
13629
  this.queryAnswers = async (params) => await this.client.queryPollAnswers(
@@ -13346,24 +13641,12 @@ var Poll = class {
13346
13641
  this.client = client;
13347
13642
  this.id = poll.id;
13348
13643
  this.state = new StateStore(this.getInitialStateFromPollResponse(poll));
13644
+ this.optimisticVotes = new OptimisticPollVotes({ client: this.client, poll: this });
13349
13645
  }
13350
13646
  get data() {
13351
13647
  return this.state.getLatestValue();
13352
13648
  }
13353
13649
  };
13354
- function getMaxVotedOptionIds(voteCountsByOption) {
13355
- let maxVotes = 0;
13356
- let winningOptions = [];
13357
- for (const [id, count] of Object.entries(voteCountsByOption ?? {})) {
13358
- if (count > maxVotes) {
13359
- winningOptions = [id];
13360
- maxVotes = count;
13361
- } else if (count === maxVotes) {
13362
- winningOptions.push(id);
13363
- }
13364
- }
13365
- return winningOptions;
13366
- }
13367
13650
  function getOwnVotesByOptionId(ownVotes) {
13368
13651
  return !ownVotes ? {} : ownVotes.reduce((acc, vote) => {
13369
13652
  if (isVoteAnswer(vote) || !vote.option_id) return acc;
@@ -13385,7 +13668,7 @@ function extractPollData(pollResponse) {
13385
13668
  voting_visibility: pollResponse.voting_visibility
13386
13669
  };
13387
13670
  }
13388
- function mapPollStateToResponse(poll) {
13671
+ function mapPollStateToResponse(poll, state = poll.data) {
13389
13672
  const {
13390
13673
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
13391
13674
  lastActivityAt,
@@ -13394,7 +13677,7 @@ function mapPollStateToResponse(poll) {
13394
13677
  ownVotesByOptionId,
13395
13678
  ownAnswer,
13396
13679
  ...restState
13397
- } = poll.data;
13680
+ } = state;
13398
13681
  const ownVotes = [
13399
13682
  ...Object.values(ownVotesByOptionId),
13400
13683
  ...ownAnswer ? [ownAnswer] : []
@@ -15179,7 +15462,7 @@ var StreamChat = class _StreamChat {
15179
15462
  return this.userAgent;
15180
15463
  }
15181
15464
  if (!this.cachedUserAgent) {
15182
- const version = "9.53.0";
15465
+ const version = "9.54.1";
15183
15466
  const { name: sdkName, version: sdkVersion } = this.sdkIdentifier ?? {};
15184
15467
  const { name: appName, version: appVersion } = this.appIdentifier ?? {};
15185
15468
  const { os, model: deviceModel } = this.deviceIdentifier ?? {};
@@ -16768,7 +17051,7 @@ var StreamChat = class _StreamChat {
16768
17051
  * @param {string} messageId
16769
17052
  * @param {string} language
16770
17053
  *
16771
- * @return {MessageResponse} Response that includes the message
17054
+ * @return {APIResponse & { message: MessageResponse }} Response that includes the translated message
16772
17055
  */
16773
17056
  async translateMessage(messageId, language) {
16774
17057
  return await this.post(