stream-chat 10.1.1 → 10.3.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 (109) hide show
  1. package/dist/cjs/index.browser.js +4736 -2819
  2. package/dist/cjs/index.browser.js.map +4 -4
  3. package/dist/cjs/index.node.js +4757 -2819
  4. package/dist/cjs/index.node.js.map +4 -4
  5. package/dist/esm/index.mjs +4736 -2819
  6. package/dist/esm/index.mjs.map +4 -4
  7. package/dist/types/channel.d.ts +62 -3
  8. package/dist/types/client.d.ts +9 -1
  9. package/dist/types/configuration/types.d.ts +2 -0
  10. package/dist/types/connection/ConnectionRecoveryManager.d.ts +1 -0
  11. package/dist/types/gen/chat/ChatApi.d.ts +12 -1
  12. package/dist/types/gen/models/index.d.ts +659 -11
  13. package/dist/types/gen/moderation/ModerationApi.d.ts +3 -1
  14. package/dist/types/index.d.ts +2 -0
  15. package/dist/types/messageComposer/attachmentManager.d.ts +2 -0
  16. package/dist/types/messageComposer/index.d.ts +1 -0
  17. package/dist/types/messageComposer/linkPreviewsManager.d.ts +1 -0
  18. package/dist/types/messageComposer/messageComposer.d.ts +33 -7
  19. package/dist/types/messageComposer/middleware/messageComposer/compositionValidation.d.ts +1 -2
  20. package/dist/types/messageComposer/middleware/messageComposer/index.d.ts +1 -0
  21. package/dist/types/messageComposer/middleware/messageComposer/scheduledMessage.d.ts +4 -0
  22. package/dist/types/messageComposer/middleware/textComposer/commandUtils.d.ts +1 -0
  23. package/dist/types/messageComposer/scheduledMessageComposition.d.ts +32 -0
  24. package/dist/types/messageMarks/MessageMarkManager.d.ts +44 -0
  25. package/dist/types/messageMarks/index.d.ts +1 -0
  26. package/dist/types/messageOperations/MessageOperations.d.ts +12 -1
  27. package/dist/types/messageOperations/index.d.ts +1 -0
  28. package/dist/types/messageOperations/reflectMessageMarkEvent.d.ts +9 -0
  29. package/dist/types/messageOperations/sendOrdering.d.ts +4 -3
  30. package/dist/types/messageOperations/types.d.ts +6 -2
  31. package/dist/types/notifications/types.d.ts +4 -0
  32. package/dist/types/offline-support/offline_support_api.d.ts +19 -1
  33. package/dist/types/offline-support/types.d.ts +19 -1
  34. package/dist/types/pagination/PaginatorView.d.ts +55 -0
  35. package/dist/types/pagination/index.d.ts +1 -0
  36. package/dist/types/pagination/paginators/BasePaginator.d.ts +49 -0
  37. package/dist/types/pagination/paginators/ChannelPaginator.d.ts +0 -9
  38. package/dist/types/pagination/paginators/MessageIntervalPaginator.d.ts +6 -0
  39. package/dist/types/pagination/paginators/MessageMarkPaginator.d.ts +61 -0
  40. package/dist/types/pagination/paginators/ScheduledMessagePaginator.d.ts +83 -0
  41. package/dist/types/pagination/paginators/index.d.ts +2 -0
  42. package/dist/types/scheduledMessages/ScheduledMessagePaginatorsManager.d.ts +47 -0
  43. package/dist/types/scheduledMessages/ScheduledMessageStatePolicy.d.ts +12 -0
  44. package/dist/types/scheduledMessages/ScheduledMessagesView.d.ts +38 -0
  45. package/dist/types/scheduledMessages/composition.d.ts +5 -0
  46. package/dist/types/scheduledMessages/constants.d.ts +56 -0
  47. package/dist/types/scheduledMessages/editResolvers.d.ts +4 -0
  48. package/dist/types/scheduledMessages/errors.d.ts +3 -0
  49. package/dist/types/scheduledMessages/eventHandlers.d.ts +8 -0
  50. package/dist/types/scheduledMessages/index.d.ts +7 -0
  51. package/dist/types/scheduledMessages/limits.d.ts +6 -0
  52. package/dist/types/scheduledMessages/types.d.ts +65 -0
  53. package/dist/types/thread.d.ts +12 -1
  54. package/dist/types/utils.d.ts +7 -0
  55. package/package.json +1 -1
  56. package/src/channel.ts +231 -7
  57. package/src/client.ts +46 -2
  58. package/src/configuration/keys.ts +2 -0
  59. package/src/configuration/shape.ts +15 -0
  60. package/src/configuration/types.ts +3 -1
  61. package/src/connection/ConnectionRecoveryManager.ts +7 -0
  62. package/src/errors.ts +11 -0
  63. package/src/gen/chat/ChatApi.ts +60 -3
  64. package/src/gen/models/index.ts +794 -23
  65. package/src/gen/moderation/ModerationApi.ts +24 -3
  66. package/src/index.ts +2 -0
  67. package/src/messageComposer/attachmentManager.ts +43 -24
  68. package/src/messageComposer/index.ts +1 -0
  69. package/src/messageComposer/messageComposer.ts +140 -32
  70. package/src/messageComposer/middleware/messageComposer/MessageComposerMiddlewareExecutor.ts +2 -0
  71. package/src/messageComposer/middleware/messageComposer/compositionValidation.ts +40 -47
  72. package/src/messageComposer/middleware/messageComposer/index.ts +1 -0
  73. package/src/messageComposer/middleware/messageComposer/scheduledMessage.ts +38 -0
  74. package/src/messageComposer/middleware/textComposer/commandUtils.ts +8 -0
  75. package/src/messageComposer/scheduledMessageComposition.ts +324 -0
  76. package/src/messageMarks/MessageMarkManager.ts +145 -0
  77. package/src/messageMarks/index.ts +1 -0
  78. package/src/messageOperations/MessageOperationStatePolicy.ts +7 -0
  79. package/src/messageOperations/MessageOperations.ts +154 -1
  80. package/src/messageOperations/index.ts +1 -0
  81. package/src/messageOperations/reflectMessageMarkEvent.ts +47 -0
  82. package/src/messageOperations/reflectReactionEvent.ts +3 -0
  83. package/src/messageOperations/sendOrdering.ts +11 -4
  84. package/src/messageOperations/types.ts +6 -2
  85. package/src/notifications/types.ts +4 -0
  86. package/src/offline-support/offline_support_api.ts +61 -1
  87. package/src/offline-support/queueableOperations.ts +6 -0
  88. package/src/offline-support/types.ts +28 -0
  89. package/src/pagination/PaginatorView.ts +103 -0
  90. package/src/pagination/index.ts +1 -0
  91. package/src/pagination/paginators/BasePaginator.ts +204 -29
  92. package/src/pagination/paginators/ChannelPaginator.ts +8 -28
  93. package/src/pagination/paginators/MessageIntervalPaginator.ts +14 -1
  94. package/src/pagination/paginators/MessageMarkPaginator.ts +222 -0
  95. package/src/pagination/paginators/ScheduledMessagePaginator.ts +352 -0
  96. package/src/pagination/paginators/index.ts +2 -0
  97. package/src/scheduledMessages/ScheduledMessagePaginatorsManager.ts +268 -0
  98. package/src/scheduledMessages/ScheduledMessageStatePolicy.ts +42 -0
  99. package/src/scheduledMessages/ScheduledMessagesView.ts +57 -0
  100. package/src/scheduledMessages/composition.ts +129 -0
  101. package/src/scheduledMessages/constants.ts +79 -0
  102. package/src/scheduledMessages/editResolvers.ts +51 -0
  103. package/src/scheduledMessages/errors.ts +45 -0
  104. package/src/scheduledMessages/eventHandlers.ts +58 -0
  105. package/src/scheduledMessages/index.ts +7 -0
  106. package/src/scheduledMessages/limits.ts +32 -0
  107. package/src/scheduledMessages/types.ts +124 -0
  108. package/src/thread.ts +41 -17
  109. package/src/utils.ts +18 -0
