stream-chat 10.2.0 → 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 (108) hide show
  1. package/dist/cjs/index.browser.js +4712 -2818
  2. package/dist/cjs/index.browser.js.map +4 -4
  3. package/dist/cjs/index.node.js +4733 -2818
  4. package/dist/cjs/index.node.js.map +4 -4
  5. package/dist/esm/index.mjs +4712 -2818
  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 +41 -0
  37. package/dist/types/pagination/paginators/ChannelPaginator.d.ts +0 -9
  38. package/dist/types/pagination/paginators/MessageMarkPaginator.d.ts +61 -0
  39. package/dist/types/pagination/paginators/ScheduledMessagePaginator.d.ts +83 -0
  40. package/dist/types/pagination/paginators/index.d.ts +2 -0
  41. package/dist/types/scheduledMessages/ScheduledMessagePaginatorsManager.d.ts +47 -0
  42. package/dist/types/scheduledMessages/ScheduledMessageStatePolicy.d.ts +12 -0
  43. package/dist/types/scheduledMessages/ScheduledMessagesView.d.ts +38 -0
  44. package/dist/types/scheduledMessages/composition.d.ts +5 -0
  45. package/dist/types/scheduledMessages/constants.d.ts +56 -0
  46. package/dist/types/scheduledMessages/editResolvers.d.ts +4 -0
  47. package/dist/types/scheduledMessages/errors.d.ts +3 -0
  48. package/dist/types/scheduledMessages/eventHandlers.d.ts +8 -0
  49. package/dist/types/scheduledMessages/index.d.ts +7 -0
  50. package/dist/types/scheduledMessages/limits.d.ts +6 -0
  51. package/dist/types/scheduledMessages/types.d.ts +65 -0
  52. package/dist/types/thread.d.ts +12 -1
  53. package/dist/types/utils.d.ts +7 -0
  54. package/package.json +1 -1
  55. package/src/channel.ts +231 -7
  56. package/src/client.ts +46 -2
  57. package/src/configuration/keys.ts +2 -0
  58. package/src/configuration/shape.ts +15 -0
  59. package/src/configuration/types.ts +3 -1
  60. package/src/connection/ConnectionRecoveryManager.ts +7 -0
  61. package/src/errors.ts +11 -0
  62. package/src/gen/chat/ChatApi.ts +60 -3
  63. package/src/gen/models/index.ts +794 -23
  64. package/src/gen/moderation/ModerationApi.ts +24 -3
  65. package/src/index.ts +2 -0
  66. package/src/messageComposer/attachmentManager.ts +43 -24
  67. package/src/messageComposer/index.ts +1 -0
  68. package/src/messageComposer/messageComposer.ts +140 -32
  69. package/src/messageComposer/middleware/messageComposer/MessageComposerMiddlewareExecutor.ts +2 -0
  70. package/src/messageComposer/middleware/messageComposer/compositionValidation.ts +40 -47
  71. package/src/messageComposer/middleware/messageComposer/index.ts +1 -0
  72. package/src/messageComposer/middleware/messageComposer/scheduledMessage.ts +38 -0
  73. package/src/messageComposer/middleware/textComposer/commandUtils.ts +8 -0
  74. package/src/messageComposer/scheduledMessageComposition.ts +324 -0
  75. package/src/messageMarks/MessageMarkManager.ts +145 -0
  76. package/src/messageMarks/index.ts +1 -0
  77. package/src/messageOperations/MessageOperationStatePolicy.ts +7 -0
  78. package/src/messageOperations/MessageOperations.ts +154 -1
  79. package/src/messageOperations/index.ts +1 -0
  80. package/src/messageOperations/reflectMessageMarkEvent.ts +47 -0
  81. package/src/messageOperations/reflectReactionEvent.ts +3 -0
  82. package/src/messageOperations/sendOrdering.ts +11 -4
  83. package/src/messageOperations/types.ts +6 -2
  84. package/src/notifications/types.ts +4 -0
  85. package/src/offline-support/offline_support_api.ts +61 -1
  86. package/src/offline-support/queueableOperations.ts +6 -0
  87. package/src/offline-support/types.ts +28 -0
  88. package/src/pagination/PaginatorView.ts +103 -0
  89. package/src/pagination/index.ts +1 -0
  90. package/src/pagination/paginators/BasePaginator.ts +179 -27
  91. package/src/pagination/paginators/ChannelPaginator.ts +8 -28
  92. package/src/pagination/paginators/MessageIntervalPaginator.ts +4 -1
  93. package/src/pagination/paginators/MessageMarkPaginator.ts +222 -0
  94. package/src/pagination/paginators/ScheduledMessagePaginator.ts +352 -0
  95. package/src/pagination/paginators/index.ts +2 -0
  96. package/src/scheduledMessages/ScheduledMessagePaginatorsManager.ts +268 -0
  97. package/src/scheduledMessages/ScheduledMessageStatePolicy.ts +42 -0
  98. package/src/scheduledMessages/ScheduledMessagesView.ts +57 -0
  99. package/src/scheduledMessages/composition.ts +129 -0
  100. package/src/scheduledMessages/constants.ts +79 -0
  101. package/src/scheduledMessages/editResolvers.ts +51 -0
  102. package/src/scheduledMessages/errors.ts +45 -0
  103. package/src/scheduledMessages/eventHandlers.ts +58 -0
  104. package/src/scheduledMessages/index.ts +7 -0
  105. package/src/scheduledMessages/limits.ts +32 -0
  106. package/src/scheduledMessages/types.ts +124 -0
  107. package/src/thread.ts +41 -17
  108. package/src/utils.ts +18 -0
