stream-chat 10.0.0-rc.26 → 10.0.0-rc.28

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 (36) hide show
  1. package/README.md +1 -1
  2. package/dist/cjs/index.browser.js +296 -54
  3. package/dist/cjs/index.browser.js.map +3 -3
  4. package/dist/cjs/index.node.js +296 -54
  5. package/dist/cjs/index.node.js.map +3 -3
  6. package/dist/esm/index.mjs +299 -57
  7. package/dist/esm/index.mjs.map +4 -4
  8. package/dist/types/ChannelManager.d.ts +2 -2
  9. package/dist/types/channel_state.d.ts +6 -5
  10. package/dist/types/connection/wsConnection/StableWSConnection.d.ts +12 -0
  11. package/dist/types/errors.d.ts +5 -1
  12. package/dist/types/gen/chat/ChannelApi.d.ts +4 -1
  13. package/dist/types/gen/chat/ChatApi.d.ts +16 -2
  14. package/dist/types/gen/models/index.d.ts +563 -103
  15. package/dist/types/gen/moderation/ModerationApi.d.ts +2 -1
  16. package/dist/types/messageOperations/MessageOperations.d.ts +6 -1
  17. package/dist/types/pagination/paginators/BasePaginator.d.ts +8 -2
  18. package/dist/types/pagination/paginators/ChannelPaginator.d.ts +22 -2
  19. package/dist/types/utils/concurrency.d.ts +1 -1
  20. package/package.json +3 -3
  21. package/src/ChannelManager.ts +27 -3
  22. package/src/channel.ts +2 -11
  23. package/src/channel_state.ts +5 -3
  24. package/src/connection/wsConnection/StableWSConnection.ts +66 -3
  25. package/src/errors.ts +20 -3
  26. package/src/gen/chat/ChannelApi.ts +57 -0
  27. package/src/gen/chat/ChatApi.ts +56 -2
  28. package/src/gen/models/index.ts +620 -105
  29. package/src/gen/moderation/ModerationApi.ts +17 -0
  30. package/src/messageComposer/middleware/messageComposer/attachments.ts +19 -9
  31. package/src/messageOperations/MessageOperationStatePolicy.ts +2 -2
  32. package/src/messageOperations/MessageOperations.ts +27 -2
  33. package/src/pagination/paginators/BasePaginator.ts +15 -3
  34. package/src/pagination/paginators/ChannelPaginator.ts +100 -10
  35. package/src/poll_optimistic_votes.ts +6 -1
  36. package/src/thread.ts +19 -2