package/src/channel.ts CHANGED
@@ -5,11 +5,24 @@ import { queueOrRun } from './offline-support/queueableOperations';
5
5
  import { MessageComposer } from './messageComposer';
6
6
  import { MessageReceiptsTracker } from './messageDelivery';
7
7
  import type { ReadStoreReconcileMeta } from './messageDelivery';
8
- import { MessagePaginator, PinnedMessagePaginator } from './pagination/paginators';
9
- import { createMessageOperations, reflectReactionEvent } from './messageOperations';
8
+ import {
9
+ MessagePaginator,
10
+ PinnedMessagePaginator,
11
+ ScheduledMessagePaginator,
12
+ } from './pagination/paginators';
13
+ import {
14
+ createMessageOperations,
15
+ reflectMessageMarkEvent,
16
+ reflectReactionEvent,
17
+ } from './messageOperations';
10
18
  import type { MessageOperations } from './messageOperations';
11
19
  import type { OperationRequestFn } from './messageOperations/types';
20
+ import type { ScheduledMessageRequestHandlers } from './scheduledMessages/types';
21
+ import { getScheduledMessageLimitsFromServerConfig } from './scheduledMessages/limits';
22
+ import { getScheduledMessageFromEvent } from './scheduledMessages/eventHandlers';
23
+ import { ScheduledMessagesView } from './scheduledMessages/ScheduledMessagesView';
12
24
  import {
25
+ channelCanScheduleMessages,
13
26
  channelHasReadEvents,
14
27
  formatMessage,
15
28
  generateChannelTempCid,
@@ -17,6 +30,7 @@ import {
17
30
  invokeEventListener,
18
31
  isThreadOnlyReply,
19
32
  logChatPromiseExecution,
33
+ runDetached,
20
34
  sanitizeOutgoingAttachments,
21
35
  } from './utils';
22
36
  import { getCarriedActiveMemberCount } from './utils/activeMemberCount';
@@ -78,6 +92,7 @@ import type {
78
92
  ChannelPushPreferencesResponse as Gen_ChannelPushPreferencesResponse,
79
93
  MuteChannelRequest as Gen_MuteChannelRequest,
80
94
  UnmuteChannelRequest as Gen_UnmuteChannelRequest,
95
+ ScheduledMessageResponse,
81
96
  UploadChannelFileRequest,
82
97
  UploadChannelRequest,
83
98
  WSEvent,
@@ -123,7 +138,7 @@ export type ChannelConfig = {
123
138
  sendMessageRequest?: OperationRequestFn<'send'>;
124
139
  retrySendMessageRequest?: OperationRequestFn<'retry'>;
125
140
  updateMessageRequest?: OperationRequestFn<'update'>;
126
- };
141
+ } & ScheduledMessageRequestHandlers;
127
142
  /**
128
143
  * Typing indicators. Defaults to enabled. ANDed with the channel type's `typing_events`. Read by
129
144
  * {@link Channel.keystroke} and {@link Channel.stopTyping}.
@@ -147,6 +162,7 @@ export type ChannelConfig = {
147
162
  * Message reminders. Defaults to enabled. ANDed with the channel type's `user_message_reminders`.
148
163
  */
149
164
  userMessageReminders: { enabled: boolean };
165
+ scheduledMessages: { enabled: boolean };
150
166
  /** Delivery receipts. Defaults to enabled. ANDed with the channel type's `delivery_events`. */
151
167
  deliveryEvents: { enabled: boolean };
152
168
  /**
@@ -154,6 +170,11 @@ export type ChannelConfig = {
154
170
  * command can be used right now is `messageComposer.isCommandDisabled(command)`.
155
171
  */
156
172
  availableCommands: Command[];
173
+ /**
174
+ * The message mark types the channel type accepts, for instance `played`. Server-owned: the
175
+ * integrator cannot set it. Empty when message marks are off for the channel type.
176
+ */
177
+ markTypes: string[];
157
178
  };
