stream-chat 10.0.0-rc.21 → 10.0.0-rc.23

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 (269) hide show
  1. package/dist/cjs/index.browser.js +2196 -3902
  2. package/dist/cjs/index.browser.js.map +3 -3
  3. package/dist/cjs/index.node.js +2197 -3902
  4. package/dist/cjs/index.node.js.map +3 -3
  5. package/dist/esm/index.mjs +2199 -3905
  6. package/dist/esm/index.mjs.map +4 -4
  7. package/dist/types/ChannelManager.d.ts +120 -233
  8. package/dist/types/CooldownTimer.d.ts +8 -23
  9. package/dist/types/EventHandlerPipeline.d.ts +17 -37
  10. package/dist/types/LiveLocationManager.d.ts +22 -50
  11. package/dist/types/api-client.d.ts +9 -14
  12. package/dist/types/channel.d.ts +253 -448
  13. package/dist/types/channel_state.d.ts +48 -95
  14. package/dist/types/client.d.ts +245 -370
  15. package/dist/types/client_state.d.ts +1 -3
  16. package/dist/types/configuration/ConfigController.d.ts +30 -124
  17. package/dist/types/configuration/InstanceConfigurationRegistry.d.ts +31 -123
  18. package/dist/types/configuration/keys.d.ts +5 -19
  19. package/dist/types/configuration/shape.d.ts +12 -29
  20. package/dist/types/configuration/types.d.ts +59 -87
  21. package/dist/types/configuration/utils/applyInstanceConfiguration.d.ts +13 -35
  22. package/dist/types/configuration/utils/copyConfigPatch.d.ts +8 -0
  23. package/dist/types/configuration/utils/declarativeSlices.d.ts +5 -16
  24. package/dist/types/configuration/utils/deepFreezeConfig.d.ts +3 -17
  25. package/dist/types/configuration/utils/serverAuthority.d.ts +9 -29
  26. package/dist/types/connection/ConnectionIdManager.d.ts +18 -40
  27. package/dist/types/connection/ConnectionRecoveryManager.d.ts +29 -120
  28. package/dist/types/connection/networkConnection/NetworkConnectionObserver.d.ts +32 -103
  29. package/dist/types/connection/networkConnection/reporters.d.ts +9 -32
  30. package/dist/types/connection/networkConnection/types.d.ts +12 -27
  31. package/dist/types/connection/wsConnection/StableWSConnection.d.ts +37 -116
  32. package/dist/types/connection/wsConnection/WSConnection.d.ts +41 -104
  33. package/dist/types/connection/wsConnection/WSConnectionFallback.d.ts +8 -16
  34. package/dist/types/connection/wsConnection/config.d.ts +8 -28
  35. package/dist/types/connection/wsConnection/types.d.ts +17 -70
  36. package/dist/types/entityStore/EntityStore.d.ts +153 -113
  37. package/dist/types/entityStore/StoreBackedItemIndex.d.ts +13 -46
  38. package/dist/types/errors.d.ts +7 -19
  39. package/dist/types/gen/chat/ChannelApi.d.ts +2 -1
  40. package/dist/types/gen/chat/ChatApi.d.ts +28 -14
  41. package/dist/types/gen/models/index.d.ts +769 -86
  42. package/dist/types/gen/moderation/ModerationApi.d.ts +4 -4
  43. package/dist/types/index.d.ts +2 -4
  44. package/dist/types/languageNames.d.ts +9 -24
  45. package/dist/types/logger.d.ts +1 -3
  46. package/dist/types/messageComposer/LocationComposer.d.ts +1 -1
  47. package/dist/types/messageComposer/attachmentIdentity.d.ts +1 -6
  48. package/dist/types/messageComposer/attachmentManager.d.ts +10 -32
  49. package/dist/types/messageComposer/attachmentUtils.d.ts +3 -14
  50. package/dist/types/messageComposer/configuration/configuration.d.ts +2 -5
  51. package/dist/types/messageComposer/configuration/types.d.ts +29 -56
  52. package/dist/types/messageComposer/linkPreviewsManager.d.ts +6 -9
  53. package/dist/types/messageComposer/messageComposer.d.ts +30 -164
  54. package/dist/types/messageComposer/middleware/attachmentManager/postUpload/attachmentEnrichment.d.ts +4 -14
  55. package/dist/types/messageComposer/middleware/messageComposer/attachments.d.ts +2 -9
  56. package/dist/types/messageComposer/middleware/pollComposer/types.d.ts +2 -4
  57. package/dist/types/messageComposer/middleware/pollComposer/validation.d.ts +7 -19
  58. package/dist/types/messageComposer/middleware/textComposer/commands.d.ts +9 -0
  59. package/dist/types/messageComposer/middleware/textComposer/mentions.d.ts +11 -18
  60. package/dist/types/messageComposer/middleware/textComposer/textMiddlewareUtils.d.ts +9 -3
  61. package/dist/types/messageComposer/middleware/textComposer/types.d.ts +1 -6
  62. package/dist/types/messageComposer/pollComposer.d.ts +8 -4
  63. package/dist/types/messageComposer/textComposer.d.ts +3 -9
  64. package/dist/types/messageComposer/types.d.ts +5 -8
  65. package/dist/types/messageDelivery/MessageDeliveryReporter.d.ts +25 -79
  66. package/dist/types/messageDelivery/MessageReceiptsTracker.d.ts +15 -82
  67. package/dist/types/messageOperations/FailedSendCache.d.ts +4 -9
  68. package/dist/types/messageOperations/MessageOperationStatePolicy.d.ts +10 -20
  69. package/dist/types/messageOperations/MessageOperations.d.ts +20 -40
  70. package/dist/types/messageOperations/applyReactionLocally.d.ts +5 -22
  71. package/dist/types/messageOperations/createMessageOperations.d.ts +3 -5
  72. package/dist/types/messageOperations/reflectReactionEvent.d.ts +5 -13
  73. package/dist/types/messageOperations/sendOrdering.d.ts +4 -7
  74. package/dist/types/messageOperations/settlePendingAttachmentUploads.d.ts +7 -15
  75. package/dist/types/messageOperations/types.d.ts +15 -30
  76. package/dist/types/middleware.d.ts +7 -5
  77. package/dist/types/moderation.d.ts +21 -14
  78. package/dist/types/notifications/NotificationManager.d.ts +8 -31
  79. package/dist/types/notifications/types.d.ts +19 -59
  80. package/dist/types/offline-support/offline_support_api.d.ts +145 -539
  81. package/dist/types/offline-support/offline_sync_manager.d.ts +18 -42
  82. package/dist/types/offline-support/queueableOperations.d.ts +24 -52
  83. package/dist/types/offline-support/types.d.ts +24 -187
  84. package/dist/types/pagination/ItemIndex.d.ts +4 -12
  85. package/dist/types/pagination/cursorDerivation/aroundPaginationFlags.d.ts +13 -0
  86. package/dist/types/pagination/cursorDerivation/createdAtAroundPaginationFlags.d.ts +2 -4
  87. package/dist/types/pagination/cursorDerivation/linearPaginationFlags.d.ts +2 -3
  88. package/dist/types/pagination/paginators/BasePaginator.d.ts +235 -622
  89. package/dist/types/pagination/paginators/ChannelPaginator.d.ts +67 -125
  90. package/dist/types/pagination/paginators/MessageIntervalPaginator.d.ts +133 -292
  91. package/dist/types/pagination/paginators/MessagePaginator.d.ts +69 -118
  92. package/dist/types/pagination/paginators/PinnedMessagePaginator.d.ts +7 -26
  93. package/dist/types/pagination/paginators/ReminderPaginator.d.ts +2 -2
  94. package/dist/types/pagination/paginators/ThreadPaginator.d.ts +15 -23
  95. package/dist/types/pagination/paginators/UserGroupPaginator.d.ts +2 -6
  96. package/dist/types/pagination/sortCompiler.d.ts +11 -22
  97. package/dist/types/pagination/utility.normalization.d.ts +5 -23
  98. package/dist/types/pagination/utility.search.d.ts +3 -8
  99. package/dist/types/poll.d.ts +14 -14
  100. package/dist/types/poll_manager.d.ts +11 -2
  101. package/dist/types/poll_optimistic_votes.d.ts +10 -14
  102. package/dist/types/reminders/Reminder.d.ts +4 -4
  103. package/dist/types/reminders/ReminderManager.d.ts +7 -20
  104. package/dist/types/search/BaseSearchSource.d.ts +7 -12
  105. package/dist/types/search/ChannelSearchSource.d.ts +7 -7
  106. package/dist/types/search/MessageSearchSource.d.ts +7 -9
  107. package/dist/types/search/SearchController.d.ts +17 -22
  108. package/dist/types/search/types.d.ts +6 -10
  109. package/dist/types/signing.d.ts +12 -3
  110. package/dist/types/thread.d.ts +23 -71
  111. package/dist/types/thread_manager.d.ts +45 -70
  112. package/dist/types/token_manager.d.ts +8 -13
  113. package/dist/types/types.d.ts +64 -125
  114. package/dist/types/types.utility.d.ts +3 -3
  115. package/dist/types/upload-utils.d.ts +5 -10
  116. package/dist/types/uploadManager.d.ts +17 -45
  117. package/dist/types/utils/FixedSizeQueueCache.d.ts +6 -11
  118. package/dist/types/utils/WithSubscriptions.d.ts +5 -15
  119. package/dist/types/utils/concurrency.d.ts +11 -19
  120. package/dist/types/utils/mergeWith/mergeWith.d.ts +8 -11
  121. package/dist/types/utils/mergeWith/mergeWithCore.d.ts +5 -13
  122. package/dist/types/utils/mergeWith/mergeWithDiff.d.ts +22 -0
  123. package/dist/types/utils/objectPath.d.ts +6 -41
  124. package/dist/types/utils/retryable.d.ts +8 -12
  125. package/dist/types/utils/throttling/throttle.d.ts +8 -23
  126. package/dist/types/utils/time.d.ts +24 -64
  127. package/dist/types/utils.d.ts +40 -86
  128. package/package.json +7 -2
  129. package/src/ChannelManager.ts +159 -300
  130. package/src/CooldownTimer.ts +11 -29
  131. package/src/EventHandlerPipeline.ts +21 -44
  132. package/src/LiveLocationManager.ts +35 -74
  133. package/src/api-client.ts +43 -61
  134. package/src/campaign.ts +1 -1
  135. package/src/channel.ts +396 -749
  136. package/src/channel_batch_updater.ts +1 -1
  137. package/src/channel_state.ts +50 -105
  138. package/src/client.ts +360 -588
  139. package/src/client_state.ts +1 -6
  140. package/src/configuration/ConfigController.ts +41 -157
  141. package/src/configuration/InstanceConfigurationRegistry.ts +42 -171
  142. package/src/configuration/index.ts +1 -1
  143. package/src/configuration/keys.ts +13 -32
  144. package/src/configuration/shape.ts +67 -70
  145. package/src/configuration/types.ts +60 -100
  146. package/src/configuration/utils/applyInstanceConfiguration.ts +21 -53
  147. package/src/configuration/utils/copyConfigPatch.ts +11 -32
  148. package/src/configuration/utils/declarativeSlices.ts +9 -39
  149. package/src/configuration/utils/deepFreezeConfig.ts +3 -17
  150. package/src/configuration/utils/index.ts +2 -4
  151. package/src/configuration/utils/serverAuthority.ts +20 -68
  152. package/src/connection/ConnectionIdManager.ts +20 -49
  153. package/src/connection/ConnectionRecoveryManager.ts +51 -178
  154. package/src/connection/networkConnection/NetworkConnectionObserver.ts +37 -114
  155. package/src/connection/networkConnection/reporters.ts +9 -36
  156. package/src/connection/networkConnection/types.ts +12 -27
  157. package/src/connection/wsConnection/StableWSConnection.ts +73 -193
  158. package/src/connection/wsConnection/WSConnection.ts +56 -131
  159. package/src/connection/wsConnection/WSConnectionFallback.ts +22 -31
  160. package/src/connection/wsConnection/config.ts +13 -48
  161. package/src/connection/wsConnection/types.ts +17 -70
  162. package/src/constants.ts +4 -4
  163. package/src/entityStore/EntityStore.ts +162 -167
  164. package/src/entityStore/StoreBackedItemIndex.ts +14 -47
  165. package/src/errors.ts +7 -19
  166. package/src/formatMessageMemo.ts +3 -9
  167. package/src/gen/chat/ChannelApi.ts +19 -0
  168. package/src/gen/chat/ChatApi.ts +87 -13
  169. package/src/gen/models/index.ts +793 -71
  170. package/src/gen/moderation/ModerationApi.ts +0 -4
  171. package/src/index.ts +10 -14
  172. package/src/languageNames.ts +9 -24
  173. package/src/logger.ts +1 -3
  174. package/src/messageComposer/LocationComposer.ts +7 -23
  175. package/src/messageComposer/MessageComposerEffectHandlers.ts +1 -2
  176. package/src/messageComposer/attachmentIdentity.ts +2 -13
  177. package/src/messageComposer/attachmentManager.ts +17 -63
  178. package/src/messageComposer/attachmentUtils.ts +3 -17
  179. package/src/messageComposer/configuration/configuration.ts +5 -8
  180. package/src/messageComposer/configuration/types.ts +29 -56
  181. package/src/messageComposer/fileUtils.ts +1 -1
  182. package/src/messageComposer/linkPreviewsManager.ts +8 -20
  183. package/src/messageComposer/messageComposer.ts +54 -222
  184. package/src/messageComposer/middleware/attachmentManager/postUpload/attachmentEnrichment.ts +4 -16
  185. package/src/messageComposer/middleware/attachmentManager/postUpload/uploadErrorHandler.ts +1 -2
  186. package/src/messageComposer/middleware/messageComposer/attachments.ts +14 -40
  187. package/src/messageComposer/middleware/messageComposer/linkPreviews.ts +3 -4
  188. package/src/messageComposer/middleware/messageComposer/textComposer.ts +1 -1
  189. package/src/messageComposer/middleware/messageComposer/userDataInjection.ts +4 -11
  190. package/src/messageComposer/middleware/pollComposer/state.ts +2 -2
  191. package/src/messageComposer/middleware/pollComposer/types.ts +2 -4
  192. package/src/messageComposer/middleware/pollComposer/validation.ts +8 -26
  193. package/src/messageComposer/middleware/textComposer/TextComposerMiddlewareExecutor.ts +1 -6
  194. package/src/messageComposer/middleware/textComposer/commandUtils.ts +1 -2
  195. package/src/messageComposer/middleware/textComposer/commands.ts +11 -16
  196. package/src/messageComposer/middleware/textComposer/mentions.ts +32 -70
  197. package/src/messageComposer/middleware/textComposer/textMiddlewareUtils.ts +10 -4
  198. package/src/messageComposer/middleware/textComposer/types.ts +1 -6
  199. package/src/messageComposer/pollComposer.ts +11 -8
  200. package/src/messageComposer/textComposer.ts +9 -59
  201. package/src/messageComposer/types.ts +9 -12
  202. package/src/messageDelivery/MessageDeliveryReporter.ts +60 -113
  203. package/src/messageDelivery/MessageReceiptsTracker.ts +21 -105
  204. package/src/messageOperations/FailedSendCache.ts +4 -9
  205. package/src/messageOperations/MessageOperationStatePolicy.ts +40 -67
  206. package/src/messageOperations/MessageOperations.ts +33 -62
  207. package/src/messageOperations/applyReactionLocally.ts +9 -28
  208. package/src/messageOperations/createMessageOperations.ts +17 -33
  209. package/src/messageOperations/reflectReactionEvent.ts +5 -13
  210. package/src/messageOperations/sendOrdering.ts +4 -7
  211. package/src/messageOperations/settlePendingAttachmentUploads.ts +10 -21
  212. package/src/messageOperations/types.ts +15 -30
  213. package/src/middleware.ts +7 -10
  214. package/src/moderation.ts +25 -21
  215. package/src/notifications/NotificationManager.ts +11 -35
  216. package/src/notifications/types.ts +19 -59
  217. package/src/offline-support/offline_support_api.ts +178 -608
  218. package/src/offline-support/offline_sync_manager.ts +25 -69
  219. package/src/offline-support/queueableOperations.ts +31 -84
  220. package/src/offline-support/types.ts +25 -188
  221. package/src/pagination/ItemIndex.ts +4 -12
  222. package/src/pagination/cursorDerivation/aroundPaginationFlags.ts +29 -0
  223. package/src/pagination/cursorDerivation/createdAtAroundPaginationFlags.ts +13 -62
  224. package/src/pagination/cursorDerivation/idAroundPaginationFlags.ts +11 -39
  225. package/src/pagination/cursorDerivation/linearPaginationFlags.ts +4 -6
  226. package/src/pagination/filterCompiler.ts +11 -25
  227. package/src/pagination/paginators/BasePaginator.ts +422 -976
  228. package/src/pagination/paginators/ChannelPaginator.ts +130 -190
  229. package/src/pagination/paginators/MessageIntervalPaginator.ts +226 -457
  230. package/src/pagination/paginators/MessagePaginator.ts +135 -175
  231. package/src/pagination/paginators/PinnedMessagePaginator.ts +13 -38
  232. package/src/pagination/paginators/ReminderPaginator.ts +12 -15
  233. package/src/pagination/paginators/ThreadPaginator.ts +16 -26
  234. package/src/pagination/paginators/UserGroupPaginator.ts +6 -17
  235. package/src/pagination/paginators/stateThrottling.ts +5 -10
  236. package/src/pagination/sortCompiler.ts +23 -50
  237. package/src/pagination/utility.normalization.ts +8 -30
  238. package/src/pagination/utility.search.ts +4 -11
  239. package/src/poll.ts +19 -19
  240. package/src/poll_manager.ts +16 -20
  241. package/src/poll_optimistic_votes.ts +17 -22
  242. package/src/reminders/Reminder.ts +5 -6
  243. package/src/reminders/ReminderManager.ts +9 -34
  244. package/src/reminders/ReminderTimer.ts +1 -2
  245. package/src/search/BaseSearchSource.ts +14 -29
  246. package/src/search/ChannelSearchSource.ts +8 -8
  247. package/src/search/MessageSearchSource.ts +19 -25
  248. package/src/search/SearchController.ts +18 -24
  249. package/src/search/types.ts +6 -10
  250. package/src/segment.ts +1 -1
  251. package/src/signing.ts +23 -3
  252. package/src/thread.ts +72 -173
  253. package/src/thread_manager.ts +59 -76
  254. package/src/token_manager.ts +11 -21
  255. package/src/types.ts +78 -126
  256. package/src/types.utility.ts +3 -3
  257. package/src/upload-utils.ts +5 -10
  258. package/src/uploadManager.ts +22 -54
  259. package/src/utils/FixedSizeQueueCache.ts +13 -21
  260. package/src/utils/WithSubscriptions.ts +5 -15
  261. package/src/utils/concurrency.ts +16 -55
  262. package/src/utils/mergeWith/mergeWith.ts +10 -13
  263. package/src/utils/mergeWith/mergeWithCore.ts +24 -81
  264. package/src/utils/mergeWith/mergeWithDiff.ts +15 -33
  265. package/src/utils/objectPath.ts +6 -41
  266. package/src/utils/retryable.ts +10 -14
  267. package/src/utils/throttling/throttle.ts +9 -25
  268. package/src/utils/time.ts +26 -66
  269. package/src/utils.ts +72 -128
