stream-chat 10.0.0-rc.8 → 10.0.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 (366) hide show
  1. package/README.md +7 -6
  2. package/dist/cjs/index.browser.js +22095 -22290
  3. package/dist/cjs/index.browser.js.map +4 -4
  4. package/dist/cjs/index.node.js +22143 -22298
  5. package/dist/cjs/index.node.js.map +4 -4
  6. package/dist/esm/index.mjs +22093 -22288
  7. package/dist/esm/index.mjs.map +4 -4
  8. package/dist/types/ChannelManager.d.ts +216 -135
  9. package/dist/types/CooldownTimer.d.ts +16 -27
  10. package/dist/types/EventHandlerPipeline.d.ts +18 -38
  11. package/dist/types/LiveLocationManager.d.ts +25 -47
  12. package/dist/types/api-client.d.ts +17 -5
  13. package/dist/types/channel.d.ts +435 -500
  14. package/dist/types/channel_state.d.ts +72 -112
  15. package/dist/types/client.d.ts +323 -440
  16. package/dist/types/client_state.d.ts +1 -3
  17. package/dist/types/configuration/ConfigController.d.ts +31 -125
  18. package/dist/types/configuration/InstanceConfigurationRegistry.d.ts +32 -124
  19. package/dist/types/configuration/keys.d.ts +5 -19
  20. package/dist/types/configuration/shape.d.ts +12 -29
  21. package/dist/types/configuration/types.d.ts +64 -79
  22. package/dist/types/configuration/utils/applyInstanceConfiguration.d.ts +14 -36
  23. package/dist/types/configuration/utils/copyConfigPatch.d.ts +8 -0
  24. package/dist/types/configuration/utils/declarativeSlices.d.ts +5 -16
  25. package/dist/types/configuration/utils/deepFreezeConfig.d.ts +3 -17
  26. package/dist/types/configuration/utils/serverAuthority.d.ts +9 -29
  27. package/dist/types/connection/ConnectionIdManager.d.ts +45 -0
  28. package/dist/types/connection/ConnectionRecoveryManager.d.ts +84 -0
  29. package/dist/types/connection/index.d.ts +4 -0
  30. package/dist/types/connection/networkConnection/NetworkConnectionObserver.d.ts +82 -0
  31. package/dist/types/connection/networkConnection/index.d.ts +3 -0
  32. package/dist/types/connection/networkConnection/reporters.d.ts +20 -0
  33. package/dist/types/connection/networkConnection/types.d.ts +40 -0
  34. package/dist/types/connection/wsConnection/StableWSConnection.d.ts +137 -0
  35. package/dist/types/connection/wsConnection/WSConnection.d.ts +105 -0
  36. package/dist/types/connection/wsConnection/WSConnectionFallback.d.ts +47 -0
  37. package/dist/types/connection/wsConnection/config.d.ts +31 -0
  38. package/dist/types/connection/wsConnection/index.d.ts +4 -0
  39. package/dist/types/connection/wsConnection/types.d.ts +46 -0
  40. package/dist/types/constants.d.ts +3 -1
  41. package/dist/types/custom_types.d.ts +0 -2
  42. package/dist/types/entityStore/EntityStore.d.ts +226 -65
  43. package/dist/types/entityStore/StoreBackedItemIndex.d.ts +19 -33
  44. package/dist/types/entityStore/index.d.ts +0 -1
  45. package/dist/types/errors.d.ts +16 -19
  46. package/dist/types/formatMessageMemo.d.ts +5 -0
  47. package/dist/types/gen/chat/ChannelApi.d.ts +5 -1
  48. package/dist/types/gen/chat/ChatApi.d.ts +149 -105
  49. package/dist/types/gen/models/index.d.ts +2540 -698
  50. package/dist/types/gen/models/timestamp-guard.d.ts +22 -0
  51. package/dist/types/gen/moderation/ModerationApi.d.ts +37 -14
  52. package/dist/types/index.d.ts +10 -5
  53. package/dist/types/{i18n/languageNames.d.ts → languageNames.d.ts} +9 -24
  54. package/dist/types/logger.d.ts +1 -3
  55. package/dist/types/messageComposer/CustomDataManager.d.ts +7 -1
  56. package/dist/types/messageComposer/LocationComposer.d.ts +8 -2
  57. package/dist/types/messageComposer/attachmentIdentity.d.ts +24 -0
  58. package/dist/types/messageComposer/attachmentManager.d.ts +52 -24
  59. package/dist/types/messageComposer/attachmentUtils.d.ts +23 -0
  60. package/dist/types/messageComposer/configuration/configuration.d.ts +2 -5
  61. package/dist/types/messageComposer/configuration/types.d.ts +38 -50
  62. package/dist/types/messageComposer/index.d.ts +1 -0
  63. package/dist/types/messageComposer/linkPreviewsManager.d.ts +12 -9
  64. package/dist/types/messageComposer/messageComposer.d.ts +60 -123
  65. package/dist/types/messageComposer/middleware/attachmentManager/postUpload/attachmentEnrichment.d.ts +10 -1
  66. package/dist/types/messageComposer/middleware/messageComposer/attachments.d.ts +4 -0
  67. package/dist/types/messageComposer/middleware/messageComposer/commandInjection.d.ts +5 -0
  68. package/dist/types/messageComposer/middleware/messageComposer/index.d.ts +2 -0
  69. package/dist/types/messageComposer/middleware/messageComposer/pollOnly.d.ts +6 -0
  70. package/dist/types/messageComposer/middleware/messageComposer/userDataInjection.d.ts +5 -0
  71. package/dist/types/messageComposer/middleware/pollComposer/types.d.ts +2 -4
  72. package/dist/types/messageComposer/middleware/pollComposer/validation.d.ts +7 -19
  73. package/dist/types/messageComposer/middleware/textComposer/commandUtils.d.ts +4 -0
  74. package/dist/types/messageComposer/middleware/textComposer/commands.d.ts +11 -2
  75. package/dist/types/messageComposer/middleware/textComposer/mentions.d.ts +20 -19
  76. package/dist/types/messageComposer/middleware/textComposer/textMiddlewareUtils.d.ts +9 -3
  77. package/dist/types/messageComposer/middleware/textComposer/types.d.ts +1 -6
  78. package/dist/types/messageComposer/pollComposer.d.ts +15 -5
  79. package/dist/types/messageComposer/textComposer.d.ts +14 -7
  80. package/dist/types/messageComposer/types.d.ts +27 -7
  81. package/dist/types/messageDelivery/MessageDeliveryReporter.d.ts +27 -80
  82. package/dist/types/messageDelivery/MessageReceiptsTracker.d.ts +43 -73
  83. package/dist/types/messageOperations/FailedSendCache.d.ts +29 -0
  84. package/dist/types/messageOperations/MessageOperationStatePolicy.d.ts +16 -22
  85. package/dist/types/messageOperations/MessageOperations.d.ts +63 -34
  86. package/dist/types/messageOperations/applyReactionLocally.d.ts +15 -0
  87. package/dist/types/messageOperations/createMessageOperations.d.ts +9 -0
  88. package/dist/types/messageOperations/index.d.ts +6 -4
  89. package/dist/types/messageOperations/reflectReactionEvent.d.ts +16 -0
  90. package/dist/types/messageOperations/sendOrdering.d.ts +14 -0
  91. package/dist/types/messageOperations/settlePendingAttachmentUploads.d.ts +20 -0
  92. package/dist/types/messageOperations/types.d.ts +43 -14
  93. package/dist/types/middleware.d.ts +10 -0
  94. package/dist/types/moderation.d.ts +21 -14
  95. package/dist/types/notifications/NotificationManager.d.ts +10 -23
  96. package/dist/types/notifications/types.d.ts +21 -57
  97. package/dist/types/offline-support/offline_support_api.d.ts +150 -528
  98. package/dist/types/offline-support/offline_sync_manager.d.ts +21 -42
  99. package/dist/types/offline-support/queueableOperations.d.ts +35 -37
  100. package/dist/types/offline-support/types.d.ts +40 -185
  101. package/dist/types/pagination/FilterBuilder.d.ts +1 -18
  102. package/dist/types/pagination/ItemIndex.d.ts +4 -12
  103. package/dist/types/pagination/cursorDerivation/aroundPaginationFlags.d.ts +13 -0
  104. package/dist/types/pagination/cursorDerivation/createdAtAroundPaginationFlags.d.ts +4 -5
  105. package/dist/types/pagination/cursorDerivation/linearPaginationFlags.d.ts +19 -5
  106. package/dist/types/pagination/index.d.ts +1 -0
  107. package/dist/types/pagination/paginators/BasePaginator.d.ts +604 -550
  108. package/dist/types/pagination/paginators/ChannelPaginator.d.ts +123 -106
  109. package/dist/types/pagination/paginators/MessageIntervalPaginator.d.ts +576 -327
  110. package/dist/types/pagination/paginators/MessagePaginator.d.ts +237 -131
  111. package/dist/types/pagination/paginators/PinnedMessagePaginator.d.ts +15 -26
  112. package/dist/types/pagination/paginators/ReminderPaginator.d.ts +4 -3
  113. package/dist/types/pagination/paginators/ThreadPaginator.d.ts +44 -0
  114. package/dist/types/pagination/paginators/UserGroupPaginator.d.ts +5 -8
  115. package/dist/types/pagination/paginators/index.d.ts +1 -0
  116. package/dist/types/pagination/sortCompiler.d.ts +11 -22
  117. package/dist/types/pagination/utility.normalization.d.ts +8 -13
  118. package/dist/types/pagination/utility.search.d.ts +3 -8
  119. package/dist/types/poll.d.ts +35 -8
  120. package/dist/types/poll_manager.d.ts +12 -2
  121. package/dist/types/poll_optimistic_votes.d.ts +57 -0
  122. package/dist/types/reminders/Reminder.d.ts +17 -7
  123. package/dist/types/reminders/ReminderManager.d.ts +13 -25
  124. package/dist/types/search/BaseSearchSource.d.ts +10 -8
  125. package/dist/types/search/ChannelSearchSource.d.ts +16 -0
  126. package/dist/types/search/MessageSearchSource.d.ts +17 -0
  127. package/dist/types/search/SearchController.d.ts +26 -28
  128. package/dist/types/search/types.d.ts +6 -10
  129. package/dist/types/signing.d.ts +12 -3
  130. package/dist/types/thread.d.ts +67 -129
  131. package/dist/types/thread_manager.d.ts +95 -66
  132. package/dist/types/token_manager.d.ts +8 -13
  133. package/dist/types/types.d.ts +81 -197
  134. package/dist/types/types.utility.d.ts +3 -3
  135. package/dist/types/upload-utils.d.ts +5 -10
  136. package/dist/types/uploadManager.d.ts +31 -11
  137. package/dist/types/utils/FixedSizeQueueCache.d.ts +8 -11
  138. package/dist/types/utils/WithSubscriptions.d.ts +6 -16
  139. package/dist/types/utils/abort.d.ts +17 -0
  140. package/dist/types/utils/concurrency.d.ts +12 -20
  141. package/dist/types/utils/mergeWith/mergeWith.d.ts +8 -11
  142. package/dist/types/utils/mergeWith/mergeWithCore.d.ts +5 -13
  143. package/dist/types/utils/mergeWith/mergeWithDiff.d.ts +22 -0
  144. package/dist/types/utils/objectPath.d.ts +6 -41
  145. package/dist/types/utils/retryable.d.ts +8 -12
  146. package/dist/types/utils/throttling/throttle.d.ts +8 -23
  147. package/dist/types/utils/time.d.ts +45 -0
  148. package/dist/types/utils.d.ts +74 -93
  149. package/package.json +14 -40
  150. package/src/ChannelManager.ts +494 -303
  151. package/src/CooldownTimer.ts +46 -59
  152. package/src/EventHandlerPipeline.ts +22 -45
  153. package/src/LiveLocationManager.ts +99 -91
  154. package/src/api-client.ts +113 -50
  155. package/src/campaign.ts +1 -1
  156. package/src/channel.ts +1098 -1351
  157. package/src/channel_batch_updater.ts +1 -1
  158. package/src/channel_state.ts +81 -174
  159. package/src/client.ts +755 -970
  160. package/src/client_state.ts +3 -8
  161. package/src/configuration/ConfigController.ts +42 -158
  162. package/src/configuration/InstanceConfigurationRegistry.ts +43 -172
  163. package/src/configuration/index.ts +1 -1
  164. package/src/configuration/keys.ts +13 -32
  165. package/src/configuration/shape.ts +169 -59
  166. package/src/configuration/types.ts +69 -92
  167. package/src/configuration/utils/applyInstanceConfiguration.ts +22 -54
  168. package/src/configuration/utils/copyConfigPatch.ts +11 -32
  169. package/src/configuration/utils/declarativeSlices.ts +9 -39
  170. package/src/configuration/utils/deepFreezeConfig.ts +3 -17
  171. package/src/configuration/utils/index.ts +2 -4
  172. package/src/configuration/utils/serverAuthority.ts +20 -68
  173. package/src/connection/ConnectionIdManager.ts +111 -0
  174. package/src/connection/ConnectionRecoveryManager.ts +257 -0
  175. package/src/connection/index.ts +4 -0
  176. package/src/connection/networkConnection/NetworkConnectionObserver.ts +204 -0
  177. package/src/connection/networkConnection/index.ts +3 -0
  178. package/src/connection/networkConnection/reporters.ts +58 -0
  179. package/src/connection/networkConnection/types.ts +45 -0
  180. package/src/{connection.ts → connection/wsConnection/StableWSConnection.ts} +230 -231
  181. package/src/connection/wsConnection/WSConnection.ts +270 -0
  182. package/src/connection/wsConnection/WSConnectionFallback.ts +250 -0
  183. package/src/connection/wsConnection/config.ts +73 -0
  184. package/src/connection/wsConnection/index.ts +4 -0
  185. package/src/connection/wsConnection/types.ts +48 -0
  186. package/src/constants.ts +7 -5
  187. package/src/custom_types.ts +0 -1
  188. package/src/entityStore/EntityStore.ts +415 -79
  189. package/src/entityStore/StoreBackedItemIndex.ts +37 -41
  190. package/src/entityStore/index.ts +0 -1
  191. package/src/errors.ts +39 -20
  192. package/src/formatMessageMemo.ts +17 -0
  193. package/src/gen/chat/ChannelApi.ts +122 -36
  194. package/src/gen/chat/ChatApi.ts +578 -1752
  195. package/src/gen/models/index.ts +2566 -3440
  196. package/src/gen/models/timestamp-guard.ts +27 -0
  197. package/src/gen/moderation/ModerationApi.ts +183 -406
  198. package/src/index.ts +32 -10
  199. package/src/languageNames.ts +88 -0
  200. package/src/logger.ts +1 -3
  201. package/src/messageComposer/CustomDataManager.ts +19 -6
  202. package/src/messageComposer/LocationComposer.ts +49 -9
  203. package/src/messageComposer/MessageComposerEffectHandlers.ts +1 -2
  204. package/src/messageComposer/attachmentIdentity.ts +54 -0
  205. package/src/messageComposer/attachmentManager.ts +170 -185
  206. package/src/messageComposer/attachmentUtils.ts +44 -0
  207. package/src/messageComposer/configuration/configuration.ts +15 -8
  208. package/src/messageComposer/configuration/types.ts +38 -50
  209. package/src/messageComposer/fileUtils.ts +1 -1
  210. package/src/messageComposer/index.ts +1 -0
  211. package/src/messageComposer/linkPreviewsManager.ts +18 -21
  212. package/src/messageComposer/messageComposer.ts +234 -179
  213. package/src/messageComposer/middleware/attachmentManager/postUpload/AttachmentPostUploadMiddlewareExecutor.ts +1 -1
  214. package/src/messageComposer/middleware/attachmentManager/postUpload/attachmentEnrichment.ts +46 -33
  215. package/src/messageComposer/middleware/attachmentManager/postUpload/uploadErrorHandler.ts +4 -1
  216. package/src/messageComposer/middleware/attachmentManager/preUpload/blockedUploadNotification.ts +1 -1
  217. package/src/messageComposer/middleware/messageComposer/MessageComposerMiddlewareExecutor.ts +6 -0
  218. package/src/messageComposer/middleware/messageComposer/attachments.ts +76 -5
  219. package/src/messageComposer/middleware/messageComposer/commandInjection.ts +10 -4
  220. package/src/messageComposer/middleware/messageComposer/customData.ts +17 -5
  221. package/src/messageComposer/middleware/messageComposer/index.ts +2 -0
  222. package/src/messageComposer/middleware/messageComposer/linkPreviews.ts +22 -12
  223. package/src/messageComposer/middleware/messageComposer/pollOnly.ts +9 -1
  224. package/src/messageComposer/middleware/messageComposer/sharedLocation.ts +7 -2
  225. package/src/messageComposer/middleware/messageComposer/textComposer.ts +1 -1
  226. package/src/messageComposer/middleware/messageComposer/userDataInjection.ts +12 -12
  227. package/src/messageComposer/middleware/pollComposer/state.ts +2 -2
  228. package/src/messageComposer/middleware/pollComposer/types.ts +2 -4
  229. package/src/messageComposer/middleware/pollComposer/validation.ts +8 -26
  230. package/src/messageComposer/middleware/textComposer/TextComposerMiddlewareExecutor.ts +8 -6
  231. package/src/messageComposer/middleware/textComposer/commandUtils.ts +10 -3
  232. package/src/messageComposer/middleware/textComposer/commands.ts +11 -16
  233. package/src/messageComposer/middleware/textComposer/mentions.ts +32 -70
  234. package/src/messageComposer/middleware/textComposer/textMiddlewareUtils.ts +10 -4
  235. package/src/messageComposer/middleware/textComposer/types.ts +1 -6
  236. package/src/messageComposer/pollComposer.ts +21 -9
  237. package/src/messageComposer/textComposer.ts +37 -57
  238. package/src/messageComposer/types.ts +39 -11
  239. package/src/messageDelivery/MessageDeliveryReporter.ts +86 -124
  240. package/src/messageDelivery/MessageReceiptsTracker.ts +122 -139
  241. package/src/messageOperations/FailedSendCache.ts +85 -0
  242. package/src/messageOperations/MessageOperationStatePolicy.ts +124 -116
  243. package/src/messageOperations/MessageOperations.ts +297 -175
  244. package/src/{entityStore → messageOperations}/applyReactionLocally.ts +13 -25
  245. package/src/messageOperations/createMessageOperations.ts +176 -0
  246. package/src/messageOperations/index.ts +6 -14
  247. package/src/messageOperations/reflectReactionEvent.ts +43 -0
  248. package/src/messageOperations/sendOrdering.ts +25 -0
  249. package/src/messageOperations/settlePendingAttachmentUploads.ts +98 -0
  250. package/src/messageOperations/types.ts +51 -13
  251. package/src/middleware.ts +13 -5
  252. package/src/moderation.ts +25 -21
  253. package/src/notifications/NotificationManager.ts +19 -28
  254. package/src/notifications/types.ts +21 -57
  255. package/src/offline-support/offline_support_api.ts +231 -681
  256. package/src/offline-support/offline_sync_manager.ts +51 -90
  257. package/src/offline-support/queueableOperations.ts +98 -73
  258. package/src/offline-support/types.ts +43 -185
  259. package/src/pagination/FilterBuilder.ts +1 -22
  260. package/src/pagination/ItemIndex.ts +4 -12
  261. package/src/pagination/cursorDerivation/aroundPaginationFlags.ts +29 -0
  262. package/src/pagination/cursorDerivation/createdAtAroundPaginationFlags.ts +17 -62
  263. package/src/pagination/cursorDerivation/idAroundPaginationFlags.ts +11 -39
  264. package/src/pagination/cursorDerivation/linearPaginationFlags.ts +53 -33
  265. package/src/pagination/filterCompiler.ts +11 -25
  266. package/src/pagination/index.ts +1 -0
  267. package/src/pagination/paginators/BasePaginator.ts +1415 -1041
  268. package/src/pagination/paginators/ChannelPaginator.ts +481 -219
  269. package/src/pagination/paginators/MessageIntervalPaginator.ts +1362 -775
  270. package/src/pagination/paginators/MessagePaginator.ts +521 -240
  271. package/src/pagination/paginators/PinnedMessagePaginator.ts +32 -40
  272. package/src/pagination/paginators/ReminderPaginator.ts +21 -16
  273. package/src/pagination/paginators/ThreadPaginator.ts +170 -0
  274. package/src/pagination/paginators/UserGroupPaginator.ts +18 -15
  275. package/src/pagination/paginators/index.ts +1 -0
  276. package/src/pagination/paginators/stateThrottling.ts +5 -10
  277. package/src/pagination/sortCompiler.ts +23 -50
  278. package/src/pagination/utility.normalization.ts +17 -24
  279. package/src/pagination/utility.search.ts +4 -11
  280. package/src/poll.ts +183 -102
  281. package/src/poll_manager.ts +24 -22
  282. package/src/poll_optimistic_votes.ts +335 -0
  283. package/src/reminders/Reminder.ts +33 -16
  284. package/src/reminders/ReminderManager.ts +23 -56
  285. package/src/reminders/ReminderTimer.ts +6 -6
  286. package/src/search/BaseSearchSource.ts +19 -25
  287. package/src/search/ChannelSearchSource.ts +43 -1
  288. package/src/search/MessageSearchSource.ts +77 -13
  289. package/src/search/SearchController.ts +39 -36
  290. package/src/search/types.ts +6 -10
  291. package/src/segment.ts +1 -1
  292. package/src/signing.ts +23 -3
  293. package/src/thread.ts +430 -712
  294. package/src/thread_manager.ts +300 -234
  295. package/src/token_manager.ts +12 -22
  296. package/src/types.ts +102 -214
  297. package/src/types.utility.ts +3 -3
  298. package/src/upload-utils.ts +5 -10
  299. package/src/uploadManager.ts +64 -18
  300. package/src/utils/FixedSizeQueueCache.ts +18 -21
  301. package/src/utils/WithSubscriptions.ts +6 -16
  302. package/src/utils/abort.ts +45 -0
  303. package/src/utils/concurrency.ts +16 -55
  304. package/src/utils/mergeWith/mergeWith.ts +10 -13
  305. package/src/utils/mergeWith/mergeWithCore.ts +24 -81
  306. package/src/utils/mergeWith/mergeWithDiff.ts +15 -33
  307. package/src/utils/objectPath.ts +6 -41
  308. package/src/utils/retryable.ts +10 -14
  309. package/src/utils/throttling/throttle.ts +9 -25
  310. package/src/utils/time.ts +64 -0
  311. package/src/utils.ts +227 -174
  312. package/codegen/i18n/callSites.ts +0 -126
  313. package/codegen/i18n/generate.ts +0 -226
  314. package/codegen/i18n/guards.ts +0 -178
  315. package/codegen/i18n/index.ts +0 -29
  316. package/codegen/i18n/stringMaps.ts +0 -91
  317. package/codegen/i18n/types.ts +0 -100
  318. package/dist/cjs/i18n.browser.js +0 -1131
  319. package/dist/cjs/i18n.browser.js.map +0 -7
  320. package/dist/cjs/i18n.node.js +0 -1160
  321. package/dist/cjs/i18n.node.js.map +0 -7
  322. package/dist/esm/i18n-codegen.mjs +0 -409
  323. package/dist/esm/i18n-codegen.mjs.map +0 -7
  324. package/dist/esm/i18n.mjs +0 -1098
  325. package/dist/esm/i18n.mjs.map +0 -7
  326. package/dist/types/ConnectionRecoveryManager.d.ts +0 -156
  327. package/dist/types/connection.d.ts +0 -139
  328. package/dist/types/entityStore/applyReactionLocally.d.ts +0 -26
  329. package/dist/types/gen/model-decoders/decoders.d.ts +0 -3
  330. package/dist/types/gen/model-decoders/event-decoder-mapping.d.ts +0 -6
  331. package/dist/types/i18n/Streami18n.d.ts +0 -168
  332. package/dist/types/i18n/TranslationBuilder.d.ts +0 -70
  333. package/dist/types/i18n/TranslationStore.d.ts +0 -57
  334. package/dist/types/i18n/dayjs.d.ts +0 -104
  335. package/dist/types/i18n/formatters.d.ts +0 -91
  336. package/dist/types/i18n/index.d.ts +0 -15
  337. package/dist/types/i18n/translator.d.ts +0 -29
  338. package/dist/types/i18n/types.d.ts +0 -262
  339. package/dist/types/i18n-codegen/callSites.d.ts +0 -10
  340. package/dist/types/i18n-codegen/generate.d.ts +0 -15
  341. package/dist/types/i18n-codegen/guards.d.ts +0 -61
  342. package/dist/types/i18n-codegen/index.d.ts +0 -29
  343. package/dist/types/i18n-codegen/stringMaps.d.ts +0 -14
  344. package/dist/types/i18n-codegen/types.d.ts +0 -94
  345. package/dist/types/insights.d.ts +0 -56
  346. package/dist/types/messageOperations/optimistic.d.ts +0 -118
  347. package/dist/types/messageOperations/persistence.d.ts +0 -21
  348. package/dist/types/pagination/utility.queryChannel.d.ts +0 -26
  349. package/dist/types/store.d.ts +0 -125
  350. package/src/ConnectionRecoveryManager.ts +0 -293
  351. package/src/gen/model-decoders/decoders.ts +0 -2710
  352. package/src/gen/model-decoders/event-decoder-mapping.ts +0 -198
  353. package/src/i18n/Streami18n.ts +0 -520
  354. package/src/i18n/TranslationBuilder.ts +0 -176
  355. package/src/i18n/TranslationStore.ts +0 -96
  356. package/src/i18n/dayjs.ts +0 -228
  357. package/src/i18n/formatters.ts +0 -461
  358. package/src/i18n/index.ts +0 -15
  359. package/src/i18n/languageNames.ts +0 -103
  360. package/src/i18n/translator.ts +0 -76
  361. package/src/i18n/types.ts +0 -375
  362. package/src/insights.ts +0 -82
  363. package/src/messageOperations/optimistic.ts +0 -249
  364. package/src/messageOperations/persistence.ts +0 -40
  365. package/src/pagination/utility.queryChannel.ts +0 -84
  366. package/src/store.ts +0 -304