158
179
 
159
180
  /**
@@ -171,6 +192,7 @@ const ownDeclarativeConfig = (
171
192
  readEvents,
172
193
  replies,
173
194
  requestHandlers,
195
+ scheduledMessages,
174
196
  typingEvents,
175
197
  userMessageReminders,
176
198
  } = slice;
@@ -180,6 +202,7 @@ const ownDeclarativeConfig = (
180
202
  readEvents,
181
203
  replies,
182
204
  requestHandlers,
205
+ scheduledMessages,
183
206
  typingEvents,
184
207
  userMessageReminders,
185
208
  } as Partial<ChannelConfig>;
@@ -188,8 +211,10 @@ const ownDeclarativeConfig = (
188
211
  export const DEFAULT_CHANNEL_CONFIG: ChannelConfig = deepFreezeConfig({
189
212
  availableCommands: [],
190
213
  deliveryEvents: { enabled: true },
214
+ markTypes: [],
191
215
  readEvents: { enabled: true, localUnreadCountEnabled: false },
192
216
  replies: { enabled: true },
217
+ scheduledMessages: { enabled: true },
193
218
  typingEvents: { enabled: true },
194
219
  userMessageReminders: { enabled: true },
195
220
  });
@@ -223,6 +248,17 @@ export class Channel extends ChannelApi {
223
248
  public readonly messageOperations: MessageOperations;
224
249
  public readonly messagePaginator: MessagePaginator;
225
250
  public readonly pinnedMessagesPaginator: PinnedMessagePaginator;
251
+ /**
252
+ * The current user's scheduled messages in this channel, thread replies included. Filled by the
253
+ * channel query (`include_scheduled_messages`), so it queries only when the response leaves them
254
+ * out. Events can define `items` before a page loads: check `hasLoadedPage`.
255
+ */
256
+ public readonly scheduledMessagesPaginator: ScheduledMessagePaginator;
257
+ /**
258
+ * The channel's own scheduled messages: a view of `scheduledMessagesPaginator` without the
259
+ * thread replies it holds too. A thread's are `thread.scheduledMessages`.
260
+ */
261
+ public readonly scheduledMessages: ScheduledMessagesView;
226
262
  public readonly cooldownTimer: CooldownTimer;
227
263
  private unsubscribeConfiguration?: Unsubscribe;
228
264
  private unsubscribeServerConfig?: Unsubscribe;
@@ -298,6 +334,21 @@ export class Channel extends ChannelApi {
298
334
  channel: this,
299
335
  paginatorOptions: { declarativeConfig: declarativeConfig?.pinnedMessagesPaginator },
300
336
  });
337
+ this.scheduledMessagesPaginator = new ScheduledMessagePaginator({
338
+ client,
339
+ // a channel created from its members gets its cid from its first query (`storeUnderServerCid`)
340
+ filter: { cid: this.cid },
341
+ id: `scheduled-message-paginator-${this.cid}`,
342
+ paginatorOptions: {
343
+ declarativeConfig: declarativeConfig?.scheduledMessagesPaginator,
344
+ },
345
+ });
346
+
347
+ this.scheduledMessages = new ScheduledMessagesView({
348
+ paginator: this.scheduledMessagesPaginator,
349
+ scope: { type: 'channel' },
350
+ });
351
+ this.scheduledMessages.registerSubscriptions();
301
352
 
302
353
  this.messageReceiptsTracker = new MessageReceiptsTracker({ channel: this });
303
354
  this.messageReceiptsTracker.registerSubscriptions();
