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
package/src/channel.ts CHANGED
@@ -1,23 +1,26 @@
1
1
  import { ChannelState, ChannelWatchStatus } from './channel_state';
2
+ import { isEqual } from './utils/mergeWith/mergeWithCore';
2
3
  import { CooldownTimer } from './CooldownTimer';
3
4
  import { queueOrRun } from './offline-support/queueableOperations';
4
5
  import { MessageComposer } from './messageComposer';
5
6
  import { MessageReceiptsTracker } from './messageDelivery';
6
7
  import type { ReadStoreReconcileMeta } from './messageDelivery';
7
8
  import { MessagePaginator, PinnedMessagePaginator } from './pagination/paginators';
8
- import {
9
- addReactionOptimistically,
10
- createMessageOperationsPersistence,
11
- deleteReactionOptimistically,
12
- MessageOperations,
13
- } from './messageOperations';
9
+ import { createMessageOperations, reflectReactionEvent } from './messageOperations';
10
+ import type { MessageOperations } from './messageOperations';
11
+ import type { OperationRequestFn } from './messageOperations/types';
14
12
  import {
15
13
  channelHasReadEvents,
16
14
  formatMessage,
17
15
  generateChannelTempCid,
18
- localMessageToNewMessagePayload,
16
+ getMemberUserId,
17
+ invokeEventListener,
18
+ isThreadOnlyReply,
19
19
  logChatPromiseExecution,
20
+ sanitizeOutgoingAttachments,
20
21
  } from './utils';
22
+ import { asTimestampNS, nowNs } from './utils/time';
23
+ import { abortError, waitUnlessAborted } from './utils/abort';
21
24
  import { normalizeUploadFile } from './upload-utils';
22
25
  import type { StreamChat } from './client';
23
26
  import { chatLoggerSystem } from './logger';
@@ -27,6 +30,7 @@ import { copyConfigPatch } from './configuration/utils/copyConfigPatch';
27
30
  import { deepFreezeConfig } from './configuration/utils/deepFreezeConfig';
28
31
  import { mergeServerRestrictions } from './configuration/utils/serverAuthority';
29
32
  import type { ServerRestrictions } from './configuration/utils/serverAuthority';
33
+ import type { CustomEventData } from './custom_types';
30
34
  import type { ChannelDeclarativeConfig } from './configuration/types';