@@ -5,7 +5,6 @@ import type {
5
5
  EventPayload,
6
6
  EventType,
7
7
  LocalMessage,
8
- MessageRequest,
9
8
  MessageResponse,
10
9
  UserResponse,
11
10
  } from '../types';
@@ -25,14 +24,14 @@ import type { StreamChat } from '../client';
25
24
  import type { AxiosError } from 'axios';
26
25
  import { OfflineDBSyncManager } from './offline_sync_manager';
27
26
  import { chatLoggerSystem } from '../logger';
28
- import { StateStore } from '../store';
27
+ import { StateStore } from '@stream-io/state-store';
29
28
  import {
30
- channelHasReadEvents,
31
29
  channelTracksReadLocally,
32
30
  formatMessage,
33
- localMessageToNewMessagePayload,
31
+ isThreadOnlyReply,
34
32
  runDetached,
35
33
  } from '../utils';
34
+ import { nowNs } from '../utils/time';
36
35
  import { isMessageUpdateReplayable } from './util';
37
36
  import { QUEUEABLE_OPERATIONS, runQueueableOperation } from './queueableOperations';
38
37
  import type { QueueableOperation } from './queueableOperations';
@@ -41,11 +40,10 @@ const logger = chatLoggerSystem.getLogger('offline-db');
41
40
  import type { WSEvent } from '../gen/models';