@@ -0,0 +1,352 @@
1
+ import type {
2
+ PaginationQueryParams,
3
+ PaginationQueryReturnValue,
4
+ PaginatorOptions,
5
+ } from './BasePaginator';
6
+ import { BasePaginator, ZERO_PAGE_CURSOR } from './BasePaginator';
7
+ import { StoreBackedItemIndex } from '../../entityStore/StoreBackedItemIndex';
8
+ import type { EntityStore, EntityStoreChangeBatch } from '../../entityStore/EntityStore';
9
+ import type { StreamChat } from '../../client';
10
+ import type {
11
+ QueryScheduledMessagesRequest,
12
+ ScheduledMessageResponse,
13
+ ScheduledMessagesFilter,
14
+ } from '../../gen/models';
15
+ import { SCHEDULED_MESSAGE_ACTIVE_STATUSES } from '../../scheduledMessages/constants';
16
+ import { generateUUIDv4 } from '../../utils';
17
+
18
+ export type ScheduledMessagePaginatorOptions = {
19
+ client: StreamChat;
20
+ /**
21
+ * The query filter, also deciding which ingested messages the list takes. `status` defaults to all
22
+ * the query accepts. Changed later through the `filter` setter.
23
+ */
24
+ filter?: ScheduledMessagesFilter;
25
+ /** Generated when omitted. */
26
+ id?: string;
27
+ paginatorOptions?: PaginatorOptions<
28
+ ScheduledMessageResponse,
29
+ QueryScheduledMessagesRequest
30
+ >;
31
+ /** Defaults to `client.scheduledMessageStore`. */
32
+ store?: EntityStore<ScheduledMessageResponse>;
33
+ };
34
+
35
+ const SCHEDULED_MESSAGES_PAGE_SIZE = 100;
36
+
37
+ const getScheduledMessageId = ({ id }: ScheduledMessageResponse) => id;
38
+
39
+ const compareValues = <TValue extends number | string>(first: TValue, second: TValue) =>
40
+ first < second ? -1 : first > second ? 1 : 0;
41
+
42
+ // Earliest first. Failed messages need no rule of their own: they failed at their send time, so they
43
+ // precede the pending ones. Ties break on `created_at` then `id`, both stable under edits.
44
+ const defaultScheduledMessagesComparator = (
45
+ first: ScheduledMessageResponse,
46
+ second: ScheduledMessageResponse,
47
+ ) =>
48
+ compareValues<number>(first.scheduled_at, second.scheduled_at) ||
49
+ compareValues<number>(first.created_at, second.created_at) ||
50
+ compareValues(first.id, second.id);
51
+
52
+ /** The current user's scheduled messages, earliest `scheduled_at` first. */
53
+ export class ScheduledMessagePaginator extends BasePaginator<
54
+ ScheduledMessageResponse,
55
+ QueryScheduledMessagesRequest
56
+ > {
57
+ private readonly client: StreamChat;
58
+ private readonly _id: string;
59
+ private _filter: ScheduledMessagesFilter;
60
+
61
+ constructor({
62
+ client,
63
+ filter = {},
64
+ id,
65
+ paginatorOptions,
66
+ store,
67
+ }: ScheduledMessagePaginatorOptions) {
68
+ const entityStore = store ?? client.scheduledMessageStore;
69
+ super(
70
+ {
71
+ initialCursor: ZERO_PAGE_CURSOR,
72
+ createItemIndex: (owner) =>
73
+ new StoreBackedItemIndex<ScheduledMessageResponse>({
74
+ getEntityId: getScheduledMessageId,
75
+ holderName: 'scheduled-message-paginator',
76
+ owner: owner as ScheduledMessagePaginator,
77
+ store: entityStore,
78
+ }),
79
+ ...paginatorOptions,
80
+ },
81
+ { newItemsAnchorBySortPosition: true, pageSize: SCHEDULED_MESSAGES_PAGE_SIZE },
82
+ );
83
+
84
+ this.client = client;
85
+ this._id = id ?? `scheduled-message-paginator-${generateUUIDv4()}`;
86
+ this._filter = filter;
87
+ this.sortComparator = defaultScheduledMessagesComparator;
88
+ }
89
+
90
+ get id() {
91
+ return this._id;
92
+ }
93
+
94
+ /** The query filter, sent as given: without a `status` the server lists all it lists. */
95
+ get filter(): ScheduledMessagesFilter {
96
+ return this._filter;
97
+ }
98
+
99
+ /** Replaces the filter and resets the list; load it again with `reload()`. */
100
+ set filter(filter: ScheduledMessagesFilter) {
101
+ this._filter = filter;
102
+ this.resetState();
103
+ }
104
+
105
+ get cid() {
106
+ return this.filter.cid;
107
+ }
108
+
109
+ public getItemId(item: ScheduledMessageResponse): string {
110
+ return getScheduledMessageId(item);
111
+ }
112
+
113
+ protected getNextQueryShape(): QueryScheduledMessagesRequest {
114
+ return { filter: this.filter, limit: this.pageSize };
115
+ }
116
+
117
+ /**
118
+ * The query filter, with the server's default statuses when it names none: matching on `status`
119
+ * is what takes sent and canceled messages out of the list. The matcher reads the array as any of
120
+ * them.
121
+ */
122
+ protected buildMatchFilters(): ScheduledMessagesFilter {
123
+ const { cid, status } = this.filter;
124
+ const statuses = status?.length ? status : SCHEDULED_MESSAGE_ACTIVE_STATUSES;
125
+
126
+ // an undefined `cid` would match nothing
127
+ return cid ? { cid, status: statuses } : { status: statuses };
128
+ }
129
+
130
+ protected override fetchQueryResponse = async ({
131
+ direction,
132
+ queryShape,
133
+ }: PaginationQueryParams<QueryScheduledMessagesRequest>): Promise<
134
+ PaginationQueryReturnValue<ScheduledMessageResponse>
135
+ > => {
136
+ const cursor = direction === 'tailward' ? this.cursor?.tailward : undefined;
137
+ const request: QueryScheduledMessagesRequest = {
138
+ ...(queryShape ?? this.getNextQueryShape()),
139
+ ...(cursor ? { next: cursor } : {}),
140
+ };
141
+
142
+ const { next, scheduled_messages: items } =
143
+ await this.client.queryScheduledMessages(request);
144
+
145
+ return { headward: null, items, tailward: next || null };
146
+ };
147
+
148
+ protected override extractQueryPage(
149
+ response: PaginationQueryReturnValue<ScheduledMessageResponse>,
150
+ ) {
151
+ return response;
152
+ }
153
+
154
+ public filterQueryResults(items: ScheduledMessageResponse[]) {
155
+ return items.filter((item) => this.matchesFilter(item));
156
+ }
157
+
158
+ public ingestItem(item: ScheduledMessageResponse): boolean {
159
+ // the list already holds this copy and placed it when it was stored (`onEntitiesChanged` places
160
+ // copies other lists store): nothing to place
161
+ if (this.getItem(item.id) === item) return false;
162
+
163
+ return this.placeItem(item);
164
+ }
165
+
166
+ /** Places `item` by the list's filter and order: moves it, or takes it out when it no longer matches. */
167
+ private placeItem(item: ScheduledMessageResponse) {
168
+ const changed = super.ingestItem(item);
169
+
170
+ if (!this.matchesFilter(item)) this._itemIndex.remove(item.id);
171
+
172
+ return changed;
173
+ }
174
+
175
+ /** The IDs the list holds. */
176
+ public getItemIds(): ReadonlySet<string> {
177
+ return new Set(this._itemIndex.values().map(getScheduledMessageId));
178
+ }
179
+
180
+ /** A page loaded and nothing more to load either way: the list holds every message it matches. */
181
+ private get holdsCompleteList() {
182
+ const { hasMoreHead, hasMoreTail } = this.state.getLatestValue();
183
+ return this.hasLoadedPage && !hasMoreHead && !hasMoreTail;
184
+ }
185
+
186
+ /**
187
+ * Applies a complete set (e.g. a channel query's `scheduled_messages`) through the paginator's own
188
+ * operations: removes what was held at `itemIdsAtRequest` and is missing, and ingests the rest. A
189
+ * list that does not hold a complete set yet is replaced by it instead. Messages taken since the
190
+ * snapshot stay. Publishes once.
191
+ */
192
+ public hydrate(
193
+ scheduledMessages: ScheduledMessageResponse[],
194
+ itemIdsAtRequest: ReadonlySet<string> = new Set(),
195
+ ) {
196
+ const snapshot = this.filterQueryResults(scheduledMessages);
197
+
198
+ if (!this.holdsCompleteList) {
199
+ this.replaceWithFirstPage({ itemIdsAtRequest, page: snapshot, tailward: null });
200
+ return;
201
+ }
202
+
203
+ const snapshotIds = new Set(snapshot.map(getScheduledMessageId));
204
+ this.batch(
205
+ () => {
206
+ // held when the request went out and missing from the response: gone on the server
207
+ itemIdsAtRequest.forEach((id) => {
208
+ if (!snapshotIds.has(id)) this.removeItem({ id });
209
+ });
210
+ snapshot.forEach((item) => this.ingestItem(item));
211
+ },
212
+ { coalesce: true },
213
+ );
214
+ }
215
+
216
+ /**
217
+ * Re-queries the first page and applies it in place: the current messages stay until the response
218
+ * lands, unlike the base `reload()`, which empties the list first. A complete response is applied
219
+ * as {@link hydrate} does; a longer list is replaced by its first page. Messages taken by events
220
+ * while the request was out stay. A failed query keeps the list and records `lastQueryError`; a
221
+ * success clears it. Only the first load publishes `isLoading`. A call while one is in flight
222
+ * joins it.
223
+ */
224
+ reload = (): Promise<void> => {
225
+ if (!this.reloadInFlight) {
226
+ const inFlight = this.reloadFirstPage().finally(() => {
227
+ if (this.reloadInFlight === inFlight) this.reloadInFlight = undefined;
228
+ });
229
+ this.reloadInFlight = inFlight;
230
+ }
231
+ return this.reloadInFlight;
232
+ };
233
+
234
+ private reloadInFlight?: Promise<void>;
235
+ private reloadGeneration = 0;
236
+
237
+ private reloadWasSuperseded(generation: number) {
238
+ return generation !== this.reloadGeneration;
239
+ }
240
+
241
+ private reloadFirstPage = async () => {
242
+ const generation = this.reloadGeneration;
243
+ const isFirstLoad = !this.hasLoadedPage;
244
+ const itemIdsAtRequest = this.getItemIds();
245
+ if (isFirstLoad) this.state.partialNext({ isLoading: true });
246
+ let applied = false;
247
+ try {
248
+ const fetchParams = {
249
+ queryShape: this.getNextQueryShape(),
250
+ retryCount: this.config.retryCount,
251
+ };
252
+ const response = await this.fetchQueryResponseWithRetries(fetchParams);
253
+ if (!response || this.reloadWasSuperseded(generation)) return;
254
+ const { items, tailward } = this.extractQueryPage(response);
255
+ if (tailward) {
256
+ this.replaceWithFirstPage({
257
+ itemIdsAtRequest,
258
+ page: this.filterQueryResults(items),
259
+ tailward,
260
+ });
261
+ } else {
262
+ this.hydrate(items, itemIdsAtRequest);
263
+ }
264
+ applied = true;
265
+ } finally {
266
+ if (!this.reloadWasSuperseded(generation)) {
267
+ const clearError = applied && this.lastQueryError;
268
+ if (isFirstLoad || clearError) {
269
+ this.state.partialNext({
270
+ ...(isFirstLoad ? { isLoading: false } : {}),
271
+ ...(clearError ? { lastQueryError: undefined } : {}),
272
+ });
273
+ }
274
+ }
275
+ }
276
+ };
277
+
278
+ /**
279
+ * Replaces the list with `page` as its first page. Messages taken by events since the request went
280
+ * out (held now, not at `itemIdsAtRequest`) stay; the others the page leaves out go. Publishes once.
281
+ */
282
+ private replaceWithFirstPage({
283
+ itemIdsAtRequest,
284
+ page,
285
+ tailward,
286
+ }: {
287
+ itemIdsAtRequest: ReadonlySet<string>;
288
+ page: ScheduledMessageResponse[];
289
+ tailward: string | null | undefined;
290
+ }) {
291
+ const pageIds = new Set(page.map(getScheduledMessageId));
292
+ const takenSinceRequest = this._itemIndex
293
+ .values()
294
+ .filter(({ id }) => !pageIds.has(id) && !itemIdsAtRequest.has(id));
295
+ const keptIds = new Set([
296
+ ...pageIds,
297
+ ...takenSinceRequest.map(getScheduledMessageId),
298
+ ]);
299
+
300
+ this.batch(
301
+ () => {
302
+ this.setIntervals([]);
303
+ this.setActiveInterval(undefined);
304
+ this.clearIntervalViews();
305
+ this._itemIndex.values().forEach(({ id }) => {
306
+ if (!keptIds.has(id)) this._itemIndex.remove(id);
307
+ });
308
+ this.setItems({
309
+ cursor: tailward
310
+ ? { headward: null, tailward }
311
+ : { headward: null, tailward: null },
312
+ isFirstPage: true,
313
+ isLastPage: !tailward,
314
+ valueOrFactory: [...page, ...takenSinceRequest].sort(this.sortComparator),
315
+ });
316
+ },
317
+ { coalesce: true },
318
+ );
319
+ }
320
+
321
+ /**
322
+ * Another list stored a newer copy of items this one holds. A change can move a scheduled message
323
+ * (`scheduled_at`) or take it out of this list (`status`), so each changed item is placed by this
324
+ * list's filter and order.
325
+ */
326
+ public onEntitiesChanged({ changedIds }: EntityStoreChangeBatch) {
327
+ this.batch(
328
+ () => {
329
+ changedIds.forEach((id) => {
330
+ const item = this.getItem(id);
331
+ if (item) this.placeItem(item);
332
+ });
333
+ },
334
+ { coalesce: true },
335
+ );
336
+ }
337
+
338
+ public onEntityRemoved(id: string, item: unknown) {
339
+ this.removeItem({ id, item: item as ScheduledMessageResponse });
340
+ }
341
+
342
+ public flushState() {
343
+ this.flushPendingPublishes();
344
+ }
345
+
346
+ public resetState() {
347
+ super.resetState();
348
+ this._itemIndex.clear();
349
+ this.reloadInFlight = undefined;
350
+ this.reloadGeneration += 1;
351
+ }
352
+ }
@@ -2,7 +2,9 @@ export * from './BasePaginator';
2
2
  export * from './ChannelPaginator';