@@ -326,6 +377,7 @@ export class Channel extends ChannelApi {
326
377
  ) as ChannelConfig),
327
378
  // Assigned, not merged: the deep merge would concatenate the lists.
328
379
  availableCommands: this.serverConfig?.commands ?? [],
380
+ markTypes: this.serverConfig?.mark_types ?? [],
329
381
  }),
330
382
  ) as ChannelConfig,
331
383
  });
@@ -366,6 +418,11 @@ export class Channel extends ChannelApi {
366
418
  deliveryEvents: { enabled: channelConfig?.delivery_events },
367
419
  readEvents: { enabled: channelConfig?.read_events },
368
420
  replies: { enabled: channelConfig?.replies },
421
+ scheduledMessages: {
422
+ enabled: channelConfig
423
+ ? !!getScheduledMessageLimitsFromServerConfig(channelConfig)
424
+ : undefined,
425
+ },
369
426
  typingEvents: { enabled: channelConfig?.typing_events },
370
427
  userMessageReminders: { enabled: channelConfig?.user_message_reminders },
371
428
  };
@@ -399,6 +456,9 @@ export class Channel extends ChannelApi {
399
456
  this.pinnedMessagesPaginator.initializeConfig(
400
457
  declarativeConfig?.pinnedMessagesPaginator,
401
458
  );
459
+ this.scheduledMessagesPaginator.initializeConfig(
460
+ declarativeConfig?.scheduledMessagesPaginator,
461
+ );
402
462
 
403
463
  // Shared key with a per-parent override, as for `messagePaginator`.
404
464
  this.messageOperations.initializeConfig(
@@ -461,10 +521,122 @@ export class Channel extends ChannelApi {
461
521
  );
462
522
  }
463
523
 
524
+ /**
525
+ * Fills the list from a channel query's `scheduled_messages`.
526
+ *
527
+ * @internal
528
+ */
529
+ hydrateScheduledMessages(
530
+ scheduledMessages: ScheduledMessageResponse[],
531
+ itemIdsAtRequest?: ReadonlySet<string>,
532
+ ) {
533
+ // a response landing after logout would bring the previous user's messages back
534
+ if (this.pendingDisposal || !this.config.scheduledMessages.enabled) return;
535
+ this.scheduledMessagesPaginator.hydrate(scheduledMessages, itemIdsAtRequest);
536
+ }
537
+
538
+ /** Without the field (over 100, or unreadable), a list that had loaded reloads itself. */
539
+ private applyScheduledMessagesFromResponse(
540
+ scheduledMessages: ScheduledMessageResponse[] | undefined,
541
+ itemIdsAtRequest: ReadonlySet<string> | undefined,
542
+ ) {
543
+ if (scheduledMessages) {
544
+ this.hydrateScheduledMessages(scheduledMessages, itemIdsAtRequest);
545
+ return;
546
+ }
547
+ const paginator = this.scheduledMessagesPaginator;
548
+ if (this.pendingDisposal || !paginator.hasLoadedPage || paginator.isLoading) return;
549
+ runDetached(paginator.reload(), { context: 'reloadScheduledMessages' });
550
+ }
551
+
552
+ ensureScheduledMessagesLoaded() {
553
+ const paginator = this.scheduledMessagesPaginator;
554
+ if (
555
+ this.pendingDisposal ||
556
+ !this.scheduledMessagesEnabled ||
557
+ paginator.hasLoadedPage ||
558
+ paginator.isLoading
559
+ ) {
560
+ return;
561
+ }
562
+ runDetached(paginator.reload(), { context: 'ensureScheduledMessagesLoaded' });
563
+ }
564
+
565
+ async scheduleMessage(...args: Parameters<ChannelApi['sendMessage']>) {
566
+ return await this.sendMessage(...args);
567
+ }
568
+
569
+ async updateScheduledMessage(...args: Parameters<ChatApi['updateScheduledMessage']>) {
570
+ return await this.getClient().updateScheduledMessage(...args);
571
+ }
572
+
573
+ async deleteScheduledMessage(...args: Parameters<ChatApi['deleteScheduledMessage']>) {
574
+ return await this.getClient().deleteScheduledMessage(...args);
575
+ }
576
+
577
+ async sendScheduledMessageNow(...args: Parameters<ChatApi['sendScheduledMessageNow']>) {
578
+ return await this.getClient().sendScheduledMessageNow(...args);
579
+ }
580
+
464
581
  async sendReaction(...args: Parameters<ChatApi['sendReaction']>) {
465
582
  return await this.getClient().sendReaction(...args);
466
583
  }
467
584
 
585
+ /**
586
+ * Marks a message for the current user, for instance `played` when the user played a voice note.
587
+ * A mark is written once: a repeat returns `created: false`, and the author's own mark is a no-op.
588
+ * Each written mark is announced with one `message.mark_added` event to the author and the marker.
589
+ * With offline support, a mark that fails for lack of a connection is queued and sent on reconnect.
590
+ *
591
+ * @param args - `({ id }, { type })`: the message ID and the mark type, for instance `'played'`.
592
+ */
593
+ async sendMessageMark(...args: Parameters<ChatApi['createMessageMark']>) {
594
+ return await queueOrRun({
595
+ channel: this,
596
+ client: this.getClient(),
597
+ task: {
598
+ channelId: this.id,
599
+ channelType: this.type,
600
+ messageId: args[0].id,
601
+ payload: args,
602
+ type: 'send-message-mark',
603
+ },
604
+ });
605
+ }
606
+
607
+ /**
608
+ * Marks a message `played` for the current user, for instance when the user starts its voice note.
609
+ * Sends nothing when the channel type has no `played` mark ({@link ChannelConfig.markTypes}) or
610
+ * without the `send-message-mark` capability. When the client holds the message, it also sends
611
+ * nothing for the user's own message or a message the user already marked. Otherwise the server
612
+ * ignores those. The message changes only when `message.mark_added` arrives, as with read state.
613
+ *
614
+ * @param messageId - The ID of the played message.
615
+ * @returns The server response, or `null` when no request went out.
616
+ */
617
+ async markMessagePlayed(messageId: string) {
618
+ const userId = this.getClient().userId;
619
+ const ownCapabilities = this.data?.own_capabilities;
620
+ if (
621
+ !userId ||
622
+ !this.config.markTypes.includes('played') ||
623
+ (Array.isArray(ownCapabilities) && !ownCapabilities.includes('send-message-mark'))
624
+ ) {
625
+ return null;
626
+ }
627
+
628
+ const message = this.getClient().messageStore.get(messageId);
629
+ if (
630
+ message &&
631
+ (message.user?.id === userId ||
632
+ message.own_marks?.some(({ type }) => type === 'played'))
633
+ ) {
634
+ return null;
635
+ }
636
+
637
+ return await this.sendMessageMark({ id: messageId }, { type: 'played' });
638
+ }
639
+
468
640
  async deleteReaction(...args: Parameters<ChatApi['deleteReaction']>) {
469
641
  return await this.getClient().deleteReaction(...args);
470
642
  }
@@ -1114,6 +1286,10 @@ export class Channel extends ChannelApi {
1114
1286
  return this.config.readEvents.enabled && channelHasReadEvents(this);
1115
1287
  }
1116
1288
 
1289
+ get scheduledMessagesEnabled(): boolean {
1290
+ return this.config.scheduledMessages.enabled && channelCanScheduleMessages(this);
1291
+ }
1292
+
1117
1293
  /**
1118
1294
  * Marks read through `MessageDeliveryReporter`: uses the `markReadRequest` handler if set, marks
1119
1295
  * read locally when read events are off and `localUnreadCountEnabled` is set, and drops the
@@ -1739,6 +1915,8 @@ export class Channel extends ChannelApi {
1739
1915
  const { channelManager } = this.getClient();
1740
1916
  const storedUnder = this.cid;
1741
1917
  this.cid = serverCid;
1918
+ if (storedUnder !== serverCid)
1919
+ this.scheduledMessagesPaginator.filter = { cid: serverCid };
1742
1920
  const isStoredUnderOldCid =
1743
1921
  storedUnder !== serverCid && channelManager.get(storedUnder) === this;
1744
1922
  // A disconnected channel is replaced by this instance, not superseded by it.
@@ -1808,10 +1986,19 @@ export class Channel extends ChannelApi {
1808
1986
  const externalQuery = placeMessages
1809
1987
  ? this.messagePaginator.prepareExternalQuery(options.messages)
1810
1988
  : undefined;
1989
+ // free when the app has no scheduled messages: the server omits the field
1990
+ const includeScheduledMessages =
1991
+ this.config.scheduledMessages.enabled &&
1992
+ options.include_scheduled_messages !== false;
1993
+ // tells messages arriving during the request apart, so the response does not drop them
1994
+ const scheduledMessageIdsAtRequest = this.scheduledMessagesPaginator.getItemIds();
1811
1995
  const state = await this.requestChannelState(
1812
- externalQuery
1813
- ? { ...options, messages: externalQuery.messagePaginationParams }
1814
- : options,
1996
+ {
1997
+ ...(includeScheduledMessages && { include_scheduled_messages: true }),
1998
+ ...(externalQuery
1999
+ ? { ...options, messages: externalQuery.messagePaginationParams }
2000
+ : options),
2001
+ },
1815
2002
  requestOptions,
1816
2003
  { placesNewestPage: externalQuery?.isNewestPage ?? false },
1817
2004
  );
@@ -1830,6 +2017,13 @@ export class Channel extends ChannelApi {
1830
2017
  });
1831
2018
  }
1832
2019
  if (placedFirstPage) this.messagePaginator.seedUnreadSnapshot();
2020
+ if (includeScheduledMessages) {
2021
+ // a channel created from members may have been superseded by the stored instance
2022
+ (this.supersededBy ?? this).applyScheduledMessagesFromResponse(
2023
+ state.scheduled_messages,
2024
+ scheduledMessageIdsAtRequest,
2025
+ );
2026
+ }
1833
2027
  return state;
1834
2028
  });
1835
2029
  }
@@ -2676,7 +2870,12 @@ export class Channel extends ChannelApi {
2676
2870
  event.channel?.frozen !== undefined &&
2677
2871
  event.channel.frozen !== channel.data?.frozen;
2678
2872
  if (isFrozenChanged) {
2679
- this.query({ state: false, messages: { limit: 0 }, watchers: { limit: 0 } });
2873
+ this.query({
2874
+ include_scheduled_messages: false,
2875
+ messages: { limit: 0 },
2876
+ state: false,
2877
+ watchers: { limit: 0 },
2878
+ });
2680
2879
  }
2681
2880
  const newChannelData = {
2682
2881
  ...event.channel,
@@ -2688,6 +2887,11 @@ export class Channel extends ChannelApi {
2688
2887
  channel.data = newChannelData;
2689
2888
  }
2690
2889
  break;
2890
+ case 'message.mark_added':
2891
+ if (event.mark) {
2892
+ reflectMessageMarkEvent(this.getClient(), event.mark);
2893
+ }
2894
+ break;
2691
2895
  case 'reaction.new':
2692
2896
  case 'reaction.updated':
2693
2897
  case 'reaction.deleted':
@@ -2740,6 +2944,17 @@ export class Channel extends ChannelApi {
2740
2944
  };
2741
2945
  break;
2742
2946
  }
2947
+ case 'scheduled_message.created':
2948
+ case 'scheduled_message.deleted':
2949
+ case 'scheduled_message.failed':
2950
+ case 'scheduled_message.sent':
2951
+ case 'scheduled_message.updated': {
2952
+ // the registered lists hear it from `client.scheduledMessagePaginators`
2953
+ const scheduledMessage = getScheduledMessageFromEvent(event);
2954
+ if (scheduledMessage)
2955
+ this.scheduledMessagesPaginator.ingestItem(scheduledMessage);
2956
+ break;
2957
+ }
2743
2958
  default:
2744
2959
  }
2745
2960
 
@@ -2886,6 +3101,13 @@ export class Channel extends ChannelApi {
2886
3101
  const message = this.messagePaginator.getItem(event.message.id);
2887
3102
  if (message) {
2888
3103
  event.message.own_reactions = message.own_reactions;
3104
+ // Events don't carry marks; keep the local ones.
3105
+ if (event.message.mark_groups === undefined && message.mark_groups !== undefined) {
3106
+ event.message.mark_groups = message.mark_groups;
3107
+ }
3108
+ if (event.message.own_marks === undefined && message.own_marks !== undefined) {
3109
+ event.message.own_marks = message.own_marks;
3110
+ }
2889
3111
  }
2890
3112
  }
2891
3113
 
@@ -2946,9 +3168,11 @@ export class Channel extends ChannelApi {
2946
3168
  this.unsubscribeServerConfig = undefined;
2947
3169
  this.messageReceiptsTracker.unregisterSubscriptions();
2948
3170
  this.cooldownTimer.unregisterSubscriptions();
3171
+ this.scheduledMessages.unregisterSubscriptions();
2949
3172
  // Otherwise the message store keeps this channel and its messages alive through its subscribers.
2950
3173
  this.messagePaginator.dispose();
2951
3174
  this.pinnedMessagesPaginator.dispose();
3175
+ this.scheduledMessagesPaginator.dispose();
2952
3176
 
2953
3177
  // One update, last, so subscribers see both together. A deleted channel must not be re-watched.
2954
3178
  this._lastWatchOptions = undefined;
package/src/client.ts CHANGED
@@ -76,7 +76,9 @@ import {
76
76
  } from './connection';
77
77
  import { MessageDeliveryReporter } from './messageDelivery';
78
78
  import { NotificationManager } from './notifications';
79
+ import { MessageMarkManager } from './messageMarks';
79
80
  import { ReminderManager } from './reminders';
81
+ import { ScheduledMessagePaginatorsManager } from './scheduledMessages';
80
82
  import type { AbstractOfflineDB } from './offline-support';
81
83
  import { FixedSizeQueueCache } from './utils/FixedSizeQueueCache';
82
84
  import { isEqual } from './utils/mergeWith/mergeWithCore';
@@ -93,6 +95,7 @@ import type {
93
95
  GetApplicationResponse as Gen_GetApplicationResponse,
94
96
  MarkDeliveredRequest as Gen_MarkDeliveredRequest,
95
97
  ImageUploadRequest,
98
+ ScheduledMessageResponse,
96
99
  WSAuthMessage,
97
100
  WSEvent,
98
101
  } from './gen/models';
@@ -162,6 +165,10 @@ export class StreamChat extends ChatApi {
162
165
  * request with `watch` or `presence` waits here for the handshake (see `requiresConnectionId`).
163
166
  */
164
167
  connectionIdManager: ConnectionIdManager;
168
+ /** Scheduled message lists the integrator registers; a channel's own list is on the channel. */
169
+ scheduledMessagePaginators: ScheduledMessagePaginatorsManager;
170
+ /** One canonical copy of each listed scheduled message, shared by every scheduled message list. */
171
+ scheduledMessageStore: EntityStore<ScheduledMessageResponse>;
165
172
  /**
166
173
  * Client-global store with one canonical copy of each message. The channel and thread paginators
167
174
  * read and write messages through it, so a message held in several of them stays consistent.
@@ -170,6 +177,8 @@ export class StreamChat extends ChatApi {
170
177
  offlineDb?: AbstractOfflineDB;
171
178
  notifications: NotificationManager;
172
179
  reminders: ReminderManager;
180
+ /** The lists of who marked a message, kept current for the session. */
181
+ messageMarks: MessageMarkManager;
173
182
  axiosInstance: AxiosInstance;
174
183
  baseURL?: string;
175
184
  cleaningIntervalRef?: ReturnType<typeof setTimeout>;
@@ -325,13 +334,19 @@ export class StreamChat extends ChatApi {
325
334
  this.messageStore = new EntityStore<LocalMessage>({
326
335
  getEntityId: (message) => message.id,
327
336
  });
328
- // Before the managers that claim channels in its store.
337
+ this.scheduledMessageStore = new EntityStore<ScheduledMessageResponse>({
338
+ getEntityId: ({ id }) => id,
339
+ });
329
340
  this.channelManager = new ChannelManager({ client: this });
330
341
  this.threads = new ThreadManager({ client: this });
331
342
  this.polls = new PollManager({ client: this });
332
343
  this.connectionRecovery = new ConnectionRecoveryManager({ client: this });
333
344
  this.connectionRecovery.registerSubscriptions();
334
345
  this.reminders = new ReminderManager({ client: this });
346
+ this.messageMarks = new MessageMarkManager({ client: this });
347
+ this.scheduledMessagePaginators = new ScheduledMessagePaginatorsManager({
348
+ client: this,
349
+ });
335
350
  this.messageDeliveryReporter = new MessageDeliveryReporter({ client: this });
336
351
  this.messageComposerCache = new FixedSizeQueueCache<string, MessageComposer>(64);
337
352
  // a cached composer, such as a message edit's, keeps the channel it was built with
@@ -764,6 +779,9 @@ export class StreamChat extends ChatApi {
764
779
  }
765
780
  this.state = new ClientState({ client: this });
766
781
  this.threads.resetState();
782
+ this.messageMarks.clear();
783
+ this.scheduledMessagePaginators.resetPaginatorStates();
784
+ this.scheduledMessageStore.clear();
767
785
  // Channel mutes are per-user: stale ones would resolve `muted` filters against the previous
768
786
  // user.
769
787
  this.mutedChannels = [];
@@ -1443,7 +1461,22 @@ export class StreamChat extends ChatApi {
1443
1461
  const idsAtRequest = channel.messagePaginator?.getHeadIntervalItemIdsAtRequest();
1444
1462
  if (idsAtRequest) headIntervalItemIdsAtRequestByCid.set(channel.cid, idsAtRequest);
1445
1463
  }
1446
- const queryChannelsResponse = await this.queryChannels(options, requestOptions);
1464
+ const scheduledMessageIdsAtRequestByCid = new Map<string, ReadonlySet<string>>();
1465
+ for (const channel of this.channelManager.values()) {
1466
+ scheduledMessageIdsAtRequestByCid.set(
1467
+ channel.cid,
1468
+ channel.scheduledMessagesPaginator.getItemIds(),
1469
+ );
1470
+ }
1471
+ // free when the app has no scheduled messages: the server omits the field
1472
+ const includeScheduledMessages =
1473
+ this.config.getConfig('channel')?.scheduledMessages?.enabled !== false;
1474
+ const queryChannelsResponse = await this.queryChannels(
1475
+ includeScheduledMessages
1476
+ ? { include_scheduled_messages: true, ...options }
1477
+ : options,
1478
+ requestOptions,
1479
+ );
1447
1480
  const channels = queryChannelsResponse.channels;
1448
1481
 
1449
1482
  this.dispatchEvent({
@@ -1466,6 +1499,17 @@ export class StreamChat extends ChatApi {
1466
1499
  options,
1467
1500
  headIntervalItemIdsAtRequestByCid,
1468
1501
  );
1502
+ // Absent from every channel past 100 in total: the lists keep what they hold rather than each
1503
+ // sending a query.
1504
+ for (const { channel, scheduled_messages } of channels ?? []) {
1505
+ if (!channel || !scheduled_messages) continue;
1506
+ this.channelManager
1507
+ .get(channel.cid)
1508
+ ?.hydrateScheduledMessages(
1509
+ scheduled_messages,
1510
+ scheduledMessageIdsAtRequestByCid.get(channel.cid),
1511
+ );
1512
+ }
1469
1513
 
1470
1514
  if (stateOptions.withResponse) {
1471
1515
  return {
@@ -58,6 +58,8 @@ export const CONSTRUCTION_ONLY_CONFIG_PATHS: Readonly<Record<string, readonly st
58
58
  'messagePaginator.unreadReferencePolicy',
59
59
  'pinnedMessagesPaginator.initialCursor',
60
60
  'pinnedMessagesPaginator.initialOffset',
61
+ 'scheduledMessagesPaginator.initialCursor',
62
+ 'scheduledMessagesPaginator.initialOffset',
61
63
  ],
62
64
  thread: [
63
65
  'messagePaginator.initialCursor',
@@ -612,6 +612,9 @@ const CHANNEL_FIELDS: Record<keyof ChannelDeclarativeConfig, ConfigNode> = {
612
612
  "The channel's pinned message list. Nested rather than top-level: a channel is its only parent.",
613
613
  ),
614
614
  requestHandlers: REQUEST_HANDLERS_NODE,
615
+ scheduledMessagesPaginator: paginatorGroup(
616
+ "The current user's scheduled messages in the channel. Filled by the channel query; it queries only when the channel query leaves them out, at most 100 per page.",
617
+ ),
615
618
  typingEvents: {
616
619
  description: 'Typing indicators for the channel.',
617
620
  fields: {
@@ -636,6 +639,18 @@ const CHANNEL_FIELDS: Record<keyof ChannelDeclarativeConfig, ConfigNode> = {
636
639
  },
637
640
  kind: 'group',
638
641
  },
642
+ scheduledMessages: {
643
+ description: 'Scheduling messages to be sent later.',
644
+ fields: {
645
+ enabled: {
646
+ description:
647
+ 'Offers scheduling messages. The app must also have the feature (its scheduled message limits are in the channel server config), and a server "no" wins. Without the own `schedule-message` capability scheduling stays off.',
648
+ kind: 'value',
649
+ type: 'boolean',
650
+ },
651
+ },
652
+ kind: 'group',
653
+ },
639
654
  userMessageReminders: {
640
655
  description: 'Message reminders: "remind me" and "save for later".',
641
656
  fields: {
@@ -86,6 +86,7 @@ export type ChannelDeclarativeConfig = {
86
86
  messagePaginator?: DeclarativeMessagePaginatorConfig;
87
87
  pinnedMessagesPaginator?: ImportedDeclarativePaginatorConfig;
88
88
  requestHandlers?: ChannelConfig['requestHandlers'];
89
+ scheduledMessagesPaginator?: ImportedDeclarativePaginatorConfig;
89
90
  /** Typing indicators, ANDed with the channel type's `typing_events`. */
90
91
  typingEvents?: Partial<ChannelConfig['typingEvents']>;
91
92
  /** Read receipts, ANDed with the channel type's `read_events`. */
@@ -94,9 +95,10 @@ export type ChannelDeclarativeConfig = {
94
95
  replies?: Partial<ChannelConfig['replies']>;
95
96
  /** Message reminders, ANDed with the channel type's `user_message_reminders`. */
96
97
  userMessageReminders?: Partial<ChannelConfig['userMessageReminders']>;
98
+ scheduledMessages?: Partial<ChannelConfig['scheduledMessages']>;
97
99
  /** Delivery receipts, ANDed with the channel type's `delivery_events`. */
98
100
  deliveryEvents?: Partial<ChannelConfig['deliveryEvents']>;
99
- // `commands` is absent: the server owns the list.
101
+ // `commands` and `mark_types` are absent: the server owns the lists.
100
102
  };
101
103
 
102
104
  export type ThreadDeclarativeConfig = {
@@ -141,6 +141,9 @@ export class ConnectionRecoveryManager extends WithSubscriptions {
141
141
  private handleReconnect() {
142
142
  if (this.config.enabled) {
143
143
  runDetached(this.recoverChannelLists(), { context: 'recoverChannelLists' });
144
+ runDetached(this.recoverScheduledMessageLists(), {
145
+ context: 'recoverScheduledMessageLists',
146
+ });
144
147
  runDetached(this.recoverActiveChannels(), { context: 'recoverActiveChannels' });
145
148
  return;
146
149
  }
@@ -191,6 +194,10 @@ export class ConnectionRecoveryManager extends WithSubscriptions {
191
194
  await this.client.channelManager.recover();
192
195
  };
193
196
 
197
+ private recoverScheduledMessageLists = async () => {
198
+ await this.client.scheduledMessagePaginators.recover();
199
+ };
200
+
194
201
  private recoverActiveChannels = async ({ isRetry = false } = {}): Promise<void> => {
195
202
  if (this.isRecovering) {
196
203
  this.recoveryRequestedAgain = true;
package/src/errors.ts CHANGED
@@ -31,6 +31,17 @@ export const APIErrorCodes: Record<string, { name: string; retryable: boolean }>
31
31
  '70': { name: 'ErrQueryChannelPermissions', retryable: false },
32
32
  '71': { name: 'ErrTooManyConnections', retryable: true },
33
33
  '99': { name: 'AppSuspendedError', retryable: false },
34
+ '114': { name: 'ScheduledMessagesDisabledError', retryable: false },
35
+ '115': { name: 'ScheduledAtTooSoonError', retryable: false },
36
+ '116': { name: 'ScheduledAtTooFarError', retryable: false },
37
+ '117': { name: 'ScheduledLimitChannelError', retryable: false },
38
+ '118': { name: 'ScheduledLimitUserError', retryable: false },
39
+ '119': { name: 'ScheduledMessageIDTakenError', retryable: false },
40
+ '120': { name: 'ScheduledMessageNotEditableError', retryable: false },
41
+ '121': { name: 'ScheduledMessageSendingError', retryable: false },
42
+ '122': { name: 'ScheduledMessageConflictError', retryable: false },
43
+ '123': { name: 'ScheduledMessageAlreadySentError', retryable: false },
44
+ '124': { name: 'ScheduledMessageCanceledError', retryable: false },
34
45
  };
35
46
 
36
47
  export type APIError = Error & {