42
41
 
43
42
  /**
44
- * Abstract base class for an offline database implementation used with StreamChat.
45
- *
46
- * Manages state and synchronization logic between the client and the offline database,
47
- * as well as contains the API providing core functionality for tracking and persisting
48
- * offline data.
43
+ * Base class for an offline DB. A subclass provides the storage by implementing the abstract
44
+ * {@link OfflineDBApi} members; the event handlers, channel guards and pending-task queue are built
45
+ * on them. A handler takes `execute`, which defaults to `true`: with `false` it returns its
46
+ * queries unexecuted, for one `executeSqlBatch`.
49
47
  *
50
48
  * @abstract
51
49
  */
@@ -59,11 +57,7 @@ export abstract class AbstractOfflineDB implements OfflineDBApi {
59
57
  syncMaxEventCount,
60
58
  }: {
61
59
  client: StreamChat;
62
- /**
63
- * Optional positive cap forwarded to the {@link OfflineDBSyncManager}, which
64
- * owns sync. `undefined` or any non-positive value means "no limit". See
65
- * {@link OfflineDBSyncManager.syncMaxEventCount}.
66
- */
60
+ /** Forwarded to {@link OfflineDBSyncManager.syncMaxEventCount}. */
67
61
  syncMaxEventCount?: number;
68
62
  }) {
69
63
  this.client = client;
@@ -78,417 +72,130 @@ export abstract class AbstractOfflineDB implements OfflineDBApi {
78
72
  });
79
73
  }
80
74
 
81
- /**
82
- * Inserts a reaction into the DB.
83
- * Will write to:
84
- * - The reactions table with the new reaction
85
- * - The message table with the message containing the new reaction
86
- * - The users table with any users associated
87
- * Will return the prepared queries for delayed execution (even if they are
88
- * already executed).
89
- *
90
- * @param {DBInsertReactionType} options
91
- * @returns {Promise<ExecuteBatchDBQueriesType>}
92
- */
75
+ /** Writes the reaction, the message carrying it and the associated users. */
93
76
  abstract insertReaction: OfflineDBApi['insertReaction'];
94
77
 
95
- /**
96
- * Upserts the list of CIDs for a filter + sort query hash.
97
- * Will write to only the table containing the cids.
98
- * Will return the prepared queries for delayed execution (even if they are
99
- * already executed).
100
- *
101
- * @param {DBUpsertCidsForQueryType} options
102
- * @returns {Promise<ExecuteBatchDBQueriesType>}
103
- */
78
+ /** Upserts the CIDs for a filter + sort query hash (cids table only). */
104
79
  abstract upsertCidsForQuery: OfflineDBApi['upsertCidsForQuery'];
105
80
 
106
81
  /**
107
- * Upserts the channels passed as an argument within the DB. Relies on
108
- * writing the properties we need from a ChannelResponse into the adequate
109
- * tables.
110
- * Will write to:
111
- * - The channels table with the channel data
112
- * - The messages table with each message associated
113
- * - The reactions table if the messages contain reactions
114
- * - The users table with all users associated
115
- * - The members table for membership and members
116
- * - The polls table for any messages that are polls
117
- * - The reads table for each user
118
- * Will return the prepared queries for delayed execution (even if they are
119
- * already executed).
120
- *
121
- * @param {DBUpsertChannelsType} options
122
- * @returns {Promise<ExecuteBatchDBQueriesType>}
82
+ * Upserts the channels and their messages, reactions, users, members, polls (for poll messages)
83
+ * and reads, each kind into its own table.
123
84
  */
124
85
  abstract upsertChannels: OfflineDBApi['upsertChannels'];
125
86
 
126
- /**
127
- * Upserts the current active user's sync status.
128
- * Will only write to the sync status table.
129
- * Will return the prepared queries for delayed execution (even if they are
130
- * already executed).
131
- *
132
- * @param {DBUpsertUserSyncStatusType} options
133
- * @returns {Promise<ExecuteBatchDBQueriesType>}
134
- */
87
+ /** Upserts the current user's sync status (sync status table only). */
135
88
  abstract upsertUserSyncStatus: OfflineDBApi['upsertUserSyncStatus'];
136
89
 
137
- /**
138
- * Upserts the app settings for the current Stream App into the DB. It
139
- * is only intended to be run once per lifecycle of the app.
140
- * Will only write to the respective app settings table.
141
- * Will return the prepared queries for delayed execution (even if they are
142
- * already executed).
143
- *
144
- * @param {DBUpsertAppSettingsType} options
145
- * @returns {Promise<ExecuteBatchDBQueriesType>}
146
- */
90
+ /** Upserts the app settings (app settings table only). Meant to run once per app lifecycle. */
147
91
  abstract upsertAppSettings: OfflineDBApi['upsertAppSettings'];
148
92
 
149
- /**
150
- * Upserts a poll fully in the DB.
151
- * Will write to the polls table. It should not update the message
152
- * associated due to how the poll state works.
153
- * Will return the prepared queries for delayed execution (even if they are
154
- * already executed).
155
- *
156
- * @param {DBUpsertPollType} options
157
- * @returns {Promise<ExecuteBatchDBQueriesType>}
158
- */
93
+ /** Upserts a poll (polls table only). It does not update the poll's message. */
159
94
  abstract upsertPoll: OfflineDBApi['upsertPoll'];
160
95
 
161
- /**
162
- * Upserts only the channel.data for the provided channels in the DB.
163
- * Will only write to the channels table.
164
- * Will return the prepared queries for delayed execution (even if they are
165
- * already executed).
166
- *
167
- * @param {DBUpsertChannelDataType} options
168
- * @returns {Promise<ExecuteBatchDBQueriesType>}
169
- */
96
+ /** Upserts only `channel.data` (channels table only). */
170
97
  abstract upsertChannelData: OfflineDBApi['upsertChannelData'];
171
98
 
172
- /**
173
- * Upserts the provided reads in the DB.
174
- * Will write to:
175
- * - The reads table
176
- * - The users table for each user associated with a read
177
- * Will return the prepared queries for delayed execution (even if they are
178
- * already executed).
179
- *
180
- * @param {DBUpsertReadsType} options
181
- * @returns {Promise<ExecuteBatchDBQueriesType>}
182
- */
99
+ /** Upserts the reads and the users they reference. */
183
100
  abstract upsertReads: OfflineDBApi['upsertReads'];
184
101
 
185
- /**
186
- * Upserts the messages in the DB.
187
- * Will write to:
188
- * - The messages table
189
- * - The reads table
190
- * - The polls table (if any messages contain polls)
191
- * - The reactions table (if any messages contain reactions)
192
- * - The users table
193
- * Will return the prepared queries for delayed execution (even if they are
194
- * already executed).
195
- *
196
- * @param {DBUpsertMessagesType} options
197
- * @returns {Promise<ExecuteBatchDBQueriesType>}
198
- */
102
+ /** Upserts the messages with their reads, polls, reactions and users. */
199
103
  abstract upsertMessages: OfflineDBApi['upsertMessages'];
200
104
 