package/README.md CHANGED
@@ -102,7 +102,7 @@ message.custom_property; // in the response object as well
102
102
  ```
103
103
 
104
104
  > [!WARNING]
105
- > Generics mechanism has been removed in version `9.0.0` in favour of the module augmentation, please see [the release guide](https://getstream.io/chat/docs/node/upgrade-stream-chat-to-v9) on how to migrate.
105
+ > Generics mechanism has been removed in version `9.0.0` in favour of the module augmentation, please see [the release guide](https://getstream.io/chat/docs/javascript/upgrade-stream-chat-to-v9/) on how to migrate.
106
106
 
107
107
  ## 🔗 (Optional) Development Setup in Combination With Our SDKs
108
108
 
@@ -1645,6 +1645,28 @@ var isTokenExpiredError = (error) => errorIsApiError(error) && error.response?.d
1645
1645
 
1646
1646
  // src/errors.ts
1647
1647
  var import_axios3 = require("axios");
1648
+
1649
+ // src/offline-support/types.ts
1650
+ var OfflineError = class extends Error {
1651
+ constructor(message, {
1652
+ type
1653
+ }) {
1654
+ super(message);
1655
+ this.name = "OfflineError";
1656
+ this.type = type;
1657
+ }
1658
+ // Vitest helper (serialized errors are too large to read)
1659
+ // https://github.com/vitest-dev/vitest/blob/v3.1.3/packages/utils/src/error.ts#L60-L62
1660
+ toJSON() {
1661
+ return {
1662
+ message: `${this.type} - ${this.message}`,
1663
+ stack: this.stack,
1664
+ name: this.name
1665
+ };
1666
+ }
1667
+ };
1668
+
1669
+ // src/errors.ts
1648
1670
  var APIErrorCodes = {
1649
1671
  "-1": { name: "InternalSystemError", retryable: true },
1650
1672
  "2": { name: "AccessKeyError", retryable: false },
@@ -1704,9 +1726,11 @@ function isWSFailure(err) {
1704
1726
  return false;
1705
1727
  }
1706
1728
  }
1729
+ var isTransportFailure = (error) => error instanceof OfflineError || (0, import_axios3.isAxiosError)(error) && !error.response && !(0, import_axios3.isCancel)(error);
1707
1730
  var parseError = (error) => {
1708
1731
  const stringError = JSON.stringify(error);
1709
- return stringError ? JSON.parse(stringError) : {};
1732
+ const parsed = stringError ? JSON.parse(stringError) : {};
1733
+ return parsed.status == null && isTransportFailure(error) ? { ...parsed, status: 0 } : parsed;
1710
1734
  };
1711
1735
  var isAlreadyExistsError = (error, parsed) => parsed.code === 4 && error instanceof Error && error.message.includes("already exists");
1712
1736
 
@@ -3407,22 +3431,24 @@ var localAttachmentToAttachment = (localAttachment) => {
3407
3431
  const { localMetadata: _localMetadata, ...attachment } = localAttachment;
3408
3432
  return attachment;
3409
3433
  };
3434
+ var isSendable = (attachment) => isFinishedUpload(attachment) || !isLocalUploadAttachment(attachment);
3410
3435
  var composeWithPendingUploads = ({
3411
3436
  composer,
3412
3437
  state
3413
3438
  }) => {
3414
3439
  const composerIsKeptAsDraft = composer.retainsCompositionOnSubmit;
3415
3440
  const relevantAttachments = composer.attachmentManager.attachments.filter(
3416
- (attachment) => isFinishedUpload(attachment) || !composerIsKeptAsDraft && (isPendingUpload(attachment) || isFailedUpload(attachment))
3441
+ (attachment) => isSendable(attachment) || !composerIsKeptAsDraft && (isPendingUpload(attachment) || isFailedUpload(attachment))
3417
3442
  );
3418
3443
  const localAttachments = (state.localMessage.attachments ?? []).concat(
3419
- // Only a finished upload has a URL; the rest keep `localMetadata` (joined to the upload record).
3444
+ // A finished upload or a non-upload is final; the rest keep `localMetadata` (joined to the upload
3445
+ // record).
3420
3446
  relevantAttachments.map(
3421
- (attachment) => isFinishedUpload(attachment) ? localAttachmentToAttachment(attachment) : attachment
3447
+ (attachment) => isSendable(attachment) ? localAttachmentToAttachment(attachment) : attachment
3422
3448
  )
3423
3449
  );
3424
3450
  const messageAttachments = (state.message.attachments ?? []).concat(
3425
- relevantAttachments.filter(isFinishedUpload).map(localAttachmentToAttachment)
3451
+ relevantAttachments.filter(isSendable).map(localAttachmentToAttachment)
3426
3452
  );
3427
3453
  if (!localAttachments.length && !messageAttachments.length) return state;
3428
3454
  return {
@@ -3465,7 +3491,7 @@ var createAttachmentsCompositionMiddleware = (composer) => ({
3465
3491
  return discard();
3466
3492
  }
3467
3493
  const attachments = (state.message.attachments ?? []).concat(
3468
- attachmentManager.successfulUploads.map(localAttachmentToAttachment)
3494
+ attachmentManager.attachments.filter(isSendable).map(localAttachmentToAttachment)
3469
3495
  );
3470
3496
  if (!attachments.length) return forward();
3471
3497
  return next({
@@ -3492,9 +3518,9 @@ var createDraftAttachmentsCompositionMiddleware = (composer) => ({
3492
3518
  }) => {
3493
3519
  const { attachmentManager } = composer;
3494
3520
  if (!attachmentManager) return forward();
3495
- const successfulUploads = attachmentManager.successfulUploads;
3496
- const attachments = successfulUploads.length ? (state.draft.attachments ?? []).concat(
3497
- successfulUploads.map(localAttachmentToAttachment)
3521
+ const sendableAttachments = attachmentManager.attachments.filter(isSendable);
3522
+ const attachments = sendableAttachments.length ? (state.draft.attachments ?? []).concat(
3523
+ sendableAttachments.map(localAttachmentToAttachment)
3498
3524
  ) : void 0;
3499
3525
  return next({
3500
3526
  ...state,
@@ -6915,10 +6941,12 @@ var BasePaginator = class {
6915
6941
  const claims = claimsActiveInterval ?? this.decidesActiveInterval({ queryShape: forcedQueryShape, reset, updateState });
6916
6942
  const activeIntervalClaim = claims ? this.claimActiveInterval() : void 0;
6917
6943
  const isForcedReset = reset === "yes" && !keepPreviousItems;
6944
+ let positionBeforeReset;
6918
6945
  if (isForcedReset) {
6919
6946
  this.clearItemStorage();
6920
6947
  this.state.next(this.getStateBeforeFirstQuery());
6921
6948
  } else if (reset === "yes" && !forcedQueryShape) {
6949
+ positionBeforeReset = { cursor: this.cursor, offset: this.offset };
6922
6950
  this.state.partialNext({
6923
6951
  cursor: this.config.initialCursor,
6924
6952
  offset: this.config.initialOffset ?? 0
@@ -6967,6 +6995,7 @@ var BasePaginator = class {
6967
6995
  direction,
6968
6996
  isFirstPage,
6969
6997
  keepPreviousItems,
6998
+ positionBeforeReset,
6970
6999
  queryShape,
6971
7000
  requestedPageSize: this.getRequestedPageSize(queryShape),
6972
7001
  updateState
@@ -6982,7 +7011,10 @@ var BasePaginator = class {
6982
7011
  this._lastQueryShape = params.queryShape;
6983
7012
  const { results } = params;
6984
7013
  if (!results) {
6985
- const stateUpdate = { isLoading: false };
7014
+ const stateUpdate = {
7015
+ isLoading: false,
7016
+ ...params.positionBeforeReset
7017
+ };
6986
7018
  this.state.partialNext(stateUpdate);
6987
7019
  return { stateCandidate: stateUpdate, targetInterval: null };
6988
7020
  }
@@ -7417,6 +7449,12 @@ var ChannelPaginator = class extends BasePaginator {
7417
7449
  this._itemsLoadedFromOfflineDB = false;
7418
7450
  /** The query in flight refreshes a cache-only interval, so its response replaces the interval. */
7419
7451
  this._replaceOfflineSeedOnResponse = false;
7452
+ /** Whether `recoverLoadedItems` runs: its pages own the list's position until it ends. */
7453
+ this._isRecoveringLoadedItems = false;
7454
+ /** A recovery asked for while one runs: the running pass stops and a new one starts. */
7455
+ this._recoveryRequestedAgain = false;
7456
+ /** A next page refused while recovering, queried once the recovery ends. See `executeQuery`. */
7457
+ this._tailQueryAwaitingRecovery = false;
7420
7458
  /**
7421
7459
  * Filters sent with the next query and used as the offline-db query key. Built from the local
7422
7460
  * filters only: the backend-resolved filter would change the query shape after the first response,
@@ -7444,11 +7482,15 @@ var ChannelPaginator = class extends BasePaginator {
7444
7482
  if (cachedQuery.predefinedFilter) {
7445
7483
  this.applyPredefinedFilterResponse(cachedQuery.predefinedFilter);
7446
7484
  }
7447
- return this.client.hydrateChannels(cachedQuery.channels, {
7448
- offlineMode: true,
7449
- skipInitialization: []
7450
- // an empty array clears existing channel messages (no duplicates)
7451
- });
7485
+ return this.client.hydrateChannels(
7486
+ cachedQuery.channels,
7487
+ {
7488
+ offlineMode: true,
7489
+ skipInitialization: []
7490
+ // an empty array clears existing channel messages (no duplicates)
7491
+ },
7492
+ request
7493
+ );
7452
7494
  }
7453
7495
  } catch (error) {
7454
7496
  chatLoggerSystem.getLogger("channel").error(error.message);
@@ -7489,16 +7531,60 @@ var ChannelPaginator = class extends BasePaginator {
7489
7531
  };
7490
7532
  /**
7491
7533
  * The reconnect refresh. Re-queries every loaded page, then drops the loaded channels no page
7492
- * returned: they were deleted, left, hidden, or no longer match the filter.
7534
+ * returned that sort within the re-queried range: they were deleted, left, hidden, or no longer
7535
+ * match the filter. Those sorting below it were not re-queried and stay.
7493
7536
  *
7494
7537
  * Each page asks for everything still to cover and the next one starts where it ended, so the
7495
7538
  * server's page cap decides the step. A failed page removes nothing. At most
7496
- * {@link MAX_RECOVERED_ITEMS} channels are re-queried: the rest are dropped.
7539
+ * {@link MAX_RECOVERED_ITEMS} channels are re-queried.
7540
+ *
7541
+ * Paging is held meanwhile: a next page asked for is queried once the recovery ends, as the list
7542
+ * end that asked for it does not ask again when the recovery changed nothing. A query of the
7543
+ * list's own already in flight is waited for, as it would make the recovery's refused.
7544
+ *
7545
+ * A call while a recovery runs returns at once and the running pass starts over from the first page
7546
+ * once its page in flight lands, as the pages before were watched on a connection that is gone.
7497
7547
  */
7498
7548
  this.recoverLoadedItems = async () => {
7549
+ if (this._isRecoveringLoadedItems) {
7550
+ this._recoveryRequestedAgain = true;
7551
+ return;
7552
+ }
7553
+ this._isRecoveringLoadedItems = true;
7554
+ try {
7555
+ do {
7556
+ this._recoveryRequestedAgain = false;
7557
+ await this.waitForQueryToSettle();
7558
+ await this.recoverLoadedPages();
7559
+ } while (this._recoveryRequestedAgain);
7560
+ } finally {
7561
+ this._isRecoveringLoadedItems = false;
7562
+ }
7563
+ if (!this._tailQueryAwaitingRecovery) return;
7564
+ this._tailQueryAwaitingRecovery = false;
7565
+ runDetached(this.toTail(), { context: "ChannelPaginator.recoverLoadedItems" });
7566
+ };
7567
+ /** Resolves once the list has no query of its own in flight. */
7568
+ this.waitForQueryToSettle = () => new Promise((resolve) => {
7569
+ if (!this.isLoading) {
7570
+ resolve();
7571
+ return;
7572
+ }
7573
+ const unsubscribe = this.state.subscribeWithSelector(
7574
+ ({ isLoading }) => ({ isLoading }),
7575
+ ({ isLoading }) => {
7576
+ if (isLoading) return;
7577
+ unsubscribe();
7578
+ resolve();
7579
+ }
7580
+ );
7581
+ });
7582
+ this.recoverLoadedPages = async () => {
7499
7583
  const loadedCids = new Set((this.items ?? []).map((channel) => channel.cid));
7500
7584
  const recoveredCount = Math.min(loadedCids.size, MAX_RECOVERED_ITEMS);
7501
7585
  const returnedCids = /* @__PURE__ */ new Set();
7586
+ let lastReturnedCid;
7587
+ let reachedEnd = false;
7502
7588
  const shape = this.getNextQueryShape();
7503
7589
  let interval = null;
7504
7590
  let offset = 0;
@@ -7513,21 +7599,36 @@ var ChannelPaginator = class extends BasePaginator {
7513
7599
  updateState: false
7514
7600
  });
7515
7601
  const page = this.getLastPageCids();
7516
- if (!result || !page) return;
7602
+ if (!result || !page || this._recoveryRequestedAgain) {
7603
+ this.state.partialNext({ offset: this.items?.length ?? 0 });
7604
+ return;
7605
+ }
7517
7606
  if (result.targetInterval) {
7518
7607
  interval = result.targetInterval;
7519
7608
  this.setActiveInterval(interval, { updateState: offset === 0 });
7520
7609
  }
7610
+ const requested = offset === 0 ? Math.max(this.pageSize, loadedCids.size) : recoveredCount - offset;
7611
+ if (page.length < Math.min(this.pageSize, requested)) reachedEnd = true;
7521
7612
  if (!page.length) break;
7522
7613
  pageCount++;
7523
7614
  for (const channel of result.stateCandidate.items ?? [])
7524
7615
  returnedCids.add(channel.cid);
7616
+ lastReturnedCid = page[page.length - 1];
7525
7617
  offset += page.length;
7526
7618
  } while (offset < recoveredCount);
7619
+ const lastReturned = lastReturnedCid ? this.client.channelManager.get(lastReturnedCid) : void 0;
7620
+ const isWithinRecoveredRange = (cid) => {
7621
+ if (reachedEnd) return true;
7622
+ const channel = this.getItem(cid);
7623
+ if (!channel || !lastReturned) return false;
7624
+ return this.sortComparator(channel, lastReturned) < 0;
7625
+ };
7527
7626
  this.batch(
7528
7627
  () => {
7529
7628
  for (const cid of loadedCids) {
7530
- if (!returnedCids.has(cid)) this.removeItem({ id: cid });
7629
+ if (!returnedCids.has(cid) && isWithinRecoveredRange(cid)) {
7630
+ this.removeItem({ id: cid });
7631
+ }
7531
7632
  }
7532
7633
  },
7533
7634
  { coalesce: true }
@@ -7661,8 +7762,14 @@ var ChannelPaginator = class extends BasePaginator {
7661
7762
  * The metadata describes the query as a whole, so it is committed only when a first page lands (a
7662
7763
  * failed query keeps the loaded list's). It is committed before `super`, which filters and ingests
7663
7764
  * the page using `matchesFilter` and the comparator this metadata feeds.
7765
+ *
7766
+ * A recovery page (see `recoverLoadedItems`) starts where the one before it ended, so it extends
7767
+ * the shown interval, though a page at a caller's shape would otherwise start one of its own.
7664
7768
  */
7665
7769
  placeQueryPage(params) {
7770
+ if (this._isRecoveringLoadedItems && params.startsSeparateInterval) {
7771
+ params = { ...params, startsSeparateInterval: false };
7772
+ }
7666
7773
  this._lastPageCids = params.results?.items.map((channel) => channel.cid);
7667
7774
  const pendingPredefinedFilter = this._pendingPredefinedFilter;
7668
7775
  this._pendingPredefinedFilter = void 0;
@@ -7740,6 +7847,10 @@ var ChannelPaginator = class extends BasePaginator {
7740
7847
  * network is not deferred.
7741
7848
  */
7742
7849
  async executeQuery(params = {}) {
7850
+ if (this._isRecoveringLoadedItems && params.direction && params.reset !== "yes") {
7851
+ if (params.direction === "tailward") this._tailQueryAwaitingRecovery = true;
7852
+ return;
7853
+ }
7743
7854
  const { offlineDb } = this.client;
7744
7855
  const effectiveParams = this._itemsLoadedFromOfflineDB && params.reset !== "yes" ? { ...params, keepPreviousItems: true, reset: "yes" } : params;
7745
7856
  const queryShape = effectiveParams.queryShape ?? this.getNextQueryShape();
@@ -7818,6 +7929,7 @@ var ChannelPaginator = class extends BasePaginator {
7818
7929
  super.resetState();
7819
7930
  this._itemIndex.clear();
7820
7931
  this._queryAwaitingSync = void 0;
7932
+ this._tailQueryAwaitingRecovery = false;
7821
7933
  }
7822
7934
  removeItem(params) {
7823
7935
  const coordinates = super.removeItem(params);
@@ -14668,6 +14780,7 @@ var pickUpdateOptions = (options) => {
14668
14780
  if (typeof options.skip_push === "boolean") picked.skip_push = options.skip_push;
14669
14781
  return picked;
14670
14782
  };
14783
+ var isFailedEdit = (localMessage) => localMessage.status === "failed" && localMessage.message_text_updated_at != null;
14671
14784
  var MessageOperations = class {
14672
14785
  constructor(ctx) {
14673
14786
  this.failedSendCache = new FailedSendCache(() => this.config);
@@ -14793,11 +14906,22 @@ var MessageOperations = class {
14793
14906
  handlers.send
14794
14907
  );
14795
14908
  }
14796
- /** A send with a cached payload: resends what failed, unless the caller passes a new one. */
14909
+ /**
14910
+ * A send with a cached payload: resends what failed, unless the caller passes a new one. A failed
14911
+ * edit is replayed as an edit instead: the server already has that message, so a send would be
14912
+ * rejected as a duplicate, and the duplicate taken for a delivered send. That holds even with a
14913
+ * cached payload: a send that failed after the server stored the message leaves one behind.
14914
+ */
14797
14915
  async retry(params) {
14916
+ if (isFailedEdit(params.localMessage)) {
14917
+ this.failedSendCache.clear(params.localMessage.id);
14918
+ return await this.update({
14919
+ localMessage: { ...params.localMessage, error: void 0, status: "received" }
14920
+ });
14921
+ }
14922
+ const cachedPayload = this.failedSendCache.get(params.localMessage.id);
14798
14923
  const handlers = this.ctx.handlers();
14799
14924
  const localMessage = { ...params.localMessage, type: "regular" };
14800
- const cachedPayload = this.failedSendCache.get(localMessage.id);
14801
14925
  await this.sendWithFailedSendCache(
14802
14926
  "retry",
14803
14927
  {
@@ -15335,6 +15459,30 @@ var ChannelApi = class {
15335
15459
  requestOptions
15336
15460
  );
15337
15461
  }
15462
+ fork(request, requestOptions) {
15463
+ if (!this.id) {
15464
+ throw new Error(
15465
+ `Channel isn't yet created, call getOrCreateDistinctChannel() before this operation`
15466
+ );
15467
+ }
15468
+ return this.chatApi.forkChannel(
15469
+ { id: this.id, type: this.type },
15470
+ request,
15471
+ requestOptions
15472
+ );
15473
+ }
15474
+ forkMessageIDs(request, requestOptions) {
15475
+ if (!this.id) {
15476
+ throw new Error(
15477
+ `Channel isn't yet created, call getOrCreateDistinctChannel() before this operation`
15478
+ );
15479
+ }
15480
+ return this.chatApi.forkMessageIDs(
15481
+ { id: this.id, type: this.type },
15482
+ request,
15483
+ requestOptions
15484
+ );
15485
+ }
15338
15486
  hide(request, requestOptions) {
15339
15487
  if (!this.id) {
15340
15488
  throw new Error(
@@ -15443,6 +15591,18 @@ var ChannelApi = class {
15443
15591
  requestOptions
15444
15592
  );
15445
15593
  }
15594
+ rewind(request, requestOptions) {
15595
+ if (!this.id) {
15596
+ throw new Error(
15597
+ `Channel isn't yet created, call getOrCreateDistinctChannel() before this operation`
15598
+ );
15599
+ }
15600
+ return this.chatApi.rewindChannel(
15601
+ { id: this.id, type: this.type },
15602
+ request,
15603
+ requestOptions
15604
+ );
15605
+ }
15446
15606
  show(request, requestOptions) {
15447
15607
  if (!this.id) {
15448
15608
  throw new Error(
@@ -17130,8 +17290,7 @@ var Channel = class extends ChannelApi {
17130
17290
  if (event.user?.id && event.created_at != null) {
17131
17291
  const eventUser = event.user;
17132
17292
  const createdAt = event.created_at;
17133
- const parsedDeliveredAt = event.last_delivered_at ? Date.parse(event.last_delivered_at) : NaN;
17134
- const resolvedDeliveredAt = Number.isFinite(parsedDeliveredAt) ? msToNs(parsedDeliveredAt) : createdAt;
17293
+ const resolvedDeliveredAt = event.last_delivered_at ?? createdAt;
17135
17294
  this._upsertReadState(
17136
17295
  eventUser.id,
17137
17296
  (currentUserReadState) => {
@@ -18768,7 +18927,10 @@ var Thread = class extends WithSubscriptions {
18768
18927
  ...current,
18769
18928
  deletedAt: message.deleted_at ?? null,
18770
18929
  parentMessage: message,
18771
- participants: normalizeThreadParticipants(message.thread_participants, current.channel.cid) ?? current.participants,
18930
+ participants: mergeThreadParticipants(
18931
+ current.participants,
18932
+ normalizeThreadParticipants(message.thread_participants, current.channel.cid)
18933
+ ),
18772
18934
  replyCount: message.reply_count ?? current.replyCount
18773
18935
  }));
18774
18936
  });
@@ -18977,6 +19139,13 @@ var normalizeThreadParticipants = (participants, channelCid) => {
18977
19139
  })
18978
19140
  );
18979
19141
  };
19142
+ var mergeThreadParticipants = (current, fromMessage) => {
19143
+ if (!fromMessage) return current;
19144
+ if (!current?.length) return fromMessage;
19145
+ const known = new Set(current.map((participant) => participant.user_id));
19146
+ const added = fromMessage.filter((participant) => !known.has(participant.user_id));
19147
+ return added.length ? [...current, ...added] : current;
19148
+ };
18980
19149
  var DEFAULT_THREAD_PARTICIPANT_LIMIT = 100;
18981
19150
  var ensureThreadChannel = (client, threadData) => {
18982
19151
  if (!threadData.channel) {
@@ -19269,6 +19438,17 @@ var ModerationApi = class {
19269
19438
  requestOptions
19270
19439
  );
19271
19440
  }
19441
+ revealMedia(request, requestOptions) {
19442
+ return this.apiClient.sendRequest(
19443
+ "POST",
19444
+ "/api/v2/moderation/reveal_media",
19445
+ void 0,
19446
+ void 0,
19447
+ request,
19448
+ "application/json",
19449
+ requestOptions
19450
+ );
19451
+ }
19272
19452
  queryReviewQueue(request, requestOptions) {
19273
19453
  return this.apiClient.sendRequest(
19274
19454
  "POST",
@@ -19961,9 +20141,14 @@ function applyOwnVoteDelta(state, {
19961
20141
  }
19962
20142
  voteCount = Math.max(voteCount - 1, 0);
19963
20143
  if (latestVotesByOption?.[optionId]) {
19964
- latestVotesByOption[optionId] = latestVotesByOption[optionId].filter(
20144
+ const latestVotes = latestVotesByOption[optionId].filter(
19965
20145
  (latestVote) => latestVote.id !== vote.id
19966
20146
  );
20147
+ if (latestVotes.length) {
20148
+ latestVotesByOption[optionId] = latestVotes;
20149
+ } else {
20150
+ delete latestVotesByOption[optionId];
20151
+ }
19967
20152
  }
19968
20153
  }
19969
20154
  for (const vote of add) {
@@ -20717,8 +20902,20 @@ var messageDeletedHandler = {
20717
20902
  handle: (context) => context.event.hard_delete ? reinsertItem(context) : void 0,
20718
20903
  id: "ChannelManager:default-handler:message.deleted"
20719
20904
  };
20905
+ var reloadListsWithoutLoadedPage = (channelManager, channel) => {
20906
+ channelManager.paginators.forEach((paginator) => {
20907
+ if (paginator.items === void 0 || paginator.isLoading) return;
20908
+ if (paginator.anchoredHeadItems.length > 0) return;
20909
+ if (!paginator.matchesFilter(channel)) return;
20910
+ paginator.toTailDebounced({ reset: "yes" });
20911
+ });
20912
+ };
20720
20913
  var channelVisibleHandler = {
20721
- handle: updateLists,
20914
+ handle: async (context) => {
20915
+ await updateLists(context);
20916
+ const channel = getCachedChannelFromEvent(context.event, context.ctx.channelManager);
20917
+ if (channel) reloadListsWithoutLoadedPage(context.ctx.channelManager, channel);
20918
+ },
20722
20919
  id: "ChannelManager:default-handler:channel.visible"
20723
20920
  };
20724
20921
  var channelHiddenHandler = {
@@ -20825,8 +21022,8 @@ var _ChannelManager = class _ChannelManager extends WithSubscriptions {
20825
21022
  * watches by default), those below it come back through `restoreInterruptedWatch`.
20826
21023
  * Never-queried paginators are skipped: they run their own first query on mount, and querying them
20827
21024
  * here would race it. Unlike {@link ChannelManager.reload}, it merges the page into the loaded
20828
- * list (`keepPreviousItems`) instead of blanking it, and is not `silent`: the `isLoading`
20829
- * transition guards against an overlapping query.
21025
+ * list (`keepPreviousItems`) instead of blanking it. Its pages are `silent` so paging is held while it
21026
+ * runs and a recovery asked for meanwhile supersedes it (see `ChannelPaginator.recoverLoadedItems`).
20830
21027
  */
20831
21028
  this.recover = async () => await Promise.allSettled(
20832
21029
  this.paginators.filter((paginator) => paginator.isInitialized).map(async (paginator) => {
@@ -21842,6 +22039,10 @@ var StableWSConnection = class {
21842
22039
  if (data.type === "health.check" || data.type === "connection.ok") {
21843
22040
  this.scheduleNextPing();
21844
22041
  }
22042
+ if (data?.type === "connection.error" && data?.error?.code === chatCodes.TOKEN_EXPIRED) {
22043
+ logger15.withExtraTags("onmessage").debug("The server reported that the token expired.", { wsID: wsId });
22044
+ this.tokenExpiredByServer = true;
22045
+ }
21845
22046
  this.client.dispatchEvent(decodedData);
21846
22047
  this.scheduleConnectionCheck();
21847
22048
  };
@@ -21868,7 +22069,7 @@ var StableWSConnection = class {
21868
22069
  logger15.withExtraTags("onclose").warn("The WebSocket connection was closed. Attempting to reconnect.", {
21869
22070
  event
21870
22071
  });
21871
- this._reconnect();
22072
+ this._reconnectAfterFailure();
21872
22073
  }
21873
22074
  };
21874
22075
  this.onerror = (wsId, event) => {
@@ -21879,7 +22080,7 @@ var StableWSConnection = class {
21879
22080
  this.isConnecting = false;
21880
22081
  this.rejectPromise?.(this._errorFromWSEvent(event));
21881
22082
  logger15.withExtraTags("onerror").warn("The WebSocket connection raised an error.", { event });
21882
- this._reconnect();
22083
+ this._reconnectAfterFailure();
21883
22084
  };
21884
22085
  /** Applies a status change; on a drop, marks the channel watches as interrupted. */
21885
22086
  this._setHealth = (healthy) => {
@@ -21916,6 +22117,7 @@ var StableWSConnection = class {
21916
22117
  };
21917
22118
  this._setupConnectionPromise = () => {
21918
22119
  this.isResolved = false;
22120
+ this.tokenExpiredByServer = false;
21919
22121
  this.connectionOpen = new Promise((resolve, reject) => {
21920
22122
  this.resolvePromise = resolve;
21921
22123
  this.rejectPromise = reject;
@@ -21961,6 +22163,7 @@ var StableWSConnection = class {
21961
22163
  this.isHealthy = false;
21962
22164
  this.wsID = 1;
21963
22165
  this.lastEvent = null;
22166
+ this.tokenExpiredByServer = false;
21964
22167
  }
21965
22168
  /** Read live from the parent, so a config update reaches an already open socket. */
21966
22169
  get config() {
@@ -22069,6 +22272,7 @@ var StableWSConnection = class {
22069
22272
  this.wsID += 1;
22070
22273
  this.isConnecting = false;
22071
22274
  this.isDisconnected = true;
22275
+ this.tokenExpiredByServer = false;
22072
22276
  this.client.connectionIdManager.invalidate();
22073
22277
  if (this.healthCheckTimeoutRef) {
22074
22278
  clearTimeout(this.healthCheckTimeoutRef);
@@ -22173,7 +22377,19 @@ var StableWSConnection = class {
22173
22377
  logger15.withExtraTags("_reconnect").info("Destroying the current WebSocket connection.");
22174
22378
  this._destroyCurrentWSConnection();
22175
22379
  if (options.refreshToken) {
22176
- await this.client.tokenManager.loadToken();
22380
+ try {
22381
+ await this.client.tokenManager.loadToken();
22382
+ } catch (error) {
22383
+ this._applyHealth(false);
22384
+ this.consecutiveFailures += 1;
22385
+ logger15.withExtraTags("_reconnect").warn("Failed to reload the token. Retrying the reconnect.", { error });
22386
+ this._reconnect({ refreshToken: true });
22387
+ return;
22388
+ }
22389
+ if (this.isConnecting || this.isHealthy) {
22390
+ logger15.withExtraTags("_reconnect").debug("Aborting the reconnect: already connecting or healthy.");
22391
+ return;
22392
+ }
22177
22393
  }
22178
22394
  try {
22179
22395
  await this._connect();
@@ -22216,6 +22432,19 @@ var StableWSConnection = class {
22216
22432
  this._reconnect({ interval: WS_NETWORK_RECOVERY_RETRY_MS });
22217
22433
  }
22218
22434
  }
22435
+ /**
22436
+ * _reconnectAfterFailure - Reconnects after the socket closed or failed. If the server
22437
+ * reported that the token expired, the token is refreshed before reconnecting.
22438
+ * Static tokens cannot be refreshed and reconnect as before.
22439
+ */
22440
+ _reconnectAfterFailure() {
22441
+ if (this.tokenExpiredByServer && !this.client.tokenManager.isStatic()) {
22442
+ logger15.withExtraTags("_reconnectAfterFailure").info("The token expired. Reloading the token and reconnecting.");
22443
+ this._reconnect({ refreshToken: true });
22444
+ return;
22445
+ }
22446
+ this._reconnect();
22447
+ }
22219
22448
  /**
22220
22449
  * Writes the status to the field and to `client.wsConnection.state`, and drops the connection ID
22221
22450
  * when it goes down. Returns whether the status changed. Every transition goes through here
@@ -23490,6 +23719,28 @@ var ChatApi = class {
23490
23719
  requestOptions
23491
23720
  );
23492
23721
  }
23722
+ forkChannel(pathParams, request, requestOptions) {
23723
+ return this.apiClient.sendRequest(
23724
+ "POST",
23725
+ "/api/v2/chat/channels/{type}/{id}/fork",
23726
+ pathParams,
23727
+ void 0,
23728
+ request,
23729
+ "application/json",
23730
+ requestOptions
23731
+ );
23732
+ }
23733
+ forkMessageIDs(pathParams, request, requestOptions) {
23734
+ return this.apiClient.sendRequest(
23735
+ "POST",
23736
+ "/api/v2/chat/channels/{type}/{id}/fork/message_ids",
23737
+ pathParams,
23738
+ void 0,
23739
+ request,
23740
+ "application/json",
23741
+ requestOptions
23742
+ );
23743
+ }
23493
23744
  hideChannel(pathParams, request, requestOptions) {
23494
23745
  return this.apiClient.sendRequest(
23495
23746
  "POST",
@@ -23591,6 +23842,17 @@ var ChatApi = class {
23591
23842
  requestOptions
23592
23843
  );
23593
23844
  }
23845
+ rewindChannel(pathParams, request, requestOptions) {
23846
+ return this.apiClient.sendRequest(
23847
+ "POST",
23848
+ "/api/v2/chat/channels/{type}/{id}/rewind",
23849
+ pathParams,
23850
+ void 0,
23851
+ request,
23852
+ "application/json",
23853
+ requestOptions
23854
+ );
23855
+ }
23594
23856
  showChannel(pathParams, request, requestOptions) {
23595
23857
  return this.apiClient.sendRequest(
23596
23858
  "POST",
@@ -24004,12 +24266,12 @@ var ChatApi = class {
24004
24266
  requestOptions
24005
24267
  );
24006
24268
  }
24007
- unreadCounts(_request, requestOptions) {
24269
+ unreadCounts(request, requestOptions) {
24008
24270
  return this.apiClient.sendRequest(
24009
24271
  "GET",
24010
24272
  "/api/v2/chat/unread",
24011
24273
  void 0,
24012
- void 0,
24274
+ request,
24013
24275
  void 0,
24014
24276
  void 0,
24015
24277
  requestOptions
@@ -24867,7 +25129,7 @@ var StreamChat = class _StreamChat extends ChatApi {
24867
25129
  return this.userAgent;
24868
25130
  }
24869
25131
  if (!this.cachedUserAgent) {
24870
- const version = "10.0.0-rc.26";
25132
+ const version = "10.0.0-rc.28";
24871
25133
  const { name: sdkName, version: sdkVersion } = this.sdkIdentifier ?? {};
24872
25134
  const { name: appName, version: appVersion } = this.appIdentifier ?? {};
24873
25135
  const { os, model: deviceModel } = this.deviceIdentifier ?? {};
@@ -26476,26 +26738,6 @@ var languageNameDefaults = Object.fromEntries(
26476
26738
  Object.entries(LANGUAGE_NAMES).map(([code, name]) => [`language.${code}`, name])
26477
26739
  );
26478
26740
 
26479
- // src/offline-support/types.ts
26480
- var OfflineError = class extends Error {
26481
- constructor(message, {
26482
- type
26483
- }) {
26484
- super(message);
26485
- this.name = "OfflineError";
26486
- this.type = type;
26487
- }
26488
- // Vitest helper (serialized errors are too large to read)
26489
- // https://github.com/vitest-dev/vitest/blob/v3.1.3/packages/utils/src/error.ts#L60-L62
26490
- toJSON() {
26491
- return {
26492
- message: `${this.type} - ${this.message}`,
26493
- stack: this.stack,
26494
- name: this.name
26495
- };
26496
- }
26497
- };
26498
-
26499
26741
  // src/offline-support/offline_sync_manager.ts
26500
26742
  var import_axios6 = require("axios");
26501
26743
  var logger20 = chatLoggerSystem.getLogger("offline-db");