31
35
  import {
32
36
  mergeDeclarativeMessageOperationsConfig,
@@ -34,46 +38,42 @@ import {
34
38
  toDeclarativePaginatorConfig,
35
39
  } from './configuration/utils/declarativeSlices';
36
40
  import type {
41
+ AddMembersRequest,
37
42
  AIState,
38
43
  BanUserOptions,
39
44
  ChannelGetOrCreateRequest,
40
45
  ChannelInput,
41
46
  ChannelMemberResponse,
42
47
  ChannelResponse,
48
+ ChannelStateResponse,
43
49
  ChannelStateResponseFields,
44
- ChannelUpdateOptions,
45
50
  Command,
46
- DeleteMessageOptions,
47
51
  Event,
48
52
  EventHandler,
49
53
  EventPayload,
50
54
  EventType,
51
55
  FileUploadInput,
56
+ FilterTagsRequest,
57
+ InviteMembersRequest,
52
58
  LocalMessage,
53
59
  MarkReadRequest,
54
60
  MarkReadResponse,
55
- MessagePaginationParams,
56
- MessageRequest,
57
61
  MessageResponse,
58
- MessageSetType,
59
62
  QueryMembersPayload,
60
- ReactionRequest,
61
- SendMessageOptions,
62
- SendReactionRequest,
63
+ RemoveMembersRequest,
63
64
  SharedLocation,
64
65
  StreamRequestOptions,
65
66
  StreamResponse,
67
+ TimestampNS,
66
68
  UnBanUserOptions,
67
69
  UpdateChannelPartialRequest,
68
70
  UpdateLiveLocationRequest,
69
- UpdateMessageOptions,
70
71
  UserResponse,
71
72
  } from './types';
72
73
  import { AIStates } from './types';
73
- import type { StateStore } from './store';
74
- import type { Unsubscribe } from './store';
74
+ import type { StateStore } from '@stream-io/state-store';
75
+ import type { Unsubscribe } from '@stream-io/state-store';
75
76
  import type {
76
- ChannelMemberRequest as Gen_ChannelMemberRequest,
77
77
  ChannelPushPreferencesResponse as Gen_ChannelPushPreferencesResponse,
78
78
  MuteChannelRequest as Gen_MuteChannelRequest,
79
79
  UnmuteChannelRequest as Gen_UnmuteChannelRequest,
@@ -86,55 +86,25 @@ import { ChannelApi } from './gen/chat/ChannelApi';
86
86
 
87
87
  const logger = chatLoggerSystem.getLogger('channel');
88
88
 
89
- // todo: move to dedicated file
90
- export type SendMessageWithStateUpdateParams = {
91
- localMessage: LocalMessage;
92
- message?: MessageRequest;
93
- options?: SendMessageOptions;
94
- /**
95
- * Per-call override for the send/retry request (advanced).
96
- * If set, it takes precedence over channel instance configuration handlers.
97
- */
98
- sendMessageRequestFn?: CustomSendMessageRequestFn;
99
- };
100
-
101
- export type RetrySendMessageWithLocalUpdateParams = Omit<
102
- SendMessageWithStateUpdateParams,
103
- 'message'
104
- >;
89
+ const WATCH_WAIT_ABORTED = 'The wait for the channel watch was aborted.';
105
90
 
106
- export type UpdateMessageWithStateUpdateParams = {
107
- localMessage: LocalMessage;
108
- options?: UpdateMessageOptions;
109
- /**
110
- * Per-call override for the update request (advanced).
111
- * If set, it takes precedence over channel instance configuration handlers.
112
- */
113
- updateMessageRequestFn?: CustomUpdateMessageRequestFn;
91
+ /** A watch query {@link Channel.watch} sent; cancelled once none of its callers waits. */
92
+ type WatchQueryInFlight = {
93
+ options: ChannelGetOrCreateRequest;
94
+ promise: Promise<void>;
95
+ abortController: AbortController;
96
+ waitingCount: number;
114
97
  };
115
98
 
116
- export type DeleteMessageWithStateUpdateParams = {
117
- localMessage: LocalMessage;
118
- options?: DeleteMessageOptions;
119
- /**
120
- * Per-call override for the delete request (advanced).
121
- * If set, it takes precedence over channel instance configuration handlers.
122
- */
123
- deleteMessageRequestFn?: CustomDeleteMessageRequestFn;
124
- };
125
-
126
- // Custom request function types for configuration
127
- export type CustomSendMessageRequestFn = (
128
- params: Omit<SendMessageWithStateUpdateParams, 'sendMessageRequestFn'>,
129
- ) => Promise<{ message: MessageResponse }>;
130
-
131
- export type CustomUpdateMessageRequestFn = (
132
- params: Omit<UpdateMessageWithStateUpdateParams, 'updateMessageRequestFn'>,
133
- ) => Promise<{ message: MessageResponse }>;
134
-
135
- export type CustomDeleteMessageRequestFn = (
136
- params: Omit<DeleteMessageWithStateUpdateParams, 'deleteMessageRequestFn'>,
137
- ) => Promise<{ message: MessageResponse }>;
99
+ /** Re-exported here because `src/messageOperations` is not in the root barrel. */
100
+ export type {
101
+ DefaultOperationRequest,
102
+ MessageOperationSpec,
103
+ OperationKind,
104
+ OperationParams,
105
+ OperationRequestFn,
106
+ OperationResponse,
107
+ } from './messageOperations/types';
138
108
 
139
109
  export type CustomMarkReadRequestFn = (params: {
140
110
  channel: Channel;
@@ -142,81 +112,53 @@ export type CustomMarkReadRequestFn = (params: {
142
112
  }) => Promise<Partial<StreamResponse<MarkReadResponse>> | null>;
143
113
 
144
114
  /**
145
- * A channel's **resolved** configuration — what {@link Channel.config} returns.
146
- *
147
- * Not `ChannelConfigWithInfo`, which is the generated type for the channel *type's server*
148
- * configuration behind {@link Channel.serverConfig}. The two are related: the gates below are the
149
- * server's flags already ANDed with what the integrator registered.
115
+ * A channel's resolved configuration, returned by {@link Channel.config}. The gates are the server's
116
+ * flags (see {@link Channel.serverConfig}) ANDed with what the integrator registered.
150
117
  */
151
118
  export type ChannelConfig = {
152
119
  requestHandlers?: {
153
- deleteMessageRequest?: CustomDeleteMessageRequestFn;
120
+ deleteMessageRequest?: OperationRequestFn<'delete'>;
154
121
  markReadRequest?: CustomMarkReadRequestFn;
155
- sendMessageRequest?: CustomSendMessageRequestFn;
156
- retrySendMessageRequest?: CustomSendMessageRequestFn;
157
- updateMessageRequest?: CustomUpdateMessageRequestFn;
122
+ sendMessageRequest?: OperationRequestFn<'send'>;
123
+ retrySendMessageRequest?: OperationRequestFn<'retry'>;
124
+ updateMessageRequest?: OperationRequestFn<'update'>;
158
125
  };
159
126
  /**
160
- * Typing indicators for this channel (defaults to enabled). ANDed with the channel type's
161
- * `typing_events`, so either side can switch them off and neither can widen.
162
- *
163
- * This is the channel-wide gate, read by {@link Channel.keystroke} and {@link Channel.stopTyping}.
164
- * `messageComposer.text.publishTypingEvents` sits on top of it as a per-composer refinement — a thread
165
- * composer can stay quiet while the channel still permits typing events.
127
+ * Typing indicators. Defaults to enabled. ANDed with the channel type's `typing_events`. Read by
128
+ * {@link Channel.keystroke} and {@link Channel.stopTyping}.
129
+ * `messageComposer.text.publishTypingEvents` further switches them off per composer.
166
130
  */
167
131
  typingEvents: { enabled: boolean };
168
132
  /**
169
- * Read receipts for this channel (defaults to enabled). ANDed with the channel type's `read_events`,
170
- * so either side can switch them off and neither can widen. Read by {@link Channel.markRead} and
171
- * {@link Channel.markUnread}.
172
- */
173
- readEvents: { enabled: boolean };
174
- /**
175
- * Threaded replies for this channel (defaults to enabled). ANDed with the channel type's `replies`.
133
+ * Read receipts. `enabled` is ANDed with the channel type's `read_events`. Together with the own
134
+ * `read-events` capability it decides {@link Channel.readEventsEnabled}, which gates counting
135
+ * unread messages, {@link Channel.markRead} and {@link Channel.markUnread}. Defaults to `true`.
136
+ *
137
+ * `localUnreadCountEnabled` applies only while read events are off
138
+ * ({@link Channel.readEventsEnabled} is false): the channel keeps counting unread messages and
139
+ * {@link Channel.markReadLocally} resets the count, sending nothing to the server. The server does
140
+ * not restrict it. Defaults to `false`.
176
141
  */
142
+ readEvents: { enabled: boolean; localUnreadCountEnabled: boolean };
143
+ /** Threaded replies. Defaults to enabled. ANDed with the channel type's `replies`. */
177
144
  replies: { enabled: boolean };
178
145
  /**
179
- * Message reminders — "remind me" and "save for later" (defaults to enabled). ANDed with the channel
180
- * type's `user_message_reminders`.
146
+ * Message reminders. Defaults to enabled. ANDed with the channel type's `user_message_reminders`.
181
147
  */
182
148
  userMessageReminders: { enabled: boolean };
183
- /**
184
- * Delivery receipts (defaults to enabled). ANDed with the channel type's `delivery_events`.
185
- */
149
+ /** Delivery receipts. Defaults to enabled. ANDed with the channel type's `delivery_events`. */
186
150
  deliveryEvents: { enabled: boolean };
187
151
  /**
188
- * The slash commands this channel type offers, as the server reports them.
189
- *
190
- * Named for availability rather than enablement on purpose: whether any given command can be *used*
191
- * right now is `messageComposer.isCommandDisabled(command)`, which depends on the message context —
192
- * editing and quoting disable different ones. A list called `enabledCommands` would routinely contain
193
- * disabled entries.
194
- *
195
- * **Server-owned, and the one field here the integrator cannot set.** It is a list rather than a gate,
196
- * so there is nothing to AND and no intent to express — the server's answer simply *is* the value, and
197
- * it is absent from the declarative tree for that reason.
198
- *
199
- * It lives on the resolved configuration anyway so that consumers never need a second place to look:
200
- * every question about what this channel permits is answered by `config`. Reading the raw
201
- * {@link Channel.serverConfig} instead is what made a UI show features the client had disabled — the
202
- * gates below have a client half, and mixing the two sources meant sometimes reading only one.
152
+ * The slash commands the channel type offers. Server-owned: the integrator cannot set it. Whether a
153
+ * command can be used right now is `messageComposer.isCommandDisabled(command)`.
203
154
  */
204
155
  availableCommands: Command[];
205
156
  };
206
157
 
207
158
  /**
208
- * Frozen for the same reason every other default config constant is: resolution spreads over it, so a
209
- * subtree no layer touches stays identical by reference and would otherwise be mutable through the
210
- * public `channel.config`. See `deepFreezeConfig`.
211
- */
212
- /**
213
- * The fields of the declarative `channel` slice that a channel resolves for **itself**.
214
- *
215
- * The slice also carries `messagePaginator`, `pinnedMessagesPaginator` and `messageOperations`, which are
216
- * handed to those objects directly (see {@link Channel.initializeConfig}). Passing the whole slice to the
217
- * controller published them on `channel.config` as well, where nothing read them: `ChannelConfig` does not
218
- * declare them, and a registration against one of them notified every `configState` subscriber for a change
219
- * that did not concern the channel.
159
+ * The fields of the declarative `channel` slice that the channel resolves for itself. The rest
160
+ * (`messagePaginator`, `pinnedMessagesPaginator`, `messageOperations`) go to those objects, see
161
+ * {@link Channel.initializeConfig}.
220
162
  */
221
163
  const ownDeclarativeConfig = (
222
164
  slice?: ChannelDeclarativeConfig,
@@ -245,65 +187,55 @@ const ownDeclarativeConfig = (
245
187
  export const DEFAULT_CHANNEL_CONFIG: ChannelConfig = deepFreezeConfig({
246
188
  availableCommands: [],
247
189
  deliveryEvents: { enabled: true },
248
- readEvents: { enabled: true },
190
+ readEvents: { enabled: true, localUnreadCountEnabled: false },
249
191
  replies: { enabled: true },
250
192
  typingEvents: { enabled: true },
251
193
  userMessageReminders: { enabled: true },
252
194
  });
253
195
 
254
- /**
255
- * The Channel class manages its own state.
256
- */
257
196
  export class Channel extends ChannelApi {
258
197
  _client: StreamChat;
259
- data: Partial<ChannelResponse> | undefined;
260
198
  _data: ChannelInput;
261
199
  cid: string;
262
- /** */
263
200
  listeners: Map<EventType, Set<EventHandler>>;
264
201
  state: ChannelState;
265
202
  lastKeyStroke?: Date;
266
203
  lastTypingEvent: Date | null;
267
204
  isTyping: boolean;
268
- /** Re-entrancy guard for {@link Channel.reload} (mirrors Thread.reload's isLoading guard). */
205
+ /** Re-entrancy guard for {@link Channel.reload}. */
269
206
  private _reloading = false;
270
- /** Refcount backing the reactive `active` flag (a shared Channel instance can have several consumers). */
207
+ /** Refcount behind the `active` flag: several consumers can hold one instance. */
271
208
  private _activeRefCount = 0;
272
- push_preferences?: Gen_ChannelPushPreferencesResponse;
209
+ /** Stops releaseUnusedChannels() from removing a channel while a query for it is still running. */
210
+ private _channelQueriesInFlight = 0;
211
+ /** The watch queries {@link Channel.watch} callers wait for, joined by equal options. */
212
+ private _watchQueriesInFlight: WatchQueryInFlight[] = [];
273
213
  /**
274
- * The shared configuration machinery. Owned rather than inherited — `Channel` already extends
275
- * `ChannelApi`, so single inheritance is spent.
276
- *
277
- * `mergeSlice: 'deep'` because the config has nested groups: registering `typingEvents.enabled` must
278
- * not drop `readEvents`. `applyAuthority` is what makes `channel.config` the *whole* answer rather
279
- * than the client's half — see {@link serverRestrictions}.
214
+ * The options of the last {@link Channel.watch} query that succeeded during the current watch: a
215
+ * `watch()` with these options has nothing to send. Cleared when the watch ends.
280
216
  */
217
+ private _lastWatchOptions?: ChannelGetOrCreateRequest;
218
+ push_preferences?: Gen_ChannelPushPreferencesResponse;
281
219
  private readonly configController: ConfigController<ChannelConfig>;
282
220
  public readonly messageComposer: MessageComposer;
283
221
  public readonly messageReceiptsTracker: MessageReceiptsTracker;
222
+ public readonly messageOperations: MessageOperations;
284
223
  public readonly messagePaginator: MessagePaginator;
285
224
  public readonly pinnedMessagesPaginator: PinnedMessagePaginator;
286
- public readonly messageOperations: MessageOperations;
287
225
  public readonly cooldownTimer: CooldownTimer;
288
- /**
289
- * Teardown for this channel's configuration subscription, released by {@link _disconnect}. Channels
290
- * are retained in `client.activeChannels`, so leaving this subscribed would keep growing the
291
- * configuration store's handler set across reconnects.
292
- */
293
226
  private unsubscribeConfiguration?: Unsubscribe;
294
- /** Teardown for the server-config re-derivation subscription, released by {@link _disconnect}. */
295
227
  private unsubscribeServerConfig?: Unsubscribe;
296
- /** The declarative slice last derived from, so a late server answer can re-derive from the same one. */
228
+ /** The declarative slice last derived from, so a late server config can re-derive from it. */
297
229
  private declarativeConfig?: Partial<ChannelConfig>;
298
230
 
299
231
  /**
300
- * Creates a `Channel` instance bound to the given chat client.
232
+ * Creates an uninitialized channel. Without an `id` its `cid` is a temporary one built from
233
+ * `data.members`, until the server answers.
301
234
  *
302
235
  * @param client - The chat client.
303
- * @param type - The type of channel.
304
- * @param id - The ID of the chat (optional).
305
- * @param data - Any additional custom params.
306
- * @returns A new uninitialized channel.
236
+ * @param type - The channel type.
237
+ * @param id - The channel ID, or `undefined` for a channel created from members.
238
+ * @param data - Data for the channel (members, custom fields).
307
239
  */
308
240
  constructor(
309
241
  client: StreamChat,
@@ -324,42 +256,38 @@ export class Channel extends ChannelApi {
324
256
  super(client, type, id);
325
257
 
326
258
  this._client = client;
327
- // used by the frontend, gets updated:
328
- this.data = data as Partial<ChannelResponse>;
329
- // this._data is used for the requests...
330
259
  this._data = { ...data };
331
- this.cid = `${type}:${id}`;
260
+ // Without an ID the cid is a temporary one: the key the channel is stored under
261
+ // (`ensure({ members })`).
262
+ this.cid =
263
+ (!id && generateChannelTempCid(type, (data.members ?? []).map(getMemberUserId))) ||
264
+ `${type}:${id}`;
332
265
  this.listeners = new Map();
333
- // perhaps the state variable should be private
334
266
  this.state = new ChannelState(this);
267
+ // after the state exists: the `data` setter writes to it
268
+ this.data = data as Partial<ChannelResponse>;
335
269
  this.lastTypingEvent = null;
336
270
  this.isTyping = false;
337
271
 
338
- // Read the declarative configuration *now*, so it can go into the sub-objects as constructor
339
- // options. Some of their fields are read once during construction (`unreadReferencePolicy`, the
340
- // initial cursor/offset), so configuring them afterwards would silently do nothing.
272
+ // Read before the sub-objects are built: some of their fields are read once at construction
273
+ // (`unreadReferencePolicy`, the initial cursor/offset).
341
274
  const declarativeConfig = client.config.getConfig('channel') ?? undefined;
342
- // The general `messagePaginator` key applies to every MessagePaginator — this channel's list and
343
- // every thread's replies. The per-parent slice below overrides it.
275
+ // The shared `messagePaginator` key applies to every MessagePaginator (channel and threads); the
276
+ // channel's own slice overrides it.
344
277
  const messagePaginatorConfig = mergeDeclarativePaginatorConfig(
345
278
  client.config.getConfig('messagePaginator') ?? undefined,
346
279
  declarativeConfig?.messagePaginator,
347
280
  );
348
281
 
349
- // The composer reads its own key (`messageComposer`) from the client, so nothing is passed here —
350
- // composer configuration is deliberately not nested under `channel`.
351
282
  this.messageComposer = new MessageComposer({
352
283
  client: this._client,
353
284
  compositionContext: this,
354
285
  });
355
286
 
356
- // Created before MessageReceiptsTracker and CooldownTimer: both read the message paginator
357
- // (receipts resolve read cursors via findItemByTimestamp; CooldownTimer.refresh reads the
358
- // latest window at construction).
287
+ // Created before MessageReceiptsTracker and CooldownTimer, which read it.
359
288
  this.messagePaginator = new MessagePaginator({
360
289
  channel: this,
361
- // Split: the policy is a constructor argument, the rest is configuration. Passing the whole slice
362
- // put a non-config key into the paginator's published `config` — see `toDeclarativePaginatorConfig`.
290
+ // A constructor argument, not config (`toDeclarativePaginatorConfig` drops it).
363
291
  unreadReferencePolicy: messagePaginatorConfig?.unreadReferencePolicy,
364
292
  paginatorOptions: {
365
293
  declarativeConfig: toDeclarativePaginatorConfig(messagePaginatorConfig),
@@ -376,107 +304,9 @@ export class Channel extends ChannelApi {
376
304
  this.cooldownTimer = new CooldownTimer({ channel: this });
377
305
  this.cooldownTimer.registerSubscriptions();
378
306
 
379
- this.messageOperations = new MessageOperations({
380
- ...createMessageOperationsPersistence({ channel: this }),
381
- ingest: (m) => {
382
- const store = this.getClient().messageStore;
383
- // The paginator is the entry point whenever it can hold the message — it owns interval
384
- // placement, and its "no longer matches the filter" branch correctly evicts a message that
385
- // stopped matching. But its filter is `{ cid, parent_id? }`, so an operation aimed at a message
386
- // this paginator does not accept (most importantly a THREAD PARENT edited or deleted from
387
- // inside the open thread, which the reply paginator rejects for having no `parent_id`) would
388
- // otherwise be silently dropped. Falling back to the client-global store reaches the message
389
- // wherever it is held and fans out to every collection holding it — the same reason
390
- // `applyReactionLocally` addresses purely by id.
391
- if (this.messagePaginator.matchesFilter(m)) {
392
- this.messagePaginator.ingestItem(m);
393
- } else if (store.has(m.id)) {
394
- store.upsert(m);
395
- }
396
- store.flushSubscribers(m.id);
397
- },
398
- // Mirrors `ingest`'s routing: a message this paginator does not hold can still be held by the
399
- // client-global store (a thread parent, a message displayed by another collection), and the
400
- // policy uses this both for its freshness comparison and to decide whether there is anything to
401
- // update optimistically at all. Reading only the paginator would make those two disagree.
402
- get: (id) =>
403
- this.messagePaginator.getItem(id) ?? this.getClient().messageStore.get(id),
404
- remove: (id) => {
405
- const parentId =
406
- this.messagePaginator.getItem(id)?.parent_id ??
407
- this.getClient().messageStore.get(id)?.parent_id;
408
-
409
- this.messagePaginator.removeItem({ id });
410
- this.pinnedMessagesPaginator.removeItem({ id });
411
-
412
- if (parentId) {
413
- this.getClient().threads.threadsById[parentId]?.messagePaginator.removeItem({
414
- id,
415
- });
416
- }
417
- },
418
- handlers: () => {
419
- const { requestHandlers } = this.configState.getLatestValue();
420
- const deleteMessageRequest = requestHandlers?.deleteMessageRequest;
421
- const sendMessageRequest = requestHandlers?.sendMessageRequest;
422
- const retrySendMessageRequest = requestHandlers?.retrySendMessageRequest;
423
- const updateMessageRequest = requestHandlers?.updateMessageRequest;
424
- return {
425
- delete: deleteMessageRequest
426
- ? (p) =>
427
- deleteMessageRequest({
428
- localMessage: p.localMessage,
429
- options: p.options,
430
- })
431
- : undefined,
432
- send: sendMessageRequest
433
- ? (p) =>
434
- sendMessageRequest({
435
- localMessage: p.localMessage,
436
- message: p.message,
437
- options: p.options,
438
- })
439
- : undefined,
440
- retry: retrySendMessageRequest
441
- ? (p) =>
442
- retrySendMessageRequest({
443
- localMessage: p.localMessage,
444
- message: p.message,
445
- options: p.options,
446
- })
447
- : undefined,
448
- update: updateMessageRequest
449
- ? (p) =>
450
- updateMessageRequest({
451
- localMessage: p.localMessage,
452
- options: p.options,
453
- })
454
- : undefined,
455
- };
456
- },
457
- defaults: {
458
- delete: async (id, o) => {
459
- const result = await this.getClient().deleteMessage({ id, ...o });
460
- return { message: result.message };
461
- },
462
- send: async (m, o) => {
463
- const result = await this.sendMessage({ message: m, ...o });
464
- return { message: result.message };
465
- },
466
- update: async (m, o) => {
467
- const result = await this.getClient().updateMessage({
468
- id: m.id,
469
- message: localMessageToNewMessagePayload(m),
470
- ...o,
471
- });
472
- return { message: result.message };
473
- },
474
- },
475
- });
307
+ this.messageOperations = createMessageOperations(this);
476
308
 
477
- // Seed the reactive mute state from the client's current `mutedChannels` (a channel created
478
- // after connect may already be muted). Kept in sync afterwards by the client fan-out on
479
- // `notification.channel_mutes_updated` / `health.check`.
309
+ // A channel created after connect may already be muted.
480
310
  this._syncMuteStatus();
481
311
 
482
312
  this.configController = new ConfigController<ChannelConfig>({
@@ -484,13 +314,8 @@ export class Channel extends ChannelApi {
484
314
  initialSlice: ownDeclarativeConfig(declarativeConfig),
485
315
  // Nested groups: naming `typingEvents.enabled` must not drop `readEvents`.
486
316
  mergeSlice: 'deep',
487
- // Frozen so a nested write throws instead of changing state silently. Freezing
488
- // DEFAULT_CHANNEL_CONFIG is not enough on its own: resolution rebuilds the gate subtrees every
489
- // time, so the resolved config holds new unfrozen objects rather than the frozen defaults.
490
- //
491
- // Copied first, because a subtree of the resolved object and the matching subtree of the slice
492
- // stored in `client.config` can be the same object — so freezing one freezes the other, and the
493
- // paginators that resolve from that slice could no longer merge into it.
317
+ // Frozen so a nested write throws. Copied first: a subtree of the resolved config can be the same
318
+ // object as one in the slice stored in `client.config`, and freezing it would freeze that slice.
494
319
  applyAuthority: (requested) =>
495
320
  deepFreezeConfig(
496
321
  copyConfigPatch({
@@ -498,57 +323,41 @@ export class Channel extends ChannelApi {
498
323
  requested,
499
324
  this.serverRestrictions,
500
325
  ) as ChannelConfig),
501
- // Assigned rather than merged: the deep merge would concatenate the two lists, and the
502
- // server owns this one outright.
326
+ // Assigned, not merged: the deep merge would concatenate the lists.
503
327
  availableCommands: this.serverConfig?.commands ?? [],
504
328
  }),
505
329
  ) as ChannelConfig,
506
330
  });
507
331
 
508
- // The server's answer usually arrives *after* construction — a channel built before it has been
509
- // queried or watched reads `serverConfig` as undefined, so the restrictions state nothing and the
510
- // defaults stand. Re-derive when this channel's config lands, or an app that disables `read_events`
511
- // server-side would keep a channel that believes read receipts are on.
512
- //
513
- // Selected by cid, and `this.cid` is read at selection time rather than captured: a channel created
514
- // from members alone starts on a temporary cid and adopts the server's in `query()`, which assigns
515
- // it *before* calling `_addChannelConfig`, so the write that carries the config is already selecting
516
- // under the real key.
332
+ // The server config usually arrives after construction: re-derive when it lands. `this.cid` is read
333
+ // at selection time because `query()` swaps a temporary cid for the real one before
334
+ // `_addChannelConfig`.
517
335
  this.unsubscribeServerConfig = client.channelServerConfigsStore.subscribeWithSelector(
518
336
  ({ configs }) => ({ channelConfig: configs[this.cid] }),
519
337
  () => this.configController.rederive(this.declarativeConfig),
520
338
  );
521
339
 
522
- // Share one derivation path with `config.reset()`, so the two cannot drift. Idempotent: the
523
- // sub-objects were already configured through their constructors above; this re-applies the
524
- // mutable half through the same code a reset uses.
340
+ // The same derivation `config.reset()` runs. The sub-objects were already configured by their
341
+ // constructors; this re-applies the mutable half.
525
342
  this.initializeConfig(declarativeConfig);
526
343
 
527
- // Last statement of the constructor: every sub-object a setup function might reach now exists.
528
- // A throwing setup function is contained by the helper, so it cannot break `client.channel()`.
344
+ // Last in the constructor: setup functions may reach every sub-object. Their errors are contained.
529
345
  this.unsubscribeConfiguration = applyInstanceConfiguration({
530
346
  args: { channel: this },
531
347
  config: client.config,
532
348
  key: 'channel',
533
349
  applyConfig: (config) => this.initializeConfig(config),
534
- // Reads the slice *fresh* rather than replaying a remembered one: by the time reset calls this,
535
- // the declarative store has been cleared, so this correctly derives the un-configured baseline.
350
+ // Reads the slice fresh: reset clears the declarative store before calling this.
536
351
  reinitializeConfig: () =>
537
352
  this.initializeConfig(client.config.getConfig('channel') ?? undefined),
538
- // This channel's message paginator also derives from the shared `messagePaginator` key, so a
539
- // change there has to run the full cycle — declarative then setup function — rather than a bare
540
- // re-derivation, which would drop the setup function's overrides.
353
+ // The message paginator and message operations also derive from these shared keys, so a change
354
+ // re-runs the full cycle (declarative, then setup function) to keep the setup function's
355
+ // overrides.
541
356
  alsoWatch: ['messagePaginator', 'messageOperations'],
542
357
  });
543
358
  }
544
359
 
545
- /**
546
- * The configuration fields this channel's *type* decides server-side.
547
- *
548
- * Both are boolean gates, so `mergeServerRestrictions` ANDs them with what was requested: either the
549
- * server or the integrator may switch a feature off, and neither can widen. Re-read on every
550
- * derivation rather than captured, so a flag that changes mid-session is picked up.
551
- */
360
+ /** Flags the channel type decides server-side (ANDed with the requested ones). */
552
361
  private get serverRestrictions(): ServerRestrictions<ChannelConfig> {
553
362
  const channelConfig = this.serverConfig;
554
363
 
@@ -562,29 +371,21 @@ export class Channel extends ChannelApi {
562
371
  }
563
372
 
564
373
  /**
565
- * Derives this channel's configuration — and its sub-objects' — from the declarative slice.
374
+ * Re-derives the configuration of the channel, its paginators and its message operations from the
375
+ * declarative slice. Runs at construction, on every change to the `channel`, `messagePaginator` or
376
+ * `messageOperations` configuration, and on `client.config.reset()`.
566
377
  *
567
- * Called by the constructor and by `client.config.reset()`. The channel owns only its own
568
- * `requestHandlers`; each sub-object derives its own configuration, so the knowledge of what
569
- * `messagePaginator.pageSize` means stays inside the paginator.
378
+ * @param declarativeConfig - The channel's declarative slice (optional).
570
379
  */
571
380
  initializeConfig(declarativeConfig?: ChannelDeclarativeConfig): void {
572
- // Remembered so the server-config subscription can re-derive from the same slice without being
573
- // handed it again — the server's answer arrives on its own schedule, not the tree's.
574
381
  this.declarativeConfig = declarativeConfig as Partial<ChannelConfig> | undefined;
575
382
 
576
- // A derivation, so it *replaces*: a handler dropped from the declarative tree has to disappear.
577
- // Anything else writing directly into `configState.requestHandlers` — the React SDK's
578
- // per-component props do — has to re-apply afterwards; see the note in `useChannelRequestHandlers`.
579
- //
580
- // The no-op guard that used to live here is now the controller's: it skips the publish when the
581
- // resolved value is deep-equal to the last one, which matters because this runs on every
582
- // `alsoWatch` key change too (a `messagePaginator` or `messageOperations` registration re-runs the
583
- // whole `channel` cycle), so the no-op publishes outnumber the real ones.
383
+ // Replaces, so a handler dropped from the declarative tree disappears. Direct writes to
384
+ // `configState.requestHandlers` must be re-applied afterwards.
385
+ // The controller skips the publish when the resolved config is deep-equal to the last one.
584
386
  this.configController.initialize(ownDeclarativeConfig(declarativeConfig));
585
387
 
586
- // The shared `messagePaginator` key applies to every MessagePaginator — this channel's list and
587
- // every thread's replies — and the per-parent slice overrides it.
388
+ // Shared key first, the channel's own slice overrides it.
588
389
  this.messagePaginator.initializeConfig(
589
390
  toDeclarativePaginatorConfig(
590
391
  mergeDeclarativePaginatorConfig(
@@ -593,14 +394,12 @@ export class Channel extends ChannelApi {
593
394
  ),
594
395
  ),
595
396
  );
596
- // Single parent, so it stays nested and takes no share of the shared key.
397
+ // No shared key: the pinned paginator has a single parent.
597
398
  this.pinnedMessagesPaginator.initializeConfig(
598
399
  declarativeConfig?.pinnedMessagesPaginator,
599
400
  );
600
401
 
601
- // `MessageOperations` backs both channel and thread sends, so it has a shared top-level key with a
602
- // per-parent override — the same shape as `messagePaginator`. Defaults are spread first so a field
603
- // dropped from the declarative tree returns to its default rather than lingering.
402
+ // Shared key with a per-parent override, as for `messagePaginator`.
604
403
  this.messageOperations.initializeConfig(
605
404
  mergeDeclarativeMessageOperationsConfig(
606
405
  this.getClient().config.getConfig('messageOperations') ?? undefined,
@@ -610,72 +409,42 @@ export class Channel extends ChannelApi {
610
409
  }
611
410
 
612
411
  /**
613
- * Returns the chat client for this channel. Throws if the channel is pending disposal — see
614
- * {@link Channel.pendingDisposal}.
412
+ * Returns the chat client for this channel.
615
413
  *
616
414
  * @returns The chat client.
415
+ * @throws If the channel is pending disposal ({@link Channel.pendingDisposal}).
617
416
  */
618
417
  getClient(): StreamChat {
619
- if (this.pendingDisposal) {
620
- throw Error(
621
- `Channel ${this.cid} is pending disposal and cannot be used. Get a fresh instance via client.channel().`,
622
- );
623
- }
418
+ if (this.pendingDisposal) throw this.disposedError();
624
419
  return this._client;
625
420
  }
626
421
 
627
- /**
628
- * Resolved configuration, as a store. Delegates rather than holding a copy, so the field and the
629
- * controller's store cannot drift.
630
- *
631
- * Still directly writable, and deliberately so: the React SDK installs per-component request handlers
632
- * by calling `partialNext({ requestHandlers })` on it. That write bypasses the controller, which is
633
- * why `requestHandlers` is the one field a re-derivation replaces wholesale — see
634
- * {@link initializeConfig}.
635
- */
422
+ private disposedError() {
423
+ return new Error(
424
+ `Channel ${this.cid} is pending disposal and cannot be used. Get a fresh instance with client.channel('${this.type}', '${this.id}').`,
425
+ );
426
+ }
427
+
636
428
  get configState(): StateStore<ChannelConfig> {
637
429
  return this.configController.state;
638
430
  }
639
431
 
640
- /**
641
- * This channel's **resolved** configuration — the shape every configurable class exposes.
642
- *
643
- * Not to be confused with {@link serverConfig}, which is this channel's configuration as the
644
- * server reports it. This one has already folded that in: `typingEvents.enabled` is the server's
645
- * `typing_events` ANDed with whatever the integrator registered, so it is the whole answer. The
646
- * near-collision is why the server side became `serverConfig`, a getter that says what it
647
- * is.
648
- */
649
432
  get config(): Readonly<ChannelConfig> {
650
433
  return this.configController.value;
651
434
  }
652
435
 
653
436
  /**
654
- * This channel's configuration as the server reports it — feature flags such as `uploads`,
655
- * `typing_events`, `read_events` and `commands`.
656
- *
657
- * Mostly a property of the channel *type*, but not only: a channel's own `config_overrides` narrow it
658
- * for that channel alone, which is why the cache behind this is keyed by cid rather than by type. See
659
- * `StreamChat._addChannelConfig`.
660
- *
661
- * `undefined` until this channel has been queried or watched — there is nothing to fall back on that
662
- * would not be another channel's overrides. {@link config} covers that case with its defaults.
663
- *
664
- * Distinct from {@link config}, which is this instance's resolved configuration and already has the
665
- * relevant flags below folded into it. Prefer `config` when deciding whether a feature is available:
666
- * this getter answers only the server's half, so gating UI on it offers features the client has
667
- * already disabled.
437
+ * The channel's configuration as the server reports it (`uploads`, `typing_events`, `commands`, ...),
438
+ * including this channel's `config_overrides`. `undefined` until the channel is queried or watched.
439
+ * Gate features on {@link config} instead: it also folds in what the integrator disabled.
668
440
  */
669
441
  get serverConfig() {
670
442
  return this.getClient().channelServerConfigs[this.cid];
671
443
  }
672
444
 
673
- _sendMessage(...args: Parameters<ChannelApi['sendMessage']>) {
674
- return super.sendMessage(...args);
675
- }
676
-
677
445
  /**
678
- * Sends a message to this channel.
446
+ * Sends a message to this channel. Strips `localMetadata` from attachments and drops those whose
447
+ * upload never completed.
679
448
  *
680
449
  * @param ...args - `[request, requestOptions]`. `request` holds the message body and optional
681
450
  * flags such as `skip_enrich_url`, `skip_push`, and `keep_channel_hidden`; `requestOptions`
@@ -683,117 +452,29 @@ export class Channel extends ChannelApi {
683
452
  * @returns The server response.
684
453
  */
685
454
  override async sendMessage(...args: Parameters<ChannelApi['sendMessage']>) {
686
- const [request] = args;
687
- const messageId = request.message?.id;
688
-
689
- return await queueOrRun({
690
- channel: this,
691
- client: this.getClient(),
692
- // Nothing to key a queue entry on without a message id, so it runs but is not queued.
693
- queue: !!messageId,
694
- task: {
695
- channelId: this.id as string,
696
- channelType: this.type,
697
- messageId,
698
- payload: args,
699
- type: 'send-message',
700
- },
701
- });
702
- }
703
-
704
- /**
705
- * Sends a message with optimistic local state update.
706
- */
707
- async sendMessageWithLocalUpdate(
708
- params: SendMessageWithStateUpdateParams,
709
- ): Promise<void> {
710
- await this.messageOperations.send(
711
- {
712
- localMessage: params.localMessage,
713
- message: params.message,
714
- options: params.options,
715
- },
716
- params.sendMessageRequestFn,
717
- );
718
- if (this.messageComposer.config.text.publishTypingEvents) await this.stopTyping();
719
- }
720
-
721
- /**
722
- * Retry sending a failed message.
723
- */
724
- async retrySendMessageWithLocalUpdate(
725
- params: Omit<SendMessageWithStateUpdateParams, 'message'>,
726
- ) {
727
- await this.messageOperations.retry(
728
- {
729
- localMessage: { ...params.localMessage, type: 'regular' },
730
- options: params.options,
731
- },
732
- params.sendMessageRequestFn,
733
- );
734
- }
455
+ const [request, requestOptions] = args;
735
456
 
736
- /**
737
- * Updates a message with optimistic local state update.
738
- */
739
- async updateMessageWithLocalUpdate(params: UpdateMessageWithStateUpdateParams) {
740
- await this.messageOperations.update(
741
- {
742
- localMessage: params.localMessage,
743
- options: params.options,
744
- },
745
- params.updateMessageRequestFn,
746
- );
747
- }
748
-
749
- /**
750
- * Deletes a message with local state update.
751
- */
752
- async deleteMessageWithLocalUpdate(params: DeleteMessageWithStateUpdateParams) {
753
- await this.messageOperations.delete(
754
- {
755
- localMessage: params.localMessage,
756
- options: params.options,
757
- },
758
- params.deleteMessageRequestFn,
457
+ return await super.sendMessage(
458
+ { ...request, message: sanitizeOutgoingAttachments(request.message) },
459
+ requestOptions,
759
460
  );
760
461
  }
761
462
 
762
- /**
763
- * Adds a reaction with an optimistic local state update - see {@link addReactionOptimistically}.
764
- */
765
- async addReactionWithLocalUpdate({
766
- messageId,
767
- reaction,
768
- options,
769
- }: {
770
- messageId: string;
771
- reaction: ReactionRequest;
772
- options?: Pick<SendReactionRequest, 'enforce_unique' | 'skip_push'>;
773
- }) {
774
- await addReactionOptimistically({ channel: this, messageId, options, reaction });
463
+ async sendReaction(...args: Parameters<ChatApi['sendReaction']>) {
464
+ return await this.getClient().sendReaction(...args);
775
465
  }
776
466
 
777
- /**
778
- * Removes the current user's reaction with an optimistic local state update - see
779
- * {@link deleteReactionOptimistically}.
780
- */
781
- async deleteReactionWithLocalUpdate({
782
- messageId,
783
- type,
784
- }: {
785
- messageId: string;
786
- type: string;
787
- }) {
788
- await deleteReactionOptimistically({ channel: this, messageId, type });
467
+ async deleteReaction(...args: Parameters<ChatApi['deleteReaction']>) {
468
+ return await this.getClient().deleteReaction(...args);
789
469
  }
790
470
 
791
471
  /**
792
- * Upload a file to this channel's file endpoint (multipart).
472
+ * Uploads a file to this channel's file endpoint (multipart).
793
473
  *
794
474
  * @param request - Upload payload. `request.file` is the file to upload.
795
- * @param requestOptions - Per-request options, e.g. `onUploadProgress` or an abort `signal` (optional).
796
- * @returns A promise resolving to `{ file: string, ... }` with the CDN URL.
475
+ * @param requestOptions - Per-request options, e.g. `onUploadProgress` or an abort `signal`
476
+ * (optional).
477
+ * @returns The upload response, with the CDN URL in `file`.
797
478
  */
798
479
  override async uploadChannelFile(
799
480
  request?: Omit<UploadChannelFileRequest, 'file'> & { file?: FileUploadInput },
@@ -806,11 +487,12 @@ export class Channel extends ChannelApi {
806
487
  }
807
488
 
808
489
  /**
809
- * Upload an image to this channel's image endpoint (multipart).
490
+ * Uploads an image to this channel's image endpoint (multipart).
810
491
  *
811
492
  * @param request - Upload payload. `request.file` is the image to upload.
812
- * @param requestOptions - Per-request options, e.g. `onUploadProgress` or an abort `signal` (optional).
813
- * @returns A promise resolving to `{ file: string, ... }` with the CDN URL.
493
+ * @param requestOptions - Per-request options, e.g. `onUploadProgress` or an abort `signal`
494
+ * (optional).
495
+ * @returns The upload response, with the CDN URL in `file`.
814
496
  */
815
497
  override async uploadChannelImage(
816
498
  request?: Omit<UploadChannelRequest, 'file'> & { file?: FileUploadInput },
@@ -822,38 +504,36 @@ export class Channel extends ChannelApi {
822
504
  );
823
505
  }
824
506
 
825
- /**
826
- * Alias for {@link uploadChannelFile}, mirroring `client.uploadFile`.
827
- */
507
+ /** Alias for {@link uploadChannelFile}. */
828
508
  uploadFile = (...args: Parameters<Channel['uploadChannelFile']>) =>
829
509
  this.uploadChannelFile(...args);
830
510
 
831
- /** Alias for {@link uploadChannelImage}, mirroring `client.uploadImage`. */
511
+ /** Alias for {@link uploadChannelImage}. */
832
512
  uploadImage = (...args: Parameters<Channel['uploadChannelImage']>) =>
833
513
  this.uploadChannelImage(...args);
834
514
 
835
- deleteFile(url: string, requestOptions?: StreamRequestOptions) {
836
- return this.deleteChannelFile({ url }, requestOptions);
837
- }
838
-
839
- deleteImage(url: string, requestOptions?: StreamRequestOptions) {
840
- return this.deleteChannelImage({ url }, requestOptions);
515
+ /**
516
+ * Deletes a file uploaded to this channel, the same request shape as `client.deleteFile`.
517
+ *
518
+ * @param request - The file to delete. `request.url` is its URL.
519
+ * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
520
+ * into the request (optional).
521
+ * @returns The server response.
522
+ */
523
+ deleteFile(request: { url: string }, requestOptions?: StreamRequestOptions) {
524
+ return this.deleteChannelFile(request, requestOptions);
841
525
  }
842
526
 
843
527
  /**
844
- * Sends an event on this channel.
528
+ * Deletes an image uploaded to this channel, the same request shape as `client.deleteImage`.
845
529
  *
846
- * @param request - For example `{ event: { type: 'message.read' } }`.
530
+ * @param request - The image to delete. `request.url` is its URL.
847
531
  * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
848
532
  * into the request (optional).
849
533
  * @returns The server response.
850
534
  */
851
- override async sendEvent(
852
- request: { event: Event },
853
- requestOptions?: StreamRequestOptions,
854
- ) {
855
- this._checkInitialized();
856
- return await super.sendEvent(request, requestOptions);
535
+ deleteImage(request: { url: string }, requestOptions?: StreamRequestOptions) {
536
+ return this.deleteChannelImage(request, requestOptions);
857
537
  }
858
538
 
859
539
  /**
@@ -870,26 +550,13 @@ export class Channel extends ChannelApi {
870
550
  request?: { payload?: Partial<QueryMembersPayload> },
871
551
  requestOptions?: StreamRequestOptions,
872
552
  ) {
873
- const payload = {
874
- type: this.type,
875
- // TODO: these should be probably optional in the OAPI spec
876
- // filter_conditions: ...
877
- } as QueryMembersPayload;
878
-
879
- if (this.id) {
880
- payload.id = this.id;
881
- } else if (Array.isArray(this.data?.members)) {
882
- payload.members = this.data.members.map((m) => ({
883
- ...m,
884
- // TODO: this should not be needed Gen_QueryMembersResponse should not come with user_id as optinal
885
- user_id: (m.user_id ?? m.user?.id) as string,
886
- }));
887
- }
888
- // Return a list of members
553
+ this._checkHasId();
554
+
889
555
  return await this.getClient().queryMembers(
890
556
  {
891
557
  payload: {
892
- ...payload,
558
+ // TODO: filter_conditions should probably be optional in the OAPI spec
559
+ ...({ type: this.type, id: this.id } as QueryMembersPayload),
893
560
  ...request?.payload,
894
561
  },
895
562
  },
@@ -898,92 +565,24 @@ export class Channel extends ChannelApi {
898
565
  }
899
566
 
900
567
  /**
901
- * Sends a reaction to a message. If offline support is enabled, it will make sure
902
- * that sending the reaction is queued up if it fails due to bad internet conditions and executed
903
- * later.
904
- *
905
- * @param ...args - `[request, requestOptions]`. `request` holds the target message ID, the
906
- * reaction object (e.g. `{ type: 'love' }`), and optional flags such as `enforce_unique` and
907
- * `skip_push`; `requestOptions` carries per-request options such as an abort `signal`.
908
- * When the call is queued for offline replay, `requestOptions` is queued with it - see the
909
- * note on signal persistence in `AbstractOfflineDB.queueTask`.
910
- * @returns The server response.
911
- */
912
- async sendReaction(...args: Parameters<ChatApi['sendReaction']>) {
913
- const [{ id: messageId }] = args;
914
-
915
- // The optimistic reaction row is written by the local-update layer (`applyReactionLocally`); here
916
- // we only queue the request for replay.
917
- return await queueOrRun({
918
- channel: this,
919
- client: this.getClient(),
920
- task: {
921
- channelId: this.id as string,
922
- channelType: this.type,
923
- messageId,
924
- payload: args,
925
- type: 'send-reaction',
926
- },
927
- });
928
- }
929
-
930
- _sendReaction(...args: Parameters<ChatApi['sendReaction']>) {
931
- return this.getClient().sendReaction(...args);
932
- }
933
-
934
- async deleteReaction(...args: Parameters<ChatApi['deleteReaction']>) {
935
- this._checkInitialized();
936
- const [request] = args;
937
-
938
- // The optimistic reaction-row removal is handled by the local-update layer
939
- // (`applyReactionLocally`); here we only queue the request for replay.
940
- return await queueOrRun({
941
- channel: this,
942
- client: this.getClient(),
943
- task: {
944
- channelId: this.id as string,
945
- channelType: this.type,
946
- messageId: request.id,
947
- payload: args,
948
- type: 'delete-reaction',
949
- },
950
- });
951
- }
952
-
953
- /**
954
- * Deletes a reaction by user and type.
955
- *
956
- * @param ...args - `[request, requestOptions]`. `request` identifies the target message and
957
- * reaction type; `requestOptions` carries per-request options such as an abort `signal` and is
958
- * never serialized into the request.
959
- * @returns The server response.
960
- */
961
- async _deleteReaction(...args: Parameters<ChatApi['deleteReaction']>) {
962
- return await this.getClient().deleteReaction(...args);
963
- }
964
-
965
- /**
966
- * Edit the channel using the inherited `update()` from `ChannelApi`. Caches the
967
- * server-returned channel onto `this.data`.
568
+ * Updates the channel and stores the returned channel in `this.data`.
968
569
  *
969
570
  * @param ...args - `[request, requestOptions]`. `request` is the channel update payload, e.g.
970
- * `{ data: { name: 'foo' }, message }`; `requestOptions` carries per-request options such as an
971
- * abort `signal` and is never serialized into the request.
571
+ * `{ data: { custom: { name: 'foo' } }, message }`; `requestOptions` carries per-request options
572
+ * such as an abort `signal` and is never serialized into the request.
972
573
  * @returns The server response.
973
574
  */
974
575
  override async update(...args: Parameters<ChannelApi['update']>) {
975
- const previousData = this.data;
976
576
  const data = await super.update(...args);
977
577
  this.data = data.channel;
978
- this.state.syncStateFromChannelData(this.data, previousData);
979
578
  return data;
980
579
  }
981
580
 
982
581
  /**
983
- * Partial update of channel properties.
582
+ * Partially updates the channel's properties and stores the returned channel in `this.data`.
984
583
  *
985
584
  * @param update - The partial update request.
986
- * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
585
+ * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
987
586
  * into the request (optional).
988
587
  * @returns The server response.
989
588
  */
@@ -992,29 +591,7 @@ export class Channel extends ChannelApi {
992
591
  requestOptions?: StreamRequestOptions,
993
592
  ) {
994
593
  const data = await this.updateChannelPartial(update, requestOptions);
995
-
996
- if (!this.getClient()._cacheEnabled) return data;
997
-
998
- const channel = data.channel;
999
- const currentCapabilities = this.data?.own_capabilities ?? [];
1000
- const newCapabilities = channel?.own_capabilities;
1001
-
1002
- const capabilitiesChanged =
1003
- newCapabilities &&
1004
- [...currentCapabilities].sort().join() !== [...newCapabilities].sort().join();
1005
-
1006
- const previousData = this.data;
1007
- this.data = channel;
1008
- this.state.syncStateFromChannelData(this.data, previousData);
1009
- // If the capabiltities are changed, we trigger the `capabilities.changed` event.
1010
- if (capabilitiesChanged) {
1011
- this.getClient().dispatchEvent({
1012
- type: 'capabilities.changed',
1013
- cid: this.cid,
1014
- own_capabilities: newCapabilities,
1015
- });
1016
- }
1017
-
594
+ this.data = data.channel;
1018
595
  return data;
1019
596
  }
1020
597
 
@@ -1022,7 +599,7 @@ export class Channel extends ChannelApi {
1022
599
  * Enables slow mode.
1023
600
  *
1024
601
  * @param coolDownInterval - The cooldown interval in seconds.
1025
- * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
602
+ * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
1026
603
  * into the request (optional).
1027
604
  * @returns The server response.
1028
605
  */
@@ -1033,19 +610,34 @@ export class Channel extends ChannelApi {
1033
610
  /**
1034
611
  * Disables slow mode.
1035
612
  *
613
+ * @param _request - Unused. Holds the request position so `requestOptions` stays the
614
+ * second argument, as on the generated methods; pass `undefined`.
1036
615
  * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
1037
616
  * into the request (optional).
1038
617
  * @returns The server response.
1039
618
  */
1040
- async disableSlowMode(requestOptions?: StreamRequestOptions) {
619
+ async disableSlowMode(
620
+ _request?: Record<string, never>,
621
+ requestOptions?: StreamRequestOptions,
622
+ ) {
1041
623
  return await this.update({ cooldown: 0 }, requestOptions);
1042
624
  }
1043
625
 
1044
626
  public async sendSharedLocation(location: SharedLocation & { message_id?: string }) {
1045
- const result = await this.sendMessage({
1046
- message: {
1047
- id: location.message_id,
1048
- shared_location: location,
627
+ this._checkHasId();
628
+
629
+ const messageId = location.message_id;
630
+ const result = await queueOrRun({
631
+ channel: this,
632
+ client: this.getClient(),
633
+ // Nothing to key a queue entry on without a message ID, so it runs but is not queued.
634
+ queue: !!messageId,
635
+ task: {
636
+ channelId: this.id,
637
+ channelType: this.type,
638
+ messageId,
639
+ payload: [{ message: { id: messageId, shared_location: location } }],
640
+ type: 'send-message',
1049
641
  },
1050
642
  });
1051
643
 
@@ -1063,11 +655,10 @@ export class Channel extends ChannelApi {
1063
655
  payload: UpdateLiveLocationRequest,
1064
656
  requestOptions?: StreamRequestOptions,
1065
657
  ) {
658
+ // Picked, not spread: callers pass a whole shared location whose extra fields must not be sent.
659
+ const { latitude, longitude, message_id } = payload;
1066
660
  const location = await this.getClient().updateLiveLocation(
1067
- {
1068
- ...payload,
1069
- end_at: new Date(),
1070
- },
661
+ { end_at: new Date(), latitude, longitude, message_id },
1071
662
  requestOptions,
1072
663
  );
1073
664
  this.getClient().dispatchEvent({
@@ -1079,13 +670,13 @@ export class Channel extends ChannelApi {
1079
670
  /**
1080
671
  * Accepts an invitation to the channel.
1081
672
  *
1082
- * @param options - The object to update the custom properties of this channel with (optional, defaults to `{}`).
673
+ * @param options - Other channel update options to send with it. Defaults to `{}`.
1083
674
  * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
1084
675
  * into the request (optional).
1085
676
  * @returns The server response.
1086
677
  */
1087
678
  async acceptInvite(
1088
- options: ChannelUpdateOptions = {},
679
+ options: NonNullable<Parameters<ChannelApi['update']>[0]> = {},
1089
680
  requestOptions?: StreamRequestOptions,
1090
681
  ) {
1091
682
  return await this.update({ accept_invite: true, ...options }, requestOptions);
@@ -1094,13 +685,13 @@ export class Channel extends ChannelApi {
1094
685
  /**
1095
686
  * Rejects an invitation to the channel.
1096
687
  *
1097
- * @param options - The object to update the custom properties of this channel with (optional, defaults to `{}`).
688
+ * @param options - Other channel update options to send with it. Defaults to `{}`.
1098
689
  * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
1099
690
  * into the request (optional).
1100
691
  * @returns The server response.
1101
692
  */
1102
693
  async rejectInvite(
1103
- options: ChannelUpdateOptions = {},
694
+ options: NonNullable<Parameters<ChannelApi['update']>[0]> = {},
1104
695
  requestOptions?: StreamRequestOptions,
1105
696
  ) {
1106
697
  return await this.update({ reject_invite: true, ...options }, requestOptions);
@@ -1109,17 +700,15 @@ export class Channel extends ChannelApi {
1109
700
  /**
1110
701
  * Adds members to the channel.
1111
702
  *
1112
- * @param members - An array of members to add to the channel.
1113
- * @param message - Message object for channel members notification (optional).
1114
- * @param options - Configuration to control the behavior while updating (optional, defaults to `{}`).
703
+ * @param request - The members to add, and any other channel update option.
704
+ * @param request.members - User IDs, or member requests (`{ user_id, channel_role?, custom? }`).
705
+ * @param request.message - Message object for channel members notification (optional).
1115
706
  * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
1116
707
  * into the request (optional).
1117
708
  * @returns The server response.
1118
709
  */
1119
710
  async addMembers(
1120
- members: string[] | Array<Gen_ChannelMemberRequest>,
1121
- message?: MessageRequest,
1122
- options: ChannelUpdateOptions = {},
711
+ { members, ...options }: AddMembersRequest,
1123
712
  requestOptions?: StreamRequestOptions,
1124
713
  ) {
1125
714
  return await this.update(
@@ -1127,7 +716,6 @@ export class Channel extends ChannelApi {
1127
716
  add_members: members.map((member) =>
1128
717
  typeof member === 'string' ? { user_id: member } : member,
1129
718
  ),
1130
- message,
1131
719
  ...options,
1132
720
  },
1133
721
  requestOptions,
@@ -1137,83 +725,49 @@ export class Channel extends ChannelApi {
1137
725
  /**
1138
726
  * Adds filter tags to the channel.
1139
727
  *
1140
- * @param tags - An array of tags to add to the channel.
1141
- * @param message - Message object for channel members notification (optional).
1142
- * @param options - Configuration to control the behavior while updating (optional, defaults to `{}`).
728
+ * @param request - The tags to add, and any other channel update option.
729
+ * @param request.tags - The tags to add.
730
+ * @param request.message - Message object for channel members notification (optional).
1143
731
  * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
1144
732
  * into the request (optional).
1145
733
  * @returns The server response.
1146
734
  */
1147
735
  async addFilterTags(
1148
- tags: string[],
1149
- message?: MessageRequest,
1150
- options: ChannelUpdateOptions = {},
736
+ { tags, ...options }: FilterTagsRequest,
1151
737
  requestOptions?: StreamRequestOptions,
1152
738
  ) {
1153
- return await this.update(
1154
- { add_filter_tags: tags, message, ...options },
1155
- requestOptions,
1156
- );
739
+ return await this.update({ add_filter_tags: tags, ...options }, requestOptions);
1157
740
  }
1158
741
 
1159
742
  /**
1160
743
  * Removes filter tags from the channel.
1161
744
  *
1162
- * @param tags - An array of tags to remove from the channel.
1163
- * @param message - Message object for channel members notification (optional).
1164
- * @param options - Configuration to control the behavior while updating (optional, defaults to `{}`).
745
+ * @param request - The tags to remove, and any other channel update option.
746
+ * @param request.tags - The tags to remove.
747
+ * @param request.message - Message object for channel members notification (optional).
1165
748
  * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
1166
749
  * into the request (optional).
1167
750
  * @returns The server response.
1168
751
  */
1169
752
  async removeFilterTags(
1170
- tags: string[],
1171
- message?: MessageRequest,
1172
- options: ChannelUpdateOptions = {},
753
+ { tags, ...options }: FilterTagsRequest,
1173
754
  requestOptions?: StreamRequestOptions,
1174
755
  ) {
1175
- return await this.update(
1176
- { remove_filter_tags: tags, message, ...options },
1177
- requestOptions,
1178
- );
1179
- }
1180
-
1181
- /**
1182
- * Adds moderators to the channel.
1183
- *
1184
- * @param members - An array of member identifiers.
1185
- * @param message - Message object for channel members notification (optional).
1186
- * @param options - Configuration to control the behavior while updating (optional, defaults to `{}`).
1187
- * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
1188
- * into the request (optional).
1189
- * @returns The server response.
1190
- */
1191
- async addModerators(
1192
- members: string[],
1193
- message?: MessageRequest,
1194
- options: ChannelUpdateOptions = {},
1195
- requestOptions?: StreamRequestOptions,
1196
- ) {
1197
- return await this.update(
1198
- { add_moderators: members, message, ...options },
1199
- requestOptions,
1200
- );
756
+ return await this.update({ remove_filter_tags: tags, ...options }, requestOptions);
1201
757
  }
1202
758
 
1203
759
  /**
1204
760
  * Invite members to the channel.
1205
761
  *
1206
- * @param members - An array of members to invite to the channel.
1207
- * @param message - Message object for channel members notification (optional).
1208
- * @param options - Configuration to control the behavior while updating (optional, defaults to `{}`).
762
+ * @param request - The members to invite, and any other channel update option.
763
+ * @param request.members - User IDs, or member requests (`{ user_id, custom }`).
764
+ * @param request.message - Message object for channel members notification (optional).
1209
765
  * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
1210
766
  * into the request (optional).
1211
767
  * @returns The server response.
1212
768
  */
1213
769
  async inviteMembers(
1214
- members: string[] | Required<Omit<Gen_ChannelMemberRequest, 'channel_role'>>[],
1215
- message?: MessageRequest,
1216
- options: ChannelUpdateOptions = {},
770
+ { members, ...options }: InviteMembersRequest,
1217
771
  requestOptions?: StreamRequestOptions,
1218
772
  ) {
1219
773
  return await this.update(
@@ -1221,7 +775,6 @@ export class Channel extends ChannelApi {
1221
775
  invites: members.map((member) =>
1222
776
  typeof member === 'string' ? { user_id: member } : member,
1223
777
  ),
1224
- message,
1225
778
  ...options,
1226
779
  },
1227
780
  requestOptions,
@@ -1231,65 +784,36 @@ export class Channel extends ChannelApi {
1231
784
  /**
1232
785
  * Removes members from the channel.
1233
786
  *
1234
- * @param members - An array of member identifiers.
1235
- * @param message - Message object for channel members notification (optional).
1236
- * @param options - Configuration to control the behavior while updating (optional, defaults to `{}`).
787
+ * @param request - The members to remove, and any other channel update option.
788
+ * @param request.members - The user IDs to remove.
789
+ * @param request.message - Message object for channel members notification (optional).
1237
790
  * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
1238
791
  * into the request (optional).
1239
792
  * @returns The server response.
1240
793
  */
1241
794
  async removeMembers(
1242
- members: string[],
1243
- message?: MessageRequest,
1244
- options: ChannelUpdateOptions = {},
1245
- requestOptions?: StreamRequestOptions,
1246
- ) {
1247
- return await this.update(
1248
- { remove_members: members, message, ...options },
1249
- requestOptions,
1250
- );
1251
- }
1252
-
1253
- /**
1254
- * Removes the moderator role from channel members.
1255
- *
1256
- * @param members - An array of member identifiers.
1257
- * @param message - Message object for channel members notification (optional).
1258
- * @param options - Configuration to control the behavior while updating (optional, defaults to `{}`).
1259
- * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
1260
- * into the request (optional).
1261
- * @returns The server response.
1262
- */
1263
- async demoteModerators(
1264
- members: string[],
1265
- message?: MessageRequest,
1266
- options: ChannelUpdateOptions = {},
795
+ { members, ...options }: RemoveMembersRequest,
1267
796
  requestOptions?: StreamRequestOptions,
1268
797
  ) {
1269
- return await this.update(
1270
- { demote_moderators: members, message, ...options },
1271
- requestOptions,
1272
- );
798
+ return await this.update({ remove_members: members, ...options }, requestOptions);
1273
799
  }
1274
800
 
1275
801
  /**
1276
- * Mutes the current channel.
802
+ * Mutes the channel.
1277
803
  *
1278
804
  * @example
1279
- * // with expiration
1280
- * await channel.mute({ expiration: moment.duration(2, 'weeks') });
805
+ * // with expiration (two weeks)
806
+ * await channel.mute({ expiration: 14 * 24 * 60 * 60 * 1000 });
1281
807
  *
1282
- * @example
1283
- * // server side
1284
- * await channel.mute({ user_id: userId });
1285
- *
1286
- * @param options - Mute options (optional, defaults to `{}`).
1287
- * @param options.expiration - Expiration in minutes (optional).
808
+ * @param options - Mute options (optional).
809
+ * @param options.expiration - Mute duration in milliseconds (optional).
1288
810
  * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
1289
811
  * into the request (optional).
1290
812
  * @returns The server response.
1291
813
  */
1292
814
  async mute(options?: Gen_MuteChannelRequest, requestOptions?: StreamRequestOptions) {
815
+ this._checkHasId();
816
+
1293
817
  return await this.getClient().muteChannel(
1294
818
  {
1295
819
  channel_cids: [this.cid],
@@ -1300,14 +824,12 @@ export class Channel extends ChannelApi {
1300
824
  }
1301
825
 
1302
826
  /**
1303
- * Unmutes the current channel.
827
+ * Unmutes the channel.
1304
828
  *
1305
829
  * @example
1306
- * // server side
1307
- * await channel.unmute({ user_id: userId });
830
+ * await channel.unmute();
1308
831
  *
1309
- * @param options - Unmute options (optional, defaults to `{}`).
1310
- * @param options.user_id - User ID (optional).
832
+ * @param options - Unmute options (optional).
1311
833
  * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
1312
834
  * into the request (optional).
1313
835
  * @returns The server response.
@@ -1316,6 +838,8 @@ export class Channel extends ChannelApi {
1316
838
  options?: Gen_UnmuteChannelRequest,
1317
839
  requestOptions?: StreamRequestOptions,
1318
840
  ) {
841
+ this._checkHasId();
842
+
1319
843
  return await this.getClient().unmuteChannel(
1320
844
  {
1321
845
  channel_cids: [this.cid],
@@ -1326,76 +850,86 @@ export class Channel extends ChannelApi {
1326
850
  }
1327
851
 
1328
852
  /**
1329
- * Archives the current channel.
853
+ * Archives the channel for the current user.
1330
854
  *
1331
855
  * @example
1332
856
  * await channel.archive();
1333
857
  *
858
+ * @param _request - Unused. Holds the request position so `requestOptions` stays the
859
+ * second argument, as on the generated methods; pass `undefined`.
1334
860
  * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
1335
861
  * into the request (optional).
1336
862
  * @returns The server response.
1337
863
  */
1338
- async archive(requestOptions?: StreamRequestOptions) {
864
+ async archive(_request?: Record<string, never>, requestOptions?: StreamRequestOptions) {
1339
865
  return await this.updateMemberPartial({ set: { archived: true } }, requestOptions);
1340
866
  }
1341
867
 
1342
868
  /**
1343
- * Unarchives the current channel.
869
+ * Unarchives the channel for the current user.
1344
870
  *
1345
871
  * @example
1346
872
  * await channel.unarchive();
1347
873
  *
874
+ * @param _request - Unused. Holds the request position so `requestOptions` stays the
875
+ * second argument, as on the generated methods; pass `undefined`.
1348
876
  * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
1349
877
  * into the request (optional).
1350
878
  * @returns The server response.
1351
879
  */
1352
- async unarchive(requestOptions?: StreamRequestOptions) {
880
+ async unarchive(
881
+ _request?: Record<string, never>,
882
+ requestOptions?: StreamRequestOptions,
883
+ ) {
1353
884
  return await this.updateMemberPartial({ set: { archived: false } }, requestOptions);
1354
885
  }
1355
886
 
1356
887
  /**
1357
- * Pins the current channel.
888
+ * Pins the channel for the current user.
1358
889
  *
1359
890
  * @example
1360
891
  * await channel.pin();
1361
892
  *
893
+ * @param _request - Unused. Holds the request position so `requestOptions` stays the
894
+ * second argument, as on the generated methods; pass `undefined`.
1362
895
  * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
1363
896
  * into the request (optional).
1364
897
  * @returns The server response.
1365
898
  */
1366
- async pin(requestOptions?: StreamRequestOptions) {
899
+ async pin(_request?: Record<string, never>, requestOptions?: StreamRequestOptions) {
1367
900
  return await this.updateMemberPartial({ set: { pinned: true } }, requestOptions);
1368
901
  }
1369
902
 
1370
903
  /**
1371
- * Unpins the current channel.
904
+ * Unpins the channel for the current user.
1372
905
  *
1373
906
  * @example
1374
907
  * await channel.unpin();
1375
908
  *
909
+ * @param _request - Unused. Holds the request position so `requestOptions` stays the
910
+ * second argument, as on the generated methods; pass `undefined`.
1376
911
  * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
1377
912
  * into the request (optional).
1378
913
  * @returns The server response.
1379
914
  */
1380
- async unpin(requestOptions?: StreamRequestOptions) {
915
+ async unpin(_request?: Record<string, never>, requestOptions?: StreamRequestOptions) {
1381
916
  return await this.updateMemberPartial({ set: { pinned: false } }, requestOptions);
1382
917
  }
1383
918
 
1384
919
  /**
1385
- * Returns the mute status for the current channel.
920
+ * Returns the mute status of the channel.
1386
921
  *
1387
- * @returns An object of the form `{ muted: true | false, createdAt: Date | null, expiresAt: Date | null }`.
922
+ * @returns `{ muted, createdAt, expiresAt }`, the timestamps in unix nanoseconds as the API sends
923
+ * them.
1388
924
  */
1389
925
  muteStatus() {
1390
- this._checkInitialized();
926
+ this._checkHasId();
1391
927
  return this.getClient()._muteStatus(this.cid);
1392
928
  }
1393
929
 
1394
930
  /**
1395
- * Recomputes this channel's reactive `state.muteStatus` from the client's current `mutedChannels`
1396
- * and publishes it only when it actually changed — so the frequent `health.check` fan-out does not
1397
- * churn subscribers. Called from the constructor and by the client whenever `mutedChannels`
1398
- * updates. Unlike `muteStatus()`, this does not require the channel to be initialized.
931
+ * Recomputes `state.muteStatus` from `client.mutedChannels`, publishing only on change (the client
932
+ * calls this on every `mutedChannels` update). Unlike `muteStatus()`, it needs no channel ID.
1399
933
  */
1400
934
  _syncMuteStatus() {
1401
935
  if (this.pendingDisposal) return;
@@ -1404,45 +938,37 @@ export class Channel extends ChannelApi {
1404
938
  const previous = this.state.getLatestValue().muteStatus;
1405
939
  const unchanged =
1406
940
  previous.muted === next.muted &&
1407
- (previous.createdAt?.getTime() ?? null) === (next.createdAt?.getTime() ?? null) &&
1408
- (previous.expiresAt?.getTime() ?? null) === (next.expiresAt?.getTime() ?? null);
941
+ (previous.createdAt ?? null) === (next.createdAt ?? null) &&
942
+ (previous.expiresAt ?? null) === (next.expiresAt ?? null);
1409
943
 
1410
944
  if (unchanged) return;
1411
945
 
1412
946
  this.state.partialNext({ muteStatus: next });
1413
947
  }
1414
948
 
1415
- sendAction(
949
+ async sendAction(
1416
950
  messageId: string,
1417
951
  formData: Record<string, string>,
1418
952
  requestOptions?: StreamRequestOptions,
1419
953
  ) {
1420
- this._checkInitialized();
1421
- return this.getClient().runMessageAction(
1422
- {
1423
- id: messageId,
1424
- form_data: formData,
1425
- },
954
+ this._checkHasId();
955
+ return await this.getClient().runMessageAction(
956
+ { id: messageId },
957
+ { form_data: formData },
1426
958
  requestOptions,
1427
959
  );
1428
960
  }
1429
961
 
1430
962
  /**
1431
- * First of the `typing.start` and `typing.stop` events based on the user's keystrokes.
1432
- * Call this on every keystroke.
963
+ * Call on every keystroke: sends `typing.start` at most every 2 seconds.
1433
964
  *
1434
965
  * @see {@link https://getstream.io/chat/docs/typing_indicators/?language=js|Docs}
1435
966
  *
1436
- * @param parentId - Set this field to `message.id` to indicate that the typing event is happening in a thread (optional).
1437
- * @param options - Optional override carrying a `user_id` (optional).
967
+ * @param parentId - The parent message ID, for a typing event in a thread (optional).
1438
968
  * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
1439
969
  * into the request (optional).
1440
970
  */
1441
- async keystroke(
1442
- parentId?: string,
1443
- options?: { user_id: string },
1444
- requestOptions?: StreamRequestOptions,
1445
- ) {
971
+ async keystroke(parentId?: string, requestOptions?: StreamRequestOptions) {
1446
972
  if (!this._isTypingIndicatorsEnabled()) {
1447
973
  return;
1448
974
  }
@@ -1450,7 +976,6 @@ export class Channel extends ChannelApi {
1450
976
  const diff = this.lastTypingEvent && now.getTime() - this.lastTypingEvent.getTime();
1451
977
  this.lastKeyStroke = now;
1452
978
  this.isTyping = true;
1453
- // send a typing.start every 2 seconds
1454
979
  if (diff === null || diff > 2000) {
1455
980
  this.lastTypingEvent = new Date();
1456
981
  await this.sendEvent(
@@ -1458,9 +983,6 @@ export class Channel extends ChannelApi {
1458
983
  event: {
1459
984
  type: 'typing.start',
1460
985
  parent_id: parentId,
1461
- ...(options || {}),
1462
- created_at: new Date(),
1463
- custom: {},
1464
986
  },
1465
987
  },
1466
988
  requestOptions,
@@ -1469,12 +991,11 @@ export class Channel extends ChannelApi {
1469
991
  }
1470
992
 
1471
993
  /**
1472
- * Sends an event to update the AI state for a specific message.
1473
- * Typically used by the server connected to the AI service to notify clients of state changes.
994
+ * Notifies watchers of a message's AI state. Meant for the server connected to the AI service.
1474
995
  *
1475
996
  * @param messageId - The ID of the message associated with the AI state.
1476
997
  * @param state - The new state of the AI process, e.g. thinking, generating.
1477
- * @param options - Parameters such as `ai_message` to include additional details in the event (optional, defaults to `{}`).
998
+ * @param options - Additional details for the event. Defaults to `{}`.
1478
999
  * @param options.ai_message - Additional message detail to include in the event (optional).
1479
1000
  * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
1480
1001
  * into the request (optional).
@@ -1488,12 +1009,13 @@ export class Channel extends ChannelApi {
1488
1009
  await this.sendEvent(
1489
1010
  {
1490
1011
  event: {
1491
- ...options,
1492
1012
  type: 'ai_indicator.update',
1493
- message_id: messageId,
1494
- ai_state: state,
1495
- created_at: new Date(),
1496
- custom: {},
1013
+ // The API reads these fields from `custom`. They aren't app custom data, hence the assertion.
1014
+ custom: {
1015
+ ...options,
1016
+ message_id: messageId,
1017
+ ai_state: state,
1018
+ } as CustomEventData,
1497
1019
  },
1498
1020
  },
1499
1021
  requestOptions,
@@ -1504,16 +1026,19 @@ export class Channel extends ChannelApi {
1504
1026
  * Sends an event to notify watchers to clear the typing/thinking UI when the AI response starts streaming.
1505
1027
  * Typically used by the server connected to the AI service to inform clients that the AI response has started.
1506
1028
  *
1029
+ * @param _request - Unused. Holds the request position so `requestOptions` stays the
1030
+ * second argument, as on the generated methods; pass `undefined`.
1507
1031
  * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
1508
1032
  * into the request (optional).
1509
1033
  */
1510
- async clearAIIndicator(requestOptions?: StreamRequestOptions) {
1034
+ async clearAIIndicator(
1035
+ _request?: Record<string, never>,
1036
+ requestOptions?: StreamRequestOptions,
1037
+ ) {
1511
1038
  await this.sendEvent(
1512
1039
  {
1513
1040
  event: {
1514
1041
  type: 'ai_indicator.clear',
1515
- created_at: new Date(),
1516
- custom: {},
1517
1042
  },
1518
1043
  },
1519
1044
  requestOptions,
@@ -1524,16 +1049,19 @@ export class Channel extends ChannelApi {
1524
1049
  * Sends an event to stop AI response generation, leaving the message in its current state.
1525
1050
  * Triggered by the user to halt the AI response process.
1526
1051
  *
1052
+ * @param _request - Unused. Holds the request position so `requestOptions` stays the
1053
+ * second argument, as on the generated methods; pass `undefined`.
1527
1054
  * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
1528
1055
  * into the request (optional).
1529
1056
  */
1530
- async stopAIResponse(requestOptions?: StreamRequestOptions) {
1057
+ async stopAIResponse(
1058
+ _request?: Record<string, never>,
1059
+ requestOptions?: StreamRequestOptions,
1060
+ ) {
1531
1061
  await this.sendEvent(
1532
1062
  {
1533
1063
  event: {
1534
1064
  type: 'ai_indicator.stop',
1535
- created_at: new Date(),
1536
- custom: {},
1537
1065
  },
1538
1066
  },
1539
1067
  requestOptions,
@@ -1541,20 +1069,13 @@ export class Channel extends ChannelApi {
1541
1069
  }
1542
1070
 
1543
1071
  /**
1544
- * Sets last typing to null and sends the `typing.stop` event.
1545
- *
1546
- * @see {@link https://getstream.io/chat/docs/typing_indicators/?language=js|Docs}
1072
+ * Resets the typing state and sends `typing.stop`.
1547
1073
  *
1548
- * @param parentId - Set this field to `message.id` to indicate that the typing event is happening in a thread (optional).
1549
- * @param options - Optional override carrying a `user_id` (optional).
1074
+ * @param parentId - The parent message ID, for a typing event in a thread (optional).
1550
1075
  * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
1551
1076
  * into the request (optional).
1552
1077
  */
1553
- async stopTyping(
1554
- parentId?: string,
1555
- options?: { user_id: string },
1556
- requestOptions?: StreamRequestOptions,
1557
- ) {
1078
+ async stopTyping(parentId?: string, requestOptions?: StreamRequestOptions) {
1558
1079
  if (!this._isTypingIndicatorsEnabled()) {
1559
1080
  return;
1560
1081
  }
@@ -1565,9 +1086,6 @@ export class Channel extends ChannelApi {
1565
1086
  event: {
1566
1087
  type: 'typing.stop',
1567
1088
  parent_id: parentId,
1568
- ...(options || {}),
1569
- created_at: new Date(),
1570
- custom: {},
1571
1089
  },
1572
1090
  },
1573
1091
  requestOptions,
@@ -1575,9 +1093,9 @@ export class Channel extends ChannelApi {
1575
1093
  }
1576
1094
 
1577
1095
  _isTypingIndicatorsEnabled(): boolean {
1578
- // The resolved value, not the raw server flag: it already ANDs the channel type's `typing_events`
1579
- // with what the integrator registered, so a client-side `typingEvents.enabled: false` is honoured
1580
- // too. The other two axes are runtime facts no configuration can express.
1096
+ // No ID yet: nobody to tell.
1097
+ if (this.isProvisional) return false;
1098
+ // The resolved value (server `typing_events` ANDed with the client's setting), not the raw flag.
1581
1099
  const { typingEvents } = this.configController.value;
1582
1100
  if (!typingEvents.enabled || !this.getClient().wsConnection?.isHealthy) {
1583
1101
  return false;
@@ -1586,44 +1104,49 @@ export class Channel extends ChannelApi {
1586
1104
  }
1587
1105
 
1588
1106
  /**
1589
- * Run this user's mark-read reporter for this channel. Delegates to
1590
- * `MessageDeliveryReporter`, which batches the underlying `markRead` request
1591
- * with the user's read receipts state.
1592
- *
1593
- * Use the inherited `markRead()` from `ChannelApi` for a direct, unbatched call.
1107
+ * Whether read events are on. `config.readEvents.enabled` (the channel type's `read_events` and
1108
+ * the client configuration) and the own `read-events` capability allow them. Unread messages are
1109
+ * counted and marked read only while it is true, unless `readEvents.localUnreadCountEnabled` keeps
1110
+ * a local count.
1111
+ */
1112
+ get readEventsEnabled(): boolean {
1113
+ return this.config.readEvents.enabled && channelHasReadEvents(this);
1114
+ }
1115
+
1116
+ /**
1117
+ * Marks read through `MessageDeliveryReporter`: uses the `markReadRequest` handler if set, marks
1118
+ * read locally when read events are off and `localUnreadCountEnabled` is set, and drops the
1119
+ * delivery candidate when a request went out. `markRead()` does none of this.
1594
1120
  *
1595
- * @param data - Mark read options (optional, defaults to `{}`).
1121
+ * @param data - Mark read options. Defaults to `{}`.
1122
+ * @returns The server response, or `null` when no request went out.
1596
1123
  */
1597
1124
  async markReadViaReporter(data: MarkReadRequest = {}) {
1598
1125
  return await this.getClient().messageDeliveryReporter.markRead(this, data);
1599
1126
  }
1600
1127
 
1601
1128
  /**
1602
- * Override of the inherited `markRead()` from `ChannelApi` that requires the
1603
- * channel to be initialized and respects the `read_events` channel config.
1129
+ * Marks the channel read.
1604
1130
  *
1605
1131
  * @param ...args - `[data, requestOptions]`. `data` holds the mark-read options;
1606
1132
  * `requestOptions` carries per-request options such as an abort `signal` and is never
1607
1133
  * serialized into the request.
1608
- * @returns The server response, or `null` if the request was skipped.
1134
+ * @returns The server response.
1135
+ * @throws If the channel is not initialized or read events are disabled.
1609
1136
  */
1610
1137
  override async markRead(...args: Parameters<ChannelApi['markRead']>) {
1611
1138
  this._checkInitialized();
1612
1139
 
1613
- if (!this.configController.value.readEvents.enabled) {
1140
+ if (!this.readEventsEnabled) {
1614
1141
  throw new Error(
1615
- "Read events are disabled — either by the channel type's `read_events` setting or by `channel.readEvents.enabled` in your configuration",
1142
+ "Read events are disabled by the channel type's `read_events` setting, by `channel.readEvents.enabled` in your configuration, or because the user lacks the `read-events` capability",
1616
1143
  );
1617
1144
  }
1618
1145
 
1619
1146
  return await super.markRead(...args);
1620
1147
  }
1621
1148
 
1622
- /**
1623
- * A vague indication of whether the channel exists on the chat backend — `true` once
1624
- * `create()`/`query()`/`watch()` has run. Store-backed and reactive: subscribe via
1625
- * `useStateStore(channel.state, (s) => ({ initialized: s.initialized }))`.
1626
- */
1149
+ /** See {@link ChannelLifecycleState.initialized}. */
1627
1150
  get initialized() {
1628
1151
  return this.state.getLatestValue().initialized;
1629
1152
  }
@@ -1633,9 +1156,26 @@ export class Channel extends ChannelApi {
1633
1156
  }
1634
1157
 
1635
1158
  /**
1636
- * Whether the channel was initialized by manually populating its state (offline hydration) rather
1637
- * than a live watch. Store-backed and reactive.
1159
+ * Whether the channel has no ID yet: it was built from members and the server assigns the ID when its
1160
+ * query is answered. Until then only that query can be sent and the cid is a temporary one.
1161
+ *
1162
+ * Not reactive: subscribe to {@link Channel.initialized}, which turns `true` with the response that
1163
+ * sets `id`.
1164
+ */
1165
+ get isProvisional() {
1166
+ return !this.id;
1167
+ }
1168
+
1169
+ /**
1170
+ * See {@link ChannelLifecycleState.supersededBy}. A superseded instance receives no events and
1171
+ * reports `watchStatus: NotWatching`: use its successor (`watch()` resolves with it). The SDK
1172
+ * does not disconnect it before logout, so call {@link Channel.disconnect} once nothing uses it.
1638
1173
  */
1174
+ get supersededBy() {
1175
+ return this.state.getLatestValue().supersededBy;
1176
+ }
1177
+
1178
+ /** See {@link ChannelLifecycleState.offlineMode}. */
1639
1179
  get offlineMode() {
1640
1180
  return this.state.getLatestValue().offlineMode;
1641
1181
  }
@@ -1645,88 +1185,137 @@ export class Channel extends ChannelApi {
1645
1185
  }
1646
1186
 
1647
1187
  /**
1648
- * Whether the channel has been torn down and is awaiting disposal (deleted, the current user
1649
- * removed, or the client disconnected). Store-backed and reactive.
1650
- *
1651
- * One-way and terminal — there is no counterpart that revives the instance. Its resources are
1652
- * already released ({@link Channel._disconnect} disposes the paginators and unregisters the
1653
- * subscriptions) and the client drops it from `activeChannels` right after, so nothing should
1654
- * touch it: it is skipped by the `client.activeChannels` lookups (so `client.channel(…)` mints a
1655
- * fresh instance), never re-watched on recovery, refused as a source of `channel.data` by the
1656
- * offline DB, and `getClient()` throws on it so a reference held across a `disconnectUser()`
1657
- * fails loudly instead of quietly requesting on a client with no user.
1188
+ * Reads `state.data`. Assigning publishes `data`, `memberCount` and `ownCapabilities` in one update.
1189
+ * If the object omits `member_count` or `own_capabilities`, the last known values are carried onto
1190
+ * a copy (the assigned object is not changed). Editing `channel.data.x` in place does not reach
1191
+ * the state. `ownCapabilities` keeps its array while the capabilities stay the same (in any
1192
+ * order), so a subscriber to it is notified only when they change.
1658
1193
  */
1659
- get pendingDisposal() {
1660
- return this.state.getLatestValue().pendingDisposal;
1194
+ get data(): Partial<ChannelResponse> | undefined {
1195
+ return this.state.getLatestValue().data;
1661
1196
  }
1662
1197
 
1663
- set pendingDisposal(pendingDisposal: boolean) {
1664
- this.state.partialNext({ pendingDisposal });
1198
+ set data(next: Partial<ChannelResponse> | undefined) {
1199
+ const {
1200
+ data: previous,
1201
+ memberCount: previousMemberCount,
1202
+ ownCapabilities: previousOwnCapabilities,
1203
+ } = this.state.getLatestValue();
1204
+ const carriedMemberCount =
1205
+ typeof next?.member_count !== 'number' && typeof previous?.member_count === 'number'
1206
+ ? previous.member_count
1207
+ : undefined;
1208
+ // `own_capabilities` stays undefined until known, so "not loaded" isn't read as "none"
1209
+ const carriedCapabilities =
1210
+ !Array.isArray(next?.own_capabilities) && Array.isArray(previous?.own_capabilities)
1211
+ ? [...previous.own_capabilities]
1212
+ : undefined;
1213
+
1214
+ const data =
1215
+ next && (carriedMemberCount !== undefined || carriedCapabilities)
1216
+ ? {
1217
+ ...next,
1218
+ ...(carriedMemberCount !== undefined && { member_count: carriedMemberCount }),
1219
+ ...(carriedCapabilities && { own_capabilities: carriedCapabilities }),
1220
+ }
1221
+ : next;
1222
+
1223
+ const memberCount = data?.member_count ?? carriedMemberCount;
1224
+ const ownCapabilities = data?.own_capabilities ?? carriedCapabilities ?? [];
1225
+ const toKey = (capabilities: readonly string[]) => [...capabilities].sort().join();
1226
+ const haveSameOwnCapabilities =
1227
+ toKey(previousOwnCapabilities) === toKey(ownCapabilities);
1228
+ this.state.partialNext({
1229
+ data,
1230
+ memberCount: memberCount ?? previousMemberCount,
1231
+ ownCapabilities: haveSameOwnCapabilities
1232
+ ? previousOwnCapabilities
1233
+ : [...ownCapabilities],
1234
+ });
1665
1235
  }
1666
1236
 
1667
1237
  /**
1668
- * Whether this client holds a server-side watch on the channel, and if not, whether it should be
1669
- * restored — see {@link ChannelWatchStatus}. Store-backed and reactive: subscribe via
1670
- * `useStateStore(channel.state, (s) => ({ watchStatus: s.watchStatus }))`.
1238
+ * See {@link ChannelLifecycleState.pendingDisposal}. Set only by {@link Channel.disconnect} and never
1239
+ * reverted: `getClient()` throws, `client.channel()` returns a fresh instance for the
1240
+ * cid, and lists and recovery skip it.
1671
1241
  */
1242
+ get pendingDisposal() {
1243
+ return this.state.getLatestValue().pendingDisposal;
1244
+ }
1245
+
1246
+ /** See {@link ChannelWatchStatus}. */
1672
1247
  get watchStatus() {
1673
1248
  return this.state.getLatestValue().watchStatus;
1674
1249
  }
1675
1250
 
1676
1251
  set watchStatus(watchStatus: ChannelWatchStatus) {
1252
+ // what the ended watch was asked for does not carry over to the next one
1253
+ if (watchStatus !== ChannelWatchStatus.Watching) this._lastWatchOptions = undefined;
1677
1254
  this.state.partialNext({ watchStatus });
1678
1255
  }
1679
1256
 
1680
1257
  /**
1681
- * Whether a consumer has declared this channel as the one it is currently consuming (see
1682
- * {@link Channel.activate}). Reactive — subscribe via
1683
- * `useStateStore(channel.state, (s) => ({ active: s.active }))`.
1258
+ * Whether a query for this channel (`watch()`, `query()`, `create()` or one of the message
1259
+ * paginator's own queries, see {@link runTrackedQuery}) awaits its response. The channel store
1260
+ * keeps the channel meanwhile.
1261
+ *
1262
+ * @internal
1684
1263
  */
1264
+ get isQueryingChannel() {
1265
+ return this._channelQueriesInFlight > 0;
1266
+ }
1267
+
1268
+ /** See {@link Channel.activate}. */
1685
1269
  get active() {
1686
1270
  return this.state.getLatestValue().active;
1687
1271
  }
1688
1272
 
1689
1273
  /**
1690
- * Declares that a consumer is now consuming this channel's own state (mirrors
1691
- * `thread.activate()`). Refcounted, as a single `Channel` instance can be held by several
1692
- * consumers at once, so it stays active until the last one deactivates.
1274
+ * Declares that a consumer is consuming this channel's own state and returns its release function.
1275
+ * Refcounted: the channel stays active until the last consumer releases, and releasing twice is a
1276
+ * no-op.
1693
1277
  *
1694
- * While active, the channel's own state takes precedence over bulk state writes: channel-list
1695
- * hydration does not re-seed its message list (its own `channel.reload()` owns that window).
1278
+ * While active, channel-list hydration places no page in the message list (`channel.reload()`
1279
+ * owns it), the message list keeps its active interval (otherwise a fresh newest page from a
1280
+ * query the list did not run is shown), and the channel stays in the channel store. A disposed
1281
+ * channel is not activated: a warning is logged and the returned release does nothing.
1696
1282
  */
1697
- activate = () => {
1283
+ activate = (): (() => void) => {
1284
+ if (this.pendingDisposal) {
1285
+ logger.withExtraTags('activate', this.cid).warn(this.disposedError().message);
1286
+ return () => undefined;
1287
+ }
1698
1288
  this._activeRefCount += 1;
1699
1289
  if (this._activeRefCount === 1) {
1700
1290
  this.state.partialNext({ active: true });
1701
1291
  }
1702
- };
1703
1292
 
1704
- /**
1705
- * Declares that a consumer has stopped consuming this channel (mirrors `thread.deactivate()`).
1706
- * Only flips `active` back to `false` once the last holder deactivates.
1707
- */
1708
- deactivate = () => {
1709
- if (this._activeRefCount === 0) return;
1710
- this._activeRefCount -= 1;
1711
- if (this._activeRefCount === 0) {
1712
- this.state.partialNext({ active: false });
1713
- }
1293
+ let released = false;
1294
+ return () => {
1295
+ if (released) return;
1296
+ released = true;
1297
+ this._activeRefCount -= 1;
1298
+ if (this._activeRefCount === 0) {
1299
+ this.state.partialNext({ active: false });
1300
+ }
1301
+ };
1714
1302
  };
1715
1303
 
1716
1304
  /**
1717
- * Marks the channel as unread from `messageId`. Only works when the `read_events` setting is enabled.
1305
+ * Marks the channel unread from a message.
1718
1306
  *
1719
1307
  * @param ...args - `[data, requestOptions]`. `data` holds the mark-unread options;
1720
1308
  * `requestOptions` carries per-request options such as an abort `signal` and is never
1721
1309
  * serialized into the request.
1722
- * @returns An API response, or `null` if the request was skipped.
1310
+ * @returns The server response.
1311
+ * @throws If the channel is not initialized or read events are disabled.
1723
1312
  */
1724
1313
  override async markUnread(...args: Parameters<ChannelApi['markUnread']>) {
1725
1314
  this._checkInitialized();
1726
1315
 
1727
- if (!this.configController.value.readEvents.enabled) {
1316
+ if (!this.readEventsEnabled) {
1728
1317
  throw new Error(
1729
- "Read events are disabled — either by the channel type's `read_events` setting or by `channel.readEvents.enabled` in your configuration",
1318
+ "Read events are disabled by the channel type's `read_events` setting, by `channel.readEvents.enabled` in your configuration, or because the user lacks the `read-events` capability",
1730
1319
  );
1731
1320
  }
1732
1321
 
@@ -1734,15 +1323,19 @@ export class Channel extends ChannelApi {
1734
1323
  }
1735
1324
 
1736
1325
  /**
1737
- * Resets this user's unread count locally, without any backend call. Intended for
1738
- * channels that have read events disabled (e.g. livestreams) when the client is created with the
1739
- * `isLocalUnreadCountEnabled` option. Dispatches a dedicated, client-only `message.read_locally` event
1740
- * that runs through the same `_handleChannelEvent` read logic as a real `message.read` (minus the
1741
- * delivery-report network sync), so the read-state update lives in one place. When offline support
1742
- * is enabled, the offline DB persists the reset for read-events-disabled channels, so the local
1743
- * count stays consistent across app restarts.
1326
+ * Resets the unread count without a backend call, for channels with read events off
1327
+ * ({@link Channel.readEventsEnabled}, e.g. livestreams) that set `readEvents.localUnreadCountEnabled`. Dispatches the client-only
1328
+ * `message.read_locally` event, handled like `message.read` minus the delivery-report sync. With
1329
+ * offline support the reset is persisted.
1744
1330
  *
1745
- * @returns The dispatched `message.read_locally` event, or `undefined` if there is no connected user.
1331
+ * The event's `last_read_message_id` is the newest server-confirmed message, whatever its type,
1332
+ * of the interval holding the channel's newest messages
1333
+ * (`messagePaginator.anchoredHeadServerConfirmedItem`). While that interval is not loaded (e.g.
1334
+ * only a jumped-to interval is), the event carries none and the read covers everything up to its
1335
+ * `created_at`.
1336
+ *
1337
+ * @returns The dispatched `message.read_locally` event, or `undefined` if there is no connected
1338
+ * user.
1746
1339
  */
1747
1340
  markReadLocally() {
1748
1341
  const client = this.getClient();
@@ -1752,8 +1345,8 @@ export class Channel extends ChannelApi {
1752
1345
  channel_id: this.id,
1753
1346
  channel_type: this.type,
1754
1347
  cid: this.cid,
1755
- created_at: new Date(),
1756
- last_read_message_id: this.messagePaginator.headmostItem?.id,
1348
+ created_at: nowNs(),
1349
+ last_read_message_id: this.messagePaginator.anchoredHeadServerConfirmedItem?.id,
1757
1350
  team: this.data?.team,
1758
1351
  type: 'message.read_locally',
1759
1352
  user: client.user as UserResponse,
@@ -1764,7 +1357,10 @@ export class Channel extends ChannelApi {
1764
1357
  }
1765
1358
 
1766
1359
  /**
1767
- * Cleans the channel state and fires stop typing if needed.
1360
+ * Sends `typing.stop` after a second without a keystroke, drops stale typing users, and resets a
1361
+ * stuck AI indicator while the connection is unhealthy. Run by the client's cleaning interval.
1362
+ *
1363
+ * @internal
1768
1364
  */
1769
1365
  clean() {
1770
1366
  if (this.lastKeyStroke) {
@@ -1777,10 +1373,8 @@ export class Channel extends ChannelApi {
1777
1373
 
1778
1374
  this.state.clean();
1779
1375
 
1780
- // Clear a stuck AI indicator when we're offline (we'd miss the ending clear/stop). The cleaning
1781
- // interval keeps ticking through transient/internet drops; closeConnection stops it, and that
1782
- // path clears the indicator itself. Gate on health, not staleness — a healthy connection must
1783
- // never cut off a long-running response.
1376
+ // Clears an AI indicator stuck because the ending clear/stop was missed while offline. Gated on
1377
+ // health, not staleness: a healthy connection must not cut off a long-running response.
1784
1378
  const client = this.getClient();
1785
1379
  if (!client.wsConnection?.isHealthy) {
1786
1380
  this.state.resetAIState();
@@ -1788,99 +1382,158 @@ export class Channel extends ChannelApi {
1788
1382
  }
1789
1383
 
1790
1384
  /**
1791
- * Loads the initial channel state and watches for changes.
1385
+ * Watches the channel and loads its state and messages. Sends nothing when that is done already
1386
+ * (`Watching`, `initialized` and `messagePaginator.hasResults`) and the call asks for nothing
1387
+ * new: it passes no options, or the same options as the last `watch()` that succeeded during the
1388
+ * current watch. Other options, e.g. `presence: true`, send a query. A `watch()` already in
1389
+ * flight with the same options is joined, not repeated.
1390
+ * Refresh a watched channel with {@link Channel.reload}. Rejects with the query's error.
1792
1391
  *
1793
- * @param options - Additional options for the query endpoint (optional).
1794
- * @returns The server response.
1392
+ * @param options - Options for the watch query (optional).
1393
+ * @param requestOptions - Per-request options (optional). Aborting `signal` ends this caller's
1394
+ * wait (at once if aborted already); the query is cancelled once every waiting caller has
1395
+ * aborted. The other options apply only when this call sends the query.
1396
+ * @returns The instance to use: this one, or the one that superseded it ({@link supersededBy}).
1397
+ */
1398
+ async watch(
1399
+ options?: ChannelGetOrCreateRequest,
1400
+ requestOptions?: StreamRequestOptions,
1401
+ ): Promise<Channel> {
1402
+ // The caller's signal ends only its own wait; the query it may share has its own.
1403
+ const { signal, ...queryRequestOptions } = requestOptions ?? {};
1404
+ if (signal?.aborted) throw abortError(signal, WATCH_WAIT_ABORTED);
1405
+ if (this.supersededBy) return this.supersededBy.watch(options, requestOptions);
1406
+
1407
+ // a copy: later changes to the caller's object must not change what is remembered or joined
1408
+ const requested = structuredClone(options ?? {});
1409
+ // Each part holds without the others: a thread query watches a channel without loading it,
1410
+ // `query()` / `create()` load no messages, a custom `doRequest` can load messages but no state.
1411
+ const isWatchedAndLoaded =
1412
+ this.watchStatus === ChannelWatchStatus.Watching &&
1413
+ this.initialized &&
1414
+ this.messagePaginator.hasResults;
1415
+ const repeatsLastWatch =
1416
+ !Object.keys(requested).length || isEqual(this._lastWatchOptions, requested);
1417
+ if (isWatchedAndLoaded && repeatsLastWatch) return this;
1418
+
1419
+ const existingJoinableQuery = this._watchQueriesInFlight.find((inFlight) =>
1420
+ isEqual(inFlight.options, requested),
1421
+ );
1422
+ const watchQuery =
1423
+ existingJoinableQuery ?? this.sendWatchQuery(requested, queryRequestOptions);
1424
+ watchQuery.waitingCount += 1;
1425
+ await waitUnlessAborted({
1426
+ abortMessage: WATCH_WAIT_ABORTED,
1427
+ onAbort: () => this.leaveWatchQuery(watchQuery),
1428
+ promise: watchQuery.promise,
1429
+ signal,
1430
+ });
1431
+ // The query may have handed the channel to an instance stored under the server's cid, which
1432
+ // has taken in the response already.
1433
+ return this.state.getLatestValue().supersededBy ?? this;
1434
+ }
1435
+
1436
+ /**
1437
+ * Sends the query {@link Channel.watch} callers wait for. It is cancelled through an abort
1438
+ * controller of its own, once no caller waits any more ({@link leaveWatchQuery}).
1439
+ */
1440
+ private sendWatchQuery(
1441
+ options: ChannelGetOrCreateRequest,
1442
+ requestOptions: Omit<StreamRequestOptions, 'signal'>,
1443
+ ): WatchQueryInFlight {
1444
+ const abortController = new AbortController();
1445
+ const promise = this.runWatchQuery(options, {
1446
+ ...requestOptions,
1447
+ signal: abortController.signal,
1448
+ });
1449
+ const watchQuery = { abortController, options, promise, waitingCount: 0 };
1450
+ this._watchQueriesInFlight.push(watchQuery);
1451
+ const forget = () => this.forgetWatchQuery(watchQuery);
1452
+ // callers get the rejection through `promise`; this only clears the entry
1453
+ promise.then(() => {
1454
+ forget();
1455
+ // what the query watched: this instance, or the one that took the channel over
1456
+ const watched = this.state.getLatestValue().supersededBy ?? this;
1457
+ if (watched.watchStatus === ChannelWatchStatus.Watching) {
1458
+ watched._lastWatchOptions = options;
1459
+ }
1460
+ }, forget);
1461
+ return watchQuery;
1462
+ }
1463
+
1464
+ /** A caller stops waiting; the last one cancels and forgets the query, so the next is new. */
1465
+ private leaveWatchQuery(watchQuery: WatchQueryInFlight) {
1466
+ watchQuery.waitingCount -= 1;
1467
+ if (watchQuery.waitingCount) return;
1468
+ this.forgetWatchQuery(watchQuery);
1469
+ watchQuery.abortController.abort();
1470
+ }
1471
+
1472
+ /** Stops offering `watchQuery` to {@link Channel.watch} callers. */
1473
+ private forgetWatchQuery(watchQuery: WatchQueryInFlight) {
1474
+ this._watchQueriesInFlight = this._watchQueriesInFlight.filter(
1475
+ (inFlight) => inFlight !== watchQuery,
1476
+ );
1477
+ }
1478
+
1479
+ /**
1480
+ * Sends a watch query, watched or not, and places the page it fetched (a page at a cursor or
1481
+ * around a message is only stored; `messagePaginator.jumpToMessage()` shows it).
1482
+ * `requestOptions.signal` also ends the wait for a live socket.
1795
1483
  */
1796
- async watch(options?: ChannelGetOrCreateRequest) {
1484
+ private async runWatchQuery(
1485
+ options?: ChannelGetOrCreateRequest,
1486
+ requestOptions?: StreamRequestOptions,
1487
+ ): Promise<void> {
1797
1488
  const defaultOptions = {
1798
1489
  state: true,
1799
1490
  watch: true,
1800
1491
  presence: false,
1801
1492
  };
1802
1493
 
1803
- // Make sure we wait for the connect promise if there is a pending one
1804
- await this.getClient().wsPromise;
1805
-
1806
- if (!this.getClient()._hasConnectionID()) {
1807
- defaultOptions.watch = false;
1808
- }
1809
-
1810
1494
  const combined = { ...defaultOptions, ...options };
1811
- const state = await this.query(combined, 'latest');
1812
- this.initialized = true;
1813
- const previousData = this.data;
1814
- this.data = state.channel;
1815
- this.state.syncStateFromChannelData(this.data, previousData);
1816
1495
 
1817
- // The message paginator is seeded synchronously inside query() (before read-state hydration),
1818
- // so a channel opened via watch() alone — a deep-link restore, a search result, a freshly
1819
- // created DM — already has its latest page loaded here.
1496
+ // `ApiClient` holds a request that watches or subscribes to presence until the handshake yields a
1497
+ // connection ID, so `watch: true` binds to a current one and `watchStatus = Watching` is truthful.
1498
+ const state = await this.runChannelQuery(combined, requestOptions, {
1499
+ placeMessages: true,
1500
+ });
1501
+ this.data = state.channel;
1820
1502
 
1821
1503
  logger.withExtraTags('watch', this.cid).info('Started watching the channel.');
1822
- return state;
1823
1504
  }
1824
1505
 
1825
1506
  /**
1826
- * Re-watch the channel and refresh its FULL loaded message window — the channel analog of
1827
- * {@link Thread.reload}. Used on reconnect to catch up AND reconcile hard deletes that happened
1828
- * while offline: a hard delete reaches other clients via no event, so an offline client only learns
1829
- * of it by diffing the re-queried page.
1507
+ * Re-watches the channel and refreshes its whole loaded message interval (the channel analogue of
1508
+ * {@link Thread.reload}). Used on reconnect. Hard deletes reach other clients through no event, so
1509
+ * the watch query reconciles the loaded newest messages with the re-queried page
1510
+ * (`messagePaginator.reconcileNewestMessages`, against the loaded IDs captured before its await).
1830
1511
  *
1831
- * This is intentionally thin: it only re-issues `watch()` with a limit sized to the loaded window
1832
- * (`items.length`, so the whole loaded window is refreshed — not the smaller channel-list page). The
1833
- * actual fold + destructive reconciliation happens inside `query()` → `seedFirstPageSync`
1834
- * (the same path the channel-list re-hydrate and connection recovery use), driven by the loaded-id
1835
- * snapshot `query()` captures before its await. Owning that single path is what lets the SDK stop
1836
- * passing the reconciliation window/snapshot itself.
1837
- *
1838
- * Preserves failed (unsent) messages: an overlap merge keeps them (the reconcile's provenance guard
1839
- * never prunes a non-server message); only a disjoint rebuild can drop them, so any that actually
1840
- * fell out are re-ingested below. The offline DB is consulted alongside the in-memory window, because
1841
- * a failed message can be absent from memory and still be the user's unsent work — a cold boot starts
1842
- * with an empty paginator, and an eviction can drop it mid-session. v9 got this from a second, lagging
1843
- * copy of the list (the React SDK's own state); with one reactive source of truth the persisted row is
1844
- * that buffer.
1512
+ * Failed (unsent) messages are kept: those loaded or in the offline DB (cold boot, eviction)
1513
+ * before the request that are no longer loaded after it are ingested again. The offline DB is
1514
+ * read on a best-effort basis.
1845
1515
  */
1846
1516
  async reload() {
1847
1517
  if (this._reloading || (!this.initialized && !this.offlineMode)) return;
1848
1518
  this._reloading = true;
1849
1519
  try {
1850
1520
  const paginator = this.messagePaginator;
1851
- const headItems = paginator.headItems;
1521
+ // The reload refreshes the interval that reaches the newest message, sized to what it holds.
1852
1522
  const requestedLimit =
1853
- Math.max(headItems.length, paginator.pageSize ?? 0) || undefined;
1523
+ Math.max(paginator.anchoredHeadItems.length, paginator.pageSize ?? 0) ||
1524
+ undefined;
1854
1525
  const offlineDb = this.getClient().offlineDb;
1855
- const failedInMemory = headItems.filter((message) => message.status === 'failed');
1856
- // Read before the await, so this cannot pick up a message that failed DURING the reload — that
1857
- // one is already in the paginator and does not need re-ingesting.
1526
+ // best effort: a failing read must not fail the reload
1858
1527
  const failedInDb = offlineDb
1859
- ? await offlineDb.getFailedMessages({ cid: this.cid })
1528
+ ? await offlineDb.getFailedMessages({ cid: this.cid }).catch(() => [])
1860
1529
  : [];
1861
- const failedById = new Map<string, LocalMessage>();
1862
- for (const message of [...failedInDb, ...failedInMemory]) {
1863
- // In-memory wins on a collision: it is at least as fresh as the row it was mirrored from.
1864
- failedById.set(message.id, message);
1865
- }
1866
- const failedBefore = [...failedById.values()];
1530
+ // after the read: a message that fails meanwhile is loaded by then
1531
+ const failedBefore = paginator.getFailedMessagesToRestore(failedInDb);
1867
1532
 
1868
- await this.watch({ messages: { limit: requestedLimit } });
1533
+ await this.runWatchQuery({ messages: { limit: requestedLimit } });
1869
1534
  this.offlineMode = false;
1870
1535
 
1871
- if (failedBefore.length) {
1872
- // Make sure the messages that failed to be sent before the watch() request are
1873
- // reingested after the watch() query.
1874
- const visible = new Set((paginator.items ?? []).map((message) => message.id));
1875
- paginator.batch(
1876
- () => {
1877
- for (const failed of failedBefore) {
1878
- if (!visible.has(failed.id)) paginator.ingestItem(failed);
1879
- }
1880
- },
1881
- { coalesce: true },
1882
- );
1883
- }
1536
+ paginator.restoreFailedMessages(failedBefore);
1884
1537
  } finally {
1885
1538
  this._reloading = false;
1886
1539
  }
@@ -1897,7 +1550,7 @@ export class Channel extends ChannelApi {
1897
1550
  override async stopWatching(...args: Parameters<ChannelApi['stopWatching']>) {
1898
1551
  const response = await super.stopWatching(...args);
1899
1552
 
1900
- // Deliberate: unlike a connection loss this must NOT be restored on reconnect.
1553
+ // Unlike a connection loss, this is not restored on reconnect.
1901
1554
  this.watchStatus = ChannelWatchStatus.NotWatching;
1902
1555
 
1903
1556
  logger.withExtraTags('stopWatching', this.cid).info('Stopped watching the channel.');
@@ -1906,21 +1559,22 @@ export class Channel extends ChannelApi {
1906
1559
  }
1907
1560
 
1908
1561
  /**
1909
- * Retrieves a list of messages by ID.
1562
+ * Retrieves messages of this channel by ID.
1910
1563
  *
1911
- * @param messageIds - The IDs of the messages to retrieve from this channel.
1564
+ * @param messageIds - The IDs of the messages to retrieve.
1912
1565
  * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
1913
1566
  * into the request (optional).
1914
- * @returns Server response.
1567
+ * @returns The server response.
1915
1568
  */
1916
1569
  getMessagesById(messageIds: string[], requestOptions?: StreamRequestOptions) {
1917
1570
  return this.getManyMessages({ ids: messageIds }, requestOptions);
1918
1571
  }
1919
1572
 
1920
1573
  /**
1921
- * Returns the last time the user marked the channel as read. If the user never marked the channel as read, this will return `null`.
1574
+ * Returns when the current user last marked the channel read.
1922
1575
  *
1923
- * @returns The last-read `Date`, `null` if never read, or `undefined` if the user is unset.
1576
+ * @returns The last-read timestamp in unix nanoseconds, `null` if never read, or `undefined` if
1577
+ * the user is unset.
1924
1578
  */
1925
1579
  lastRead() {
1926
1580
  const { userId } = this.getClient();
@@ -1932,38 +1586,37 @@ export class Channel extends ChannelApi {
1932
1586
  _countMessageAsUnread(message: LocalMessage | MessageResponse) {
1933
1587
  if (message.shadowed) return false;
1934
1588
  if (message.silent) return false;
1935
- if (message.parent_id && !message.show_in_channel) return false;
1589
+ if (isThreadOnlyReply(message)) return false;
1936
1590
  if (message.user?.id === this.getClient().userId) return false;
1937
1591
  if (message.user?.id && this.getClient().userMuteStatus(message.user.id))
1938
1592
  return false;
1939
1593
 
1940
- // Return false if channel doesn't allow read events, unless the client opted into a local
1941
- // unread count (e.g. livestreams where read events are disabled). See `isLocalUnreadCountEnabled`.
1942
- if (
1943
- !this.getClient().options.isLocalUnreadCountEnabled &&
1944
- !channelHasReadEvents(this)
1945
- ) {
1594
+ // Not counted when read events are disabled, unless `readEvents.localUnreadCountEnabled` is set.
1595
+ if (!this.config.readEvents.localUnreadCountEnabled && !this.readEventsEnabled) {
1946
1596
  return false;
1947
1597
  }
1948
1598
 
1949
1599
  // FIXME: see #1265, adjust and count new messages even when the channel is muted
1950
- // Read mute state directly from the client to avoid _checkInitialized() — this method
1951
- // is invoked from _handleChannelEvent (e.g. message.new) before .watch() resolves.
1952
- if (this.getClient()._muteStatus(this.cid).muted) return false;
1600
+ if (this.muteStatus().muted) return false;
1953
1601
 
1954
1602
  return true;
1955
1603
  }
1956
1604
 
1957
1605
  /**
1958
- * Count of unread messages.
1606
+ * Counts the unread messages.
1607
+ *
1608
+ * Counting from `lastRead` counts within the channel's newest messages that are loaded (see
1609
+ * {@link newestKnownMessages}).
1959
1610
  *
1960
- * @param lastRead - The time that the user read a message (optional, defaults to the current user's read state).
1961
- * @returns Unread count.
1611
+ * @param lastRead - The time the user read a message, in unix nanoseconds (optional). Defaults to
1612
+ * the current user's read state.
1613
+ * @returns The unread count.
1962
1614
  */
1963
- countUnread(lastRead?: Date | null) {
1964
- if (!lastRead) return this.state.unreadCount;
1615
+ countUnread(lastRead?: TimestampNS | null) {
1616
+ // Nullish, not falsy: `0` is a valid timestamp.
1617
+ if (lastRead == null) return this.state.unreadCount;
1965
1618
  let count = 0;
1966
- const latestMessages = this.messagePaginator.headItems;
1619
+ const latestMessages = this.newestKnownMessages();
1967
1620
  for (let i = 0; i < latestMessages.length; i += 1) {
1968
1621
  const message = latestMessages[i];
1969
1622
  if (message.created_at > lastRead && this._countMessageAsUnread(message)) {
@@ -1974,21 +1627,57 @@ export class Channel extends ChannelApi {
1974
1627
  }
1975
1628
 
1976
1629
  /**
1977
- * Count the number of unread messages mentioning the current user.
1630
+ * The channel's newest messages that are loaded: the interval that reaches the newest message (the
1631
+ * paginator's anchored head), or, while that interval is not loaded, the messages received live
1632
+ * since. An interval reached by a jump is never part of it, as the messages between it and the
1633
+ * newest are unknown.
1634
+ */
1635
+ private newestKnownMessages() {
1636
+ const paginator = this.messagePaginator;
1637
+ return paginator.anchoredHeadItem !== undefined
1638
+ ? paginator.anchoredHeadItems
1639
+ : paginator.logicalHeadItems;
1640
+ }
1641
+
1642
+ /**
1643
+ * Lowers the own unread count by the unread ones among `deletedMessages`, as they were before the
1644
+ * delete. The server lowers it for every unread message deleted, except in a soft bulk delete
1645
+ * (`user.messages.deleted`), and does not send the new count. Unread messages that are not loaded
1646
+ * cannot be counted; the next query brings the server's count.
1647
+ *
1648
+ * @internal
1649
+ */
1650
+ _lowerUnreadCountForDeletedMessages(deletedMessages: LocalMessage[]) {
1651
+ const lastRead = this.lastRead();
1652
+ if (lastRead == null || this.state.unreadCount === 0) return;
1653
+ const deletedUnread = deletedMessages.filter(
1654
+ (message) =>
1655
+ message.type !== 'deleted' &&
1656
+ message.created_at > lastRead &&
1657
+ this._countMessageAsUnread(message),
1658
+ ).length;
1659
+ if (deletedUnread > 0) {
1660
+ this._setOwnUnreadCount(Math.max(0, this.state.unreadCount - deletedUnread));
1661
+ }
1662
+ }
1663
+
1664
+ /**
1665
+ * Counts the unread messages that mention the current user, within the channel's newest messages
1666
+ * that are loaded (see {@link newestKnownMessages}).
1978
1667
  *
1979
- * @returns Unread mentions count.
1668
+ * @returns The unread mentions count.
1980
1669
  */
1981
1670
  countUnreadMentions() {
1982
1671
  const lastRead = this.lastRead();
1983
1672
  const userId = this.getClient().userId;
1984
1673
 
1985
1674
  let count = 0;
1986
- const latestMessages = this.messagePaginator.headItems;
1675
+ const latestMessages = this.newestKnownMessages();
1987
1676
  for (let i = 0; i < latestMessages.length; i += 1) {
1988
1677
  const message = latestMessages[i];
1989
1678
  if (
1990
1679
  this._countMessageAsUnread(message) &&
1991
- (!lastRead || message.created_at > lastRead) &&
1680
+ (lastRead == null || message.created_at > lastRead) &&
1992
1681
  message.mentioned_users?.some((user) => user.id === userId)
1993
1682
  ) {
1994
1683
  count++;
@@ -1998,7 +1687,7 @@ export class Channel extends ChannelApi {
1998
1687
  }
1999
1688
 
2000
1689
  /**
2001
- * Creates a new channel.
1690
+ * Creates the channel without watching it.
2002
1691
  *
2003
1692
  * @param options - Channel query options (optional).
2004
1693
  * @returns The server response.
@@ -2010,176 +1699,251 @@ export class Channel extends ChannelApi {
2010
1699
  state: false,
2011
1700
  presence: false,
2012
1701
  };
2013
- return await this.query(defaultOptions, 'latest');
1702
+ // It asks for no channel state (`state: false`), so it brings no page of messages to place.
1703
+ return await this.runChannelQuery(defaultOptions, undefined, {
1704
+ placeMessages: false,
1705
+ });
2014
1706
  };
2015
1707
 
2016
1708
  /**
2017
- * Queries the API to load messages, members, or other channel fields.
1709
+ * Moves this channel, created without an ID, from its temporary cid to the one the server gave it.
1710
+ * If another instance already holds that cid, it stays stored and takes over from this one
1711
+ * ({@link ChannelManager.supersedeChannel}).
1712
+ */
1713
+ private storeUnderServerCid(
1714
+ response: ChannelStateResponseFields,
1715
+ { watch }: { watch?: boolean },
1716
+ ) {
1717
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1718
+ const serverCid = response.channel!.cid;
1719
+ const { channelManager } = this.getClient();
1720
+ const storedUnder = this.cid;
1721
+ this.cid = serverCid;
1722
+ const isStoredUnderOldCid =
1723
+ storedUnder !== serverCid && channelManager.get(storedUnder) === this;
1724
+ // A disconnected channel is replaced by this instance, not superseded by it.
1725
+ if (channelManager.get(serverCid)?.pendingDisposal) {
1726
+ channelManager.removeChannel(serverCid);
1727
+ }
1728
+ const stored = channelManager.get(serverCid);
1729
+
1730
+ if (!stored) {
1731
+ if (
1732
+ !isStoredUnderOldCid ||
1733
+ !channelManager.changeChannelId(storedUnder, serverCid)
1734
+ ) {
1735
+ channelManager.getOrCreateChannel(serverCid, () => this);
1736
+ }
1737
+ return;
1738
+ }
1739
+
1740
+ if (stored === this) return;
1741
+ logger
1742
+ .withExtraTags('query', serverCid)
1743
+ .warn(
1744
+ 'Another instance of this channel is stored and takes over from this one (see channel.supersededBy).',
1745
+ );
1746
+ channelManager.supersedeChannel(this, stored, response, {
1747
+ storedUnder: isStoredUnderOldCid ? storedUnder : undefined,
1748
+ watch,
1749
+ });
1750
+ }
1751
+
1752
+ /**
1753
+ * Queries the API for messages, members and other channel fields.
1754
+ *
1755
+ * The returned messages are not added to {@link Channel.messagePaginator}: the paginator loads its
1756
+ * own pages, and {@link Channel.watch} / {@link Channel.create} place the page they query.
2018
1757
  *
2019
1758
  * @param options - The query options (optional, defaults to `{}`).
2020
- * @param messageSetToAddToIfDoesNotExist - It's possible to load disjunct sets of a channel's
2021
- * messages into state. Use `current` to load the initial channel state or to extend the
2022
- * currently displayed messages; use `latest` to load/extend the latest messages; `new` is
2023
- * used for loading a specific message and its surroundings (optional, defaults to `'current'`).
2024
1759
  * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
2025
1760
  * into the request (optional).
2026
- * @returns A query response.
1761
+ * @returns The query response.
2027
1762
  */
2028
1763
  async query(
2029
1764
  options: ChannelGetOrCreateRequest = {},
2030
- messageSetToAddToIfDoesNotExist: MessageSetType = 'current',
2031
1765
  requestOptions?: StreamRequestOptions,
2032
1766
  ) {
2033
- // Snapshot the loaded message ids BEFORE the network await, for a latest-window (re)seed only.
2034
- // When this query re-seeds an already-loaded window (reconnect / re-hydrate), seedFirstPageSync
2035
- // reconciles the fresh page against what is loaded, and the snapshot lets it tell an offline
2036
- // hard-delete (in the snapshot, absent from the page) from a message that arrives live
2037
- // during the fetch (not in the snapshot). Captured here — the only place with the pre-await state —
2038
- // so callers (channel.reload, watch) need not thread it. Empty on a cold open, so it is harmless.
2039
- // TODO(perf/cleanup): `headItems` materializes full message objects (intervalToItems) just to map
2040
- // them down to ids. A cheaper, clearer equivalent is a straight copy of the paginator index's own
2041
- // id set — expose `memberIds` on StoreBackedItemIndex (e.g. `snapshotMembers()` returning
2042
- // `new Set(this.memberIds)`) and use it here AND in client.queryChannelsAndHydrate. The broader
2043
- // scope (all intervals vs just the head) is inert: the reconcile only consults head ids, older
2044
- // island ids are never at/above-newest, and local messages are guarded by isServerConfirmedMessage.
2045
- const candidateIds =
2046
- messageSetToAddToIfDoesNotExist === 'latest'
2047
- ? new Set(this.messagePaginator.headItems.map((message) => message.id))
2048
- : undefined;
1767
+ return await this.runChannelQuery(options, requestOptions, { placeMessages: false });
1768
+ }
2049
1769
 
2050
- // The INITIAL channel-open query honors the paginator's OWN pageSize (light on native, 25) rather
2051
- // than the server's larger default — opening loads the same page size it paginates by. A caller
2052
- // that already knows how much to fetch passes an explicit messages.limit, which is respected as-is:
2053
- // a reconnect/re-hydrate sizes it to the loaded window (channel.reload → items.length), and
2054
- // pagination/around pass their own cursors + limit.
2055
- const requestedPageSize = options?.messages?.limit ?? this.messagePaginator.pageSize;
1770
+ /**
1771
+ * The query behind `query()`, `watch()` and `create()`, in three steps: sends the request
1772
+ * ({@link requestChannelState}), has the message paginator place the returned page when
1773
+ * `placeMessages` is set (a watch query), then applies the rest of the response
1774
+ * ({@link applyChannelStateFromResponse}), all as a tracked query ({@link runTrackedQuery}).
1775
+ *
1776
+ * The page is placed before the rest is applied, because the rest reads the loaded messages: read
1777
+ * and delivery positions that come without a message id are looked up among them, and the latest
1778
+ * message is reported as delivered. A first page then takes the unread snapshot, from the read
1779
+ * state the rest brought. The message paginator's own queries keep the same order: they place
1780
+ * their page, then apply the rest with {@link applyChannelStateFromResponse}.
1781
+ */
1782
+ private async runChannelQuery(
1783
+ options: ChannelGetOrCreateRequest,
1784
+ requestOptions: StreamRequestOptions | undefined,
1785
+ { placeMessages }: { placeMessages: boolean },
1786
+ ) {
1787
+ return await this.runTrackedQuery(async () => {
1788
+ const externalQuery = placeMessages
1789
+ ? this.messagePaginator.prepareExternalQuery(options.messages)
1790
+ : undefined;
1791
+ const state = await this.requestChannelState(
1792
+ externalQuery
1793
+ ? { ...options, messages: externalQuery.messagePaginationParams }
1794
+ : options,
1795
+ requestOptions,
1796
+ { placesNewestPage: externalQuery?.isNewestPage ?? false },
1797
+ );
1798
+ let placedFirstPage = false;
1799
+ try {
1800
+ if (externalQuery && Array.isArray(state.messages)) {
1801
+ placedFirstPage = externalQuery.placePage(state.messages.map(formatMessage));
1802
+ }
1803
+ } finally {
1804
+ // The rest of a response that arrived is applied even when placing its page failed: a
1805
+ // watch the server registered is recorded, and the read state is taken in.
1806
+ // Only the newest page is the latest message set, for the offline database to store.
1807
+ this.applyChannelStateFromResponse(state, {
1808
+ isLatestMessageSet: externalQuery?.isNewestPage ?? false,
1809
+ watch: options.watch,
1810
+ });
1811
+ }
1812
+ if (placedFirstPage) this.messagePaginator.seedUnreadSnapshot();
1813
+ return state;
1814
+ });
1815
+ }
2056
1816
 
2057
- // Make sure we wait for the connect promise if there is a pending one
2058
- await this.getClient().wsPromise;
1817
+ /**
1818
+ * Runs `run`, a query of this channel, as a tracked query: refused for a disposed instance, and
1819
+ * the channel counts as being queried until `run` settles ({@link isQueryingChannel}), so the
1820
+ * channel store keeps it meanwhile. Used by {@link runChannelQuery} and by the message
1821
+ * paginator's own queries.
1822
+ *
1823
+ * `run` starts synchronously: a paginator query publishes its loading flag before anything is
1824
+ * awaited, which keeps a second query in the same tick from starting.
1825
+ *
1826
+ * @internal
1827
+ */
1828
+ async runTrackedQuery<T>(run: () => Promise<T>): Promise<T> {
1829
+ // A disposed instance is done for good: its query would load it again and, for a watch,
1830
+ // register a watch whose events go to the instance now stored for the cid. So it is refused.
1831
+ if (this.pendingDisposal) throw this.disposedError();
1832
+ // a count, not a flag: queries of one channel overlap (a watch while the paginator loads more)
1833
+ this._channelQueriesInFlight += 1;
1834
+ try {
1835
+ return await run();
1836
+ } finally {
1837
+ this._channelQueriesInFlight -= 1;
1838
+ }
1839
+ }
2059
1840
 
1841
+ /**
1842
+ * Sends the channel query and takes in what the response says about the channel itself: its id,
1843
+ * the cid it is stored under, its config, and its `last_message_at`, against which the message
1844
+ * paginator's head interval is checked before any page is placed (see
1845
+ * `MessagePaginator.unmarkStaleHead`). The request of {@link runChannelQuery} and of the message
1846
+ * paginator's own queries, which run it as a tracked query ({@link runTrackedQuery}); it does not
1847
+ * track the query itself. Refused for a disposed instance, before anything is sent.
1848
+ *
1849
+ * `placesNewestPage`: the caller places the newest page with this response, which brings the
1850
+ * newest messages up to date, so the head interval is not checked.
1851
+ *
1852
+ * @internal
1853
+ */
1854
+ async requestChannelState(
1855
+ options: ChannelGetOrCreateRequest,
1856
+ requestOptions: StreamRequestOptions | undefined,
1857
+ { placesNewestPage = false }: { placesNewestPage?: boolean } = {},
1858
+ ): Promise<StreamResponse<ChannelStateResponse>> {
1859
+ if (this.pendingDisposal) throw this.disposedError();
2060
1860
  const queryPayload: ChannelGetOrCreateRequest = {
2061
1861
  data: this._data,
2062
1862
  state: true,
2063
1863
  ...options,
2064
- // Ask the server for exactly the initial-open page size (not its default), so the loaded window
2065
- // matches the paginator's pageSize. Explicit messages (reconnect/around/pagination) pass through.
2066
- messages:
2067
- options?.messages ??
2068
- (messageSetToAddToIfDoesNotExist === 'latest'
2069
- ? { limit: requestedPageSize }
2070
- : undefined),
2071
1864
  };
2072
1865
 
2073
1866
  const state = this.id
2074
1867
  ? await this.getOrCreate(queryPayload, requestOptions)
2075
1868
  : await this.getClient().getOrCreateDistinctChannel(
2076
- {
2077
- type: this.type,
2078
- ...queryPayload,
2079
- },
1869
+ { type: this.type },
1870
+ queryPayload,
2080
1871
  requestOptions,
2081
1872
  );
2082
1873
 
2083
1874
  // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2084
1875
  const channel = state.channel!;
2085
1876
 
2086
- // update the channel id if it was missing
2087
1877
  if (!this.id) {
2088
1878
  this.id = channel.id;
2089
- this.cid = channel.cid;
2090
- // set the channel as active...
2091
-
2092
- const tempChannelCid = generateChannelTempCid(
2093
- this.type,
2094
- state.members.map((member) => member.user_id || member.user?.id || ''),
2095
- );
2096
-
2097
- if (tempChannelCid && tempChannelCid in this.getClient().activeChannels) {
2098
- // This gets set in `client.channel()` function, when channel is created
2099
- // using members, not id.
2100
- delete this.getClient().activeChannels[tempChannelCid];
2101
- }
2102
-
2103
- if (
2104
- !(this.cid in this.getClient().activeChannels) &&
2105
- this.getClient()._cacheEnabled()
2106
- ) {
2107
- this.getClient().activeChannels[this.cid] = this;
2108
- }
1879
+ this.storeUnderServerCid(state, { watch: queryPayload.watch });
2109
1880
  }
2110
1881
 
2111
1882
  this.getClient()._addChannelConfig(channel);
2112
1883
 
2113
- // The composer derives part of its configuration from this channel's server-side config, which for a
2114
- // channel opened via `client.channel(type, id)` arrives only now — after the composer was built. A
2115
- // composer with registered subscriptions hears about it through the store; one without has no other
2116
- // route, so it is told here.
2117
- //
2118
- // Restrictions, not a request: passing the server's value to `updateConfig` would record a server
2119
- // *permission* as something the client asked for, and so re-enable a feature an integrator had
2120
- // deliberately turned off (**DV-18**).
1884
+ // The composer's server config arrives here for a channel opened via `ensure({ type, id })`. A
1885
+ // composer with registered subscriptions hears it through the store, one without is told here.
1886
+ // Applied as restrictions: `updateConfig` would record a server permission as a client request and
1887
+ // re-enable a feature the integrator turned off.
2121
1888
  this.messageComposer.applyServerRestrictions();
2122
1889
 
2123
- // Seed the message paginator with the first (latest) page BEFORE _initializeState, which
2124
- // hydrates the read state and (via MessageReceiptsTracker) resolves read/delivered cursors
2125
- // against this paginator. Seeding first guarantees the tracker sees a populated timeline; a
2126
- // later async seed would run after the reconcile and mislabel delivery status. Only the
2127
- // latest-page open paths (watch/create) pass 'latest' — the paginator's own pagination queries
2128
- // use 'current' and must not be reseeded as a first page here.
2129
- if (messageSetToAddToIfDoesNotExist === 'latest' && Array.isArray(state.messages)) {
2130
- // Pass the query's message pagination options through: a channel can be opened AROUND a
2131
- // message (id_around / created_at_around), in which case the fetched page is a jump window,
2132
- // not the latest page — the paginator must reconcile it with jump semantics.
2133
- this.messagePaginator.seedFirstPageSync(
2134
- state.messages.map(formatMessage),
2135
- requestedPageSize,
2136
- options?.messages,
2137
- // Re-seed of an already-loaded window folds + reconciles instead of blanking (see above).
2138
- { candidateIds, reconcile: true },
2139
- );
1890
+ // This response's `last_message_at`, before any page is placed: the paginator tells from it whether
1891
+ // a page reaches the newest message (`_initializeState` sets it too, after).
1892
+ this.messagePaginator.setQueriedLatestMessageAt(channel.last_message_at);
1893
+ // Checked before any page is placed, as a page that reaches the newest message marks its own
1894
+ // interval as the head.
1895
+ if (!placesNewestPage && this.isHeadLeftWithoutRefresh(queryPayload)) {
1896
+ this.messagePaginator.unmarkStaleHead();
2140
1897
  }
2141
1898
 
2142
- // The request carrying `watch: true` came back, so the server has registered this connection as
2143
- // a watcher. Only ever set here because a `watch: false` query does NOT unwatch server-side, so it
2144
- // must not clear the flag.
2145
- if (queryPayload.watch) {
1899
+ return state;
1900
+ }
1901
+
1902
+ /**
1903
+ * Whether nothing but this query brings the head interval up to date, so its `last_message_at` may
1904
+ * show the interval stale: the watch was stopped (`NotWatching`), or this query itself watches
1905
+ * again after a dropped connection (`WasWatching`), leaving nothing to re-watch with the newest
1906
+ * page. While the channel is watched, a message the interval lacks is still on its way; after a
1907
+ * dropped connection, the re-watch that follows places the newest page (see
1908
+ * `ConnectionRecoveryManager`).
1909
+ */
1910
+ private isHeadLeftWithoutRefresh(query: ChannelGetOrCreateRequest): boolean {
1911
+ if (this.watchStatus === ChannelWatchStatus.NotWatching) return true;
1912
+ return this.watchStatus === ChannelWatchStatus.WasWatching && !!query.watch;
1913
+ }
1914
+
1915
+ /**
1916
+ * Applies a channel query response: watch status, read/members state, polls, reminders, composer,
1917
+ * channel data, and the `channels.queried` event and offline write. Called once the response's
1918
+ * page of messages, if any, is placed (see {@link runChannelQuery}).
1919
+ *
1920
+ * @internal
1921
+ */
1922
+ applyChannelStateFromResponse(
1923
+ state: ChannelStateResponseFields,
1924
+ { isLatestMessageSet, watch }: { isLatestMessageSet: boolean; watch?: boolean },
1925
+ ) {
1926
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1927
+ const channel = state.channel!;
1928
+
1929
+ if (this.supersededBy) {
1930
+ // The stored instance took over the watch (`supersedeChannel`), so this one receives no events.
1931
+ this.watchStatus = ChannelWatchStatus.NotWatching;
1932
+ } else if (watch) {
1933
+ // Set only here: a `watch: false` query does not unwatch server-side, so it must not clear it.
2146
1934
  this.watchStatus = ChannelWatchStatus.Watching;
2147
1935
  }
2148
1936
 
2149
- // Seed read/members/pinned/thread-cleanup state; the message list is in the paginator.
1937
+ // Seeds read, members, pinned and thread-cleanup state (messages live in the paginator).
2150
1938
  this._initializeState(state);
2151
- // The queried page is the latest set unless this was a jump/around query.
2152
- const isLatestMessageSet =
2153
- messageSetToAddToIfDoesNotExist === 'latest' &&
2154
- !options?.messages?.id_around &&
2155
- !(options?.messages as MessagePaginationParams | undefined)?.created_at_around;
2156
-
2157
1939
  this.getClient().polls.hydratePollCache(state.messages, true);
2158
1940
  this.getClient().reminders.hydrateState(state.messages);
2159
1941
 
2160
1942
  this.messageComposer.initStateFromChannelResponse(state);
2161
1943
 
2162
- const areCapabilitiesChanged =
2163
- [...(channel.own_capabilities || [])].sort().join() !==
2164
- [
2165
- ...(this.data && Array.isArray(this.data?.own_capabilities)
2166
- ? this.data.own_capabilities
2167
- : []),
2168
- ]
2169
- .sort()
2170
- .join();
2171
- const previousData = this.data;
2172
1944
  this.data = channel;
2173
- this.state.syncStateFromChannelData(this.data, previousData);
2174
- this.offlineMode = false;
2175
-
2176
- if (areCapabilitiesChanged) {
2177
- this.getClient().dispatchEvent({
2178
- type: 'capabilities.changed',
2179
- cid: this.cid,
2180
- own_capabilities: channel.own_capabilities ?? [],
2181
- });
2182
- }
1945
+ // One update before the events below: the offline DB reads it when handling them.
1946
+ this.state.partialNext({ initialized: true, offlineMode: false });
2183
1947
 
2184
1948
  this.getClient().dispatchEvent({
2185
1949
  type: 'channels.queried',
@@ -2198,18 +1962,18 @@ export class Channel extends ChannelApi {
2198
1962
  );
2199
1963
 
2200
1964
  this.getClient().syncDeliveredCandidates([this]);
2201
- return state;
2202
1965
  }
2203
1966
 
2204
1967
  /**
2205
- * Bans a user from a channel.
1968
+ * Bans a user from this channel.
2206
1969
  *
2207
1970
  * @param targetUserId - The user to ban.
2208
1971
  * @param options - Ban options.
2209
1972
  * @returns The server response.
2210
1973
  */
2211
1974
  async banUser(targetUserId: string, options: Omit<BanUserOptions, 'channel_cid'>) {
2212
- this._checkInitialized();
1975
+ this._checkHasId();
1976
+
2213
1977
  return await this.getClient().moderation.ban({
2214
1978
  ...options,
2215
1979
  target_user_id: targetUserId,
@@ -2218,41 +1982,15 @@ export class Channel extends ChannelApi {
2218
1982
  }
2219
1983
 
2220
1984
  /**
2221
- * Hides the channel from `queryChannels` for the user until a message is added.
2222
- * If `clear_history` is set to `true`, all messages will be removed for the user.
2223
- *
2224
- * @param ...args - `[request, requestOptions]`. Pass `request: { clear_history: true }` to clear
2225
- * message history for the user; `requestOptions` carries per-request options such as an abort
2226
- * `signal` and is never serialized into the request.
2227
- * @returns The server response.
2228
- */
2229
- override async hide(...args: Parameters<ChannelApi['hide']>) {
2230
- this._checkInitialized();
2231
- return await super.hide(...args);
2232
- }
2233
-
2234
- /**
2235
- * Removes the hidden status for a channel. Ensures the channel is initialized first.
2236
- *
2237
- * @param ...args - `[request, requestOptions]`. `request` is the show-channel payload;
2238
- * `requestOptions` carries per-request options such as an abort `signal` and is never
2239
- * serialized into the request.
2240
- * @returns The server response.
2241
- */
2242
- override async show(...args: Parameters<ChannelApi['show']>) {
2243
- this._checkInitialized();
2244
- return await super.show(...args);
2245
- }
2246
-
2247
- /**
2248
- * Removes the bans for a user on a channel.
1985
+ * Removes the bans of a user on this channel.
2249
1986
  *
2250
1987
  * @param targetUserId - The user to unban.
2251
1988
  * @param options - Unban options (optional).
2252
1989
  * @returns The server response.
2253
1990
  */
2254
1991
  async unbanUser(targetUserId: string, options?: UnBanUserOptions) {
2255
- this._checkInitialized();
1992
+ this._checkHasId();
1993
+
2256
1994
  return await this.getClient().unbanUser(targetUserId, {
2257
1995
  ...options,
2258
1996
  type: this.type,
@@ -2261,18 +1999,20 @@ export class Channel extends ChannelApi {
2261
1999
  }
2262
2000
 
2263
2001
  /**
2264
- * Casts or cancels one or more votes on a poll.
2002
+ * Casts a vote on a poll. `removeVote()` removes one.
2265
2003
  *
2266
- * @param ...args - `[request, requestOptions]`. `request` holds the target message ID, poll ID,
2267
- * and the vote to cast (or an empty payload to cancel); `requestOptions` carries per-request
2268
- * options such as an abort `signal` and is never serialized into the request.
2004
+ * @param ...args - `[pathParams, request, requestOptions]`. `pathParams` holds the target
2005
+ * `message_id` and `poll_id`; `request` holds the vote to cast; `requestOptions` carries
2006
+ * per-request options such as an abort `signal` and is never serialized into the request.
2269
2007
  * @returns The poll vote response.
2270
2008
  */
2271
2009
  async vote(...args: Parameters<ChatApi['castPollVote']>) {
2010
+ this._checkHasId();
2272
2011
  return await this.getClient().castPollVote(...args);
2273
2012
  }
2274
2013
 
2275
2014
  async removeVote(...args: Parameters<ChatApi['deletePollVote']>) {
2015
+ this._checkHasId();
2276
2016
  return await this.getClient().deletePollVote(...args);
2277
2017
  }
2278
2018
 
@@ -2280,18 +2020,17 @@ export class Channel extends ChannelApi {
2280
2020
  return await super.createDraft(...args);
2281
2021
  }
2282
2022
 
2283
- /**
2284
- * Creates or updates a draft message in a channel. If offline support is enabled, the
2285
- * call is queued so it is replayed on reconnect.
2286
- */
2023
+ /** Creates or updates a draft. With offline support the call is queued and replayed on reconnect. */
2287
2024
  override async createDraft(...args: Parameters<ChannelApi['createDraft']>) {
2025
+ this._checkHasId();
2026
+
2288
2027
  const [request] = args;
2289
2028
 
2290
2029
  return await queueOrRun({
2291
2030
  channel: this,
2292
2031
  client: this.getClient(),
2293
2032
  task: {
2294
- channelId: this.id as string,
2033
+ channelId: this.id,
2295
2034
  channelType: this.type,
2296
2035
  threadId: request.message?.parent_id,
2297
2036
  payload: args,
@@ -2304,18 +2043,17 @@ export class Channel extends ChannelApi {
2304
2043
  return await super.deleteDraft(...args);
2305
2044
  }
2306
2045
 
2307
- /**
2308
- * Deletes a draft message from a channel or a thread. If offline support is enabled, the
2309
- * call is queued so it is replayed on reconnect.
2310
- */
2046
+ /** Deletes a draft. With offline support the call is queued and replayed on reconnect. */
2311
2047
  override async deleteDraft(...args: Parameters<ChannelApi['deleteDraft']>) {
2048
+ this._checkHasId();
2049
+
2312
2050
  const [request] = args;
2313
2051
 
2314
2052
  return await queueOrRun({
2315
2053
  channel: this,
2316
2054
  client: this.getClient(),
2317
2055
  task: {
2318
- channelId: this.id as string,
2056
+ channelId: this.id,
2319
2057
  channelType: this.type,
2320
2058
  threadId: request?.parent_id,
2321
2059
  payload: args,
@@ -2325,7 +2063,7 @@ export class Channel extends ChannelApi {
2325
2063
  }
2326
2064
 
2327
2065
  /**
2328
- * Listens to events on this channel.
2066
+ * Listens to events on this channel. A callback alone listens to all events.
2329
2067
  *
2330
2068
  * @example
2331
2069
  * channel.on('message.new', (event) => {
@@ -2337,17 +2075,23 @@ export class Channel extends ChannelApi {
2337
2075
  * console.log(event.type);
2338
2076
  * });
2339
2077
  *
2340
- * @param callbackOrString - The event type to listen for, or the callback when listening to all events.
2341
- * @param callbackOrNothing - The callback to call when an event type was provided (optional).
2078
+ * @param eventType - The event type to listen for.
2079
+ * @param callback - Called with each event of that type.
2342
2080
  * @returns An object with an `unsubscribe()` method.
2343
2081
  */
2344
- on<T extends EventType | string>(
2082
+ on<T extends EventType>(
2345
2083
  eventType: T,
2346
2084
  callback: EventHandler<T>,
2347
2085
  ): { unsubscribe: () => void };
2086
+ /**
2087
+ * Listens to all events on this channel.
2088
+ *
2089
+ * @param callback - Called with every event.
2090
+ * @returns An object with an `unsubscribe()` method.
2091
+ */
2348
2092
  on(callback: EventHandler): { unsubscribe: () => void };
2349
2093
  on(
2350
- callbackOrString: EventHandler | string,
2094
+ callbackOrString: EventHandler | EventType,
2351
2095
  callbackOrNothing?: EventHandler,
2352
2096
  ): { unsubscribe: () => void } {
2353
2097
  const key = callbackOrNothing ? (callbackOrString as EventType) : 'all';
@@ -2380,14 +2124,22 @@ export class Channel extends ChannelApi {
2380
2124
  }
2381
2125
 
2382
2126
  /**
2383
- * Removes the event handler.
2127
+ * Removes a listener for one event type.
2128
+ *
2129
+ * @param eventType - The event type it listens to.
2130
+ * @param callback - The listener to remove.
2131
+ */
2132
+ off<T extends EventType>(eventType: T, callback: EventHandler<T>): void;
2133
+ /**
2134
+ * Removes a listener for all events.
2384
2135
  *
2385
- * @param callbackOrString - The event type, or the callback when removing an all-events listener.
2386
- * @param callbackOrNothing - The callback to remove when an event type was provided (optional).
2136
+ * @param callback - The listener to remove.
2387
2137
  */
2388
- off<T extends EventType | string>(eventType: T, callback: EventHandler): void;
2389
2138
  off(callback: EventHandler): void;
2390
- off(callbackOrString: EventHandler | string, callbackOrNothing?: EventHandler): void {
2139
+ off(
2140
+ callbackOrString: EventHandler | EventType,
2141
+ callbackOrNothing?: EventHandler,
2142
+ ): void {
2391
2143
  const key = callbackOrNothing ? (callbackOrString as EventType) : 'all';
2392
2144
  const callback = callbackOrNothing
2393
2145
  ? callbackOrNothing
@@ -2457,12 +2209,9 @@ export class Channel extends ChannelApi {
2457
2209
  }
2458
2210
 
2459
2211
  /**
2460
- * Sets the current user's unread count. The count lives in exactly one place — the reactive
2461
- * `read[userId].unread_messages`, which is what the unread badge reads and what
2462
- * `state.unreadCount` derives from — so channel-wide resets (`channel.truncated`, "all channels
2463
- * read") must route through here rather than writing a count of their own.
2212
+ * Sets the current user's unread count in `read[userId].unread_messages`, the one place it lives
2213
+ * (`state.unreadCount` derives from it). Returns whether the count changed.
2464
2214
  */
2465
- /** @returns whether the count actually changed, so callers can react only to the channels it did. */
2466
2215
  _setOwnUnreadCount(unreadCount: number): boolean {
2467
2216
  if (this.pendingDisposal) return false;
2468
2217
 
@@ -2470,7 +2219,7 @@ export class Channel extends ChannelApi {
2470
2219
  if (!userId) return false;
2471
2220
 
2472
2221
  const currentUserReadState = this.state.read[userId];
2473
- // only reconcile an existing read entry; never fabricate one just to store a count
2222
+ // Only updates an existing read entry, never creates one.
2474
2223
  if (!currentUserReadState || currentUserReadState.unread_messages === unreadCount) {
2475
2224
  return false;
2476
2225
  }
@@ -2492,6 +2241,15 @@ export class Channel extends ChannelApi {
2492
2241
  .debug(`Received an event of type "${event.type}".`, { event });
2493
2242
 
2494
2243
  const channelState = channel.state;
2244
+
2245
+ // The server unhides a channel on any new message without sending `channel.visible`.
2246
+ if (
2247
+ (event.type === 'message.new' || event.type === 'notification.message_new') &&
2248
+ channel.data?.hidden
2249
+ ) {
2250
+ channel.data = { ...channel.data, hidden: false };
2251
+ }
2252
+
2495
2253
  switch (event.type) {
2496
2254
  case 'typing.start':
2497
2255
  if (event.user?.id) {
@@ -2514,44 +2272,37 @@ export class Channel extends ChannelApi {
2514
2272
  case 'ai_indicator.stop':
2515
2273
  channelState.partialNext({ aiState: AIStates.Stop });
2516
2274
  break;
2517
- // `notification.mark_read` is the only read signal for a channel the user is not watching, since
2518
- // `message.read` goes to watchers only. `message.read_locally` is the local stand-in when read
2519
- // events are disabled (livestreams). Both reuse the `message.read` logic, minus its delivery sync.
2275
+ // `notification.mark_read` is the only read signal for a channel the user is not watching
2276
+ // (`message.read` goes to watchers only). `message.read_locally` is the local stand-in when read
2277
+ // events are disabled. All share the `message.read` logic.
2520
2278
  case 'notification.mark_read':
2521
2279
  case 'message.read_locally':
2522
2280
  case 'message.read':
2523
2281
  if (
2524
2282
  event.user?.id &&
2525
- event.created_at &&
2526
- // the same event announces a thread read, which says nothing about the channel
2527
- !(event.type === 'notification.mark_read' && event.thread_id)
2283
+ event.created_at != null &&
2284
+ // A thread read (`thread_id` on `notification.mark_read`, `thread` on `message.read`) is the
2285
+ // `thread` object's business and must not reset the channel's unread count.
2286
+ !(event.type === 'notification.mark_read' && event.thread_id) &&
2287
+ !('thread' in event && event.thread)
2528
2288
  ) {
2529
2289
  const eventUser = event.user;
2530
- const readAtDate = new Date(event.created_at);
2531
- const toDate = (value?: string | Date) =>
2532
- value ? (value instanceof Date ? value : new Date(value)) : undefined;
2533
- const userReadState = this._upsertReadState(
2290
+ const readAt = event.created_at;
2291
+ this._upsertReadState(
2534
2292
  eventUser.id,
2535
2293
  (currentUserReadState) => {
2536
- const currentDeliveredAt = toDate(currentUserReadState?.last_delivered_at);
2294
+ const currentDeliveredAt = currentUserReadState?.last_delivered_at;
2537
2295
 
2538
2296
  return {
2539
- // preserve delivery information already known for user
2540
2297
  ...currentUserReadState,
2541
- ...(currentUserReadState?.last_read
2542
- ? { last_read: toDate(currentUserReadState.last_read) }
2543
- : null),
2544
- ...(currentDeliveredAt
2545
- ? { last_delivered_at: currentDeliveredAt }
2546
- : null),
2547
- last_read: readAtDate,
2298
+ last_read: readAt,
2548
2299
  last_read_message_id: event.last_read_message_id,
2549
2300
  last_delivered_at:
2550
- !currentDeliveredAt || currentDeliveredAt < readAtDate
2551
- ? readAtDate
2301
+ !currentDeliveredAt || currentDeliveredAt < readAt
2302
+ ? readAt
2552
2303
  : currentDeliveredAt,
2553
2304
  last_delivered_message_id:
2554
- !currentDeliveredAt || currentDeliveredAt < readAtDate
2305
+ !currentDeliveredAt || currentDeliveredAt < readAt
2555
2306
  ? (event.last_read_message_id ??
2556
2307
  currentUserReadState?.last_delivered_message_id)
2557
2308
  : currentUserReadState?.last_delivered_message_id,
@@ -2562,14 +2313,13 @@ export class Channel extends ChannelApi {
2562
2313
  },
2563
2314
  { changedUserIds: [eventUser.id] },
2564
2315
  );
2565
- void userReadState;
2566
2316
 
2567
2317
  const client = this.getClient();
2568
2318
  const isOwnEvent = event.user?.id === client.user?.id;
2569
2319
 
2570
2320
  if (isOwnEvent) {
2571
- // Delivery reporting buffers a `markChannelsDelivered` network request; the local read
2572
- // must not hit the backend, so only sync for the real server `message.read`.
2321
+ // Delivery reporting buffers a `markChannelsDelivered` request, which a local read must not
2322
+ // trigger: only the server `message.read` syncs.
2573
2323
  if (event.type === 'message.read') {
2574
2324
  client.syncDeliveredCandidates([this]);
2575
2325
  }
@@ -2578,24 +2328,18 @@ export class Channel extends ChannelApi {
2578
2328
  break;
2579
2329
  case 'message.delivered':
2580
2330
  // todo: update also on thread
2581
- if (event.user?.id && event.created_at) {
2331
+ if (event.user?.id && event.created_at != null) {
2582
2332
  const eventUser = event.user;
2583
2333
  const createdAt = event.created_at;
2584
- const toDate = (value?: string | Date) =>
2585
- value ? (value instanceof Date ? value : new Date(value)) : undefined;
2586
- const resolvedDeliveredAt = new Date(event.last_delivered_at ?? createdAt);
2587
- const userReadState = this._upsertReadState(
2334
+ const resolvedDeliveredAt = event.last_delivered_at ?? createdAt;
2335
+ this._upsertReadState(
2588
2336
  eventUser.id,
2589
2337
  (currentUserReadState) => {
2590
- const currentDeliveredAt = toDate(currentUserReadState?.last_delivered_at);
2591
- const currentReadAt = toDate(currentUserReadState?.last_read);
2338
+ const currentDeliveredAt = currentUserReadState?.last_delivered_at;
2339
+ const currentReadAt = currentUserReadState?.last_read;
2592
2340
 
2593
2341
  return {
2594
2342
  ...currentUserReadState,
2595
- ...(currentReadAt ? { last_read: currentReadAt } : null),
2596
- ...(currentDeliveredAt
2597
- ? { last_delivered_at: currentDeliveredAt }
2598
- : null),
2599
2343
  last_delivered_at:
2600
2344
  currentDeliveredAt && currentDeliveredAt > resolvedDeliveredAt
2601
2345
  ? currentDeliveredAt
@@ -2606,19 +2350,17 @@ export class Channel extends ChannelApi {
2606
2350
  : event.last_delivered_message_id,
2607
2351
  user: eventUser,
2608
2352
  // delivery events can be received before read events
2609
- last_read: currentReadAt ?? new Date(createdAt),
2353
+ last_read: currentReadAt ?? createdAt,
2610
2354
  unread_messages: currentUserReadState?.unread_messages ?? 0,
2611
2355
  };
2612
2356
  },
2613
2357
  { changedUserIds: [eventUser.id] },
2614
2358
  );
2615
- void userReadState;
2616
2359
 
2617
2360
  const client = this.getClient();
2618
2361
  const isOwnEvent = event.user?.id === client.user?.id;
2619
2362
 
2620
- // make sure not to report deliveries that were
2621
- // already confirmed from own user from another device
2363
+ // Do not report deliveries the own user already confirmed from another device.
2622
2364
  if (isOwnEvent) {
2623
2365
  client.syncDeliveredCandidates([this]);
2624
2366
  }
@@ -2627,28 +2369,37 @@ export class Channel extends ChannelApi {
2627
2369
  case 'user.watching.start':
2628
2370
  case 'user.updated':
2629
2371
  if (event.user?.id) {
2630
- channelState.watchers[event.user.id] = event.user;
2372
+ channelState.watchers = {
2373
+ ...channelState.watchers,
2374
+ [event.user.id]: event.user,
2375
+ };
2376
+ channel.getClient().state.updateUserReference(event.user, channel.cid);
2631
2377
  }
2632
2378
  break;
2633
2379
  case 'user.watching.stop':
2634
- if (event.user?.id) {
2635
- delete channelState.watchers[event.user.id];
2380
+ if (event.user?.id && channelState.watchers[event.user.id]) {
2381
+ const newWatchers = { ...channelState.watchers };
2382
+ delete newWatchers[event.user.id];
2383
+ channelState.watchers = newWatchers;
2636
2384
  }
2637
2385
  break;
2638
2386
  case 'message.deleted':
2639
2387
  if (event.message) {
2640
2388
  this._extendEventWithOwnReactions(event);
2641
2389
  const formattedMessage = formatMessage(event.message);
2642
- const isThreadReply =
2643
- !!event.message.parent_id && !event.message.show_in_channel;
2390
+ // the server lowers unread count regardless of the type of deletion
2391
+ const deletedMessage = this.getClient().messageStore.get(event.message.id);
2392
+ if (deletedMessage) this._lowerUnreadCountForDeletedMessages([deletedMessage]);
2644
2393
  // Thread-only replies are handled by the Thread object; the channel owns the main list.
2645
- if (!isThreadReply) {
2394
+ if (!isThreadOnlyReply(event.message)) {
2646
2395
  if (event.hard_delete) {
2647
2396
  this.messagePaginator.removeItem({ id: event.message.id });
2648
2397
  this.pinnedMessagesPaginator.removeItem({ id: event.message.id });
2649
2398
  } else {
2650
- this.messagePaginator.ingestItem(formattedMessage);
2651
- this.pinnedMessagesPaginator.ingestItem(formattedMessage);
2399
+ // A soft delete changes neither `created_at` nor `pinned`: one store write reaches every
2400
+ // holder, where an `ingestItem` per collection would re-emit each active interval.
2401
+ const store = this.getClient().messageStore;
2402
+ if (store.has(event.message.id)) store.upsert(formattedMessage);
2652
2403
  }
2653
2404
  }
2654
2405
  this.messagePaginator.reflectQuotedMessageUpdate(formattedMessage);
@@ -2657,13 +2408,15 @@ export class Channel extends ChannelApi {
2657
2408
  break;
2658
2409
  case 'user.messages.deleted':
2659
2410
  if (event.user) {
2660
- const deletedAt = new Date(event.created_at ?? Date.now());
2411
+ const deletedAt = event.created_at ?? nowNs();
2661
2412
  const hardDelete = !!event.hard_delete;
2662
- this.messagePaginator.applyMessageDeletionForUser({
2413
+ const deletedMessages = this.messagePaginator.applyMessageDeletionForUser({
2663
2414
  userId: event.user.id,
2664
2415
  hardDelete,
2665
2416
  deletedAt,
2666
2417
  });
2418
+ // the server keeps the unread count on a soft bulk delete
2419
+ if (hardDelete) this._lowerUnreadCountForDeletedMessages(deletedMessages);
2667
2420
  this.pinnedMessagesPaginator.applyMessageDeletionForUser({
2668
2421
  userId: event.user.id,
2669
2422
  hardDelete,
@@ -2674,32 +2427,23 @@ export class Channel extends ChannelApi {
2674
2427
  case 'message.new':
2675
2428
  if (event.message) {
2676
2429
  const client = this.getClient();
2677
- /* if message belongs to current user, always assume timestamp is changed to filter it out and add again to avoid duplication */
2678
2430
  const ownMessage = event.user?.id === client.user?.id;
2679
- const isThreadMessage =
2680
- event.message.parent_id && !event.message.show_in_channel;
2681
-
2431
+ const isThreadMessage = isThreadOnlyReply(event.message);
2682
2432
  if (!isThreadMessage) {
2683
- // ingestItem advances the paginator's tracked latest message (→ last_message_at). A
2684
- // message that arrives while the viewer has scrolled to an older window lands in the
2685
- // head interval, not the active one, so the view is preserved without an isUpToDate flag.
2686
- this.messagePaginator.ingestItem(formatMessage(event.message));
2687
- // ingestItem auto-adds when pinned (matchesFilter { pinned: true }).
2688
- this.pinnedMessagesPaginator.ingestItem(formatMessage(event.message));
2433
+ // `ingestItem` advances the tracked latest message. A message arriving while the viewer
2434
+ // is in an older interval lands in the head interval, leaving the view as it is.
2435
+ const formattedMessage = formatMessage(event.message);
2436
+ this.messagePaginator.ingestItem(formattedMessage);
2437
+ // Added only when pinned (`matchesFilter`).
2438
+ this.pinnedMessagesPaginator.ingestItem(formattedMessage);
2689
2439
  }
2690
2440
 
2691
- // do not increase the unread count - the back-end does not increase the count neither in the following cases:
2692
- // 1. the message is mine
2693
- // 2. the message is a thread reply from any user
2441
+ // The back-end does not count own messages or thread replies as unread.
2694
2442
  const preventUnreadCountUpdate = ownMessage || isThreadMessage;
2695
2443
  if (preventUnreadCountUpdate) break;
2696
2444
 
2697
- // The own unread count IS `read[ownUserId].unread_messages` (see
2698
- // `ChannelState.unreadCount`), so the own row is what carries the own-unread gating: a
2699
- // message that does not count as unread (silent/shadowed/muted) never bumps it, and neither
2700
- // does one arriving while the user is viewing the latest messages — the SDK is about to mark
2701
- // it read itself, and the count/snapshot would flash until it does. The other users' rows
2702
- // are receipt bookkeeping and keep their blanket bump.
2445
+ // The own row bumps only for a message that counts as unread and arrives outside the live
2446
+ // view (the SDK marks it read there). Other users' rows always bump: they are receipt data.
2703
2447
  const countsAsOwnUnread =
2704
2448
  !this.messagePaginator.isViewingLive &&
2705
2449
  this._countMessageAsUnread(event.message);
@@ -2707,7 +2451,7 @@ export class Channel extends ChannelApi {
2707
2451
  if (event.user?.id) {
2708
2452
  const eventUser = event.user;
2709
2453
  const eventUserId = eventUser.id;
2710
- const createdAt = new Date(event.created_at ?? Date.now());
2454
+ const createdAt = event.created_at ?? nowNs();
2711
2455
  const eventMessageId = event.message.id;
2712
2456
  const ownUserId = client.userId;
2713
2457
  this._patchReadState(
@@ -2727,7 +2471,7 @@ export class Channel extends ChannelApi {
2727
2471
  last_delivered_message_id: eventMessageId,
2728
2472
  };
2729
2473
  } else if (userId === ownUserId && !countsAsOwnUnread) {
2730
- // does not count towards the own unread count — leave the row untouched
2474
+ // Not counted as own unread: leave the row untouched.
2731
2475
  continue;
2732
2476
  } else {
2733
2477
  nextReadState[userId] = {
@@ -2738,14 +2482,12 @@ export class Channel extends ChannelApi {
2738
2482
  }
2739
2483
  }
2740
2484
 
2741
- // Seed the own row when the channel has none yet — an uninitialized channel (see
2742
- // regression #1732) or one queried with `state: false`, where `_initializeState`
2743
- // never ran to seed it. Without this the own count has nowhere to live and stops
2744
- // accumulating. `last_read` is epoch: nothing has been read, which is exactly how
2745
- // every "no last read" consumer already treats a missing value.
2485
+ // Seeds the own row when the channel has none (uninitialized, or queried with
2486
+ // `state: false` so `_initializeState` never ran): the count needs a row to live in.
2487
+ // `last_read` is the epoch: nothing has been read.
2746
2488
  if (ownUserId && countsAsOwnUnread && !currentReadState[ownUserId]) {
2747
2489
  nextReadState[ownUserId] = {
2748
- last_read: new Date(0),
2490
+ last_read: asTimestampNS(0),
2749
2491
  unread_messages: 1,
2750
2492
  user: (client.user ?? { id: ownUserId }) as UserResponse,
2751
2493
  };
@@ -2758,9 +2500,9 @@ export class Channel extends ChannelApi {
2758
2500
  }
2759
2501
 
2760
2502
  if (countsAsOwnUnread) {
2761
- this.messagePaginator.setUnreadSnapshot({
2762
- unreadCount: channelState.unreadCount,
2763
- });
2503
+ const { unreadCount } =
2504
+ this.messagePaginator.unreadStateSnapshot.getLatestValue();
2505
+ this.messagePaginator.setUnreadSnapshot({ unreadCount: unreadCount + 1 });
2764
2506
  }
2765
2507
 
2766
2508
  client.syncDeliveredCandidates([this]);
@@ -2771,27 +2513,39 @@ export class Channel extends ChannelApi {
2771
2513
  if (event.message) {
2772
2514
  this._extendEventWithOwnReactions(event);
2773
2515
  const formattedMessage = formatMessage(event.message);
2774
- if (!event.message.parent_id) {
2516
+ const { parent_id: parentId } = event.message;
2517
+ const { threads } = this.getClient();
2518
+ // to avoid double state publish
2519
+ const isAppliedByThread =
2520
+ !!parentId && threads.hasSubscriptions && !!threads.get(parentId);
2521
+ if (!isThreadOnlyReply(event.message) && !isAppliedByThread) {
2775
2522
  this.messagePaginator.ingestItem(formattedMessage);
2776
2523
  this.messagePaginator.reflectQuotedMessageUpdate(formattedMessage);
2777
- // ingestItem auto-adds on pin / auto-removes on unpin (matchesFilter { pinned: true }).
2524
+ // Added on pin, removed on unpin (`matchesFilter`).
2778
2525
  this.pinnedMessagesPaginator.ingestItem(formattedMessage);
2779
2526
  this.pinnedMessagesPaginator.reflectQuotedMessageUpdate(formattedMessage);
2527
+ } else {
2528
+ const isListedAsPinned =
2529
+ (this.pinnedMessagesPaginator.locateByItem(formattedMessage).interval
2530
+ ?.currentIndex ?? -1) > -1;
2531
+ const isPinChange = formattedMessage.pinned !== isListedAsPinned;
2532
+ if (!isAppliedByThread || isPinChange) {
2533
+ // Added on pin, removed on unpin (`matchesFilter`).
2534
+ this.pinnedMessagesPaginator.ingestItem(formattedMessage);
2535
+ }
2780
2536
  }
2781
2537
  }
2782
2538
  break;
2783
- case 'channel.truncated':
2784
- if (event.channel?.truncated_at) {
2785
- const truncatedAtDate = new Date(event.channel.truncated_at);
2786
-
2787
- this._setOwnUnreadCount(this.countUnread(truncatedAtDate));
2788
- // Partial truncation: keep messages newer than the cutoff. clearStateAndCache would wipe
2789
- // the whole paginator (readers now source from it), so use the partial truncate. The
2790
- // channel-wide read/unread context is reset by the truncation, so drop the unread snapshot
2791
- // too (clearStateAndCache did this for the full-truncate branch).
2792
- this.messagePaginator.truncate({ truncatedAt: truncatedAtDate });
2539
+ case 'channel.truncated': {
2540
+ if (event.channel) channel.data = { ...channel.data, ...event.channel };
2541
+ const truncatedAt = event.channel?.truncated_at;
2542
+ if (truncatedAt != null) {
2543
+ this._setOwnUnreadCount(this.countUnread(truncatedAt));
2544
+ // Partial truncation keeps messages newer than the cutoff, so the paginator is not wiped. It
2545
+ // resets the channel-wide read context, so the unread snapshot goes too.
2546
+ this.messagePaginator.truncate({ truncatedAt });
2793
2547
  this.messagePaginator.clearUnreadSnapshot();
2794
- this.pinnedMessagesPaginator.truncate({ truncatedAt: truncatedAtDate });
2548
+ this.pinnedMessagesPaginator.truncate({ truncatedAt });
2795
2549
  } else {
2796
2550
  this._setOwnUnreadCount(0);
2797
2551
  this.messagePaginator.clearStateAndCache();
@@ -2800,11 +2554,13 @@ export class Channel extends ChannelApi {
2800
2554
 
2801
2555
  // system messages don't increment unread counts
2802
2556
  if (event.message) {
2803
- this.messagePaginator.ingestItem(formatMessage(event.message));
2804
- this.pinnedMessagesPaginator.ingestItem(formatMessage(event.message));
2557
+ const formattedMessage = formatMessage(event.message);
2558
+ this.messagePaginator.ingestItem(formattedMessage);
2559
+ this.pinnedMessagesPaginator.ingestItem(formattedMessage);
2805
2560
  }
2806
2561
 
2807
2562
  break;
2563
+ }
2808
2564
  case 'member.added':
2809
2565
  case 'member.updated': {
2810
2566
  const memberCopy: ChannelMemberResponse = {
@@ -2824,6 +2580,7 @@ export class Channel extends ChannelApi {
2824
2580
  ...channelState.members,
2825
2581
  [memberCopy.user.id]: memberCopy,
2826
2582
  };
2583
+ channel.getClient().state.updateUserReference(memberCopy.user, channel.cid);
2827
2584
  }
2828
2585
 
2829
2586
  const currentUserId = this.getClient().userId;
@@ -2836,32 +2593,47 @@ export class Channel extends ChannelApi {
2836
2593
  }
2837
2594
  break;
2838
2595
  }
2839
- case 'member.removed':
2840
- if (event.user?.id) {
2596
+ case 'member.removed': {
2597
+ // The spec documents `event.user` as the user who removed the member, so the removed
2598
+ // user is read from `event.member` first.
2599
+ const removedUserId =
2600
+ event.member?.user?.id ?? event.member?.user_id ?? event.user?.id;
2601
+ if (removedUserId) {
2841
2602
  const newMembers = {
2842
2603
  ...channelState.members,
2843
2604
  };
2844
2605
 
2845
- delete newMembers[event.user.id];
2606
+ delete newMembers[removedUserId];
2846
2607
 
2847
2608
  channelState.members = newMembers;
2848
2609
 
2849
- // TODO?: unset membership
2610
+ if (removedUserId === this.getClient().userId) {
2611
+ channelState.membership = {} as ChannelMemberResponse;
2612
+ }
2613
+
2614
+ this._patchReadState(
2615
+ (currentReadState) => {
2616
+ if (!currentReadState[removedUserId]) return currentReadState;
2617
+ const { [removedUserId]: _removed, ...nextReadState } = currentReadState;
2618
+ return nextReadState;
2619
+ },
2620
+ { removedUserIds: [removedUserId] },
2621
+ );
2850
2622
  }
2851
2623
  break;
2624
+ }
2852
2625
  case 'notification.mark_unread': {
2853
2626
  const ownMessage = event.user?.id === this.getClient().user?.id;
2854
- if (!ownMessage || !event.user || !event.last_read_at) break;
2627
+ if (!ownMessage || !event.user || event.last_read_at == null) break;
2855
2628
  const eventUser = event.user;
2856
2629
  const lastReadAt = event.last_read_at;
2857
2630
  const unreadCount = event.unread_messages ?? 0;
2858
2631
  this._upsertReadState(
2859
2632
  eventUser.id,
2860
2633
  (currentUserReadState) => ({
2861
- // keep the message delivery info
2862
2634
  ...currentUserReadState,
2863
2635
  first_unread_message_id: event.first_unread_message_id,
2864
- last_read: new Date(lastReadAt),
2636
+ last_read: lastReadAt,
2865
2637
  last_read_message_id: event.last_read_message_id,
2866
2638
  user: eventUser,
2867
2639
  unread_messages: unreadCount,
@@ -2886,7 +2658,6 @@ export class Channel extends ChannelApi {
2886
2658
  if (isFrozenChanged) {
2887
2659
  this.query({ state: false, messages: { limit: 0 }, watchers: { limit: 0 } });
2888
2660
  }
2889
- const previousChannelData = channel.data;
2890
2661
  const newChannelData = {
2891
2662
  ...event.channel,
2892
2663
  hidden: event.channel?.hidden ?? channel.data?.hidden,
@@ -2895,70 +2666,28 @@ export class Channel extends ChannelApi {
2895
2666
  event.channel?.own_capabilities ?? channel.data?.own_capabilities,
2896
2667
  };
2897
2668
  channel.data = newChannelData;
2898
- channel.state.syncStateFromChannelData(channel.data, previousChannelData);
2899
2669
  }
2900
2670
  break;
2901
2671
  case 'reaction.new':
2902
- if (event.message && event.reaction) {
2903
- const { reaction } = event;
2904
- // Reflect main messages AND show_in_channel replies (both live in these paginators);
2905
- // pure replies are handled by the thread's own reaction subscription.
2906
- if (!event.message?.parent_id || event.message.show_in_channel) {
2907
- this.messagePaginator.reflectReaction({ message: event.message, reaction });
2908
- this.pinnedMessagesPaginator.reflectReaction({
2909
- message: event.message,
2910
- reaction,
2911
- });
2912
- }
2913
- }
2914
- break;
2915
- case 'reaction.deleted':
2916
- if (event.message && event.reaction) {
2917
- const { reaction } = event;
2918
- if (
2919
- event.message &&
2920
- (!event.message.parent_id || event.message.show_in_channel)
2921
- ) {
2922
- this.messagePaginator.reflectReaction({
2923
- message: event.message,
2924
- reaction,
2925
- removed: true,
2926
- });
2927
- this.pinnedMessagesPaginator.reflectReaction({
2928
- message: event.message,
2929
- reaction,
2930
- removed: true,
2931
- });
2932
- }
2933
- }
2934
- break;
2935
2672
  case 'reaction.updated':
2673
+ case 'reaction.deleted':
2936
2674
  if (event.message && event.reaction) {
2937
- const { reaction } = event;
2938
- // assuming reaction.updated is only called if enforce_unique is true
2939
- if (!event.message?.parent_id || event.message.show_in_channel) {
2940
- this.messagePaginator.reflectReaction({
2941
- enforceUnique: true,
2942
- message: event.message,
2943
- reaction,
2944
- });
2945
- this.pinnedMessagesPaginator.reflectReaction({
2946
- enforceUnique: true,
2947
- message: event.message,
2948
- reaction,
2949
- });
2950
- }
2675
+ reflectReactionEvent(this.getClient(), {
2676
+ // reaction.updated is only sent when enforce_unique is set
2677
+ enforceUnique: event.type === 'reaction.updated',
2678
+ message: event.message,
2679
+ reaction: event.reaction,
2680
+ removed: event.type === 'reaction.deleted',
2681
+ });
2951
2682
  }
2952
2683
  break;
2953
2684
  case 'channel.hidden': {
2954
- const previousChannelData = channel.data;
2955
2685
  channel.data = {
2956
2686
  // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2957
2687
  ...channel.data!,
2958
2688
  blocked: event.channel?.blocked ?? false,
2959
2689
  hidden: true,
2960
2690
  };
2961
- channel.state.syncStateFromChannelData(channel.data, previousChannelData);
2962
2691
  if (event.clear_history) {
2963
2692
  this.messagePaginator.clearStateAndCache();
2964
2693
  this.pinnedMessagesPaginator.clearStateAndCache();
@@ -2966,35 +2695,31 @@ export class Channel extends ChannelApi {
2966
2695
  break;
2967
2696
  }
2968
2697
  case 'channel.visible': {
2969
- const previousChannelData = channel.data;
2970
2698
  channel.data = {
2971
2699
  // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2972
2700
  ...channel.data!,
2973
2701
  blocked: event.channel?.blocked ?? false,
2974
2702
  hidden: false,
2975
2703
  };
2976
- channel.state.syncStateFromChannelData(channel.data, previousChannelData);
2977
2704
  this.getClient().offlineDb?.handleChannelVisibilityEvent({ event });
2978
2705
  break;
2979
2706
  }
2980
2707
  case 'user.banned':
2708
+ case 'user.unbanned': {
2981
2709
  if (!event.user?.id) break;
2982
- channelState.members[event.user.id] = {
2983
- ...(channelState.members[event.user.id] || {}),
2984
- shadow_banned: !!event.shadow,
2985
- banned: !event.shadow,
2986
- user: { ...(channelState.members[event.user.id]?.user || {}), ...event.user },
2987
- };
2988
- break;
2989
- case 'user.unbanned':
2990
- if (!event.user?.id) break;
2991
- channelState.members[event.user.id] = {
2992
- ...(channelState.members[event.user.id] || {}),
2993
- shadow_banned: false,
2994
- banned: false,
2995
- user: { ...(channelState.members[event.user.id]?.user || {}), ...event.user },
2710
+ const isBanned = event.type === 'user.banned';
2711
+ const member = channelState.members[event.user.id];
2712
+ channelState.members = {
2713
+ ...channelState.members,
2714
+ [event.user.id]: {
2715
+ ...(member || {}),
2716
+ shadow_banned: isBanned && !!event.shadow,
2717
+ banned: isBanned && !event.shadow,
2718
+ user: { ...(member?.user || {}), ...event.user },
2719
+ },
2996
2720
  };
2997
2721
  break;
2722
+ }
2998
2723
  default:
2999
2724
  }
3000
2725
 
@@ -3005,15 +2730,33 @@ export class Channel extends ChannelApi {
3005
2730
  }
3006
2731
  }
3007
2732
 
3008
- _callChannelListeners = (event: WSEvent) => {
3009
- const allSet = this.listeners.get('all');
3010
- const targetSet = this.listeners.get(event.type);
2733
+ _callChannelListeners = (event: Event) => {
2734
+ // Snapshot: a listener added while handling an event must not be invoked for it (`on` adds in
2735
+ // place and iterating a `Set` visits entries appended mid-iteration).
2736
+ const listeners = [
2737
+ ...(this.listeners.get('all') ?? []),
2738
+ ...(this.listeners.get(event.type) ?? []),
2739
+ ];
3011
2740
 
3012
- [allSet, targetSet].forEach((set) =>
3013
- set?.forEach((handleEvent) => handleEvent(event)),
3014
- );
2741
+ for (const listener of listeners) {
2742
+ invokeEventListener(listener, event, logger);
2743
+ }
3015
2744
  };
3016
2745
 
2746
+ /**
2747
+ * Throws if the channel has no ID (created from members only). Narrows `id` to `string`. Call it
2748
+ * before any request that uses `this.cid`: it is a string (possibly temporary) even without an ID,
2749
+ * so TypeScript does not flag a missing check.
2750
+ */
2751
+ _checkHasId(): asserts this is this & { id: string } {
2752
+ if (!this.id) {
2753
+ throw new Error(
2754
+ `Channel isn't yet created, call getOrCreateDistinctChannel() before this operation`,
2755
+ );
2756
+ }
2757
+ }
2758
+
2759
+ /** Throws unless the channel was queried or populated from the offline DB. */
3017
2760
  _checkInitialized() {
3018
2761
  if (!this.initialized && !this.offlineMode) {
3019
2762
  throw Error(
@@ -3025,30 +2768,26 @@ export class Channel extends ChannelApi {
3025
2768
  _initializeState(state: ChannelStateResponseFields) {
3026
2769
  const { state: clientState, user, userID } = this.getClient();
3027
2770
 
3028
- // add the members and users
3029
2771
  if (state.members) {
3030
2772
  this._hydrateMembers({ members: state.members });
3031
-
3032
- for (const member of state.members) {
3033
- if (member.user) {
3034
- clientState.updateUserReference(member.user, this.cid);
3035
- }
3036
- }
3037
2773
  }
3038
2774
 
3039
2775
  if (state.membership) {
3040
2776
  this.state.membership = state.membership;
2777
+ // the members page of a large channel may leave out the current user, so register them here
2778
+ if (state.membership.user) {
2779
+ clientState.updateUserReference(state.membership.user, this.cid);
2780
+ }
3041
2781
  }
3042
2782
 
3043
- // Seed the message paginator's `lastMessageAt` aggregate from the server's authoritative
3044
- // `last_message_at`. The first-page seed (Channel.query / client.hydrateActiveChannels) also
3045
- // advances it from ingested messages; both feed the same monotonic max, so this additionally
3046
- // covers the path where the paginator seed is skipped (an already-loaded channel the viewer has
3047
- // jumped away from, where re-seeding would clobber their window).
3048
- this.messagePaginator.seedLastMessageAt(state.channel?.last_message_at);
2783
+ // Each channel response's `last_message_at` replaces the queried `latestMessageAt`. Callers
2784
+ // that place a message page set it before placing it, so the paginator can tell whether
2785
+ // the page reaches the newest message; this covers the responses whose page is not placed, such
2786
+ // as a channel-list query for a channel the viewer has jumped away from.
2787
+ this.messagePaginator.setQueriedLatestMessageAt(state.channel?.last_message_at);
3049
2788
 
3050
- // Seed the pinned-messages paginator from the same response.
3051
- this.pinnedMessagesPaginator.seedFirstPageSync(
2789
+ // The pinned list's first page comes with the channel's state.
2790
+ this.pinnedMessagesPaginator.placeExternalQueryPage(
3052
2791
  (state.pinned_messages || []).map(formatMessage),
3053
2792
  this.pinnedMessagesPaginator.pageSize,
3054
2793
  );
@@ -3058,22 +2797,22 @@ export class Channel extends ChannelApi {
3058
2797
  if (state.watcher_count !== undefined) {
3059
2798
  this.state.watcher_count = state.watcher_count;
3060
2799
  }
3061
- // convert the arrays into objects for easier syncing...
3062
- if (state.watchers) {
2800
+ if (state.watchers?.length) {
2801
+ const watchers = { ...this.state.watchers };
3063
2802
  for (const watcher of state.watchers) {
3064
2803
  if (watcher) {
3065
2804
  clientState.updateUserReference(watcher, this.cid);
3066
- this.state.watchers[watcher.id] = watcher;
2805
+ watchers[watcher.id] = watcher;
3067
2806
  }
3068
2807
  }
2808
+ this.state.watchers = watchers;
3069
2809
  }
3070
2810
 
3071
- // initialize read state to last message or current time if the channel is empty
3072
- // if the user is a member, this value will be overwritten later on otherwise this ensures
3073
- // that everything up to this point is not marked as unread
2811
+ // Initialized to the latest message (or now, if empty) so nothing up to here counts as
2812
+ // unread. A member's entry is overwritten below.
3074
2813
  const readUpdates: ChannelState['read'] = {};
3075
2814
  if (userID != null) {
3076
- const last_read = this.messagePaginator.lastMessageAt || new Date();
2815
+ const last_read = this.messagePaginator.latestMessageAt ?? nowNs();
3077
2816
  if (user) {
3078
2817
  readUpdates[user.id] = {
3079
2818
  user: user as UserResponse,
@@ -3083,15 +2822,12 @@ export class Channel extends ChannelApi {
3083
2822
  }
3084
2823
  }
3085
2824
 
3086
- // apply read state if part of the state
3087
2825
  if (state.read) {
3088
2826
  for (const read of state.read) {
3089
2827
  readUpdates[read.user.id] = {
3090
- last_delivered_at: read.last_delivered_at
3091
- ? new Date(read.last_delivered_at)
3092
- : undefined,
2828
+ last_delivered_at: read.last_delivered_at ?? undefined,
3093
2829
  last_delivered_message_id: read.last_delivered_message_id,
3094
- last_read: new Date(read.last_read),
2830
+ last_read: read.last_read,
3095
2831
  last_read_message_id: read.last_read_message_id,
3096
2832
  unread_messages: read.unread_messages ?? 0,
3097
2833
  user: read.user,
@@ -3125,9 +2861,8 @@ export class Channel extends ChannelApi {
3125
2861
  if (!event.message) {
3126
2862
  return;
3127
2863
  }
3128
- // The channel message list is owned by the paginator; enrich from it. Thread-only replies are
3129
- // not in the paginator (getItem returns undefined) — the Thread object preserves their
3130
- // own_reactions on its own reply store.
2864
+ // Enriched from the paginator, which owns the channel message list. Thread-only replies are not in
2865
+ // it: the Thread object preserves their `own_reactions`.
3131
2866
  const message = this.messagePaginator.getItem(event.message.id);
3132
2867
  if (message) {
3133
2868
  event.message.own_reactions = message.own_reactions;
@@ -3139,18 +2874,16 @@ export class Channel extends ChannelApi {
3139
2874
  overrideCurrentState = true,
3140
2875
  }: {
3141
2876
  members: ChannelMemberResponse[];
3142
- /**
3143
- * If set to `true` then `ChannelState.members` will be overriden with the newly
3144
- * provided `members`, setting this property to `false` will merge current `ChannelState.members`
3145
- * object with the newly provided `members`
3146
- * (new members with the same `userId` will replace the old ones).
3147
- */
2877
+ /** `true` replaces `state.members`. `false` merges (a new member replaces one with the same ID). */
3148
2878
  overrideCurrentState?: boolean;
3149
2879
  }) {
2880
+ const clientState = this.getClient().state;
3150
2881
  const newMembersById = members.reduce<ChannelState['members']>(
3151
2882
  (membersById, member) => {
3152
2883
  if (member.user) {
3153
2884
  membersById[member.user.id] = member;
2885
+ // lets `user.updated` and `user.presence.changed` reach this member
2886
+ clientState.updateUserReference(member.user, this.cid);
3154
2887
  }
3155
2888
  return membersById;
3156
2889
  },
@@ -3159,7 +2892,7 @@ export class Channel extends ChannelApi {
3159
2892
 
3160
2893
  if (overrideCurrentState) {
3161
2894
  this.state.members = newMembersById;
3162
- } else if (!overrideCurrentState && members.length) {
2895
+ } else if (members.length) {
3163
2896
  this.state.members = {
3164
2897
  ...this.state.members,
3165
2898
  ...newMembersById,
@@ -3167,27 +2900,41 @@ export class Channel extends ChannelApi {
3167
2900
  }
3168
2901
  }
3169
2902
 
3170
- _disconnect() {
3171
- logger.withExtraTags('_disconnect', this.cid).info('Disconnecting the channel.');
2903
+ /**
2904
+ * Ends the instance for good: unsubscribes from the configuration and the server config, stops the
2905
+ * receipts tracker and the cooldown timer, disposes both paginators, then sets
2906
+ * `pendingDisposal: true` and `watchStatus: NotWatching`. It sends no request, so the server keeps a
2907
+ * watch this connection held until the connection ends. Calling it again does nothing.
2908
+ *
2909
+ * The SDK calls it when a channel ends (deleted, current user removed, logout, released as unused).
2910
+ * It does not remove the channel from the channel store. The SDK's own ends remove it; after a
2911
+ * direct call it stays until `client.channelManager.releaseUnusedChannels()`, or until `ensure()`
2912
+ * for the same cid replaces it.
2913
+ */
2914
+ disconnect() {
2915
+ // Once only: a second run would drop subscription counts other consumers hold.
2916
+ if (this.pendingDisposal) return;
2917
+ logger.withExtraTags('disconnect', this.cid).info('Disconnecting the channel.');
3172
2918
 
3173
- // Tear down the channel.state subscriptions BEFORE flipping `pendingDisposal` — that setter
3174
- // now publishes to the store, so no subscriber handler runs against a half-torn-down channel.
2919
+ // Subscriptions are released before `pendingDisposal` flips, so no handler runs on a
2920
+ // half-disconnected channel.
3175
2921
 
3176
- // Runs the `'channel'` setup function's teardown and removes this channel from the configuration
3177
- // store's subscribers. Cleared so a repeated `_disconnect` cannot double-run it.
2922
+ // Runs the `'channel'` setup function's teardown and unsubscribes from the configuration store.
3178
2923
  this.unsubscribeConfiguration?.();
3179
2924
  this.unsubscribeConfiguration = undefined;
3180
2925
  this.unsubscribeServerConfig?.();
3181
2926
  this.unsubscribeServerConfig = undefined;
3182
2927
  this.messageReceiptsTracker.unregisterSubscriptions();
3183
- // A deleted channel (or one the user was removed from) must not be re-watched — see #2599.
3184
- this.watchStatus = ChannelWatchStatus.NotWatching;
3185
- this.pendingDisposal = true;
3186
2928
  this.cooldownTimer.unregisterSubscriptions();
3187
- // Release the store-backed paginators so the message store no longer pins this removed channel
3188
- // (and its whole message graph) through its subscriber registry. The channel is being discarded
3189
- // here (pending disposal + deleted from activeChannels, never reused), mirroring Thread teardown.
2929
+ // Otherwise the message store keeps this channel and its messages alive through its subscribers.
3190
2930
  this.messagePaginator.dispose();
3191
2931
  this.pinnedMessagesPaginator.dispose();
2932
+
2933
+ // One update, last, so subscribers see both together. A deleted channel must not be re-watched.
2934
+ this._lastWatchOptions = undefined;
2935
+ this.state.partialNext({
2936
+ pendingDisposal: true,
2937
+ watchStatus: ChannelWatchStatus.NotWatching,
2938
+ });
3192
2939
  }
3193
2940
  }