201
- /**
202
- * Upserts the members in the DB.
203
- * Will write to:
204
- * - The users table (for each user associated with a member)
205
- * - The members table
206
- * Will return the prepared queries for delayed execution (even if they are
207
- * already executed).
208
- *
209
- * @param {DBUpsertMembersType} options
210
- * @returns {Promise<ExecuteBatchDBQueriesType>}
211
- */
105
+ /** Upserts the members and their users. */
212
106
  abstract upsertMembers: OfflineDBApi['upsertMembers'];
213
107
 
214
108
  /**
215
- * Updates a reaction in the DB. Will update the DB the same way
216
- * a reaction.updated event would (it assumes enforce_unique is true
217
- * and removes all other reactions associated with the user.
218
- * Will write to the reactions table.
219
- * Will return the prepared queries for delayed execution (even if they are
220
- * already executed).
221
- *
222
- * @param {DBUpdateReactionType} options
223
- * @returns {Promise<ExecuteBatchDBQueriesType>}
109
+ * Applies a reaction as a `reaction.updated` event would: it assumes `enforce_unique` and
110
+ * replaces the user's other reactions. Also writes the reacting user and the message's reaction
111
+ * groups.
224
112
  */
225
113
  abstract updateReaction: OfflineDBApi['updateReaction'];
226
114
 
227
- /**
228
- * Updates a single message in the DB. This is used as a faster
229
- * alternative to upsertMessages with more optimized queries.
230
- * Will write to the messages table.
231
- * Will return the prepared queries for delayed execution (even if they are
232
- * already executed).
233
- *
234
- * @param {DBUpdateMessageType} options
235
- * @returns {Promise<ExecuteBatchDBQueriesType>}
236
- */
115
+ /** Updates a single message (messages table only) with leaner queries than `upsertMessages`. */
237
116
  abstract updateMessage: OfflineDBApi['updateMessage'];
238
117
 
239
- /**
240
- * Fetches the provided draft from the DB. Should return as close to
241
- * the server side DraftResponse as possible.
242
- *
243
- * @param {DBGetDraftType} options
244
- * @returns {Promise<DraftResponse | null>}
245
- */
118
+ /** Returns the draft as close to the server's `DraftResponse` as possible. */
246
119
  abstract getDraft: OfflineDBApi['getDraft'];
247
- /**
248
- * Upserts a draft in the DB.
249
- * Will write to the draft table upserting the draft.
250
- * Will return the prepared queries for delayed execution (even if they are
251
- * already executed).
252
- *
253
- * @param {DBUpsertDraftType} options
254
- * @returns {Promise<ExecuteBatchDBQueriesType>}
255
- */
120
+
121
+ /** Upserts a draft (drafts table only). */
256
122
  abstract upsertDraft: OfflineDBApi['upsertDraft'];
257
- /**
258
- * Deletes a draft from the DB.
259
- * Will write to the draft table removing the draft.
260
- * Will return the prepared queries for delayed execution (even if they are
261
- * already executed).
262
- *
263
- * @param {DBDeleteDraftType} options
264
- * @returns {Promise<ExecuteBatchDBQueriesType>}
265
- */
123
+
124
+ /** Deletes a draft (drafts table only). */
266
125
  abstract deleteDraft: OfflineDBApi['deleteDraft'];
267
126
 
268
127
  /**
269
- * Fetches the provided channels from the DB and aggregates all data associated
270
- * with them in a single ChannelStateResponseFields. The implementation itself is responsible
271
- * for aggregating and serialization of all of the data. Should return as close to
272
- * the server side ChannelStateResponseFields as possible.
273
- *
274
- * @param {DBGetChannelsType} options
275
- * @returns {Promise<Omit<ChannelStateResponseFields, 'duration'>[] | null>}
128
+ * Returns each channel with all its stored data aggregated, as close to the server's
129
+ * `ChannelStateResponseFields` as possible. The implementation does the aggregation.
276
130
  */
277
131
  abstract getChannels: OfflineDBApi['getChannels'];
278
132
 
279
133
  /**
280
- * Fetches the channels from the DB that were the last known response to a filters & sort
281
- * hash as a query and aggregates all data associated with them in a single ChannelStateResponseFields.
282
- * The implementation itself is responsible for aggregating and serialization of all of the data.
283
- * Should return as close to the server side ChannelStateResponseFields as possible.
284
- *
285
- * @param {DBGetChannelsForQueryType} options
286
- * @returns {Promise<Omit<ChannelStateResponseFields, 'duration'>[] | null>}
134
+ * The channels last cached for a filters + sort hash, in query order, with the predefined filter
135
+ * that produced them. Channels are aggregated as in `getChannels`.
287
136
  */
288
137
  abstract getChannelsForQuery: OfflineDBApi['getChannelsForQuery'];
289
138
 
290
- /**
291
- * Will return a list of all available CIDs in the DB. The same can be achieved
292
- * by fetching all channels, however this is meant to be much faster as a query.
293
- *
294
- * @returns {Promise<string[]>}
295
- */
139
+ /** All CIDs in the DB. Much cheaper than fetching all channels. */
296
140
  abstract getAllChannelCids: OfflineDBApi['getAllChannelCids'];
297
141
 
298
- /**
299
- * Fetches the timestamp of the last sync of the DB.
300
- *
301
- * @param {DBGetLastSyncedAtType} options
302
- * @returns {Promise<string | undefined>}
303
- */
304
142
  abstract getLastSyncedAt: OfflineDBApi['getLastSyncedAt'];
305
143
 
306
- /**
307
- * Fetches all pending tasks from the DB. It will return them in an
308
- * ordered fashion by the time they were created.
309
- *
310
- * @param {DBGetPendingTasksType} [conditions]
311
- * @returns {Promise<PendingTask[]>}
312
- */
144
+ /** Pending tasks ordered by creation time, optionally only one message's. */
313
145
  abstract getPendingTasks: OfflineDBApi['getPendingTasks'];
314
146
 
315
- /**
316
- * Fetches the app settings stored in the DB. Is mainly meant to be used
317
- * only while offline and opening the application, as we only update the
318
- * app settings whenever they are fetched again so it has the potential to
319
- * be stale.
320
- *
321
- * @param {DBGetAppSettingsType} options
322
- * @returns {Promise<GetApplicationResponse | null>}
323
- */
147
+ /** The stored app settings. They only refresh when fetched again, so they can be stale. */
324
148
  abstract getAppSettings: OfflineDBApi['getAppSettings'];
325
149
 
326
- /**
327
- * Fetches reactions from the DB for a given filter & sort hash and
328
- * for a given message ID.
329
- *
330
- * @param {DBGetReactionsType} options
331
- * @returns {Promise<ReactionResponse[] | null>}
332
- */
333
150
  abstract getReactions: OfflineDBApi['getReactions'];
334
151
 
335
- /**
336
- * Executes multiple queries in a batched fashion. It will also be done
337
- * within a transaction.
338
- *
339
- * @param {ExecuteBatchDBQueriesType} queries
340
- * @returns {Promise<unknown>}
341
- */
152
+ /** Runs the queries in one transaction. */
342
153
  abstract executeSqlBatch: OfflineDBApi['executeSqlBatch'];
343
154
 
344
- /**
345
- * Adds a pending task to the pending tasks table. Can only be one of the
346
- * supported types of pending tasks, otherwise its execution will throw.
347
- * Will return the prepared queries for delayed execution (even if they are
348
- * already executed).
349
- *
350
- * @param {PendingTask} task
351
- * @returns {Promise<() => Promise<void>>}
352
- */
155
+ /** Adds a pending task. Executing a task of an unsupported type throws. */
353
156
  abstract addPendingTask: OfflineDBApi['addPendingTask'];
354
157
 
355
- /**
356
- * Updates a pending task in the DB, given its ID.
357
- * Will return the prepared queries for delayed execution (even if they are
358
- * already executed).
359
- *
360
- * @param {DBUpdatePendingTaskType} options
361
- * @returns {Promise<ExecuteBatchDBQueriesType>}
362
- */
363
158
  abstract updatePendingTask: OfflineDBApi['updatePendingTask'];
364
159
 
365
- /**
366
- * Deletes a pending task from the DB, given its ID.
367
- * Will return the prepared queries for delayed execution (even if they are
368
- * already executed).
369
- *
370
- * @param {DBDeletePendingTaskType} options
371
- * @returns {Promise<ExecuteBatchDBQueriesType>}
372
- */
373
160
  abstract deletePendingTask: OfflineDBApi['deletePendingTask'];
374
161
 
375
- /**
376
- * Deletes a reaction from the DB.
377
- * Will write to the reactions table removing the reaction.
378
- * Will return the prepared queries for delayed execution (even if they are
379
- * already executed).
380
- *
381
- * @param {DBDeleteReactionType} options
382
- * @returns {Promise<ExecuteBatchDBQueriesType>}
383
- */
384
162
  abstract deleteReaction: OfflineDBApi['deleteReaction'];
385
163
 
386
- /**
387
- * Deletes a member from the DB.
388
- * Will only write to the members table.
389
- * Will return the prepared queries for delayed execution (even if they are
390
- * already executed).
391
- *
392
- * @param {DBDeleteMemberType} options
393
- * @returns {Promise<ExecuteBatchDBQueriesType>}
394
- */
395
164
  abstract deleteMember: OfflineDBApi['deleteMember'];
396
165
 
397
- /**
398
- * Deletes a channel from the DB.
399
- * It will also delete all other entities associated with the channel in
400
- * a cascading fashion (messages, reactions, members etc.).
401
- * Will return the prepared queries for delayed execution (even if they are
402
- * already executed).
403
- *
404
- * @param {DBDeleteChannelType} options
405
- * @returns {Promise<ExecuteBatchDBQueriesType>}
406
- */
166
+ /** Deletes the channel and everything associated with it (messages, reactions, members, ...). */
407
167
  abstract deleteChannel: OfflineDBApi['deleteChannel'];
408
168
 
409
- /**
410
- * Deletes multiple messages for a given channel. Works as `channel.truncated` would.
411
- * Should remove entities primarily from the messages table and then from all associated
412
- * tables in a cascading fashion (reactions, polls etc.).
413
- * Will return the prepared queries for delayed execution (even if they are
414
- * already executed).
415
- *
416
- * @param {DBDeleteMessagesForChannelType} options
417
- * @returns {Promise<ExecuteBatchDBQueriesType>}
418
- */
169
+ /** Deletes a channel's messages as `channel.truncated` would, cascading to their reactions. */
419
170
  abstract deleteMessagesForChannel: OfflineDBApi['deleteMessagesForChannel'];
420
171
 
421
- /**
422
- * Deletes all pending tasks from the DB.
423
- * Will only update the pending tasks table.
424
- * Will return the prepared queries for delayed execution (even if they are
425
- * already executed).
426
- *
427
- * @param {DBDropPendingTasksType} options
428
- * @returns {Promise<ExecuteBatchDBQueriesType>}
429
- */
172
+ /** Deletes all pending tasks of a message (pending tasks table only). */
430
173
  abstract dropPendingTasks: OfflineDBApi['dropPendingTasks'];
431
174
 
432
- /**
433
- * Deletes a message from the DB.
434
- * All other entities associated with the message will also be deleted
435
- * in a cascading fashion (reactions, polls etc.).
436
- * Will return the prepared queries for delayed execution (even if they are
437
- * already executed).
438
- *
439
- * @param {DBDeleteMessageType} options
440
- * @returns {Promise<ExecuteBatchDBQueriesType>}
441
- */
175
+ /** Deletes the message and cascades to its reactions, polls, etc. */
442
176
  abstract hardDeleteMessage: OfflineDBApi['hardDeleteMessage'];
443
177
 