@@ -10,18 +10,12 @@ import type { Unsubscribe } from '@stream-io/state-store';
10
10
  const logger = chatLoggerSystem.getLogger('offline-db');
11
11
 
12
12
  /**
13
- * Manages synchronization between the local offline database and the Stream backend.
14
- *
15
- * Responsible for detecting connection changes, syncing channel data, and executing
16
- * pending tasks queued during offline periods. This class ensures the database remains
17
- * consistent with the server once connectivity is restored.
13
+ * Keeps the offline DB in line with the server. When the socket becomes healthy it replays the
14
+ * tasks queued while offline, then syncs missed events into the DB.
18
15
  */
19
16
  export class OfflineDBSyncManager {
20
17
  public isSynced = false;
21
- /**
22
- * Releases the subscription to the socket's status store. A bare unsubscribe now that this reads a
23
- * store rather than an event, which no longer wraps it in an object.
24
- */
18
+ /** Releases the subscription to the socket's status store. */
25
19
  public connectionChangedListener: Unsubscribe | null = null;
26
20
  private syncStatusListeners: Array<(status: boolean) => void> = [];
27
21
  private scheduledSyncStatusCallbacks: Map<string | symbol, () => Promise<void>> =
@@ -29,13 +23,9 @@ export class OfflineDBSyncManager {
29
23
  private client: StreamChat;
30
24
  private offlineDb: AbstractOfflineDB;
31
25
  /**
32
- * Optional positive cap on the number of events a single `/sync` response may
33
- * contain before this manager skips event replay into local storage and relies
34
- * on the reconnect-time channel refresh (queryChannels + `channel.watch()`) to
35
- * bring visible surfaces up to date.
36
- *
37
- * `undefined` or any non-positive value means "no limit" and event replay always
38
- * runs with whatever maximum the server decides to return.
26
+ * Cap on the events a single `/sync` response may contain. Above it, event replay into local
27
+ * storage is skipped and the reconnect-time channel refresh updates what is visible. `undefined`
28
+ * or non-positive means no limit.
39
29
  */
40
30
  public readonly syncMaxEventCount?: number;
41
31
 
@@ -54,38 +44,26 @@ export class OfflineDBSyncManager {
54
44
  }
55
45
 
56
46
  /**
57
- * Initializes the sync manager. Should only be called once per session.
58
- *
59
- * Cleans up old listeners if re-initialized to avoid memory leaks.
60
- * Starts syncing immediately if already connected, otherwise waits for reconnection.
47
+ * Syncs immediately when the socket is already healthy, then on every later healthy transition.
48
+ * Re-initializing replaces the previous subscription.
61
49
  */
62
50
  public init = async () => {
63
51
  try {
64
- // If the WebSocket connection is already active, then call
65
- // the sync API straight away and also execute pending API calls.
66
- // Otherwise wait for the socket's status store to report one.
67
52
  if (this.client.user?.id && this.client.wsConnection?.isHealthy) {
68
53
  await this.syncAndExecutePendingTasks();
69
54
  await this.invokeSyncStatusListeners(true);
70
55
  }
71
56
 
72
- // If a listener has already been registered, unsubscribe from it so
73
- // that it can be reinstated. This can happen if we reconnect with a
74
- // different user or the component invoking the init() function gets
75
- // unmounted and then remounted again. This part of the code makes
76
- // sure the stale listener doesn't produce a memory leak.
77
57
  this.connectionChangedListener?.();
78
58
 
79
- // Syncing is about reaching the server over this socket, so this reads the socket's own store.
80
- // The device's network status is a separate fact with its own store, and a device with a
81
- // network but no socket has nothing to sync over.
59
+ // Follows the socket, not the device's network status: the sync catches up the events the
60
+ // socket missed, so it runs once the socket is back and delivering new ones.
82
61
  let wasHealthy: boolean | undefined;
83
62
  this.connectionChangedListener =
84
63
  this.client.wsConnection.state.subscribeWithSelector(
85
64
  ({ isHealthy }) => ({ isHealthy }),
86
65
  async ({ isHealthy }) => {
87
- // The immediate first call establishes the baseline. It is the current status rather than
88
- // a change, and the block above has already acted on it.
66
+ // The first call reports the current status (handled above), not a change.
89
67
  const previous = wasHealthy;
90
68
  wasHealthy = isHealthy;
91
69
  if (previous === undefined) return;
@@ -106,7 +84,7 @@ export class OfflineDBSyncManager {
106
84
  };
107
85
 
108
86
  /**
109
- * Registers a listener that is called whenever the sync status changes.
87
+ * Calls `listener` with the new sync status on every change.
110
88
  *
111
89
  * @param listener - A callback invoked with the new sync status (`true` or `false`).
112
90
  * @returns An object with an `unsubscribe` function to remove the listener.
@@ -124,9 +102,11 @@ export class OfflineDBSyncManager {
124
102
  };
125
103
 
126
104
  /**
127
- * Schedules a one-time callback to be invoked after the next successful sync.
105
+ * Runs a callback once, the next time the sync status turns `true` (after the next sync attempt,
106
+ * even a failed one).
128
107
  *
129
- * @param tag - A unique key to identify and manage the callback.
108
+ * @param tag - A unique key to identify and manage the callback. Scheduling the same tag replaces
109
+ * it.
130
110
  * @param callback - An async function to run after sync.
131
111
  */
132
112
  public scheduleSyncStatusChangeCallback = (
@@ -136,11 +116,7 @@ export class OfflineDBSyncManager {
136
116
  this.scheduledSyncStatusCallbacks.set(tag, callback);
137
117
  };
138
118
 
139
- /**
140
- * Invokes all registered sync status listeners and executes any scheduled sync callbacks.
141
- *
142
- * @param status - The new sync status (`true` or `false`).
143
- */
119
+ /** Notifies the listeners and, on `true`, runs and clears the scheduled callbacks. */
144
120
  private invokeSyncStatusListeners = async (status: boolean) => {
145
121
  this.isSynced = status;
146
122
  this.syncStatusListeners.forEach((l) => {
@@ -161,26 +137,19 @@ export class OfflineDBSyncManager {
161
137
  }
162
138
  },
163
139
  );
164
- // Every callback is isolated above, so Promise.all never rejects and clear()
165
- // always runs (no double-execution on the next sync).
140
+ // Each callback catches its own error, so `clear()` always runs.
166
141
  await Promise.all(promises);
167
142
  this.scheduledSyncStatusCallbacks.clear();
168
143
  }
169
144
  };
170
145
 
171
- /**
172
- * Performs synchronization with the Stream backend.
173
- *
174
- * This includes downloading events since the last sync, updating the local DB,
175
- * and handling sync failures (e.g., if syncing beyond the allowed retention window).
176
- */
146
+ /** Replays the events since the last sync into the DB, or resets the DB if too much was missed. */
177
147
  private sync = async () => {
178
148
  if (!this.client?.user) {
179
149
  return;
180
150
  }
181
151
  try {
182
152
  const cids = await this.offlineDb.getAllChannelCids();
183
- // If there are no channels, then there is no need to sync.
184
153
  if (cids.length === 0) {
185
154
  return;
186
155
  }
@@ -194,14 +163,12 @@ export class OfflineDBSyncManager {
194
163
  const lastSyncedAtDate = new Date(lastSyncedAt);
195
164
  const nowDate = new Date();
196
165
 
197
- // Calculate the difference in days
198
166
  const diff = Math.floor(
199
167
  (nowDate.getTime() - lastSyncedAtDate.getTime()) / (1000 * 60 * 60 * 24),
200
168
  );
201
169
 
202
170
  if (diff > 30) {
203
- // stream backend will send an error if we try to sync after 30 days.
204
- // In that case reset the entire DB and start fresh.
171
+ // The backend rejects a sync older than 30 days.
205
172
  await this.offlineDb.resetDB();
206
173
  } else {
207
174
  const result = await this.client.sync({
@@ -209,7 +176,6 @@ export class OfflineDBSyncManager {
209
176
  last_sync_at: lastSyncedAtDate,
210
177
  });
211
178
 
212
- // Opt-in positive cap owned by this manager; undefined/non-positive = no limit.
213
179
  const { syncMaxEventCount } = this;
214
180
  const exceedsLimit =
215
181
  typeof syncMaxEventCount === 'number' &&
@@ -244,7 +210,6 @@ export class OfflineDBSyncManager {
244
210
  .error('An error occurred while syncing the database.', { error: e });
245
211
 
246
212
  if (isAxiosError(e) && e.code === 'ECONNABORTED') {
247
- // If the sync was aborted due to timeout, we can simply return
248
213
  return;
249
214
  }
250
215
 
@@ -254,22 +219,15 @@ export class OfflineDBSyncManager {
254
219
  return;
255
220
  }
256
221
 
257
- // Error will be raised by the sync API if there are too many events.
258
- // In that case reset the entire DB and start fresh.
259
- // We avoid resetting the DB if the error is due to timeout.
222
+ // The sync API errors when there are too many events, so reset. A timeout (above) must not.
260
223
  await this.offlineDb.resetDB();
261
224
  }
262
225
  };
263
226
 
264
227
  /**
265
- * Executes any tasks that were queued while offline and then performs a sync.
266
- *
267
- * Each step is isolated so a failure in one does not prevent the other, and
268
- * neither can escape to the callers (init + the status subscription).
269
- * This guarantees the subsequent invokeSyncStatusListeners(true) always runs,
270
- * so isSynced recovers to true and gated channel queries are unblocked.
271
- * Failed syncs degrade to "possibly stale data until the next query" rather
272
- * than freezing all future queries. See issue #1816.
228
+ * Replays queued tasks, then syncs. Each step swallows its own failure so the caller always goes
229
+ * on to `invokeSyncStatusListeners(true)`: a failed sync leaves possibly stale data rather than
230
+ * blocking later channel queries.
273
231
  */
274
232
  private syncAndExecutePendingTasks = async () => {
275
233
  try {
@@ -277,9 +235,7 @@ export class OfflineDBSyncManager {
277
235
  } catch (error) {
278
236
  console.log('Error executing pending tasks during sync.', error);
279
237
  }
280
- // Note: sync() has its own try/catch, but its catch block calls resetDB(),
281
- // which can itself throw on a corrupted DB and re-reject. This outer guard
282
- // absorbs that case.
238
+ // `sync` can still reject: its catch calls `resetDB()`, which can throw on a corrupted DB.
283
239
  try {
284
240
  await this.sync();
285
241
  } catch (error) {
@@ -4,45 +4,28 @@ import type { Channel } from '../channel';
4
4
  import type { StreamChat } from '../client';
5
5
  import type { PendingTask, PendingTaskOf, QueueableResult, QueueableType } from './types';
6
6
 
7
+ const logger = chatLoggerSystem.getLogger('offline-db');
8
+
7
9
  /**
8
- * How one queued operation is replayed, and what a replay does beyond the request itself.
9
- *
10
- * `run` is typed from {@link QueueableOperationSignatures}, so an entry cannot resolve to the wrong
11
- * method or spread the wrong payload into it.
10
+ * How one queued operation runs, on a first attempt and on a replay.
12
11
  *
13
12
  * @internal
14
13
  */
15
- const logger = chatLoggerSystem.getLogger('offline-db');
16
-
17
14
  export type QueueableOperation<T extends QueueableType> = {
18
- /**
19
- * How a failed QUEUEING attempt is logged. Declared per operation rather than passed in per call,
20
- * because the wording is a property of the operation, not of the caller — and the caller is then left
21
- * saying only which operation it wants.
22
- */
15
+ /** How a rejected `queueTask` attempt is logged. */
23
16
  logFailureAs: { message: string; method: string };
24
- /**
25
- * Whether a replay has to look the channel up from the task. Such a task is only queued when it
26
- * carries `channelId` and `channelType`, because without them it could never be replayed.
27
- */
17
+ /** Whether a replay needs the channel. Such a task is only queued with a channel type and ID. */
28
18
  needsChannel: boolean;
29
19
  /**
30
- * Performs the request. Used both for a first attempt and for a replay.
31
- *
32
- * `channel` is the instance the CALLER already holds, when there is one. A first attempt comes from a
33
- * channel's or thread's `messageOperations`, or a `Channel` method such as `createDraft`, and must run
34
- * on that exact channel; only a replay has to look one up.
20
+ * Performs the request. `channel` is the instance the caller already holds (a first attempt); a
21
+ * replay has none and resolves it from the task.
35
22
  */
36
23
  run: (params: {
37
24
  channel?: Channel;
38
25
  client: StreamChat;
39
26
  task: PendingTaskOf<T>;
40
27
  }) => Promise<QueueableResult<T>>;
41
- /**
42
- * Local state to settle AFTER a replay, and only after a replay — a first attempt has an optimistic
43
- * layer above it that already owns this. Declared per operation rather than hidden in a branch,
44
- * because "a replay does more than a first attempt" is the kind of asymmetry that goes unnoticed.
45
- */
28
+ /** Settles local state after a replay only: a first attempt has an optimistic layer for it. */
46
29
  onReplay?: (params: {
47
30
  client: StreamChat;
48
31
  result: QueueableResult<T>;
@@ -51,16 +34,9 @@ export type QueueableOperation<T extends QueueableType> = {
51
34
  };
52
35
 
53
36
  /**
54
- * The channel an operation runs on: the caller's own instance when it has one, and otherwise resolved
55
- * from the task.
56
- *
57
- * Preferring the caller's instance is not an optimisation. `client.channelManager.ensure()` returns the stored
58
- * instance only while it is in the channel store and not `pendingDisposal` — otherwise it CONSTRUCTS a
59
- * new `Channel`, which builds paginators and a composer and registers subscriptions. A first attempt
60
- * always has the real instance in hand, so it should never risk that.
61
- *
62
- * A replay has no instance, so it resolves from the task. Every channel-scoped operation carries
63
- * `channelType`/`channelId`; a task that reached the queue without them cannot be replayed at all.
37
+ * The caller's channel when it has one, else the one resolved from the task. The caller's instance
38
+ * is preferred because `channelManager.ensure` constructs a new `Channel` when none is stored (or
39
+ * it is `pendingDisposal`).
64
40
  */
65
41
  const channelOf = (client: StreamChat, task: PendingTask, channel?: Channel): Channel => {
66
42
  if (channel) return channel;
@@ -75,8 +51,7 @@ const channelOf = (client: StreamChat, task: PendingTask, channel?: Channel): Ch
75
51
  };
76
52
 
77
53
  /**
78
- * The registry: one entry per queueable operation, and the mapped type means a missing entry does not
79
- * compile.
54
+ * One entry per queueable operation.
80
55
  *
81
56
  * @internal
82
57
  */
@@ -114,11 +89,7 @@ export const QUEUEABLE_OPERATIONS: {
114
89
  'send-message': {
115
90
  needsChannel: true,
116
91
  logFailureAs: { message: 'Sending the message failed.', method: 'sendMessage' },
117
- /**
118
- * A replayed send is the first time local state learns the message exists server-side: the
119
- * optimistic layer that would normally reconcile it belongs to a `MessageOperations` call that
120
- * finished (and failed) long ago.
121
- */
92
+ // A replayed send is the first time local state learns the message exists server-side.
122
93
  onReplay: ({ client, result, task }) => {
123
94
  const message = result?.message;
124
95
  if (!message) return;
@@ -147,30 +118,16 @@ export const QUEUEABLE_OPERATIONS: {
147
118
  };
148
119
 
149
120
  /**
150
- * The shape every offline-aware request shares: try it through the pending-task queue so it can be
151
- * replayed on reconnect, and otherwise — no offline DB, queueing not possible, or the queued attempt
152
- * rejected — run it directly.
153
- *
154
- * Both paths resolve through {@link QUEUEABLE_OPERATIONS}, so "what this task actually runs" is defined
155
- * once. Before, the caller passed its own direct call alongside the task, which meant the first attempt
156
- * and the replay were two independent statements of the same thing.
121
+ * Runs the task through `offlineDb.queueTask` (queued for replay on an ephemeral failure), or
122
+ * directly when there is no offline DB, `queue` is `false` or the task is not replayable.
157
123
  *
158
- * Note the direct call is BOTH the no-offline-DB path — its actual purpose — and, on a queue failure, a
159
- * second attempt at a request that may already have reached the server. That predates this helper and
160
- * is unchanged by it; having one place to fix it is a reason this exists.
161
- *
162
- * A failed queueing attempt is logged, not rethrown: falling back to running the request directly is
163
- * the point. What it is logged as comes off the operation's own `logFailureAs`, so a caller says which
164
- * operation it wants and nothing about how to describe it.
124
+ * If `queueTask` rejects, the failure is logged and the request runs directly. It may already have
125
+ * reached the server or been stored for replay, so it can repeat.
165
126
  *
166
127
  * @internal
167
128
  *
168
- * @param params.channel - The channel instance the caller already holds, so a first attempt runs on
169
- * that exact object rather than one `client.channelManager.ensure()` might reconstruct.
170
- * @param params.client - Resolves the operation, and carries the offline DB when one is registered.
171
- * @param params.queue - Whether this task can be queued at all. `false` for a send with no message id,
172
- * which there is nothing to key a queue entry on — it still runs, just not through the queue.
173
- * @param params.task - Which operation to run, and the arguments to run it with.
129
+ * @param params.channel - The caller's channel instance, so a first attempt runs on that object.
130
+ * @param params.queue - `false` for a send with no message ID (nothing to key a queue entry on).
174
131
  */
175
132
  export const queueOrRun = async <T extends QueueableType>({
176
133
  channel,
@@ -185,8 +142,7 @@ export const queueOrRun = async <T extends QueueableType>({
185
142
  }): Promise<QueueableResult<T>> => {
186
143
  const { offlineDb } = client;
187
144
  const operation = QUEUEABLE_OPERATIONS[task.type];
188
- // We never queue a task that could not be replayed. It still runs once, so the request reports the
189
- // problem itself, i.e that the channel has no id yet.
145
+ // A task that could not be replayed is not queued, but still runs so the request reports why.
190
146
  const replayable = !operation.needsChannel || !!(task.channelType && task.channelId);
191
147
 
192
148
  if (offlineDb && queue && replayable) {
@@ -194,8 +150,6 @@ export const queueOrRun = async <T extends QueueableType>({
194
150
  return await offlineDb.queueTask<QueueableResult<T>>({ task });
195
151
  } catch (error) {
196
152
  const { message, method } = operation.logFailureAs;
197
- // The cid comes from the task when it carries a channel, so a channel-scoped failure is logged
198
- // against its channel without the caller having to say so.
199
153
  const cid =
200
154
  task.channelType && task.channelId
201
155
  ? [`${task.channelType}:${task.channelId}`]
@@ -208,7 +162,7 @@ export const queueOrRun = async <T extends QueueableType>({
208
162
  };
209
163
 
210
164
  /**
211
- * Resolves a task to its operation and runs it. Shared by a first attempt and by a replay.
165
+ * Runs a task through its operation, for a first attempt and for a replay.
212
166
  *
213
167
  * @internal
214
168
  */
@@ -229,9 +183,8 @@ export const runQueueableOperation = async <T extends QueueableType>({
229
183
  );
230
184
  }
231
185
 
232
- // A payload read back from the offline DB went through JSON, which turns an omitted argument -
233
- // say no `request` between `pathParams` and `requestOptions` - into `null`, and an optional or
234
- // defaulted parameter only stands in for `undefined`.
186
+ // A payload read back from the offline DB went through JSON, which turns an omitted argument into
187
+ // `null`, and optional or defaulted parameters only accept `undefined`.
235
188
  const payload = task.payload.map(
236
189
  (arg) => arg ?? undefined,
237
190
  ) as PendingTaskOf<T>['payload'];
@@ -240,17 +193,13 @@ export const runQueueableOperation = async <T extends QueueableType>({
240
193
  };
241
194
 
242
195
  /**
243
- * Whether this message's mutation is sitting in the offline queue waiting to be replayed. A queued
244
- * mutation is pending, not failed: nothing to roll back and nothing to mark.
245
- *
246
- * Reads the queue. Inferring it from the error's shape ("an initialized offline DB plus an
247
- * `isEphemeral` error, so it must have been queued") over-reports, because the queue declines
248
- * tasks no error shape can predict — an `update-message` whose payload still points at a local
249
- * attachment URL is refused by `isMessageUpdateReplayable`, and the edit would then be suppressed as
250
- * "pending" with nothing to replay it. A row in the pending-tasks table is the actual fact.
196
+ * Whether this message has a mutation of one of `types` waiting in the offline queue. A queued
197
+ * mutation is pending, not failed.
251
198
  *
252
- * Ordering is safe: `queueTask` awaits `handleAddPendingTask` before it rethrows, so the row exists by
253
- * the time an operation's `catch` runs.
199
+ * It reads the queue because the queue can decline a task (for example an `update-message` refused
200
+ * by `isMessageUpdateReplayable`), which the error alone cannot tell. `queueTask` awaits
201
+ * `handleAddPendingTask` before it rethrows, so the row exists by the time an operation's `catch`
202
+ * runs.
254
203
  */
255
204
  export const isQueuedForReplay = async (
256
205
  client: StreamChat,
@@ -258,12 +207,10 @@ export const isQueuedForReplay = async (
258
207
  types: readonly QueueableType[],
259
208
  ): Promise<boolean> => {
260
209
  const { offlineDb } = client;
261
- // No queue at all, so nothing can be pending. `initialized` matters as much as existence: a DB whose
262
- // `init()` never succeeded cannot hold a pending task.
210
+ // A DB whose `init()` never succeeded cannot hold a pending task.
263
211
  if (!offlineDb?.state.getLatestValue().initialized) return false;
264
212
 
265
- // Optional-chained: `getPendingTasks` is part of the `OfflineDBApi` an integrator can implement, so
266
- // this must not assume a well-formed return.
213
+ // `getPendingTasks` is implemented by the integrator, so the return is not assumed well-formed.
267
214
  const pending = await offlineDb.getPendingTasks({ messageId });
268
215
 
269
216
  return !!pending?.some((task) => types.includes(task.type));