3
3
  export { MessageIntervalPaginator } from './MessageIntervalPaginator';
4
4
  export * from './MessagePaginator';
5
+ export * from './MessageMarkPaginator';
5
6
  export * from './PinnedMessagePaginator';
6
7
  export * from './ReminderPaginator';
8
+ export * from './ScheduledMessagePaginator';
7
9
  export * from './UserGroupPaginator';
8
10
  export * from './ThreadPaginator';
@@ -0,0 +1,268 @@
1
+ import { StateStore } from '@stream-io/state-store';
2
+ import { EventHandlerPipeline } from '../EventHandlerPipeline';
3
+ import { WithSubscriptions } from '../utils/WithSubscriptions';
4
+ import { ScheduledMessageErrorReason } from './constants';
5
+ import { getScheduledMessageErrorReason } from './errors';
6
+ import { DEFAULT_SCHEDULED_MESSAGE_EVENT_HANDLERS } from './eventHandlers';
7
+ import type { Unsubscribe } from '@stream-io/state-store';
8
+ import type { StreamChat } from '../client';
9
+ import type { ScheduledMessageResponse } from '../gen/models';
10
+ import type { ScheduledMessagePaginator } from '../pagination/paginators/ScheduledMessagePaginator';
11
+ import type {
12
+ AddScheduledMessageEventHandlerParams,
13
+ RemoveScheduledMessageEventHandlersParams,
14
+ ScheduledMessagePaginatorsManagerEventHandlerContext,
15
+ ScheduledMessagePaginatorsManagerEventHandlers,
16
+ ScheduledMessagePaginatorsManagerEventType,
17
+ ScheduledMessagePaginatorsManagerOptions,
18
+ ScheduledMessagePaginatorsManagerState,
19
+ SetScheduledMessageEventHandlersParams,
20
+ } from './types';
21
+
22
+ const MANAGER_NAME = 'ScheduledMessagePaginatorsManager';
23
+
24
+ const isDisabledError = (error: Error | undefined) =>
25
+ !!error &&
26
+ getScheduledMessageErrorReason(error) === ScheduledMessageErrorReason.Disabled;
27
+
28
+ const createInitialState = (): ScheduledMessagePaginatorsManagerState => ({
29
+ isDisabled: false,
30
+ paginators: [],
31
+ });
32
+
33
+ const copyEventHandlers = (
34
+ handlers: ScheduledMessagePaginatorsManagerEventHandlers,
35
+ ): ScheduledMessagePaginatorsManagerEventHandlers => {
36
+ const copy: ScheduledMessagePaginatorsManagerEventHandlers = {};
37
+ for (const [eventType, eventHandlers] of Object.entries(handlers)) {
38
+ if (eventHandlers) copy[eventType] = [...eventHandlers];
39
+ }
40
+ return copy;
41
+ };
42
+
43
+ const dedupeById = (paginators: ScheduledMessagePaginator[]) => {
44
+ const seenIds = new Set<string>();
45
+ return paginators.filter(({ id }) => {
46
+ if (seenIds.has(id)) return false;
47
+ seenIds.add(id);
48
+ return true;
49
+ });
50
+ };
51
+
52
+ const sameOrder = (
53
+ first: ScheduledMessagePaginator[],
54
+ second: ScheduledMessagePaginator[],
55
+ ) =>
56
+ first.length === second.length &&
57
+ first.every((paginator, index) => paginator === second[index]);
58
+
59
+ export class ScheduledMessagePaginatorsManager extends WithSubscriptions {
60
+ private eventHandlerPipelines = new Map<
61
+ ScheduledMessagePaginatorsManagerEventType,
62
+ EventHandlerPipeline<ScheduledMessagePaginatorsManagerEventHandlerContext>
63
+ >();
64
+ private queryErrorUnsubscribeByPaginator = new Map<
65
+ ScheduledMessagePaginator,
66
+ Unsubscribe
67
+ >();
68
+
69
+ public readonly client: StreamChat;
70
+ public state: StateStore<ScheduledMessagePaginatorsManagerState>;
71
+
72
+ constructor({
73
+ client,
74
+ eventHandlers = ScheduledMessagePaginatorsManager.getDefaultHandlers(),
75
+ }: ScheduledMessagePaginatorsManagerOptions) {
76
+ super();
77
+ this.client = client;
78
+ this.state = new StateStore<ScheduledMessagePaginatorsManagerState>(
79
+ createInitialState(),
80
+ );
81
+
82
+ this.installEventHandlers(eventHandlers);
83
+ }
84
+
85
+ public static getDefaultHandlers(): ScheduledMessagePaginatorsManagerEventHandlers {
86
+ return copyEventHandlers(DEFAULT_SCHEDULED_MESSAGE_EVENT_HANDLERS);
87
+ }
88
+
89
+ get paginators() {
90
+ return this.state.getLatestValue().paginators;
91
+ }
92
+
93
+ get isDisabled() {
94
+ return this.state.getLatestValue().isDisabled;
95
+ }
96
+
97
+ get pipelines() {
98
+ return this.eventHandlerPipelines;
99
+ }
100
+
101
+ private get eventHandlerContext(): ScheduledMessagePaginatorsManagerEventHandlerContext {
102
+ return { scheduledMessagePaginators: this };
103
+ }
104
+
105
+ private installEventHandlers(handlers: ScheduledMessagePaginatorsManagerEventHandlers) {
106
+ for (const [eventType, eventHandlers] of Object.entries(handlers)) {
107
+ if (eventHandlers) this.ensurePipeline(eventType).replaceAll(eventHandlers);
108
+ }
109
+ }
110
+
111
+ private watchQueryErrors(paginator: ScheduledMessagePaginator) {
112
+ if (this.queryErrorUnsubscribeByPaginator.has(paginator)) return;
113
+
114
+ const unsubscribe = paginator.state.subscribeWithSelector(
115
+ ({ lastQueryError }) => ({ lastQueryError }),
116
+ this.updateIsDisabled,
117
+ );
118
+
119
+ this.queryErrorUnsubscribeByPaginator.set(paginator, unsubscribe);
120
+ }
121
+
122
+ private unwatchQueryErrors(paginator: ScheduledMessagePaginator) {
123
+ this.queryErrorUnsubscribeByPaginator.get(paginator)?.();
124
+ this.queryErrorUnsubscribeByPaginator.delete(paginator);
125
+ this.updateIsDisabled();
126
+ }
127
+
128
+ private updateIsDisabled = () => {
129
+ const isDisabled = this.paginators.some(({ lastQueryError }) =>
130
+ isDisabledError(lastQueryError),
131
+ );
132
+
133
+ this.state.partialNext({ isDisabled });
134
+ };
135
+
136
+ public ensurePipeline(eventType: ScheduledMessagePaginatorsManagerEventType) {
137
+ const existingPipeline = this.eventHandlerPipelines.get(eventType);
138
+ if (existingPipeline) return existingPipeline;
139
+
140
+ const pipeline =
141
+ new EventHandlerPipeline<ScheduledMessagePaginatorsManagerEventHandlerContext>({
142
+ id: `${MANAGER_NAME}:${eventType}`,
143
+ });
144
+ this.eventHandlerPipelines.set(eventType, pipeline);
145
+
146
+ return pipeline;
147
+ }
148
+
149
+ public addEventHandler({
150
+ eventType,
151
+ ...payload
152
+ }: AddScheduledMessageEventHandlerParams): Unsubscribe {
153
+ return this.ensurePipeline(eventType).insert(payload);
154
+ }
155
+
156
+ public setEventHandlers({
157
+ eventType,
158
+ handlers,
159
+ }: SetScheduledMessageEventHandlersParams) {
160
+ return this.ensurePipeline(eventType).replaceAll(handlers);
161
+ }
162
+
163
+ public removeEventHandlers({
164
+ eventType,
165
+ handlers,
166
+ }: RemoveScheduledMessageEventHandlersParams) {
167
+ const pipeline = this.eventHandlerPipelines.get(eventType);
168
+ handlers.forEach((params) => pipeline?.remove(params));
169
+ }
170
+
171
+ public getPaginatorById(id: string): ScheduledMessagePaginator | undefined {
172
+ return this.paginators.find((paginator) => paginator.id === id);
173
+ }
174
+
175
+ public setPaginators(paginators: ScheduledMessagePaginator[]) {
176
+ const nextPaginators = dedupeById(paginators);
177
+ const currentPaginators = this.paginators;
178
+ if (sameOrder(currentPaginators, nextPaginators)) return;
179
+
180
+ const detached = currentPaginators.filter(
181
+ (paginator) => !nextPaginators.includes(paginator),
182
+ );
183
+ const attached = nextPaginators.filter(
184
+ (paginator) => !currentPaginators.includes(paginator),
185
+ );
186
+
187
+ this.state.partialNext({ paginators: nextPaginators });
188
+
189
+ detached.forEach((paginator) => {
190
+ this.unwatchQueryErrors(paginator);
191
+ paginator.cancelScheduledQuery();
192
+ });
193
+ attached.forEach((paginator) => this.watchQueryErrors(paginator));
194
+ }
195
+
196
+ public clearPaginators(): ScheduledMessagePaginator[] {
197
+ const cleared = this.paginators;
198
+ this.setPaginators([]);
199
+ return cleared;
200
+ }
201
+
202
+ public insertPaginator({
203
+ index,
204
+ paginator,
205
+ }: {
206
+ paginator: ScheduledMessagePaginator;
207
+ index?: number;
208
+ }) {
209
+ const paginators = this.paginators.filter(({ id }) => id !== paginator.id);
210
+ const validIndex = Math.max(
211
+ 0,
212
+ Math.min(index ?? paginators.length, paginators.length),
213
+ );
214
+ paginators.splice(validIndex, 0, paginator);
215
+ this.setPaginators(paginators);
216
+ }
217
+
218
+ public removePaginator(
219
+ paginatorOrId: ScheduledMessagePaginator | string,
220
+ ): ScheduledMessagePaginator | undefined {
221
+ const id = typeof paginatorOrId === 'string' ? paginatorOrId : paginatorOrId.id;
222
+ const removed = this.getPaginatorById(id);
223
+ if (!removed) return undefined;
224
+ this.setPaginators(this.paginators.filter((paginator) => paginator !== removed));
225
+ return removed;
226
+ }
227
+
228
+ public resetPaginatorStates() {
229
+ this.paginators.forEach((paginator) => {
230
+ paginator.cancelScheduledQuery();
231
+ paginator.resetState();
232
+ });
233
+ this.state.partialNext({ isDisabled: false });
234
+ }
235
+
236
+ public ingest = (scheduledMessage: ScheduledMessageResponse) => {
237
+ this.paginators.forEach((paginator) => paginator.ingestItem(scheduledMessage));
238
+ };
239
+
240
+ public recover = async () => {
241
+ const loadedPaginators = this.paginators.filter(({ hasLoadedPage }) => hasLoadedPage);
242
+
243
+ await Promise.allSettled(loadedPaginators.map((paginator) => paginator.reload()));
244
+ };
245
+
246
+ /**
247
+ * Starts syncing the registered lists with the client's WS events. Nothing keeps them in sync
248
+ * until this is called, so an integration has to call it once a user is connected and call the
249
+ * returned unsubscribe (or {@link unregisterSubscriptions}) on teardown. The Stream UI SDKs do
250
+ * this for you; a pure-LLC integration must do it itself. Ref-counted, so several holders can
251
+ * share one manager and only the last unsubscribe tears the subscriptions down.
252
+ */
253
+ public registerSubscriptions(): Unsubscribe {
254
+ if (!this.hasSubscriptions) {
255
+ this.addUnsubscribeFunction(
256
+ this.client.on((event) => {
257
+ this.eventHandlerPipelines
258
+ .get(event.type)
259
+ ?.run(event, this.eventHandlerContext);
260
+ }).unsubscribe,
261
+ );
262
+ }
263
+
264
+ this.incrementRefCount();
265
+
266
+ return () => this.unregisterSubscriptions();
267
+ }
268
+ }
@@ -0,0 +1,42 @@
1
+ import { SCHEDULED_MESSAGE_STATUS } from './constants';
2
+ import { isScheduledMessageNotFoundError } from './errors';
3
+ import type { ScheduledMessageResponse } from '../gen/models';
4
+
5
+ export type ScheduledMessageOperationKind = 'schedule' | 'update' | 'cancel' | 'sendNow';
6
+
7
+ export type ScheduledMessageStatePolicyContext = {
8
+ ingest: (scheduledMessage: ScheduledMessageResponse) => void;
9
+ get: (id: string) => ScheduledMessageResponse | undefined;
10
+ };
11
+
12
+ export class ScheduledMessageStatePolicy {
13
+ private ctx: ScheduledMessageStatePolicyContext;
14
+
15
+ constructor(ctx: ScheduledMessageStatePolicyContext) {
16
+ this.ctx = ctx;
17
+ }
18
+
19
+ success(
20
+ kind: ScheduledMessageOperationKind,
21
+ scheduledMessage: ScheduledMessageResponse | undefined,
22
+ ) {
23
+ if (!scheduledMessage) return;
24
+
25
+ if (kind === 'cancel') {
26
+ this.ctx.ingest({ ...scheduledMessage, status: SCHEDULED_MESSAGE_STATUS.Canceled });
27
+ return;
28
+ }
29
+
30
+ this.ctx.ingest(scheduledMessage);
31
+ }
32
+
33
+ failure(kind: ScheduledMessageOperationKind, id: string | undefined, error: unknown) {
34
+ if (kind === 'schedule' || kind === 'sendNow') return;
35
+ if (!id || !isScheduledMessageNotFoundError(error)) return;
36
+
37
+ const stored = this.ctx.get(id);
38
+ if (stored) {
39
+ this.ctx.ingest({ ...stored, status: SCHEDULED_MESSAGE_STATUS.Canceled });
40
+ }
41
+ }
42
+ }