444
- /**
445
- * Updates a message with a deleted_at value in the DB.
446
- * Will only update the messages table, as the message is simply marked
447
- * as deleted and not removed from the DB.
448
- * Will return the prepared queries for delayed execution (even if they are
449
- * already executed).
450
- *
451
- * @param {DBDeleteMessageType} options
452
- * @returns {Promise<ExecuteBatchDBQueriesType>}
453
- */
178
+ /** Sets `deleted_at` on the message (messages table only) instead of removing it. */
454
179
  abstract softDeleteMessage: OfflineDBApi['softDeleteMessage'];
455
180
 
456
- /**
457
- * Drops all tables and reinitializes the connection to the DB.
458
- *
459
- * @returns {Promise<unknown>}
460
- */
181
+ /** Drops all tables and reinitializes the DB connection. */
461
182
  abstract resetDB: OfflineDBApi['resetDB'];
462
183
 
463
- /**
464
- * A utility query that checks whether a specific channel exists in the DB.
465
- * Technically the same as actually fetching that channel through other queries,
466
- * but much faster.
467
- *
468
- * @param {DBChannelExistsType} options
469
- * @returns {Promise<boolean>}
470
- */
184
+ /** Whether the channel is in the DB. Much cheaper than fetching it. */
471
185
  abstract channelExists: OfflineDBApi['channelExists'];
472
186
 
473
- /**
474
- * Initializes the DB (typically creating a simple file handle as a connection pointer for
475
- * SQLite and likely similar for other DBs).
476
- *
477
- * @returns {Promise<boolean>}
478
- */
187
+ /** Opens the DB connection (for SQLite, typically a file handle). */
479
188
  abstract initializeDB: OfflineDBApi['initializeDB'];
480
189
 
481
190
  /**
482
- * Initializes the DB as well as its syncManager for a given userId.
483
- * It will update the DBs reactive state with initialization values.
191
+ * Initializes the DB and its sync manager for a user, and updates `state`.
484
192
  *
485
- * @param userId - the user ID for which we want to initialize
193
+ * @param userId - The user ID for which we want to initialize.
486
194
  */
