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