487
195
  public init = async (userId: string) => {
488
196
  try {
489
197
  if (!this.shouldInitialize(userId)) {
490
- // Note: We need this to return as changing the API is a breaking change.
491
- // This will change in the next major release.
198
+ // `initializeDB` has to resolve to a boolean: changing it is a breaking change.
492
199
  const initialized = await this.initializeDB();
493
200
  if (initialized) {
494
201
  await this.syncManager.init();
@@ -506,9 +213,10 @@ export abstract class AbstractOfflineDB implements OfflineDBApi {
506
213
  };
507
214
 
508
215
  /**
509
- * Checks whether the DB should be initialized or if it has been initialized already.
216
+ * Checks whether the DB is already initialized for a user.
510
217
  *
511
- * @param userId - the user ID for which we want to check initialization
218
+ * @param userId - The user ID for which we want to check initialization.
219
+ * @returns Whether the DB is initialized for `userId`.
512
220
  */
513
221
  public shouldInitialize(userId: string): boolean {
514
222
  const { userId: userIdFromState, initialized } = this.state.getLatestValue();
@@ -516,14 +224,11 @@ export abstract class AbstractOfflineDB implements OfflineDBApi {
516
224
  }
517
225
 
518
226
  /**
519
- * A utility method used to execute a query in a detached manner. The callback
520
- * passed uses a reference to the DB itself and will handle errors gracefully
521
- * and silently. Only really meant to be used for write queries that need to
522
- * be run in synchronous functions.
227
+ * Runs a write query detached, for synchronous callers. A failure is logged, not thrown. No-op
228
+ * until the DB is initialized.
523
229
  *
524
- * @param queryCallback - a callback wrapping all query logic that is to be executed
525
- * @param method - a utility parameter used for proper logging (will make sure the method
526
- * is logged on failure)
230
+ * @param queryCallback - A callback wrapping all query logic that is to be executed.
231
+ * @param options.method - The method name logged on failure.
527
232
  */
528
233
  public executeQuerySafely = <T>(
529
234
  queryCallback: (db: AbstractOfflineDB) => Promise<T>,
@@ -537,23 +242,17 @@ export abstract class AbstractOfflineDB implements OfflineDBApi {
537
242
  };
538
243
 
539
244
  /**
540
- * A utility method used to guard a certain DB query with the possible non-existance
541
- * of a channel inside of the DB. If the channel we want to guard against does not exist
542
- * in the DB yet, it will try to:
543
- *
544
- * 1. Use the channel from the WS event
545
- * 2. Use the channel from state
546
- *
547
- * and upsert the channels in the DB.
548
- *
549
- * If both fail, it will not execute the query as it would result in a foreign key constraint
550
- * error.
551
- *
552
- * @param event - The WS event we are trying to process.
553
- * @param event.execute - Whether to immediately execute the operation (optional, defaults to `true`).
554
- * @param event.forceUpdate - Whether to upsert the channel data anyway (optional, defaults to `false`).
555
- * @param createQueries - A callback that creates the queries to execute.
556
- * @returns The list of prepared queries (executed when `execute` is `true`).
245
+ * Runs `createQueries` so they cannot fail on the channel's foreign key. When the channel is
246
+ * not in the DB it is upserted first, from the event's channel or else the one in state. If
247
+ * neither exists the queries are dropped.
248
+ *
249
+ * @param options.event - The WS event we are trying to process.
250
+ * @param options.execute - Whether to immediately execute the queries. Defaults to `true`.
251
+ * @param options.forceUpdate - Whether to upsert the channel data even when it is stored.
252
+ * Defaults to `false`.
253
+ * @param createQueries - Builds the queries. It receives the effective `execute` flag and must run
254
+ * its queries when that is `true`, because the fast path relies on that write throwing.
255
+ * @returns The prepared queries.
557
256
  */
558
257
  public queriesWithChannelGuard = async (
559
258
  {
@@ -577,24 +276,14 @@ export abstract class AbstractOfflineDB implements OfflineDBApi {
577
276
  return await createQueries(execute);
578
277
  }
579
278
 
580
- // Fast path: assume the channel row is there — which it is for all but a handful of situations
581
- // (an event arriving before the first query persisted the channel, or after a `resetDB`) — and pay
582
- // for the guard only when the write actually fails. Every statement these callbacks build is an
583
- // upsert, so re-running them behind the guard is idempotent.
584
- //
585
- // Worth the inversion because this runs on EVERY live WS event: the probe it replaces is a native
586
- // round-trip, which on device costs about as much as the write it was protecting.
587
- //
588
- // Only available when we are the ones executing. An `execute: false` caller is collecting queries
589
- // for someone else's batch, so there is no failure here for us to catch and the channel row has to
590
- // be secured up front. `forceUpdate` skips it too — that caller wants the channel data written
591
- // regardless of whether a row already exists.
279
+ // Fast path: write first and probe for the channel only when the write fails (this runs on
280
+ // every live event and the probe is a native round-trip). Safe because the queries are upserts.
281
+ // Not available to `execute: false` (nothing to catch) or `forceUpdate` (always writes it).
592
282
  if (execute && !forceUpdate) {
593
283
  try {
594
284
  return await createQueries(true);
595
285
  } catch (error) {
596
- // A missing channel row is the only failure this guard can repair; anything else is a genuine
597
- // error and must not be retried.
286
+ // A missing channel row is the only failure this guard repairs.
598
287
  if (await this.channelExists({ cid })) throw error;
599
288
  }
600
289
  return await this.queriesBehindChannelGuard({
@@ -612,11 +301,8 @@ export abstract class AbstractOfflineDB implements OfflineDBApi {
612
301
  };
613
302
 
614
303
  /**
615
- * Prepends the channel row to `createQueries`' output so the queries cannot fail on the `cid`
616
- * foreign key, sourcing the channel from the event and falling back to the in-memory channel.
617
- *
618
- * Skips the write entirely when neither can supply it: without a channel row the queries would fail
619
- * anyway, and dropping the event is what the caller expects.
304
+ * Prepends the channel row to `createQueries`' output, sourced from the event or else the
305
+ * in-memory channel. Returns no queries when neither can supply it.
620
306
  */
621
307
  private queriesBehindChannelGuard = async ({
622
308
  createQueries,
@@ -636,11 +322,11 @@ export abstract class AbstractOfflineDB implements OfflineDBApi {
636
322
 
637
323
  let channelData = channelFromEvent;
638
324
  if (!channelData && event_.channel_type && event_.channel_id) {
639
- const channelFromState = this.client.channel(
640
- event_.channel_type,
641
- event_.channel_id,
325
+ // `get`, not `ensure`: `ensure` would store an empty channel when none is loaded.
326
+ const channelFromState = this.client.channelManager.get(
327
+ `${event_.channel_type}:${event_.channel_id}`,
642
328
  );
643
- if (channelFromState.initialized && !channelFromState.pendingDisposal) {
329
+ if (channelFromState?.initialized && !channelFromState.pendingDisposal) {
644
330
  channelData = channelFromState.data as unknown as ChannelResponse;
645
331
  }
646
332
  }
@@ -679,13 +365,13 @@ export abstract class AbstractOfflineDB implements OfflineDBApi {
679
365
  };
680
366
 
681
367
  /**
682
- * Handles a message.new event. Will always use a channel guard for the inner queries
683
- * and it is going to make sure that both messages and reads are upserted. It will not
684
- * try to fetch the reads from the DB first and it will rely on channel.state to handle
685
- * the number of unreads.
368
+ * Upserts the message and, when another user sent it, the current user's read (from
369
+ * `channel.state`). The channel guard upserts a missing channel row only with `execute: false`;
370
+ * with `execute: true` (the default) the row is not guarded.
686
371
  *
687
- * @param payload.event - the WS event we are trying to process
688
- * @param payload.execute - Whether to immediately execute the operation (optional, defaults to `true`).
372
+ * @param payload.event - The WS event we are trying to process.
373
+ * @param payload.execute - Whether to immediately execute the queries. Defaults to `true`.
374
+ * @returns The prepared queries.
689
375
  */
690
376
  public handleNewMessage = async ({
691
377
  event,
@@ -697,27 +383,25 @@ export abstract class AbstractOfflineDB implements OfflineDBApi {
697
383
  const client = this.client;
698
384
  const { cid, message, user } = event;
699
385
 
700
- if (!message || (message.parent_id && !message.show_in_channel)) {
386
+ if (!message || isThreadOnlyReply(message)) {
701
387
  return [];
702
388
  }
703
389
 
704
- const finalQueries = await this.queriesWithChannelGuard(
390
+ return await this.queriesWithChannelGuard(
705
391
  { event, execute },
706
- async () => {
392
+ async (executeOverride) => {
707
393
  let queries = await this.upsertMessages({
708
394
  execute: false,
709
395
  messages: [message],
710
396
  });
711
397
  if (cid && client.user && client.user.id !== user?.id) {
712
398
  const userId = client.user.id;
713
- const channel = client.activeChannels[cid];
714
- // Persist the current user's read state for channels that track reads server-side. When the
715
- // client opted into a local unread count, also persist it for read-events-disabled channels
716
- // (e.g. livestreams) so the client-local count survives a cold start. The server never sends
717
- // a read for those, so state.read[userId] may be absent here; fall back accordingly and rely
718
- // on countUnread() (the aggregate the local count maintains) for the value.
399
+ const channel = client.channelManager.get(cid);
400
+ // Persists the read state for channels that track reads server-side, and for
401
+ // read-events-disabled channels with a local unread count (their `state.read[userId]`
402
+ // can be absent).
719
403
  const tracksReadLocally = channelTracksReadLocally(channel);
720
- if (channel && (channelHasReadEvents(channel) || tracksReadLocally)) {
404
+ if (channel && (channel.readEventsEnabled || tracksReadLocally)) {
721
405
  const ownReads = channel.state.read[userId];
722
406
  const unreadCount = channel.countUnread();
723
407
  const upsertReadsQueries = await this.upsertReads({
@@ -725,14 +409,12 @@ export abstract class AbstractOfflineDB implements OfflineDBApi {
725
409
  execute: false,
726
410
  reads: [
727
411
  {
728
- last_read: ownReads?.last_read ?? new Date(0),
412
+ last_read: ownReads?.last_read ?? 0,
729
413
  last_read_message_id: ownReads?.last_read_message_id,
730
414
  unread_messages: unreadCount,
731
- // `client.user` is `ClientUser` (everything optional but `id`), so a
732
- // cast to the populated shape is unavoidable — it holds after connect.
733
- // `blocked_user_ids` is supplied rather than asserted: the connect payload
734
- // omits it when nothing is blocked, while `UserResponse` always carries it
735
- // (the server sends `[]` for other users).
415
+ // `client.user` is `ClientUser` (all optional but `id`), so the cast holds only
416
+ // after connect. `blocked_user_ids` is supplied because the connect payload
417
+ // omits it when nothing is blocked.
736
418
  user: {
737
419
  ...client.user,
738
420
  blocked_user_ids: client.user.blocked_user_ids ?? [],
@@ -743,23 +425,21 @@ export abstract class AbstractOfflineDB implements OfflineDBApi {
743
425
  queries = [...queries, ...upsertReadsQueries];
744
426
  }
745
427
  }
428
+ // Executed here so the guard's write-first path can catch a missing channel row.
429
+ if (executeOverride) {
430
+ await this.executeSqlBatch(queries);
431
+ }
746
432
  return queries;
747
433
  },
748
434
  );
749
-
750
- if (execute) {
751
- await this.executeSqlBatch(finalQueries);
752
- }
753
-
754
- return finalQueries;
755
435
  };
756
436
 
757
437
  /**
758
- * A handler for message deletion. It provides a channel guard and determines whether
759
- * it should hard delete or soft delete the message.
438
+ * Hard or soft deletes the message, depending on `event.hard_delete`.
760
439
  *
761
- * @param payload.event - the WS event we are trying to process
762
- * @param payload.execute - Whether to immediately execute the operation (optional, defaults to `true`).
440
+ * @param payload.event - The WS event we are trying to process.
441
+ * @param payload.execute - Whether to immediately execute the queries. Defaults to `true`.
442
+ * @returns The prepared queries.
763
443
  */
764
444
  public handleDeleteMessage = async ({
765
445
  event,
@@ -787,12 +467,11 @@ export abstract class AbstractOfflineDB implements OfflineDBApi {
787
467
  };
788
468
 
789
469
  /**
790
- * A utility method used for removing a message that has already failed from the
791
- * state as well as the DB. We want to drop all pending tasks and finally hard
792
- * delete the message from the DB.
470
+ * Drops the message's pending tasks and hard deletes it.
793
471
  *
794
472
  * @param payload.messageId - The ID of the message we want to remove.
795
- * @param payload.execute - Whether to immediately execute the operation (optional, defaults to `true`).
473
+ * @param payload.execute - Whether to immediately execute the queries. Defaults to `true`.
474
+ * @returns The prepared queries.
796
475
  */
797
476
  public handleRemoveMessage = async ({
798
477
  messageId,
@@ -819,13 +498,11 @@ export abstract class AbstractOfflineDB implements OfflineDBApi {
819
498
  };
820
499
 
821
500
  /**
822
- * Hard-delete a set of messages by id in a single transaction. A convenience over N individual
823
- * {@link hardDeleteMessage} calls: collects each delete's queries (`execute: false`) and runs them
824
- * as one batch. Used e.g. by destructive reconciliation on reconnect to mirror a set of in-memory
825
- * removals into the DB. No-op for an empty set.
501
+ * Hard deletes the messages in one transaction.
826
502
  *
827
- * @param payload.ids - The ids of the messages to hard-delete.
828
- * @param payload.execute - Whether to immediately execute the operation (optional, defaults to `true`).
503
+ * @param payload.ids - The IDs of the messages to hard delete.
504
+ * @param payload.execute - Whether to immediately execute the queries. Defaults to `true`.
505
+ * @returns The prepared queries.
829
506
  */
830
507
  public hardDeleteMessages = async ({
831
508
  ids,
@@ -847,20 +524,14 @@ export abstract class AbstractOfflineDB implements OfflineDBApi {
847
524
  };
848
525
 
849
526
  /**
850
- * Upsert a single message, first making sure its channel row exists so the insert cannot fail on the
851
- * foreign key.
852
- *
853
- * Concrete on purpose — it composes {@link channelExists}, {@link upsertChannelData} and
854
- * {@link upsertMessages}, so every implementation inherits it and no custom offline DB has to
855
- * implement anything new (same reasoning as {@link hardDeleteMessages}).
856
- *
857
- * The guard matters because the message-operations engine writes optimistically, and the very first
858
- * message in a freshly created channel can reach here before that channel has ever been persisted.
859
- * `upsertMessages` alone is used rather than `updateMessage` because `updateMessage` is an
860
- * UPDATE — it no-ops when the row does not exist yet, which is exactly the write-ahead case.
861
- *
862
- * @param payload.message - The message to persist. Its `cid` decides which channel row is guarded.
863
- * @param payload.execute - Whether to immediately execute the operation (optional, defaults to `true`).
527
+ * Upserts a message and writes its channel row when that row is missing (the first optimistic
528
+ * write in a new channel can precede the channel's persistence). Upserts because an UPDATE no-ops
529
+ * on a missing row. When the row is missing and the channel is not loaded in memory, or the
530
+ * message has no `cid`, nothing is written.
531
+ *
532
+ * @param payload.message - The message to persist. Its `cid` decides the guarded channel row.
533
+ * @param payload.execute - Whether to immediately execute the queries. Defaults to `true`.
534
+ * @returns The prepared queries.
864
535
  */
865
536
  public upsertMessageWithChannelGuard = async ({
866
537
  message,
@@ -874,9 +545,7 @@ export abstract class AbstractOfflineDB implements OfflineDBApi {
874
545
 
875
546
  const messages = [message] as unknown as MessageResponse[];
876
547
 
877
- // Same inversion as `queriesWithChannelGuard`: attempt the write, and only reach for the channel
878
- // row when it actually fails. This runs on every optimistic message write, and the probe it
879
- // replaces is a native round-trip costing a meaningful fraction of the write itself.
548
+ // Write first and probe for the channel only on failure, as in `queriesWithChannelGuard`.
880
549
  if (execute) {
881
550
  try {
882
551
  return await this.upsertMessages({ messages, execute: true });
@@ -893,11 +562,7 @@ export abstract class AbstractOfflineDB implements OfflineDBApi {
893
562
  return await this.upsertMessageBehindChannelGuard({ cid, messages, execute });
894
563
  };
895
564
 
896
- /**
897
- * Writes the channel row ahead of the messages so the insert cannot fail on the `cid` foreign key.
898
- * Skips the write when there is nothing to build a channel row from — the message stays correct in
899
- * memory either way, and an insert that cannot resolve its foreign key is not worth attempting.
900
- */
565
+ /** Writes the channel row ahead of the messages. Skips the write when no row can be built. */
901
566
  private upsertMessageBehindChannelGuard = async ({
902
567
  cid,
903
568
  execute,
@@ -907,7 +572,7 @@ export abstract class AbstractOfflineDB implements OfflineDBApi {
907
572
  execute: boolean;
908
573
  messages: MessageResponse[];
909
574
  }): Promise<ExecuteBatchDBQueriesType> => {
910
- const channel = this.client.activeChannels[cid];
575
+ const channel = this.client.channelManager.get(cid);
911
576
  if (!channel?.initialized || channel.pendingDisposal) {
912
577
  logger
913
578
  .withExtraTags('upsertMessageWithChannelGuard', cid)
@@ -931,18 +596,12 @@ export abstract class AbstractOfflineDB implements OfflineDBApi {
931
596
  };
932
597
 
933
598
  /**
934
- * The messages of a channel that are still in a local `failed` state, i.e. composed by this user but
935
- * never accepted by the server.
936
- *
937
- * Concrete, composed from the existing {@link getChannels} primitive, so it adds nothing to
938
- * {@link OfflineDBApi} that a custom offline DB would have to implement.
939
- *
940
- * This is the buffer that lets a failed message survive. v9 recovered such messages by diffing a
941
- * second, lagging copy of the message list (the React SDK state) against `channel.state`; with a
942
- * single reactive source of truth the persisted row is the only place that memory can be
943
- * re-populated from — see `Channel.reload`.
599
+ * The channel's persisted messages with a local `failed` status, which `Channel.reload` and
600
+ * `Thread.reload` re-ingest. Built on {@link getChannels}, so a custom offline DB implements
601
+ * nothing extra.
944
602
  *
945
603
  * @param payload.cid - The channel whose failed messages to read.
604
+ * @returns The failed messages, formatted.
946
605
  */
947
606
  public getFailedMessages = async ({
948
607
  cid,
@@ -961,15 +620,12 @@ export abstract class AbstractOfflineDB implements OfflineDBApi {
961
620
  };
962
621
 
963
622
  /**
964
- * A utility method to handle read events. It will calculate the state of the reads if
965
- * present in the event, or optionally rely on the hard override in unreadMessages.
966
- * The unreadMessages argument is useful for cases where we know the exact number of unreads
967
- * (for example reading an entire channel), but `unread_messages` might not necessarily exist
968
- * in the event (or it exists with a stale value if we know what we want to ultimately update to).
623
+ * Upserts the reads of a read event.
969
624
  *
970
625
  * @param payload.event - The WS event we are trying to process.
971
- * @param payload.unreadMessages - An override of `unread_messages` that will be preferred when upserting reads.
972
- * @param payload.execute - Whether to immediately execute the operation (optional, defaults to `true`).
626
+ * @param payload.unreadMessages - An override of `event.unread_messages`.
627
+ * @param payload.execute - Whether to immediately execute the queries. Defaults to `true`.
628
+ * @returns The prepared queries.
973
629
  */
974
630
  public handleRead = async ({
975
631
  event,
@@ -986,13 +642,20 @@ export abstract class AbstractOfflineDB implements OfflineDBApi {
986
642
  execute?: boolean;
987
643
  }) => {
988
644
  const {
989
- received_at: last_read = new Date(),
990
645
  last_read_message_id,
991
646
  // @ts-expect-error property missing
992
647
  unread_messages = 0,
993
648
  user,
994
649
  cid,
995
650
  } = event;
651
+ // Mirrors what `Channel` writes into `state.read`: mark-unread uses the server's
652
+ // `last_read_at`, other read events its `created_at`. `received_at` is the local clock, so only
653
+ // a fallback.
654
+ const last_read =
655
+ (event.type === 'notification.mark_unread' ? event.last_read_at : undefined) ??
656
+ event.created_at ??
657
+ event.received_at ??
658
+ nowNs();
996
659
 
997
660
  const overriddenUnreadMessages = unreadMessages ?? unread_messages;
998
661
 
@@ -1017,12 +680,11 @@ export abstract class AbstractOfflineDB implements OfflineDBApi {
1017
680
  };
1018
681
 
1019
682
  /**
1020
- * A utility method used to handle member events. It guards the processing
1021
- * of each event with a channel guard and also forces an update of member_count
1022
- * for the respective channel if applicable.
683
+ * Removes or upserts the member, forcing a channel upsert so `member_count` updates.
1023
684
  *
1024
- * @param payload.event - the WS event we are trying to process
1025
- * @param payload.execute - Whether to immediately execute the operation (optional, defaults to `true`).
685
+ * @param payload.event - The WS event we are trying to process.
686
+ * @param payload.execute - Whether to immediately execute the queries. Defaults to `true`.
687
+ * @returns The prepared queries.
1026
688
  */
1027
689
  public handleMemberEvent = async ({
1028
690
  event,
@@ -1034,7 +696,6 @@ export abstract class AbstractOfflineDB implements OfflineDBApi {
1034
696
  const { member, cid, type } = event;
1035
697
 
1036
698
  if (member && cid) {
1037
- // we force update here so that member_count gets updated
1038
699
  // TODO: Although this is more than fine for now, we should look into
1039
700
  // changing this to be an actual update to the DB instead.
1040
701
  return await this.queriesWithChannelGuard(
@@ -1057,11 +718,11 @@ export abstract class AbstractOfflineDB implements OfflineDBApi {
1057
718
  };
1058
719
 
1059
720
  /**
1060
- * A utility method used to handle message.updated events. It guards each
1061
- * event handler within a channel guard.
721
+ * Updates the message behind the channel guard. Thread replies are ignored.
1062
722
  *
1063
- * @param payload.event - the WS event we are trying to process
1064
- * @param payload.execute - Whether to immediately execute the operation (optional, defaults to `true`).
723
+ * @param payload.event - The WS event we are trying to process.
724
+ * @param payload.execute - Whether to immediately execute the queries. Defaults to `true`.
725
+ * @returns The prepared queries.
1065
726
  */
1066
727
  public handleMessageUpdatedEvent = async ({
1067
728
  event,
@@ -1084,14 +745,11 @@ export abstract class AbstractOfflineDB implements OfflineDBApi {
1084
745
  };
1085
746
 
1086
747
  /**
1087
- * An event handler for channel.visible and channel.hidden events. We need a separate
1088
- * handler because event.channel.hidden does not arrive with the baseline event, so a
1089
- * simple upsertion is not enough.
1090
- * It will update the hidden property of a channel to true if handling the `channel.hidden`
1091
- * event and to false if handling `channel.visible`.
748
+ * Sets `hidden` from the event type, as the event's channel does not carry it.
1092
749
  *
1093
- * @param payload. - the WS event we are trying to process
1094
- * @param payload.execute - Whether to immediately execute the operation (optional, defaults to `true`).
750
+ * @param payload.event - The WS event we are trying to process.
751
+ * @param payload.execute - Whether to immediately execute the queries. Defaults to `true`.
752
+ * @returns The prepared queries.
1095
753
  */
1096
754
  public handleChannelVisibilityEvent = async ({
1097
755
  event,
@@ -1114,12 +772,11 @@ export abstract class AbstractOfflineDB implements OfflineDBApi {
1114
772
  };
1115
773
 
1116
774
  /**
1117
- * A utility handler used to handle channel.truncated events. It handles both
1118
- * removing all messages and relying on truncated_at as well. It will also upsert
1119
- * reads adequately (and calculate the correct unread messages when truncating).
775
+ * Deletes the channel's messages (before `truncated_at` when set) and upserts the reads.
1120
776
  *
1121
- * @param payload.event - the WS event we are trying to process
1122
- * @param payload.execute - Whether to immediately execute the operation (optional, defaults to `true`).
777
+ * @param payload.event - The WS event we are trying to process.
778
+ * @param payload.execute - Whether to immediately execute the queries. Defaults to `true`.
779
+ * @returns The prepared queries.
1123
780
  */
1124
781
  public handleChannelTruncatedEvent = async ({
1125
782
  event,
@@ -1140,19 +797,16 @@ export abstract class AbstractOfflineDB implements OfflineDBApi {
1140
797
 
1141
798
  let finalQueries = [...truncateQueries];
1142
799
 
1143
- // Persist read state for channels that track reads server-side. When the client opted into a
1144
- // local unread count, also persist it for read-events-disabled channels (e.g. livestreams) so
1145
- // the client-local count survives a cold start. state.read[userId] may be absent for those, so
1146
- // fall back accordingly.
800
+ // Same condition as in `handleNewMessage`.
1147
801
  const userId = ownUser.id;
1148
- const activeChannel = this.client.activeChannels[cid];
802
+ const activeChannel = this.client.channelManager.get(cid);
1149
803
  const tracksReadLocally = channelTracksReadLocally(activeChannel);
1150
- if (activeChannel && (channelHasReadEvents(activeChannel) || tracksReadLocally)) {
804
+ if (activeChannel && (activeChannel.readEventsEnabled || tracksReadLocally)) {
1151
805
  const ownReads = activeChannel.state.read[userId];
1152
806
 
1153
807
  let unreadCount = 0;
1154
- if (truncated_at) {
1155
- unreadCount = activeChannel.countUnread(new Date(truncated_at));
808
+ if (truncated_at != null) {
809
+ unreadCount = activeChannel.countUnread(truncated_at);
1156
810
  }
1157
811
 
1158
812
  const upsertReadQueries = await this.upsertReads({
@@ -1160,10 +814,9 @@ export abstract class AbstractOfflineDB implements OfflineDBApi {
1160
814
  execute: false,
1161
815
  reads: [
1162
816
  {
1163
- last_read: ownReads?.last_read ?? new Date(0),
817
+ last_read: ownReads?.last_read ?? 0,
1164
818
  last_read_message_id: ownReads?.last_read_message_id,
1165
819
  unread_messages: unreadCount,
1166
- // See the note above: supply `blocked_user_ids`, do not assert it.
1167
820
  user: {
1168
821
  ...ownUser,
1169
822
  blocked_user_ids: ownUser.blocked_user_ids ?? [],
@@ -1185,14 +838,11 @@ export abstract class AbstractOfflineDB implements OfflineDBApi {
1185
838
  };
1186
839
 
1187
840
  /**
1188
- * A utility handler for all reaction events. It wraps the inner queries
1189
- * within a channel guard and maps them like so:
1190
- * - reaction.new -> insertReaction
1191
- * - reaction.updated -> updateReaction
1192
- * - reaction.deleted -> deleteReaction
841
+ * Maps `reaction.new`, `.updated` and `.deleted` to the matching reaction write.
1193
842
  *
1194
- * @param payload.event - the WS event we are trying to process
1195
- * @param payload.execute - Whether to immediately execute the operation (optional, defaults to `true`).
843
+ * @param payload.event - The WS event we are trying to process.
844
+ * @param payload.execute - Whether to immediately execute the queries. Defaults to `true`.
845
+ * @returns The prepared queries.
1196
846
  */
1197
847
  public handleReactionEvent = async ({
1198
848
  event,
@@ -1230,12 +880,11 @@ export abstract class AbstractOfflineDB implements OfflineDBApi {
1230
880
  };
1231
881
 
1232
882
  /**
1233
- * A utility handler for all draft events:
1234
- * - draft.updated -> updateDraft
1235
- * - draft.deleted -> deleteDraft
883
+ * Maps `draft.updated` and `draft.deleted` to `upsertDraft` and `deleteDraft`.
1236
884
  *
1237
- * @param payload.event - the WS event we are trying to process
1238
- * @param payload.execute - Whether to immediately execute the operation (optional, defaults to `true`).
885
+ * @param payload.event - The WS event we are trying to process.
886
+ * @param payload.execute - Whether to immediately execute the queries. Defaults to `true`.
887
+ * @returns The prepared queries.
1239
888
  */
1240
889
  handleDraftEvent = async ({
1241
890
  event,
@@ -1269,12 +918,11 @@ export abstract class AbstractOfflineDB implements OfflineDBApi {
1269
918
  };
1270
919
 
1271
920
  /**
1272
- * A generic event handler that decides which DB API to invoke based on
1273
- * event.type for all events we are currently handling. It is used to both
1274
- * react on WS events as well as process the sync API events.
921
+ * Routes an event to its handler by type. Used for WS events and for sync events.
1275
922
  *
1276
- * @param payload.event - the WS event we are trying to process
1277
- * @param payload.execute - Whether to immediately execute the operation (optional, defaults to `true`).
923
+ * @param payload.event - The WS event we are trying to process.
924
+ * @param payload.execute - Whether to immediately execute the queries. Defaults to `true`.
925
+ * @returns The prepared queries.
1278
926
  */
1279
927
  public handleEvent = async ({
1280
928
  event,
@@ -1305,15 +953,17 @@ export abstract class AbstractOfflineDB implements OfflineDBApi {
1305
953
  }
1306
954
 
1307
955
  if (type === 'message.read' || type === 'notification.mark_read') {
956
+ // The DB stores channel reads only, so thread read events are skipped.
957
+ if (event.thread) return [];
1308
958
  return this.handleRead({ event, unreadMessages: 0, execute });
1309
959
  }
1310
960
 
1311
- // `message.read_locally` is the client-only reset dispatched by `Channel.markReadLocally()`. Only
1312
- // persist it for read-events-disabled channels with the local unread count opted in (the only
1313
- // situation it is ever dispatched), so it can never touch channels that track reads server-side.
961
+ // The client-only reset from `Channel.markReadLocally()`: persisted only for channels with a
962
+ // local unread count, never for channels that track reads server-side.
1314
963
  if (type === 'message.read_locally') {
1315
- const localChannel = event.cid ? this.client.activeChannels[event.cid] : undefined;
1316
- // channelTracksReadLocally returns false when localChannel is undefined, so no extra guard.
964
+ const localChannel = event.cid
965
+ ? this.client.channelManager.get(event.cid)
966
+ : undefined;
1317
967
  if (channelTracksReadLocally(localChannel)) {
1318
968
  return this.handleRead({ event, unreadMessages: 0, execute });
1319
969
  }
@@ -1339,13 +989,8 @@ export abstract class AbstractOfflineDB implements OfflineDBApi {
1339
989
  return await this.handleDraftEvent({ event, execute });
1340
990
  }
1341
991
 
1342
- // Note: It is a bit counter-intuitive that we do not touch the messages in the
1343
- // offline DB when receiving notification.message_new, however we do this
1344
- // because we anyway cannot get the messages for a channel until we run
1345
- // either channel.watch() or channel.query(...) to get them. So, when
1346
- // receiving the event we only upsert the channel data and we leave the
1347
- // rest of the entities to be updated whenever we actually start watching
1348
- // or we at least query.
992
+ // `notification.message_new` only upserts the channel data: its messages are stored when the
993
+ // channel is watched or queried.
1349
994
  if (
1350
995
  (type === 'channel.updated' ||
1351
996
  type === 'notification.message_new' ||
@@ -1372,36 +1017,16 @@ export abstract class AbstractOfflineDB implements OfflineDBApi {
1372
1017
  };
1373
1018
 
1374
1019
  /**
1375
- * A method used to enqueue a pending task if the execution of it fails.
1376
- * It will try to do the following:
1377
- *
1378
- * 1. Execute the task immediately
1379
- * 2. If this fails, checks if the failure was due to something valid for a pending task
1380
- * 3. If it is, it will insert the task in the pending tasks table
1381
- *
1382
- * It will return the response from the execution if it succeeded.
1383
- *
1384
- * A task payload is the argument list of the method being replayed, so it carries that
1385
- * method's trailing `requestOptions` too. How far an `AbortSignal` in there survives depends on
1386
- * the path:
1020
+ * Executes the task now. On an {@link isEphemeral} failure the task goes to
1021
+ * `handleAddPendingTask`, and the error is rethrown. With an unhealthy socket it fails with an
1022
+ * `OfflineError` without executing.
1387
1023
  *
1388
- * - Step 1 above never leaves memory, so the signal is live and the call is cancellable exactly
1389
- * as it would be outside the queue. This is the common case.
1390
- * - A task that reaches the pending-tasks table survives only as far as the concrete
1391
- * implementation's storage allows. {@link OfflineDBApi.addPendingTask} and
1392
- * {@link OfflineDBApi.getPendingTasks} make no serialization promise either way: a store that
1393
- * hands back the object it was given keeps the signal live, while one that encodes the payload
1394
- * (as a SQLite-backed store does) revives it as an inert `{}`. Across a process restart it is
1395
- * always the latter.
1024
+ * The payload carries the request options, including an `AbortSignal`. It is live while the task
1025
+ * runs now, but a replay from the table gets an inert `{}` when the store serializes the payload
1026
+ * (always across a restart), and `ApiClient` then runs the request uncancellable.
1396
1027
  *
1397
- * `ApiClient` drops a signal it cannot listen to rather than handing it to axios (which would
1398
- * throw), so a replay that lost its signal simply runs uncancellable.
1399
- *
1400
- * Note that cancelling is not a way to drop a queued task after the fact — an aborted request is
1401
- * a definitive rejection ({@link isEphemeral} is `false` for it), so it is never queued in the
1402
- * first place.
1403
- *
1404
- * @param task - the pending task we want to execute
1028
+ * @param payload.task - The pending task we want to execute.
1029
+ * @returns The response of the task's request.
1405
1030
  */
1406
1031
  public queueTask = async <T>({ task }: { task: PendingTask }): Promise<T> => {
1407
1032
  const attemptTaskExecution = async () => {
@@ -1423,117 +1048,62 @@ export abstract class AbstractOfflineDB implements OfflineDBApi {
1423
1048
  }
1424
1049
  };
1425
1050
 
1426
- /**
1427
- * A utility method that determines if a failed task should be skipped (NOT added to the queue) -
1428
- * i.e. the failure is a definitive rejection rather than an ephemeral/retryable one. A task is
1429
- * kept in the queue only when its error is {@link isEphemeral} (connection/network error or a
1430
- * retryable server code). A non retryable server response (i.e bad request, not allowed etc) is
1431
- * skipped since retrying it would never succeed, and so is a request the caller cancelled via
1432
- * `StreamRequestOptions.signal` - replaying it would defeat the point of aborting.
1433
- *
1434
- * @param error - The error thrown while executing the failed task.
1435
- */
1051
+ /** A definitive rejection (non-retryable server error or a cancelled request) is not queued. */
1436
1052
  private shouldSkipQueueingTask = (error: AxiosError<APIError>) => !isEphemeral(error);
1437
1053
 
1438
- private mergeFailedMessageUpdateIntoPendingSendMessage = ({
1439
- editedMessage,
1440
- pendingMessage,
1441
- }: {
1442
- editedMessage: LocalMessage | Partial<MessageResponse>;
1443
- pendingMessage: MessageRequest;
1444
- }) => {
1445
- const normalizedEditedMessageSource = {
1446
- ...editedMessage,
1447
- } as LocalMessage & { message_text_updated_at?: string };
1448
-
1449
- if ((editedMessage as LocalMessage).status === 'failed') {
1450
- delete normalizedEditedMessageSource.message_text_updated_at;
1451
- }
1452
-
1453
- const normalizedEditedMessage = localMessageToNewMessagePayload(
1454
- normalizedEditedMessageSource,
1455
- );
1456
- const pendingMessageStatus = (pendingMessage as { status?: string }).status;
1457
-
1458
- return {
1459
- ...pendingMessage,
1460
- ...normalizedEditedMessage,
1461
- ...(typeof pendingMessageStatus !== 'undefined'
1462
- ? { status: pendingMessageStatus }
1463
- : {}),
1464
- } as MessageRequest;
1465
- };
1466
-
1467
1054
  private isPendingSendMessageTask = (
1468
1055
  task: PendingTask,
1469
1056
  ): task is Extract<PendingTask, { type: 'send-message' }> =>
1470
1057
  task.type === 'send-message';
1471
1058
 
1472
- private handleOfflineFailedUpdateMessagePendingTask = async (
1059
+ /**
1060
+ * Folds an edit of a never-sent message into its queued `send-message` task, so a replay sends
1061
+ * the edited text once. The send task keeps its row and so its place in the queue. With no send
1062
+ * task the edit is queued on its own if `isMessageUpdateReplayable` allows it.
1063
+ *
1064
+ * A queued send is the only reliable sign the server never saw the message (a `failed` status can
1065
+ * also come from a rejected edit). The payloads are already `MessageRequest`s, so they merge by
1066
+ * plain spread: normalizing again would turn a flattened `mentioned_users` into `[undefined]`.
1067
+ */
1068
+ private handleUpdateMessagePendingTask = async (
1473
1069
  task: Extract<PendingTask, { type: 'update-message' }>,
1474
1070
  ) => {
1475
- const [{ id, message }] = task.payload;
1476
- if (!id) {
1477
- return;
1478
- }
1479
-
1071
+ const [{ id }, { message }] = task.payload;
1480
1072
  const pendingTasks = await this.getPendingTasks({ messageId: id });
1481
- const pendingSendMessageTask = pendingTasks.find(this.isPendingSendMessageTask);
1073
+ const sendTask = pendingTasks.find(this.isPendingSendMessageTask);
1482
1074
 
1483
- if (!pendingSendMessageTask) {
1484
- return;
1485
- }
1075
+ // No queued send, or one without an ID to rewrite (a task read from the DB always has one).
1076
+ if (sendTask?.id === undefined) {
1077
+ if (!isMessageUpdateReplayable(message)) return;
1486
1078
 
1487
- const updatedPendingSendMessage = this.mergeFailedMessageUpdateIntoPendingSendMessage(
1488
- {
1489
- // TODO: this is not good, we have too many message types, should probably only have two (request, response)
1490
- editedMessage: message as unknown as LocalMessage,
1491
- pendingMessage: pendingSendMessageTask.payload[0].message as MessageRequest,
1492
- },
1493
- );
1494
-
1495
- const updatedPendingTask: Extract<PendingTask, { type: 'send-message' }> = {
1496
- ...pendingSendMessageTask,
1497
- payload: [
1498
- {
1499
- ...pendingSendMessageTask.payload[0],
1500
- message: updatedPendingSendMessage,
1501
- },
1502
- ],
1503
- };
1504
-
1505
- if (pendingSendMessageTask.id) {
1506
- await this.updatePendingTask({
1507
- id: pendingSendMessageTask.id,
1508
- task: updatedPendingTask,
1509
- });
1079
+ await this.addPendingTask(task);
1510
1080
  return;
1511
1081
  }
1512
1082
 
1513
- await this.addPendingTask({
1514
- ...updatedPendingTask,
1515
- id: undefined,
1083
+ const [sendRequest, ...sendRequestOptions] = sendTask.payload;
1084
+
1085
+ await this.updatePendingTask({
1086
+ id: sendTask.id,
1087
+ task: {
1088
+ ...sendTask,
1089
+ payload: [
1090
+ { ...sendRequest, message: { ...sendRequest.message, ...message } },
1091
+ ...sendRequestOptions,
1092
+ ],
1093
+ },
1516
1094
  });
1517
1095
  };
1518
1096
 
1519
1097
  /**
1520
- * Central ingress for persisting pending tasks. It either stores the task as-is
1521
- * or rewrites an existing pending `send-message` task for offline edits of failed messages.
1098
+ * Stores the task. An edit of a never-sent message is folded into its queued send instead. With no
1099
+ * queued send, an edit `isMessageUpdateReplayable` refuses (attachments still on local URLs) is
1100
+ * dropped.
1101
+ *
1102
+ * @param payload.task - The pending task to store.
1522
1103
  */
1523
1104
  public handleAddPendingTask = async ({ task }: { task: PendingTask }) => {
1524
- if (
1525
- task.type === 'update-message' &&
1526
- !isMessageUpdateReplayable(task.payload[0].message ?? {})
1527
- ) {
1528
- return;
1529
- }
1530
-
1531
- if (
1532
- task.type === 'update-message' &&
1533
- !this.client.wsConnection?.isHealthy &&
1534
- (task.payload[0].message as { status?: string } | undefined)?.status === 'failed'
1535
- ) {
1536
- await this.handleOfflineFailedUpdateMessagePendingTask(task);
1105
+ if (task.type === 'update-message') {
1106
+ await this.handleUpdateMessagePendingTask(task);
1537
1107
  return;
1538
1108
  }
1539
1109
 
@@ -1541,30 +1111,8 @@ export abstract class AbstractOfflineDB implements OfflineDBApi {
1541
1111
  };
1542
1112
 
1543
1113
  /**
1544
- * Executes a task from the list of supported pending tasks. Currently supported pending tasks
1545
- * are:
1546
- * - Updating a message
1547
- * - Deleting a message
1548
- * - Sending a reaction
1549
- * - Removing a reaction
1550
- * - Sending a message
1551
- * - Creating a draft
1552
- * - Deleting a draft
1553
- * It will throw if we try to execute a pending task that is not supported.
1554
- *
1555
- * @param task - The task we want to execute
1556
- * @param isPendingTask - a control value telling us if it's an actual pending task being executed
1557
- * or delayed execution
1558
- */
1559
- /**
1560
- * Replays one queued operation, through the {@link QUEUEABLE_OPERATIONS} registry rather than a
1561
- * per-type branch here — the same registry a first attempt resolves through, so the two cannot
1562
- * describe different requests.
1563
- *
1564
- * @param task - the task to run.
1565
- * @param isPendingTask - whether this is a replay rather than a first attempt. A first attempt has an
1566
- * optimistic layer above it that settles local state; a replay does not, so some operations have to
1567
- * settle it themselves (see `onReplay`).
1114
+ * Runs the task through {@link QUEUEABLE_OPERATIONS}. With `isPendingTask` (a replay) it also
1115
+ * runs the operation's `onReplay`.
1568
1116
  */
1569
1117
  private executeTask = async <T extends QueueableType>(
1570
1118
  { task }: { task: PendingTaskOf<T> },
@@ -1581,10 +1129,8 @@ export abstract class AbstractOfflineDB implements OfflineDBApi {
1581
1129
  };
1582
1130
 
1583
1131
  /**
1584
- * A utility method used to execute all pending tasks. As each task succeeds execution,
1585
- * it is going to be removed from the DB. If the execution failed due to a valid reason
1586
- * it is going to remove the pending task from the DB even if execution fails, otherwise
1587
- * it will keep it for the next time we try to execute all pending taks.
1132
+ * Replays the pending tasks in order and deletes each one that succeeded or was definitively
1133
+ * rejected. A task that failed for an ephemeral reason stays for the next run.
1588
1134
  */
1589
1135
  public executePendingTasks = async () => {
1590
1136
  const queue = await this.getPendingTasks();
@@ -1601,9 +1147,13 @@ export abstract class AbstractOfflineDB implements OfflineDBApi {
1601
1147
  true,
1602
1148
  );
1603
1149
  } catch (e) {
1150
+ const operation = QUEUEABLE_OPERATIONS[task.type] as QueueableOperation<
1151
+ typeof task.type
1152
+ >;
1153
+ operation.onReplayRejected?.({ client: this.client, error: e, task });
1154
+
1604
1155
  const error = e as AxiosError<APIError>;
1605
1156
  if (!this.shouldSkipQueueingTask(error)) {
1606
- // executing the pending task has failed, so keep it in the queue
1607
1157
  continue;
1608
1158
  }
1609
1159
  }