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

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 (298) hide show
  1. package/README.md +11 -8
  2. package/dist/cjs/index.browser.js +15397 -12090
  3. package/dist/cjs/index.browser.js.map +4 -4
  4. package/dist/cjs/index.node.js +15349 -11991
  5. package/dist/cjs/index.node.js.map +4 -4
  6. package/dist/esm/index.mjs +15164 -11880
  7. package/dist/esm/index.mjs.map +4 -4
  8. package/dist/types/ChannelManager.d.ts +246 -6
  9. package/dist/types/CooldownTimer.d.ts +22 -8
  10. package/dist/types/EventHandlerPipeline.d.ts +12 -16
  11. package/dist/types/LiveLocationManager.d.ts +69 -6
  12. package/dist/types/api-client.d.ts +22 -9
  13. package/dist/types/channel.d.ts +550 -300
  14. package/dist/types/channel_state.d.ts +167 -22
  15. package/dist/types/client.d.ts +325 -305
  16. package/dist/types/configuration/ConfigController.d.ts +172 -0
  17. package/dist/types/configuration/InstanceConfigurationRegistry.d.ts +192 -0
  18. package/dist/types/configuration/index.d.ts +3 -0
  19. package/dist/types/configuration/keys.d.ts +31 -0
  20. package/dist/types/configuration/shape.d.ts +58 -0
  21. package/dist/types/configuration/types.d.ts +206 -50
  22. package/dist/types/configuration/utils/applyInstanceConfiguration.d.ts +59 -0
  23. package/dist/types/configuration/utils/copyConfigPatch.d.ts +1 -0
  24. package/dist/types/configuration/utils/declarativeSlices.d.ts +24 -0
  25. package/dist/types/configuration/utils/deepFreezeConfig.d.ts +22 -0
  26. package/dist/types/configuration/utils/index.d.ts +1 -0
  27. package/dist/types/configuration/utils/serverAuthority.d.ts +49 -0
  28. package/dist/types/connection/ConnectionIdManager.d.ts +67 -0
  29. package/dist/types/connection/ConnectionRecoveryManager.d.ts +164 -0
  30. package/dist/types/connection/index.d.ts +4 -0
  31. package/dist/types/connection/networkConnection/NetworkConnectionObserver.d.ts +153 -0
  32. package/dist/types/connection/networkConnection/index.d.ts +3 -0
  33. package/dist/types/connection/networkConnection/reporters.d.ts +43 -0
  34. package/dist/types/connection/networkConnection/types.d.ts +55 -0
  35. package/dist/types/connection/wsConnection/StableWSConnection.d.ts +204 -0
  36. package/dist/types/connection/wsConnection/WSConnection.d.ts +168 -0
  37. package/dist/types/connection/wsConnection/WSConnectionFallback.d.ts +55 -0
  38. package/dist/types/connection/wsConnection/config.d.ts +51 -0
  39. package/dist/types/connection/wsConnection/index.d.ts +4 -0
  40. package/dist/types/connection/wsConnection/types.d.ts +99 -0
  41. package/dist/types/constants.d.ts +3 -1
  42. package/dist/types/entityStore/EntityStore.d.ts +160 -40
  43. package/dist/types/entityStore/StoreBackedItemIndex.d.ts +48 -29
  44. package/dist/types/entityStore/index.d.ts +0 -1
  45. package/dist/types/errors.d.ts +24 -4
  46. package/dist/types/formatMessageMemo.d.ts +5 -0
  47. package/dist/types/gen/chat/ChannelApi.d.ts +51 -23
  48. package/dist/types/gen/chat/ChatApi.d.ts +215 -168
  49. package/dist/types/gen/models/index.d.ts +2164 -557
  50. package/dist/types/gen/models/timestamp-guard.d.ts +22 -0
  51. package/dist/types/gen/moderation/ModerationApi.d.ts +39 -32
  52. package/dist/types/gen-imports.d.ts +1 -0
  53. package/dist/types/index.d.ts +20 -7
  54. package/dist/types/languageNames.d.ts +97 -0
  55. package/dist/types/logger.d.ts +1 -1
  56. package/dist/types/messageComposer/CustomDataManager.d.ts +7 -1
  57. package/dist/types/messageComposer/LocationComposer.d.ts +10 -4
  58. package/dist/types/messageComposer/attachmentIdentity.d.ts +11 -0
  59. package/dist/types/messageComposer/attachmentManager.d.ts +48 -10
  60. package/dist/types/messageComposer/attachmentUtils.d.ts +34 -0
  61. package/dist/types/messageComposer/configuration/commands.configuration.d.ts +1 -3
  62. package/dist/types/messageComposer/configuration/configuration.d.ts +9 -1
  63. package/dist/types/messageComposer/configuration/index.d.ts +0 -1
  64. package/dist/types/messageComposer/configuration/types.d.ts +57 -1
  65. package/dist/types/messageComposer/index.d.ts +1 -0
  66. package/dist/types/messageComposer/linkPreviewsManager.d.ts +10 -4
  67. package/dist/types/messageComposer/messageComposer.d.ts +210 -14
  68. package/dist/types/messageComposer/middleware/attachmentManager/postUpload/attachmentEnrichment.d.ts +20 -1
  69. package/dist/types/messageComposer/middleware/messageComposer/attachments.d.ts +11 -0
  70. package/dist/types/messageComposer/middleware/messageComposer/types.d.ts +2 -2
  71. package/dist/types/messageComposer/middleware/pollComposer/index.d.ts +1 -0
  72. package/dist/types/messageComposer/middleware/pollComposer/state.d.ts +3 -2
  73. package/dist/types/messageComposer/middleware/pollComposer/types.d.ts +9 -2
  74. package/dist/types/messageComposer/middleware/pollComposer/validation.d.ts +44 -0
  75. package/dist/types/messageComposer/middleware/textComposer/commands.d.ts +2 -2
  76. package/dist/types/messageComposer/middleware/textComposer/mentions.d.ts +94 -229
  77. package/dist/types/messageComposer/pollComposer.d.ts +8 -3
  78. package/dist/types/messageComposer/textComposer.d.ts +9 -1
  79. package/dist/types/messageComposer/types.d.ts +7 -3
  80. package/dist/types/messageDelivery/MessageDeliveryReporter.d.ts +64 -8
  81. package/dist/types/messageDelivery/MessageReceiptsTracker.d.ts +48 -11
  82. package/dist/types/messageOperations/FailedSendCache.d.ts +34 -0
  83. package/dist/types/messageOperations/MessageOperationStatePolicy.d.ts +52 -6
  84. package/dist/types/messageOperations/MessageOperations.d.ts +94 -11
  85. package/dist/types/{entityStore → messageOperations}/applyReactionLocally.d.ts +8 -2
  86. package/dist/types/messageOperations/createMessageOperations.d.ts +11 -0
  87. package/dist/types/messageOperations/index.d.ts +7 -1
  88. package/dist/types/messageOperations/reflectReactionEvent.d.ts +24 -0
  89. package/dist/types/messageOperations/sendOrdering.d.ts +17 -0
  90. package/dist/types/messageOperations/settlePendingAttachmentUploads.d.ts +28 -0
  91. package/dist/types/messageOperations/types.d.ts +66 -1
  92. package/dist/types/middleware.d.ts +8 -0
  93. package/dist/types/moderation.d.ts +18 -4
  94. package/dist/types/notifications/NotificationManager.d.ts +43 -2
  95. package/dist/types/notifications/types.d.ts +55 -42
  96. package/dist/types/offline-support/offline_support_api.d.ts +128 -12
  97. package/dist/types/offline-support/offline_sync_manager.d.ts +26 -5
  98. package/dist/types/offline-support/queueableOperations.d.ts +106 -0
  99. package/dist/types/offline-support/types.d.ts +77 -28
  100. package/dist/types/pagination/FilterBuilder.d.ts +1 -18
  101. package/dist/types/pagination/cursorDerivation/createdAtAroundPaginationFlags.d.ts +2 -1
  102. package/dist/types/pagination/cursorDerivation/linearPaginationFlags.d.ts +21 -3
  103. package/dist/types/pagination/filterCompiler.d.ts +5 -0
  104. package/dist/types/pagination/paginators/BasePaginator.d.ts +331 -7
  105. package/dist/types/pagination/paginators/ChannelPaginator.d.ts +54 -11
  106. package/dist/types/pagination/paginators/MessageIntervalPaginator.d.ts +283 -66
  107. package/dist/types/pagination/paginators/MessagePaginator.d.ts +10 -9
  108. package/dist/types/pagination/paginators/PinnedMessagePaginator.d.ts +17 -1
  109. package/dist/types/pagination/paginators/ReminderPaginator.d.ts +8 -8
  110. package/dist/types/pagination/paginators/ThreadPaginator.d.ts +57 -0
  111. package/dist/types/pagination/paginators/index.d.ts +1 -0
  112. package/dist/types/pagination/utility.normalization.d.ts +29 -2
  113. package/dist/types/poll.d.ts +41 -14
  114. package/dist/types/poll_manager.d.ts +3 -2
  115. package/dist/types/poll_optimistic_votes.d.ts +61 -0
  116. package/dist/types/reminders/Reminder.d.ts +17 -7
  117. package/dist/types/reminders/ReminderManager.d.ts +34 -6
  118. package/dist/types/search/BaseSearchSource.d.ts +50 -25
  119. package/dist/types/search/ChannelMemberSearchSource.d.ts +11 -6
  120. package/dist/types/search/ChannelSearchSource.d.ts +27 -5
  121. package/dist/types/search/MessageSearchSource.d.ts +36 -6
  122. package/dist/types/search/SearchController.d.ts +44 -11
  123. package/dist/types/search/UserSearchSource.d.ts +11 -5
  124. package/dist/types/search/types.d.ts +14 -1
  125. package/dist/types/signing.d.ts +0 -157
  126. package/dist/types/thread.d.ts +118 -62
  127. package/dist/types/thread_manager.d.ts +124 -35
  128. package/dist/types/token_manager.d.ts +5 -8
  129. package/dist/types/types.d.ts +138 -562
  130. package/dist/types/types.utility.d.ts +8 -0
  131. package/dist/types/upload-utils.d.ts +20 -0
  132. package/dist/types/uploadManager.d.ts +50 -2
  133. package/dist/types/utils/FixedSizeQueueCache.d.ts +2 -0
  134. package/dist/types/utils/WithSubscriptions.d.ts +1 -1
  135. package/dist/types/utils/objectPath.d.ts +49 -0
  136. package/dist/types/utils/time.d.ts +85 -0
  137. package/dist/types/utils.d.ts +63 -40
  138. package/package.json +22 -33
  139. package/src/ChannelManager.ts +561 -109
  140. package/src/CooldownTimer.ts +55 -45
  141. package/src/EventHandlerPipeline.ts +13 -23
  142. package/src/LiveLocationManager.ts +191 -37
  143. package/src/api-client.ts +144 -53
  144. package/src/channel.ts +1573 -1050
  145. package/src/channel_state.ts +239 -129
  146. package/src/client.ts +843 -892
  147. package/src/client_state.ts +2 -2
  148. package/src/configuration/ConfigController.ts +298 -0
  149. package/src/configuration/InstanceConfigurationRegistry.ts +430 -0
  150. package/src/configuration/index.ts +7 -0
  151. package/src/configuration/keys.ts +86 -0
  152. package/src/configuration/shape.ts +776 -0
  153. package/src/configuration/types.ts +218 -60
  154. package/src/configuration/utils/applyInstanceConfiguration.ts +184 -0
  155. package/src/configuration/utils/copyConfigPatch.ts +61 -0
  156. package/src/configuration/utils/declarativeSlices.ts +81 -0
  157. package/src/configuration/utils/deepFreezeConfig.ts +33 -0
  158. package/src/configuration/utils/index.ts +5 -0
  159. package/src/configuration/utils/serverAuthority.ts +146 -0
  160. package/src/connection/ConnectionIdManager.ts +153 -0
  161. package/src/connection/ConnectionRecoveryManager.ts +371 -0
  162. package/src/connection/index.ts +4 -0
  163. package/src/connection/networkConnection/NetworkConnectionObserver.ts +281 -0
  164. package/src/connection/networkConnection/index.ts +3 -0
  165. package/src/connection/networkConnection/reporters.ts +85 -0
  166. package/src/connection/networkConnection/types.ts +60 -0
  167. package/src/{connection.ts → connection/wsConnection/StableWSConnection.ts} +242 -151
  168. package/src/connection/wsConnection/WSConnection.ts +345 -0
  169. package/src/connection/wsConnection/WSConnectionFallback.ts +259 -0
  170. package/src/connection/wsConnection/config.ts +108 -0
  171. package/src/connection/wsConnection/index.ts +4 -0
  172. package/src/connection/wsConnection/types.ts +101 -0
  173. package/src/constants.ts +5 -3
  174. package/src/entityStore/EntityStore.ts +350 -10
  175. package/src/entityStore/StoreBackedItemIndex.ts +66 -37
  176. package/src/entityStore/index.ts +0 -1
  177. package/src/errors.ts +40 -7
  178. package/src/formatMessageMemo.ts +23 -0
  179. package/src/gen/chat/ChannelApi.ts +230 -44
  180. package/src/gen/chat/ChatApi.ts +1047 -1745
  181. package/src/gen/models/index.ts +2378 -3721
  182. package/src/gen/models/timestamp-guard.ts +27 -0
  183. package/src/gen/moderation/ModerationApi.ts +218 -388
  184. package/src/gen-imports.ts +1 -0
  185. package/src/index.ts +82 -6
  186. package/src/languageNames.ts +103 -0
  187. package/src/logger.ts +1 -1
  188. package/src/messageComposer/CustomDataManager.ts +10 -1
  189. package/src/messageComposer/LocationComposer.ts +68 -20
  190. package/src/messageComposer/attachmentIdentity.ts +39 -0
  191. package/src/messageComposer/attachmentManager.ts +191 -68
  192. package/src/messageComposer/attachmentUtils.ts +58 -0
  193. package/src/messageComposer/configuration/commands.configuration.ts +1 -26
  194. package/src/messageComposer/configuration/configuration.ts +22 -3
  195. package/src/messageComposer/configuration/index.ts +0 -1
  196. package/src/messageComposer/configuration/types.ts +58 -1
  197. package/src/messageComposer/index.ts +1 -0
  198. package/src/messageComposer/linkPreviewsManager.ts +16 -10
  199. package/src/messageComposer/messageComposer.ts +487 -98
  200. package/src/messageComposer/middleware/attachmentManager/postUpload/AttachmentPostUploadMiddlewareExecutor.ts +1 -1
  201. package/src/messageComposer/middleware/attachmentManager/postUpload/attachmentEnrichment.ts +58 -33
  202. package/src/messageComposer/middleware/attachmentManager/postUpload/uploadErrorHandler.ts +7 -2
  203. package/src/messageComposer/middleware/attachmentManager/preUpload/blockedUploadNotification.ts +3 -2
  204. package/src/messageComposer/middleware/messageComposer/attachments.ts +98 -1
  205. package/src/messageComposer/middleware/messageComposer/linkPreviews.ts +20 -10
  206. package/src/messageComposer/middleware/messageComposer/sharedLocation.ts +7 -2
  207. package/src/messageComposer/middleware/messageComposer/types.ts +2 -7
  208. package/src/messageComposer/middleware/messageComposer/userDataInjection.ts +11 -6
  209. package/src/messageComposer/middleware/pollComposer/index.ts +1 -0
  210. package/src/messageComposer/middleware/pollComposer/state.ts +43 -11
  211. package/src/messageComposer/middleware/pollComposer/types.ts +9 -2
  212. package/src/messageComposer/middleware/pollComposer/validation.ts +76 -0
  213. package/src/messageComposer/middleware/textComposer/commandUtils.ts +3 -2
  214. package/src/messageComposer/middleware/textComposer/commands.ts +1 -2
  215. package/src/messageComposer/middleware/textComposer/mentions.ts +91 -39
  216. package/src/messageComposer/pollComposer.ts +11 -3
  217. package/src/messageComposer/textComposer.ts +36 -4
  218. package/src/messageComposer/types.ts +19 -14
  219. package/src/messageDelivery/MessageDeliveryReporter.ts +154 -53
  220. package/src/messageDelivery/MessageReceiptsTracker.ts +136 -64
  221. package/src/messageOperations/FailedSendCache.ts +90 -0
  222. package/src/messageOperations/MessageOperationStatePolicy.ts +269 -27
  223. package/src/messageOperations/MessageOperations.ts +340 -136
  224. package/src/{entityStore → messageOperations}/applyReactionLocally.ts +10 -3
  225. package/src/messageOperations/createMessageOperations.ts +192 -0
  226. package/src/messageOperations/index.ts +7 -0
  227. package/src/messageOperations/reflectReactionEvent.ts +51 -0
  228. package/src/messageOperations/sendOrdering.ts +28 -0
  229. package/src/messageOperations/settlePendingAttachmentUploads.ts +110 -0
  230. package/src/messageOperations/types.ts +74 -0
  231. package/src/middleware.ts +11 -0
  232. package/src/moderation.ts +47 -24
  233. package/src/notifications/NotificationManager.ts +73 -3
  234. package/src/notifications/configuration.ts +10 -8
  235. package/src/notifications/types.ts +58 -42
  236. package/src/offline-support/offline_support_api.ts +380 -197
  237. package/src/offline-support/offline_sync_manager.ts +105 -32
  238. package/src/offline-support/queueableOperations.ts +270 -0
  239. package/src/offline-support/types.ts +85 -39
  240. package/src/pagination/FilterBuilder.ts +1 -22
  241. package/src/pagination/cursorDerivation/createdAtAroundPaginationFlags.ts +11 -7
  242. package/src/pagination/cursorDerivation/linearPaginationFlags.ts +25 -7
  243. package/src/pagination/filterCompiler.ts +17 -0
  244. package/src/pagination/paginators/BasePaginator.ts +731 -81
  245. package/src/pagination/paginators/ChannelPaginator.ts +210 -102
  246. package/src/pagination/paginators/MessageIntervalPaginator.ts +703 -193
  247. package/src/pagination/paginators/MessagePaginator.ts +45 -36
  248. package/src/pagination/paginators/PinnedMessagePaginator.ts +74 -28
  249. package/src/pagination/paginators/ReminderPaginator.ts +15 -13
  250. package/src/pagination/paginators/ThreadPaginator.ts +181 -0
  251. package/src/pagination/paginators/UserGroupPaginator.ts +8 -1
  252. package/src/pagination/paginators/index.ts +1 -0
  253. package/src/pagination/utility.normalization.ts +37 -9
  254. package/src/poll.ts +189 -112
  255. package/src/poll_manager.ts +14 -8
  256. package/src/poll_optimistic_votes.ts +335 -0
  257. package/src/reminders/Reminder.ts +34 -16
  258. package/src/reminders/ReminderManager.ts +68 -41
  259. package/src/reminders/ReminderTimer.ts +7 -6
  260. package/src/search/BaseSearchSource.ts +133 -40
  261. package/src/search/ChannelMemberSearchSource.ts +27 -18
  262. package/src/search/ChannelSearchSource.ts +61 -7
  263. package/src/search/MessageSearchSource.ts +133 -28
  264. package/src/search/SearchController.ts +93 -16
  265. package/src/search/UserSearchSource.ts +27 -13
  266. package/src/search/types.ts +14 -1
  267. package/src/signing.ts +1 -315
  268. package/src/thread.ts +503 -511
  269. package/src/thread_manager.ts +339 -204
  270. package/src/token_manager.ts +12 -32
  271. package/src/types.ts +159 -780
  272. package/src/types.utility.ts +14 -0
  273. package/src/upload-utils.ts +53 -0
  274. package/src/uploadManager.ts +85 -7
  275. package/src/utils/FixedSizeQueueCache.ts +5 -0
  276. package/src/utils/WithSubscriptions.ts +1 -1
  277. package/src/utils/objectPath.ts +67 -0
  278. package/src/utils/time.ts +104 -0
  279. package/src/utils.ts +209 -157
  280. package/dist/types/base64.d.ts +0 -2
  281. package/dist/types/configuration/InstanceConfigurationService.d.ts +0 -26
  282. package/dist/types/connection.d.ts +0 -146
  283. package/dist/types/connection_fallback.d.ts +0 -42
  284. package/dist/types/gen/model-decoders/decoders.d.ts +0 -3
  285. package/dist/types/gen/model-decoders/event-decoder-mapping.d.ts +0 -6
  286. package/dist/types/insights.d.ts +0 -58
  287. package/dist/types/pagination/utility.queryChannel.d.ts +0 -26
  288. package/dist/types/permissions.d.ts +0 -55
  289. package/dist/types/store.d.ts +0 -125
  290. package/src/base64.ts +0 -78
  291. package/src/configuration/InstanceConfigurationService.ts +0 -73
  292. package/src/connection_fallback.ts +0 -215
  293. package/src/gen/model-decoders/decoders.ts +0 -2680
  294. package/src/gen/model-decoders/event-decoder-mapping.ts +0 -198
  295. package/src/insights.ts +0 -83
  296. package/src/pagination/utility.queryChannel.ts +0 -84
  297. package/src/permissions.ts +0 -102
  298. package/src/store.ts +0 -304
package/src/channel.ts CHANGED
@@ -1,188 +1,277 @@
1
- import type { AxiosRequestConfig } from 'axios';
2
- import { ChannelState } from './channel_state';
1
+ import { ChannelState, ChannelWatchStatus } from './channel_state';
2
+ import { isEqual } from './utils/mergeWith/mergeWithCore';
3
3
  import { CooldownTimer } from './CooldownTimer';
4
- import { isEphemeral } from './errors';
5
- import { applyReactionLocally } from './entityStore';
4
+ import { queueOrRun } from './offline-support/queueableOperations';
6
5
  import { MessageComposer } from './messageComposer';
7
6
  import { MessageReceiptsTracker } from './messageDelivery';
8
7
  import type { ReadStoreReconcileMeta } from './messageDelivery';
9
8
  import { MessagePaginator, PinnedMessagePaginator } from './pagination/paginators';
10
- import { MessageOperations } from './messageOperations';
9
+ import { createMessageOperations, reflectReactionEvent } from './messageOperations';
10
+ import type { MessageOperations } from './messageOperations';
11
+ import type { OperationRequestFn } from './messageOperations/types';
11
12
  import {
12
13
  channelHasReadEvents,
13
14
  formatMessage,
14
15
  generateChannelTempCid,
15
- localMessageToNewMessagePayload,
16
+ getMemberUserId,
17
+ invokeEventListener,
16
18
  logChatPromiseExecution,
19
+ sanitizeOutgoingAttachments,
17
20
  } from './utils';
21
+ import { asTimestampNS, msToNs, nowNs } from './utils/time';
22
+ import { normalizeUploadFile } from './upload-utils';
18
23
  import type { StreamChat } from './client';
19
24
  import { chatLoggerSystem } from './logger';
20
- import { DEFAULT_QUERY_CHANNEL_MESSAGE_LIST_PAGE_SIZE } from './constants';
25
+ import { applyInstanceConfiguration } from './configuration/utils/applyInstanceConfiguration';
26
+ import { ConfigController } from './configuration/ConfigController';
27
+ import { copyConfigPatch } from './configuration/utils/copyConfigPatch';
28
+ import { deepFreezeConfig } from './configuration/utils/deepFreezeConfig';
29
+ import { mergeServerRestrictions } from './configuration/utils/serverAuthority';
30
+ import type { ServerRestrictions } from './configuration/utils/serverAuthority';
31
+ import type { ChannelDeclarativeConfig } from './configuration/types';
32
+ import {
33
+ mergeDeclarativeMessageOperationsConfig,
34
+ mergeDeclarativePaginatorConfig,
35
+ toDeclarativePaginatorConfig,
36
+ } from './configuration/utils/declarativeSlices';
21
37
  import type {
22
38
  AIState,
23
- APIResponse,
24
39
  BanUserOptions,
25
- ChannelData,
26
40
  ChannelGetOrCreateRequest,
41
+ ChannelInput,
27
42
  ChannelMemberResponse,
28
43
  ChannelResponse,
29
44
  ChannelStateResponseFields,
30
45
  ChannelUpdateOptions,
31
- CreateDraftResponse,
32
- DeleteMessageOptions,
46
+ Command,
33
47
  Event,
34
- EventAPIResponse,
35
48
  EventHandler,
36
49
  EventPayload,
37
50
  EventType,
38
- GetRepliesAPIResponse,
39
- GetRepliesRequest,
51
+ FileUploadInput,
40
52
  LocalMessage,
41
53
  MarkReadRequest,
42
- MarkUnreadRequest,
43
- MessagePaginationOptions,
54
+ MarkReadResponse,
55
+ MessagePaginationParams,
44
56
  MessageRequest,
45
57
  MessageResponse,
46
58
  MessageSetType,
47
- PinnedMessagePaginationOptions,
48
- PinnedMessagesSort,
49
59
  QueryMembersPayload,
50
- ReactionAPIResponse,
51
- ReactionRequest,
52
- SearchPayload,
53
- SendMessageOptions,
54
- SendReactionRequest,
55
60
  SharedLocation,
61
+ StreamRequestOptions,
62
+ StreamResponse,
63
+ TimestampNS,
56
64
  UnBanUserOptions,
57
65
  UpdateChannelPartialRequest,
58
66
  UpdateLiveLocationRequest,
59
- UpdateMessageOptions,
60
67
  UserResponse,
61
68
  } from './types';
62
- import type { RoleName } from './permissions';
63
- import { StateStore } from './store';
69
+ import { AIStates } from './types';
70
+ import type { StateStore } from '@stream-io/state-store';
71
+ import type { Unsubscribe } from '@stream-io/state-store';
64
72
  import type {
65
73
  ChannelMemberRequest as Gen_ChannelMemberRequest,
66
74
  ChannelPushPreferencesResponse as Gen_ChannelPushPreferencesResponse,
67
- ChannelStopWatchingRequest as Gen_ChannelStopWatchingRequest,
68
- CreateDraftRequest as Gen_CreateDraftRequest,
69
- HideChannelRequest as Gen_HideChannelRequest,
70
75
  MuteChannelRequest as Gen_MuteChannelRequest,
71
- SendMessageRequest as Gen_SendMessageRequest,
72
- ShowChannelRequest as Gen_ShowChannelRequest,
73
76
  UnmuteChannelRequest as Gen_UnmuteChannelRequest,
74
- UpdateChannelRequest as Gen_UpdateChannelRequest,
77
+ UploadChannelFileRequest,
78
+ UploadChannelRequest,
75
79
  WSEvent,
76
80
  } from './gen/models';
77
81
  import type { ChatApi } from './gen/chat/ChatApi';
78
82
  import { ChannelApi } from './gen/chat/ChannelApi';
79
83
 
80
84
  const logger = chatLoggerSystem.getLogger('channel');
81
- const offlineDbLogger = chatLoggerSystem.getLogger('offline-db');
82
-
83
- // todo: move to dedicated file
84
- export type SendMessageWithStateUpdateParams = {
85
- localMessage: LocalMessage;
86
- message?: MessageRequest;
87
- options?: SendMessageOptions;
88
- /**
89
- * Per-call override for the send/retry request (advanced).
90
- * If set, it takes precedence over channel instance configuration handlers.
91
- */
92
- sendMessageRequestFn?: CustomSendMessageRequestFn;
93
- };
94
-
95
- export type RetrySendMessageWithLocalUpdateParams = Omit<
96
- SendMessageWithStateUpdateParams,
97
- 'message'
98
- >;
99
-
100
- export type UpdateMessageWithStateUpdateParams = {
101
- localMessage: LocalMessage;
102
- options?: UpdateMessageOptions;
103
- /**
104
- * Per-call override for the update request (advanced).
105
- * If set, it takes precedence over channel instance configuration handlers.
106
- */
107
- updateMessageRequestFn?: CustomUpdateMessageRequestFn;
108
- };
109
-
110
- export type DeleteMessageWithStateUpdateParams = {
111
- localMessage: LocalMessage;
112
- options?: DeleteMessageOptions;
113
- /**
114
- * Per-call override for the delete request (advanced).
115
- * If set, it takes precedence over channel instance configuration handlers.
116
- */
117
- deleteMessageRequestFn?: CustomDeleteMessageRequestFn;
118
- };
119
-
120
- // Custom request function types for configuration
121
- export type CustomSendMessageRequestFn = (
122
- params: Omit<SendMessageWithStateUpdateParams, 'sendMessageRequestFn'>,
123
- ) => Promise<{ message: MessageResponse }>;
124
85
 
125
- export type CustomUpdateMessageRequestFn = (
126
- params: Omit<UpdateMessageWithStateUpdateParams, 'updateMessageRequestFn'>,
127
- ) => Promise<{ message: MessageResponse }>;
128
-
129
- export type CustomDeleteMessageRequestFn = (
130
- params: Omit<DeleteMessageWithStateUpdateParams, 'deleteMessageRequestFn'>,
131
- ) => Promise<{ message: MessageResponse }>;
86
+ /**
87
+ * The message-operation vocabulary, re-exported so it has a public path: `src/messageOperations` is
88
+ * not part of the root barrel, while `src/index.ts` re-exports this module wholesale.
89
+ *
90
+ * `OperationParams<K>` and `OperationRequestFn<K>` are the one spelling for every operation's
91
+ * parameters and request function — both derived from `MessageOperationSpec`, so adding an operation
92
+ * kind extends them rather than needing a new hand-written pair.
93
+ */
94
+ export type {
95
+ DefaultOperationRequest,
96
+ MessageOperationSpec,
97
+ OperationKind,
98
+ OperationParams,
99
+ OperationRequestFn,
100
+ OperationResponse,
101
+ } from './messageOperations/types';
132
102
 
133
103
  export type CustomMarkReadRequestFn = (params: {
134
104
  channel: Channel;
135
105
  options?: MarkReadRequest;
136
- }) => Promise<EventAPIResponse | null>;
106
+ }) => Promise<Partial<StreamResponse<MarkReadResponse>> | null>;
137
107
 
138
- export type ChannelInstanceConfig = {
108
+ /**
109
+ * A channel's **resolved** configuration — what {@link Channel.config} returns.
110
+ *
111
+ * Not `ChannelConfigWithInfo`, which is the generated type for the channel *type's server*
112
+ * configuration behind {@link Channel.serverConfig}. The two are related: the gates below are the
113
+ * server's flags already ANDed with what the integrator registered.
114
+ */
115
+ export type ChannelConfig = {
139
116
  requestHandlers?: {
140
- deleteMessageRequest?: CustomDeleteMessageRequestFn;
117
+ deleteMessageRequest?: OperationRequestFn<'delete'>;
141
118
  markReadRequest?: CustomMarkReadRequestFn;
142
- sendMessageRequest?: CustomSendMessageRequestFn;
143
- retrySendMessageRequest?: CustomSendMessageRequestFn;
144
- updateMessageRequest?: CustomUpdateMessageRequestFn;
119
+ sendMessageRequest?: OperationRequestFn<'send'>;
120
+ retrySendMessageRequest?: OperationRequestFn<'retry'>;
121
+ updateMessageRequest?: OperationRequestFn<'update'>;
145
122
  };
123
+ /**
124
+ * Typing indicators for this channel (defaults to enabled). ANDed with the channel type's
125
+ * `typing_events`, so either side can switch them off and neither can widen.
126
+ *
127
+ * This is the channel-wide gate, read by {@link Channel.keystroke} and {@link Channel.stopTyping}.
128
+ * `messageComposer.text.publishTypingEvents` sits on top of it as a per-composer refinement — a thread
129
+ * composer can stay quiet while the channel still permits typing events.
130
+ */
131
+ typingEvents: { enabled: boolean };
132
+ /**
133
+ * Read receipts for this channel. `enabled` (defaults to true) is ANDed with the channel type's
134
+ * `read_events`, so either side can switch them off and neither can widen. Read by
135
+ * {@link Channel.markRead} and {@link Channel.markUnread}.
136
+ *
137
+ * `localUnreadCountEnabled` (defaults to false) applies only once `enabled` is false: the channel
138
+ * keeps counting unread messages for this user and {@link Channel.markReadLocally} resets that
139
+ * count, with nothing sent to the server. It is deliberately outside the server's authority -
140
+ * counting locally is what an integrator does *because* the server declines to.
141
+ */
142
+ readEvents: { enabled: boolean; localUnreadCountEnabled: boolean };
143
+ /**
144
+ * Threaded replies for this channel (defaults to enabled). ANDed with the channel type's `replies`.
145
+ */
146
+ replies: { enabled: boolean };
147
+ /**
148
+ * Message reminders — "remind me" and "save for later" (defaults to enabled). ANDed with the channel
149
+ * type's `user_message_reminders`.
150
+ */
151
+ userMessageReminders: { enabled: boolean };
152
+ /**
153
+ * Delivery receipts (defaults to enabled). ANDed with the channel type's `delivery_events`.
154
+ */
155
+ deliveryEvents: { enabled: boolean };
156
+ /**
157
+ * The slash commands this channel type offers, as the server reports them.
158
+ *
159
+ * Named for availability rather than enablement on purpose: whether any given command can be *used*
160
+ * right now is `messageComposer.isCommandDisabled(command)`, which depends on the message context —
161
+ * editing and quoting disable different ones. A list called `enabledCommands` would routinely contain
162
+ * disabled entries.
163
+ *
164
+ * **Server-owned, and the one field here the integrator cannot set.** It is a list rather than a gate,
165
+ * so there is nothing to AND and no intent to express — the server's answer simply *is* the value, and
166
+ * it is absent from the declarative tree for that reason.
167
+ *
168
+ * It lives on the resolved configuration anyway so that consumers never need a second place to look:
169
+ * every question about what this channel permits is answered by `config`. Reading the raw
170
+ * {@link Channel.serverConfig} instead is what made a UI show features the client had disabled — the
171
+ * gates below have a client half, and mixing the two sources meant sometimes reading only one.
172
+ */
173
+ availableCommands: Command[];
174
+ };
175
+
176
+ /**
177
+ * Frozen for the same reason every other default config constant is: resolution spreads over it, so a
178
+ * subtree no layer touches stays identical by reference and would otherwise be mutable through the
179
+ * public `channel.config`. See `deepFreezeConfig`.
180
+ */
181
+ /**
182
+ * The fields of the declarative `channel` slice that a channel resolves for **itself**.
183
+ *
184
+ * The slice also carries `messagePaginator`, `pinnedMessagesPaginator` and `messageOperations`, which are
185
+ * handed to those objects directly (see {@link Channel.initializeConfig}). Passing the whole slice to the
186
+ * controller published them on `channel.config` as well, where nothing read them: `ChannelConfig` does not
187
+ * declare them, and a registration against one of them notified every `configState` subscriber for a change
188
+ * that did not concern the channel.
189
+ */
190
+ const ownDeclarativeConfig = (
191
+ slice?: ChannelDeclarativeConfig,
192
+ ): Partial<ChannelConfig> | undefined => {
193
+ if (!slice) return undefined;
194
+
195
+ const {
196
+ deliveryEvents,
197
+ readEvents,
198
+ replies,
199
+ requestHandlers,
200
+ typingEvents,
201
+ userMessageReminders,
202
+ } = slice;
203
+
204
+ return {
205
+ deliveryEvents,
206
+ readEvents,
207
+ replies,
208
+ requestHandlers,
209
+ typingEvents,
210
+ userMessageReminders,
211
+ } as Partial<ChannelConfig>;
146
212
  };
147
213
 
214
+ export const DEFAULT_CHANNEL_CONFIG: ChannelConfig = deepFreezeConfig({
215
+ availableCommands: [],
216
+ deliveryEvents: { enabled: true },
217
+ readEvents: { enabled: true, localUnreadCountEnabled: false },
218
+ replies: { enabled: true },
219
+ typingEvents: { enabled: true },
220
+ userMessageReminders: { enabled: true },
221
+ });
222
+
148
223
  /**
149
224
  * The Channel class manages its own state.
150
225
  */
151
226
  export class Channel extends ChannelApi {
152
227
  _client: StreamChat;
153
- data: Partial<ChannelResponse> | undefined;
154
- _data: ChannelData;
228
+ _data: ChannelInput;
155
229
  cid: string;
156
230
  /** */
157
231
  listeners: Map<EventType, Set<EventHandler>>;
158
232
  state: ChannelState;
159
- /**
160
- * This boolean is a vague indication of whether the channel exists on chat backend.
161
- *
162
- * If the value is true, then that means the channel has been initialized by either calling
163
- * channel.create() or channel.query() or channel.watch().
164
- *
165
- * If the value is false, then channel may or may not exist on the backend. The only way to ensure
166
- * is by calling channel.create() or channel.query() or channel.watch().
167
- */
168
- initialized: boolean;
169
- /**
170
- * Indicates whether channel has been initialized by manually populating the state with some messages, members etc.
171
- * Static state indicates that channel exists on backend, but is not being watched yet.
172
- */
173
- offlineMode: boolean;
174
233
  lastKeyStroke?: Date;
175
234
  lastTypingEvent: Date | null;
176
235
  isTyping: boolean;
177
- disconnected: boolean;
236
+ /** Re-entrancy guard for {@link Channel.reload} (mirrors Thread.reload's isLoading guard). */
237
+ private _reloading = false;
238
+ /** Refcount backing the reactive `active` flag (a shared Channel instance can have several consumers). */
239
+ private _activeRefCount = 0;
240
+ private _channelQueriesInFlight = 0;
241
+ /**
242
+ * The watch {@link Channel.ensureWatched} started and is still waiting for the response, with its
243
+ * options. Later `ensureWatched()` calls with the same options wait for it instead of sending
244
+ * another request; `watch()` calls are not recorded here.
245
+ */
246
+ private _ensureWatchedInFlight?: {
247
+ options: ChannelGetOrCreateRequest;
248
+ promise: Promise<unknown>;
249
+ };
178
250
  push_preferences?: Gen_ChannelPushPreferencesResponse;
179
- public readonly configState = new StateStore<ChannelInstanceConfig>({});
251
+ /**
252
+ * The shared configuration machinery. Owned rather than inherited — `Channel` already extends
253
+ * `ChannelApi`, so single inheritance is spent.
254
+ *
255
+ * `mergeSlice: 'deep'` because the config has nested groups: registering `typingEvents.enabled` must
256
+ * not drop `readEvents`. `applyAuthority` is what makes `channel.config` the *whole* answer rather
257
+ * than the client's half — see {@link serverRestrictions}.
258
+ */
259
+ private readonly configController: ConfigController<ChannelConfig>;
180
260
  public readonly messageComposer: MessageComposer;
181
261
  public readonly messageReceiptsTracker: MessageReceiptsTracker;
262
+ public readonly messageOperations: MessageOperations;
182
263
  public readonly messagePaginator: MessagePaginator;
183
264
  public readonly pinnedMessagesPaginator: PinnedMessagePaginator;
184
- public readonly messageOperations: MessageOperations;
185
265
  public readonly cooldownTimer: CooldownTimer;
266
+ /**
267
+ * Teardown for this channel's configuration subscription, released by {@link disconnect}. Left
268
+ * subscribed, a disconnected channel would stay in the configuration store's handler set for good.
269
+ */
270
+ private unsubscribeConfiguration?: Unsubscribe;
271
+ /** Teardown for the server-config re-derivation subscription, released by {@link disconnect}. */
272
+ private unsubscribeServerConfig?: Unsubscribe;
273
+ /** The declarative slice last derived from, so a late server answer can re-derive from the same one. */
274
+ private declarativeConfig?: Partial<ChannelConfig>;
186
275
 
187
276
  /**
188
277
  * Creates a `Channel` instance bound to the given chat client.
@@ -197,7 +286,7 @@ export class Channel extends ChannelApi {
197
286
  client: StreamChat,
198
287
  type: string,
199
288
  id: string | undefined,
200
- data: ChannelData,
289
+ data: ChannelInput,
201
290
  ) {
202
291
  const validTypeRe = /^[\w_-]+$/;
203
292
  const validIDRe = /^[\w!_-]+$/;
@@ -212,20 +301,34 @@ export class Channel extends ChannelApi {
212
301
  super(client, type, id);
213
302
 
214
303
  this._client = client;
215
- // used by the frontend, gets updated:
216
- this.data = data as Partial<ChannelResponse>;
217
304
  // this._data is used for the requests...
218
305
  this._data = { ...data };
219
- this.cid = `${type}:${id}`;
306
+ // A channel created from members has no id until the server answers; until then its cid is the
307
+ // temporary one built from the members, the key it is stored under (`ensure({ members })`).
308
+ this.cid =
309
+ (!id && generateChannelTempCid(type, (data.members ?? []).map(getMemberUserId))) ||
310
+ `${type}:${id}`;
220
311
  this.listeners = new Map();
221
312
  // perhaps the state variable should be private
222
313
  this.state = new ChannelState(this);
223
- this.initialized = false;
224
- this.offlineMode = false;
314
+ // after the state exists: the `data` setter writes to it
315
+ this.data = data as Partial<ChannelResponse>;
225
316
  this.lastTypingEvent = null;
226
317
  this.isTyping = false;
227
- this.disconnected = false;
228
318
 
319
+ // Read the declarative configuration *now*, so it can go into the sub-objects as constructor
320
+ // options. Some of their fields are read once during construction (`unreadReferencePolicy`, the
321
+ // initial cursor/offset), so configuring them afterwards would silently do nothing.
322
+ const declarativeConfig = client.config.getConfig('channel') ?? undefined;
323
+ // The general `messagePaginator` key applies to every MessagePaginator — this channel's list and
324
+ // every thread's replies. The per-parent slice below overrides it.
325
+ const messagePaginatorConfig = mergeDeclarativePaginatorConfig(
326
+ client.config.getConfig('messagePaginator') ?? undefined,
327
+ declarativeConfig?.messagePaginator,
328
+ );
329
+
330
+ // The composer reads its own key (`messageComposer`) from the client, so nothing is passed here —
331
+ // composer configuration is deliberately not nested under `channel`.
229
332
  this.messageComposer = new MessageComposer({
230
333
  client: this._client,
231
334
  compositionContext: this,
@@ -234,346 +337,320 @@ export class Channel extends ChannelApi {
234
337
  // Created before MessageReceiptsTracker and CooldownTimer: both read the message paginator
235
338
  // (receipts resolve read cursors via findItemByTimestamp; CooldownTimer.refresh reads the
236
339
  // latest window at construction).
237
- this.messagePaginator = new MessagePaginator({ channel: this });
238
- this.pinnedMessagesPaginator = new PinnedMessagePaginator({ channel: this });
340
+ this.messagePaginator = new MessagePaginator({
341
+ channel: this,
342
+ // Split: the policy is a constructor argument, the rest is configuration. Passing the whole slice
343
+ // put a non-config key into the paginator's published `config` — see `toDeclarativePaginatorConfig`.
344
+ unreadReferencePolicy: messagePaginatorConfig?.unreadReferencePolicy,
345
+ paginatorOptions: {
346
+ declarativeConfig: toDeclarativePaginatorConfig(messagePaginatorConfig),
347
+ },
348
+ });
349
+ this.pinnedMessagesPaginator = new PinnedMessagePaginator({
350
+ channel: this,
351
+ paginatorOptions: { declarativeConfig: declarativeConfig?.pinnedMessagesPaginator },
352
+ });
239
353
 
240
354
  this.messageReceiptsTracker = new MessageReceiptsTracker({ channel: this });
241
355
  this.messageReceiptsTracker.registerSubscriptions();
242
356
 
243
357
  this.cooldownTimer = new CooldownTimer({ channel: this });
358
+ this.cooldownTimer.registerSubscriptions();
359
+
360
+ this.messageOperations = createMessageOperations(this);
361
+
362
+ // Seed the reactive mute state from the client's current `mutedChannels` (a channel created
363
+ // after connect may already be muted). Kept in sync afterwards by the client fan-out on
364
+ // `notification.channel_mutes_updated` / `health.check`.
365
+ this._syncMuteStatus();
366
+
367
+ this.configController = new ConfigController<ChannelConfig>({
368
+ defaults: DEFAULT_CHANNEL_CONFIG,
369
+ initialSlice: ownDeclarativeConfig(declarativeConfig),
370
+ // Nested groups: naming `typingEvents.enabled` must not drop `readEvents`.
371
+ mergeSlice: 'deep',
372
+ // Frozen so a nested write throws instead of changing state silently. Freezing
373
+ // DEFAULT_CHANNEL_CONFIG is not enough on its own: resolution rebuilds the gate subtrees every
374
+ // time, so the resolved config holds new unfrozen objects rather than the frozen defaults.
375
+ //
376
+ // Copied first, because a subtree of the resolved object and the matching subtree of the slice
377
+ // stored in `client.config` can be the same object — so freezing one freezes the other, and the
378
+ // paginators that resolve from that slice could no longer merge into it.
379
+ applyAuthority: (requested) =>
380
+ deepFreezeConfig(
381
+ copyConfigPatch({
382
+ ...(mergeServerRestrictions(
383
+ requested,
384
+ this.serverRestrictions,
385
+ ) as ChannelConfig),
386
+ // Assigned rather than merged: the deep merge would concatenate the two lists, and the
387
+ // server owns this one outright.
388
+ availableCommands: this.serverConfig?.commands ?? [],
389
+ }),
390
+ ) as ChannelConfig,
391
+ });
244
392
 
245
- this.messageOperations = new MessageOperations({
246
- ingest: (m) => {
247
- this.messagePaginator.ingestItem(m);
248
- this.getClient().messageStore.flushSubscribers(m.id);
249
- },
250
- get: (id) => this.messagePaginator.getItem(id),
251
- handlers: () => {
252
- const { requestHandlers } = this.configState.getLatestValue();
253
- const deleteMessageRequest = requestHandlers?.deleteMessageRequest;
254
- const sendMessageRequest = requestHandlers?.sendMessageRequest;
255
- const retrySendMessageRequest = requestHandlers?.retrySendMessageRequest;
256
- const updateMessageRequest = requestHandlers?.updateMessageRequest;
257
- return {
258
- delete: deleteMessageRequest
259
- ? (p) =>
260
- deleteMessageRequest({
261
- localMessage: p.localMessage,
262
- options: p.options,
263
- })
264
- : undefined,
265
- send: sendMessageRequest
266
- ? (p) =>
267
- sendMessageRequest({
268
- localMessage: p.localMessage,
269
- message: p.message,
270
- options: p.options,
271
- })
272
- : undefined,
273
- retry: retrySendMessageRequest
274
- ? (p) =>
275
- retrySendMessageRequest({
276
- localMessage: p.localMessage,
277
- message: p.message,
278
- options: p.options,
279
- })
280
- : undefined,
281
- update: updateMessageRequest
282
- ? (p) =>
283
- updateMessageRequest({
284
- localMessage: p.localMessage,
285
- options: p.options,
286
- })
287
- : undefined,
288
- };
289
- },
290
- defaults: {
291
- delete: async (id, o) => {
292
- const result = await this.getClient().deleteMessage({ id, ...o });
293
- return { message: result.message };
294
- },
295
- send: async (m, o) => {
296
- const result = await this.sendMessage({ message: m, ...o });
297
- return { message: result.message };
298
- },
299
- update: async (m, o) => {
300
- const result = await this.getClient().updateMessage({
301
- id: m.id,
302
- message: localMessageToNewMessagePayload(m),
303
- ...o,
304
- });
305
- return { message: result.message };
306
- },
307
- },
393
+ // The server's answer usually arrives *after* construction — a channel built before it has been
394
+ // queried or watched reads `serverConfig` as undefined, so the restrictions state nothing and the
395
+ // defaults stand. Re-derive when this channel's config lands, or an app that disables `read_events`
396
+ // server-side would keep a channel that believes read receipts are on.
397
+ //
398
+ // Selected by cid, and `this.cid` is read at selection time rather than captured: a channel created
399
+ // from members alone starts on a temporary cid and adopts the server's in `query()`, which assigns
400
+ // it *before* calling `_addChannelConfig`, so the write that carries the config is already selecting
401
+ // under the real key.
402
+ this.unsubscribeServerConfig = client.channelServerConfigsStore.subscribeWithSelector(
403
+ ({ configs }) => ({ channelConfig: configs[this.cid] }),
404
+ () => this.configController.rederive(this.declarativeConfig),
405
+ );
406
+
407
+ // Share one derivation path with `config.reset()`, so the two cannot drift. Idempotent: the
408
+ // sub-objects were already configured through their constructors above; this re-applies the
409
+ // mutable half through the same code a reset uses.
410
+ this.initializeConfig(declarativeConfig);
411
+
412
+ // Last statement of the constructor: every sub-object a setup function might reach now exists.
413
+ // A throwing setup function is contained by the helper, so it cannot break
414
+ // `client.channelManager.ensure()`.
415
+ this.unsubscribeConfiguration = applyInstanceConfiguration({
416
+ args: { channel: this },
417
+ config: client.config,
418
+ key: 'channel',
419
+ applyConfig: (config) => this.initializeConfig(config),
420
+ // Reads the slice *fresh* rather than replaying a remembered one: by the time reset calls this,
421
+ // the declarative store has been cleared, so this correctly derives the un-configured baseline.
422
+ reinitializeConfig: () =>
423
+ this.initializeConfig(client.config.getConfig('channel') ?? undefined),
424
+ // This channel's message paginator also derives from the shared `messagePaginator` key, so a
425
+ // change there has to run the full cycle — declarative then setup function — rather than a bare
426
+ // re-derivation, which would drop the setup function's overrides.
427
+ alsoWatch: ['messagePaginator', 'messageOperations'],
308
428
  });
309
429
  }
310
430
 
311
431
  /**
312
- * Returns the chat client for this channel. Throws if `client.disconnect()` was called.
432
+ * The configuration fields this channel's *type* decides server-side.
313
433
  *
314
- * @returns The chat client.
434
+ * Both are boolean gates, so `mergeServerRestrictions` ANDs them with what was requested: either the
435
+ * server or the integrator may switch a feature off, and neither can widen. Re-read on every
436
+ * derivation rather than captured, so a flag that changes mid-session is picked up.
315
437
  */
316
- getClient(): StreamChat {
317
- if (this.disconnected === true) {
318
- throw Error(`You can't use a channel after client.disconnect() was called`);
319
- }
320
- return this._client;
438
+ private get serverRestrictions(): ServerRestrictions<ChannelConfig> {
439
+ const channelConfig = this.serverConfig;
440
+
441
+ return {
442
+ deliveryEvents: { enabled: channelConfig?.delivery_events },
443
+ readEvents: { enabled: channelConfig?.read_events },
444
+ replies: { enabled: channelConfig?.replies },
445
+ typingEvents: { enabled: channelConfig?.typing_events },
446
+ userMessageReminders: { enabled: channelConfig?.user_message_reminders },
447
+ };
321
448
  }
322
449
 
323
450
  /**
324
- * Returns the config for this channel ID (CID).
325
- *
326
- * @returns The channel config.
327
- */
328
- getConfig() {
329
- const client = this.getClient();
330
- return client.configs[this.cid];
331
- }
451
+ * Derives this channel's configuration — and its sub-objects' — from the declarative slice.
452
+ *
453
+ * Called by the constructor and by `client.config.reset()`. The channel owns only its own
454
+ * `requestHandlers`; each sub-object derives its own configuration, so the knowledge of what
455
+ * `messagePaginator.pageSize` means stays inside the paginator.
456
+ */
457
+ initializeConfig(declarativeConfig?: ChannelDeclarativeConfig): void {
458
+ // Remembered so the server-config subscription can re-derive from the same slice without being
459
+ // handed it again — the server's answer arrives on its own schedule, not the tree's.
460
+ this.declarativeConfig = declarativeConfig as Partial<ChannelConfig> | undefined;
461
+
462
+ // A derivation, so it *replaces*: a handler dropped from the declarative tree has to disappear.
463
+ // Anything else writing directly into `configState.requestHandlers` — the React SDK's
464
+ // per-component props do — has to re-apply afterwards; see the note in `useChannelRequestHandlers`.
465
+ //
466
+ // The no-op guard that used to live here is now the controller's: it skips the publish when the
467
+ // resolved value is deep-equal to the last one, which matters because this runs on every
468
+ // `alsoWatch` key change too (a `messagePaginator` or `messageOperations` registration re-runs the
469
+ // whole `channel` cycle), so the no-op publishes outnumber the real ones.
470
+ this.configController.initialize(ownDeclarativeConfig(declarativeConfig));
471
+
472
+ // The shared `messagePaginator` key applies to every MessagePaginator — this channel's list and
473
+ // every thread's replies — and the per-parent slice overrides it.
474
+ this.messagePaginator.initializeConfig(
475
+ toDeclarativePaginatorConfig(
476
+ mergeDeclarativePaginatorConfig(
477
+ this.getClient().config.getConfig('messagePaginator') ?? undefined,
478
+ declarativeConfig?.messagePaginator,
479
+ ),
480
+ ),
481
+ );
482
+ // Single parent, so it stays nested and takes no share of the shared key.
483
+ this.pinnedMessagesPaginator.initializeConfig(
484
+ declarativeConfig?.pinnedMessagesPaginator,
485
+ );
332
486
 
333
- _sendMessage(request: Gen_SendMessageRequest) {
334
- return super.sendMessage(request);
487
+ // `MessageOperations` backs both channel and thread sends, so it has a shared top-level key with a
488
+ // per-parent override — the same shape as `messagePaginator`. Defaults are spread first so a field
489
+ // dropped from the declarative tree returns to its default rather than lingering.
490
+ this.messageOperations.initializeConfig(
491
+ mergeDeclarativeMessageOperationsConfig(
492
+ this.getClient().config.getConfig('messageOperations') ?? undefined,
493
+ declarativeConfig?.messageOperations,
494
+ ),
495
+ );
335
496
  }
336
497
 
337
498
  /**
338
- * Sends a message to this channel.
499
+ * Returns the chat client for this channel. Throws if the channel is pending disposal — see
500
+ * {@link Channel.pendingDisposal}.
339
501
  *
340
- * @param request - The send message request payload, including the message body and optional flags
341
- * such as `skip_enrich_url`, `skip_push`, and `keep_channel_hidden`.
342
- * @returns The server response.
502
+ * @returns The chat client.
343
503
  */
344
- override async sendMessage(request: Gen_SendMessageRequest) {
345
- try {
346
- const offlineDb = this.getClient().offlineDb;
347
- const messageId = request.message?.id;
348
- if (offlineDb && messageId) {
349
- return await offlineDb.queueTask<Awaited<ReturnType<ChatApi['sendMessage']>>>({
350
- task: {
351
- channelId: this.id as string,
352
- channelType: this.type,
353
- messageId,
354
- payload: [request],
355
- type: 'send-message',
356
- },
357
- });
358
- }
359
- } catch (error) {
360
- offlineDbLogger
361
- .withExtraTags('sendMessage', this.cid)
362
- .error('Sending the message failed.', { error });
363
- }
364
- return await this._sendMessage(request);
504
+ getClient(): StreamChat {
505
+ if (this.pendingDisposal) throw this.disposedError();
506
+ return this._client;
365
507
  }
366
508
 
367
- /**
368
- * Sends a message with optimistic local state update.
369
- */
370
- async sendMessageWithLocalUpdate(
371
- params: SendMessageWithStateUpdateParams,
372
- ): Promise<void> {
373
- await this.messageOperations.send(
374
- {
375
- localMessage: params.localMessage,
376
- message: params.message,
377
- options: params.options,
378
- },
379
- params.sendMessageRequestFn,
509
+ /** What a call on a disposed instance fails with: it is done for good, and how to get a live one. */
510
+ private disposedError() {
511
+ return new Error(
512
+ `Channel ${this.cid} is pending disposal and cannot be used. Get a fresh instance via client.channelManager.ensure().`,
380
513
  );
381
- if (this.messageComposer.config.text.publishTypingEvents) await this.stopTyping();
382
514
  }
383
515
 
384
516
  /**
385
- * Retry sending a failed message.
517
+ * Resolved configuration, as a store. Delegates rather than holding a copy, so the field and the
518
+ * controller's store cannot drift.
519
+ *
520
+ * Still directly writable, and deliberately so: the React SDK installs per-component request handlers
521
+ * by calling `partialNext({ requestHandlers })` on it. That write bypasses the controller, which is
522
+ * why `requestHandlers` is the one field a re-derivation replaces wholesale — see
523
+ * {@link initializeConfig}.
386
524
  */
387
- async retrySendMessageWithLocalUpdate(
388
- params: Omit<SendMessageWithStateUpdateParams, 'message'>,
389
- ) {
390
- await this.messageOperations.retry(
391
- {
392
- localMessage: { ...params.localMessage, type: 'regular' },
393
- options: params.options,
394
- },
395
- params.sendMessageRequestFn,
396
- );
525
+ get configState(): StateStore<ChannelConfig> {
526
+ return this.configController.state;
397
527
  }
398
528
 
399
529
  /**
400
- * Updates a message with optimistic local state update.
530
+ * This channel's **resolved** configuration — the shape every configurable class exposes.
531
+ *
532
+ * Not to be confused with {@link serverConfig}, which is this channel's configuration as the
533
+ * server reports it. This one has already folded that in: `typingEvents.enabled` is the server's
534
+ * `typing_events` ANDed with whatever the integrator registered, so it is the whole answer. The
535
+ * near-collision is why the server side became `serverConfig`, a getter that says what it
536
+ * is.
401
537
  */
402
- async updateMessageWithLocalUpdate(params: UpdateMessageWithStateUpdateParams) {
403
- await this.messageOperations.update(
404
- {
405
- localMessage: params.localMessage,
406
- options: params.options,
407
- },
408
- params.updateMessageRequestFn,
409
- );
538
+ get config(): Readonly<ChannelConfig> {
539
+ return this.configController.value;
410
540
  }
411
541
 
412
542
  /**
413
- * Deletes a message with local state update.
543
+ * This channel's configuration as the server reports it — feature flags such as `uploads`,
544
+ * `typing_events`, `read_events` and `commands`.
545
+ *
546
+ * Mostly a property of the channel *type*, but not only: a channel's own `config_overrides` narrow it
547
+ * for that channel alone, which is why the cache behind this is keyed by cid rather than by type. See
548
+ * `StreamChat._addChannelConfig`.
549
+ *
550
+ * `undefined` until this channel has been queried or watched — there is nothing to fall back on that
551
+ * would not be another channel's overrides. {@link config} covers that case with its defaults.
552
+ *
553
+ * Distinct from {@link config}, which is this instance's resolved configuration and already has the
554
+ * relevant flags below folded into it. Prefer `config` when deciding whether a feature is available:
555
+ * this getter answers only the server's half, so gating UI on it offers features the client has
556
+ * already disabled.
414
557
  */
415
- async deleteMessageWithLocalUpdate(params: DeleteMessageWithStateUpdateParams) {
416
- await this.messageOperations.delete(
417
- {
418
- localMessage: params.localMessage,
419
- options: params.options,
420
- },
421
- params.deleteMessageRequestFn,
422
- );
558
+ get serverConfig() {
559
+ return this.getClient().channelServerConfigs[this.cid];
423
560
  }
424
561
 
425
562
  /**
426
- * Adds a reaction with an optimistic local state update: the reaction is applied to the cached
427
- * message immediately ({@link applyReactionLocally}), then the request is
428
- * fired via {@link Channel.sendReaction} (which owns the offline-DB write + queue). The
429
- * server-authoritative counts reconcile on the response; the message is rolled back on failure.
563
+ * Sends a message to this channel.
564
+ *
565
+ * @param ...args - `[request, requestOptions]`. `request` holds the message body and optional
566
+ * flags such as `skip_enrich_url`, `skip_push`, and `keep_channel_hidden`; `requestOptions`
567
+ * carries per-request options such as an abort `signal` and is never serialized into the request.
568
+ * @returns The server response.
430
569
  */
431
- async addReactionWithLocalUpdate({
432
- messageId,
433
- reaction,
434
- options,
435
- }: {
436
- messageId: string;
437
- reaction: ReactionRequest;
438
- options?: Pick<SendReactionRequest, 'enforce_unique' | 'skip_push'>;
439
- }) {
440
- const client = this.getClient();
441
- const undo = applyReactionLocally(client, {
442
- enforceUnique: options?.enforce_unique ?? false,
443
- messageId,
444
- reaction,
445
- });
570
+ override async sendMessage(...args: Parameters<ChannelApi['sendMessage']>) {
571
+ this._checkHasId();
446
572
 
447
- try {
448
- const response = await this.sendReaction({ id: messageId, reaction, ...options });
449
- // reconcile the server copy only if we still hold it — a bare upsert of an unheld id would
450
- // orphan it (the store's refcount GC only reclaims held ids).
451
- if (response?.message && client.messageStore.has(response.message.id)) {
452
- client.messageStore.upsert(formatMessage(response.message));
453
- }
454
- } catch (error) {
455
- if (undo && (!client.offlineDb || !isEphemeral(error as Error))) {
456
- undo();
457
- }
458
- throw error;
459
- }
573
+ const [request, requestOptions] = args;
574
+
575
+ return await super.sendMessage(
576
+ { ...request, message: sanitizeOutgoingAttachments(request.message) },
577
+ requestOptions,
578
+ );
460
579
  }
461
580
 
462
- /**
463
- * Removes the current user's reaction with an optimistic local state update, mirroring
464
- * {@link Channel.addReactionWithLocalUpdate}.
465
- */
466
- async deleteReactionWithLocalUpdate({
467
- messageId,
468
- type,
469
- }: {
470
- messageId: string;
471
- type: string;
472
- }) {
473
- const client = this.getClient();
474
- const undo = applyReactionLocally(client, {
475
- messageId,
476
- reaction: { type },
477
- removed: true,
478
- });
581
+ async sendReaction(...args: Parameters<ChatApi['sendReaction']>) {
582
+ return await this.getClient().sendReaction(...args);
583
+ }
479
584
 
480
- try {
481
- const response = await this.deleteReaction({ id: messageId, type });
482
- // reconcile the server copy only if we still hold it — a bare upsert of an unheld id would
483
- // orphan it (the store's refcount GC only reclaims held ids).
484
- if (response?.message && client.messageStore.has(response.message.id)) {
485
- client.messageStore.upsert(formatMessage(response.message));
486
- }
487
- } catch (error) {
488
- if (undo && (!client.offlineDb || !isEphemeral(error as Error))) {
489
- undo();
490
- }
491
- throw error;
492
- }
585
+ async deleteReaction(...args: Parameters<ChatApi['deleteReaction']>) {
586
+ return await this.getClient().deleteReaction(...args);
493
587
  }
494
588
 
495
589
  /**
496
- * Upload a file to this channel’s file endpoint (multipart). Forwards to the client’s `sendFile` implementation.
590
+ * Upload a file to this channel's file endpoint (multipart).
497
591
  *
498
- * @param uri - File source: URL string, `File`, `Buffer`, or readable stream (Node).
499
- * @param name - File name sent in the multipart body (optional).
500
- * @param contentType - MIME type; defaults are applied when omitted (optional).
501
- * @param user - User payload appended to the form as JSON (optional).
502
- * @param axiosRequestConfig - Axios per-request config, merged after upload defaults, e.g. `onUploadProgress`, `signal` from `AbortController` (optional).
592
+ * @param request - Upload payload. `request.file` is the file to upload.
593
+ * @param requestOptions - Per-request options, e.g. `onUploadProgress` or an abort `signal` (optional).
503
594
  * @returns A promise resolving to `{ file: string, ... }` with the CDN URL.
504
595
  */
505
- sendFile(
506
- uri: string | NodeJS.ReadableStream | Buffer | File,
507
- name?: string,
508
- contentType?: string,
509
- user?: UserResponse,
510
- axiosRequestConfig?: AxiosRequestConfig,
596
+ override async uploadChannelFile(
597
+ request?: Omit<UploadChannelFileRequest, 'file'> & { file?: FileUploadInput },
598
+ requestOptions?: StreamRequestOptions,
511
599
  ) {
512
- return this.getClient().api.sendFile(
513
- `${this._channelURL()}/file`,
514
- uri,
515
- name,
516
- contentType,
517
- user,
518
- axiosRequestConfig,
600
+ return await super.uploadChannelFile(
601
+ { ...request, file: normalizeUploadFile(request?.file) as unknown as string },
602
+ requestOptions,
519
603
  );
520
604
  }
521
605
 
522
606
  /**
523
- * Upload an image to this channel's image endpoint (multipart). Uses the same transport as `sendFile`.
607
+ * Upload an image to this channel's image endpoint (multipart).
524
608
  *
525
- * @param uri - Image source: URL string, `File`, or readable stream (Node). For `Buffer` uploads, use `sendFile` toward the channel file endpoint instead.
526
- * @param name - File name sent in the multipart body (optional).
527
- * @param contentType - MIME type (optional).
528
- * @param user - User payload appended to the form as JSON (optional).
529
- * @param axiosRequestConfig - Axios per-request config, merged after upload defaults, e.g. `onUploadProgress`, `signal` (optional).
609
+ * @param request - Upload payload. `request.file` is the image to upload.
610
+ * @param requestOptions - Per-request options, e.g. `onUploadProgress` or an abort `signal` (optional).
530
611
  * @returns A promise resolving to `{ file: string, ... }` with the CDN URL.
531
612
  */
532
- sendImage(
533
- uri: string | NodeJS.ReadableStream | File,
534
- name?: string,
535
- contentType?: string,
536
- user?: UserResponse,
537
- axiosRequestConfig?: AxiosRequestConfig,
613
+ override async uploadChannelImage(
614
+ request?: Omit<UploadChannelRequest, 'file'> & { file?: FileUploadInput },
615
+ requestOptions?: StreamRequestOptions,
538
616
  ) {
539
- return this.getClient().api.sendFile(
540
- `${this._channelURL()}/image`,
541
- uri,
542
- name,
543
- contentType,
544
- user,
545
- axiosRequestConfig,
617
+ return await super.uploadChannelImage(
618
+ { ...request, file: normalizeUploadFile(request?.file) as unknown as string },
619
+ requestOptions,
546
620
  );
547
621
  }
548
622
 
549
- deleteFile(url: string) {
550
- return this.deleteChannelFile({ url });
623
+ /**
624
+ * Alias for {@link uploadChannelFile}, mirroring `client.uploadFile`.
625
+ */
626
+ uploadFile = (...args: Parameters<Channel['uploadChannelFile']>) =>
627
+ this.uploadChannelFile(...args);
628
+
629
+ /** Alias for {@link uploadChannelImage}, mirroring `client.uploadImage`. */
630
+ uploadImage = (...args: Parameters<Channel['uploadChannelImage']>) =>
631
+ this.uploadChannelImage(...args);
632
+
633
+ deleteFile(url: string, requestOptions?: StreamRequestOptions) {
634
+ return this.deleteChannelFile({ url }, requestOptions);
551
635
  }
552
636
 
553
- deleteImage(url: string) {
554
- return this.deleteChannelImage({ url });
637
+ deleteImage(url: string, requestOptions?: StreamRequestOptions) {
638
+ return this.deleteChannelImage({ url }, requestOptions);
555
639
  }
556
640
 
557
641
  /**
558
642
  * Sends an event on this channel.
559
643
  *
560
- * @param event - For example `{ type: 'message.read' }`.
644
+ * @param request - For example `{ event: { type: 'message.read' } }`.
645
+ * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
646
+ * into the request (optional).
561
647
  * @returns The server response.
562
648
  */
563
- override async sendEvent(request: { event: Event }) {
564
- this._checkInitialized();
565
- return await super.sendEvent(request);
566
- }
567
-
568
- /**
569
- * Queries messages.
570
- *
571
- * @param request - The search request payload (optional). The inner `payload` accepts
572
- * MongoDB-style filters and additional options such as `user_id`.
573
- * @returns The search messages response.
574
- */
575
- async search(request?: { payload?: SearchPayload }) {
576
- return await this.getClient().search(request);
649
+ override async sendEvent(
650
+ request: { event: Event },
651
+ requestOptions?: StreamRequestOptions,
652
+ ) {
653
+ return await super.sendEvent(request, requestOptions);
577
654
  }
578
655
 
579
656
  /**
@@ -582,9 +659,15 @@ export class Channel extends ChannelApi {
582
659
  * @param request - The query members request payload (optional). The inner `payload` accepts
583
660
  * MongoDB-style filters, sort directions (e.g. `[{ field: 'created_at', direction: -1 }]`),
584
661
  * and pagination options (`limit`, `offset`).
662
+ * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
663
+ * into the request (optional).
585
664
  * @returns The query members response.
586
665
  */
587
- async queryMembers(request?: { payload?: Partial<QueryMembersPayload> }) {
666
+ async queryMembers(
667
+ request?: { payload?: Partial<QueryMembersPayload> },
668
+ requestOptions?: StreamRequestOptions,
669
+ ) {
670
+ this._checkHasId();
588
671
  const payload = {
589
672
  type: this.type,
590
673
  // TODO: these should be probably optional in the OAPI spec
@@ -601,104 +684,29 @@ export class Channel extends ChannelApi {
601
684
  }));
602
685
  }
603
686
  // Return a list of members
604
- return await this.getClient().queryMembers({
605
- payload: {
606
- ...payload,
607
- ...request?.payload,
687
+ return await this.getClient().queryMembers(
688
+ {
689
+ payload: {
690
+ ...payload,
691
+ ...request?.payload,
692
+ },
608
693
  },
609
- });
610
- }
611
-
612
- /**
613
- * Sends a reaction to a message. If offline support is enabled, it will make sure
614
- * that sending the reaction is queued up if it fails due to bad internet conditions and executed
615
- * later.
616
- *
617
- * @param request - The send-reaction request payload, including the target message ID, the
618
- * reaction object (e.g. `{ type: 'love' }`), and optional flags such as `enforce_unique` and
619
- * `skip_push`.
620
- * @returns The server response.
621
- */
622
- async sendReaction(request: Parameters<ChatApi['sendReaction']>[0]) {
623
- const { id: messageId } = request;
624
-
625
- try {
626
- const offlineDb = this.getClient().offlineDb;
627
- if (offlineDb) {
628
- // The optimistic reaction row is written by the local-update layer
629
- // (`applyReactionLocally`); here we only queue the request for replay.
630
- return await offlineDb.queueTask<ReactionAPIResponse>({
631
- task: {
632
- channelId: this.id as string,
633
- channelType: this.type,
634
- messageId,
635
- payload: [request],
636
- type: 'send-reaction',
637
- },
638
- });
639
- }
640
- } catch (error) {
641
- offlineDbLogger
642
- .withExtraTags('sendReaction', this.cid)
643
- .error('Sending the reaction failed.', { error });
644
- }
645
-
646
- return this._sendReaction(request);
647
- }
648
-
649
- _sendReaction(request: Parameters<ChatApi['sendReaction']>[0]) {
650
- return this.getClient().sendReaction(request);
651
- }
652
-
653
- async deleteReaction(request: Parameters<ChatApi['deleteReaction']>[0]) {
654
- this._checkInitialized();
655
-
656
- try {
657
- const offlineDb = this.getClient().offlineDb;
658
- if (offlineDb) {
659
- // The optimistic reaction-row removal is handled by the local-update layer
660
- // (`applyReactionLocally`); here we only queue the request for replay.
661
- return await offlineDb.queueTask<ReactionAPIResponse>({
662
- task: {
663
- channelId: this.id as string,
664
- channelType: this.type,
665
- messageId: request.id,
666
- payload: [request],
667
- type: 'delete-reaction',
668
- },
669
- });
670
- }
671
- } catch (error) {
672
- offlineDbLogger
673
- .withExtraTags('deleteReaction', this.cid)
674
- .error('Deleting the reaction failed.', { error });
675
- }
676
-
677
- return await this._deleteReaction(request);
678
- }
679
-
680
- /**
681
- * Deletes a reaction by user and type.
682
- *
683
- * @param request - The delete reaction request payload identifying the target message and reaction type.
684
- * @returns The server response.
685
- */
686
- async _deleteReaction(request: Parameters<ChatApi['deleteReaction']>[0]) {
687
- return await this.getClient().deleteReaction(request);
694
+ requestOptions,
695
+ );
688
696
  }
689
697
 
690
698
  /**
691
699
  * Edit the channel using the inherited `update()` from `ChannelApi`. Caches the
692
700
  * server-returned channel onto `this.data`.
693
701
  *
694
- * @param request - Channel update payload, e.g. `{ data: { name: 'foo' }, message }` (optional).
702
+ * @param ...args - `[request, requestOptions]`. `request` is the channel update payload, e.g.
703
+ * `{ data: { name: 'foo' }, message }`; `requestOptions` carries per-request options such as an
704
+ * abort `signal` and is never serialized into the request.
695
705
  * @returns The server response.
696
706
  */
697
- override async update(request?: Gen_UpdateChannelRequest) {
698
- const previousData = this.data;
699
- const data = await super.update(request);
707
+ override async update(...args: Parameters<ChannelApi['update']>) {
708
+ const data = await super.update(...args);
700
709
  this.data = data.channel;
701
- this._syncStateFromChannelData(this.data, previousData);
702
710
  return data;
703
711
  }
704
712
 
@@ -706,12 +714,15 @@ export class Channel extends ChannelApi {
706
714
  * Partial update of channel properties.
707
715
  *
708
716
  * @param update - The partial update request.
717
+ * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
718
+ * into the request (optional).
709
719
  * @returns The server response.
710
720
  */
711
- async updatePartial(update: UpdateChannelPartialRequest) {
712
- const data = await this.updateChannelPartial(update);
713
-
714
- if (!this.getClient()._cacheEnabled) return data;
721
+ async updatePartial(
722
+ update: UpdateChannelPartialRequest,
723
+ requestOptions?: StreamRequestOptions,
724
+ ) {
725
+ const data = await this.updateChannelPartial(update, requestOptions);
715
726
 
716
727
  const channel = data.channel;
717
728
  const currentCapabilities = this.data?.own_capabilities ?? [];
@@ -721,9 +732,7 @@ export class Channel extends ChannelApi {
721
732
  newCapabilities &&
722
733
  [...currentCapabilities].sort().join() !== [...newCapabilities].sort().join();
723
734
 
724
- const previousData = this.data;
725
735
  this.data = channel;
726
- this._syncStateFromChannelData(this.data, previousData);
727
736
  // If the capabiltities are changed, we trigger the `capabilities.changed` event.
728
737
  if (capabilitiesChanged) {
729
738
  this.getClient().dispatchEvent({
@@ -740,26 +749,45 @@ export class Channel extends ChannelApi {
740
749
  * Enables slow mode.
741
750
  *
742
751
  * @param coolDownInterval - The cooldown interval in seconds.
752
+ * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
753
+ * into the request (optional).
743
754
  * @returns The server response.
744
755
  */
745
- async enableSlowMode(coolDownInterval: number) {
746
- return await this.update({ cooldown: coolDownInterval });
756
+ async enableSlowMode(coolDownInterval: number, requestOptions?: StreamRequestOptions) {
757
+ return await this.update({ cooldown: coolDownInterval }, requestOptions);
747
758
  }
748
759
 
749
760
  /**
750
761
  * Disables slow mode.
751
762
  *
763
+ * @param _request - Unused. Holds the request position so `requestOptions` stays the
764
+ * second argument, as on the generated methods; pass `undefined`.
765
+ * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
766
+ * into the request (optional).
752
767
  * @returns The server response.
753
768
  */
754
- async disableSlowMode() {
755
- return await this.update({ cooldown: 0 });
769
+ async disableSlowMode(
770
+ _request?: Record<string, never>,
771
+ requestOptions?: StreamRequestOptions,
772
+ ) {
773
+ return await this.update({ cooldown: 0 }, requestOptions);
756
774
  }
757
775
 
758
776
  public async sendSharedLocation(location: SharedLocation & { message_id?: string }) {
759
- const result = await this.sendMessage({
760
- message: {
761
- id: location.message_id,
762
- shared_location: location,
777
+ this._checkHasId();
778
+
779
+ const messageId = location.message_id;
780
+ const result = await queueOrRun({
781
+ channel: this,
782
+ client: this.getClient(),
783
+ // Nothing to key a queue entry on without a message id, so it runs but is not queued.
784
+ queue: !!messageId,
785
+ task: {
786
+ channelId: this.id,
787
+ channelType: this.type,
788
+ messageId,
789
+ payload: [{ message: { id: messageId, shared_location: location } }],
790
+ type: 'send-message',
763
791
  },
764
792
  });
765
793
 
@@ -773,11 +801,18 @@ export class Channel extends ChannelApi {
773
801
  return result;
774
802
  }
775
803
 
776
- public async stopLiveLocationSharing(payload: UpdateLiveLocationRequest) {
777
- const location = await this.getClient().updateLiveLocation({
778
- ...payload,
779
- end_at: new Date(),
780
- });
804
+ public async stopLiveLocationSharing(
805
+ payload: UpdateLiveLocationRequest,
806
+ requestOptions?: StreamRequestOptions,
807
+ ) {
808
+ this._checkHasId();
809
+ // Picked rather than spread: callers hand over a whole shared location (`created_by_device_id`,
810
+ // `channel_cid`, timestamps, …), and the request is sent as given.
811
+ const { latitude, longitude, message_id } = payload;
812
+ const location = await this.getClient().updateLiveLocation(
813
+ { end_at: new Date(), latitude, longitude, message_id },
814
+ requestOptions,
815
+ );
781
816
  this.getClient().dispatchEvent({
782
817
  live_location: location,
783
818
  type: 'live_location_sharing.stopped',
@@ -788,20 +823,30 @@ export class Channel extends ChannelApi {
788
823
  * Accepts an invitation to the channel.
789
824
  *
790
825
  * @param options - The object to update the custom properties of this channel with (optional, defaults to `{}`).
826
+ * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
827
+ * into the request (optional).
791
828
  * @returns The server response.
792
829
  */
793
- async acceptInvite(options: ChannelUpdateOptions = {}) {
794
- return await this.update({ accept_invite: true, ...options });
830
+ async acceptInvite(
831
+ options: ChannelUpdateOptions = {},
832
+ requestOptions?: StreamRequestOptions,
833
+ ) {
834
+ return await this.update({ accept_invite: true, ...options }, requestOptions);
795
835
  }
796
836
 
797
837
  /**
798
838
  * Rejects an invitation to the channel.
799
839
  *
800
840
  * @param options - The object to update the custom properties of this channel with (optional, defaults to `{}`).
841
+ * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
842
+ * into the request (optional).
801
843
  * @returns The server response.
802
844
  */
803
- async rejectInvite(options: ChannelUpdateOptions = {}) {
804
- return await this.update({ reject_invite: true, ...options });
845
+ async rejectInvite(
846
+ options: ChannelUpdateOptions = {},
847
+ requestOptions?: StreamRequestOptions,
848
+ ) {
849
+ return await this.update({ reject_invite: true, ...options }, requestOptions);
805
850
  }
806
851
 
807
852
  /**
@@ -810,20 +855,26 @@ export class Channel extends ChannelApi {
810
855
  * @param members - An array of members to add to the channel.
811
856
  * @param message - Message object for channel members notification (optional).
812
857
  * @param options - Configuration to control the behavior while updating (optional, defaults to `{}`).
858
+ * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
859
+ * into the request (optional).
813
860
  * @returns The server response.
814
861
  */
815
862
  async addMembers(
816
863
  members: string[] | Array<Gen_ChannelMemberRequest>,
817
864
  message?: MessageRequest,
818
865
  options: ChannelUpdateOptions = {},
866
+ requestOptions?: StreamRequestOptions,
819
867
  ) {
820
- return await this.update({
821
- add_members: members.map((member) =>
822
- typeof member === 'string' ? { user_id: member } : member,
823
- ),
824
- message,
825
- ...options,
826
- });
868
+ return await this.update(
869
+ {
870
+ add_members: members.map((member) =>
871
+ typeof member === 'string' ? { user_id: member } : member,
872
+ ),
873
+ message,
874
+ ...options,
875
+ },
876
+ requestOptions,
877
+ );
827
878
  }
828
879
 
829
880
  /**
@@ -832,14 +883,20 @@ export class Channel extends ChannelApi {
832
883
  * @param tags - An array of tags to add to the channel.
833
884
  * @param message - Message object for channel members notification (optional).
834
885
  * @param options - Configuration to control the behavior while updating (optional, defaults to `{}`).
886
+ * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
887
+ * into the request (optional).
835
888
  * @returns The server response.
836
889
  */
837
890
  async addFilterTags(
838
891
  tags: string[],
839
892
  message?: MessageRequest,
840
893
  options: ChannelUpdateOptions = {},
894
+ requestOptions?: StreamRequestOptions,
841
895
  ) {
842
- return await this.update({ add_filter_tags: tags, message, ...options });
896
+ return await this.update(
897
+ { add_filter_tags: tags, message, ...options },
898
+ requestOptions,
899
+ );
843
900
  }
844
901
 
845
902
  /**
@@ -848,46 +905,20 @@ export class Channel extends ChannelApi {
848
905
  * @param tags - An array of tags to remove from the channel.
849
906
  * @param message - Message object for channel members notification (optional).
850
907
  * @param options - Configuration to control the behavior while updating (optional, defaults to `{}`).
908
+ * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
909
+ * into the request (optional).
851
910
  * @returns The server response.
852
911
  */
853
912
  async removeFilterTags(
854
913
  tags: string[],
855
914
  message?: MessageRequest,
856
915
  options: ChannelUpdateOptions = {},
916
+ requestOptions?: StreamRequestOptions,
857
917
  ) {
858
- return await this.update({ remove_filter_tags: tags, message, ...options });
859
- }
860
-
861
- /**
862
- * Adds moderators to the channel.
863
- *
864
- * @param members - An array of member identifiers.
865
- * @param message - Message object for channel members notification (optional).
866
- * @param options - Configuration to control the behavior while updating (optional, defaults to `{}`).
867
- * @returns The server response.
868
- */
869
- async addModerators(
870
- members: string[],
871
- message?: MessageRequest,
872
- options: ChannelUpdateOptions = {},
873
- ) {
874
- return await this.update({ add_moderators: members, message, ...options });
875
- }
876
-
877
- /**
878
- * Sets member roles in a channel.
879
- *
880
- * @param roles - List of role assignments.
881
- * @param message - Message object for channel members notification (optional).
882
- * @param options - Configuration to control the behavior while updating (optional, defaults to `{}`).
883
- * @returns The server response.
884
- */
885
- async assignRoles(
886
- roles: { channel_role: RoleName; user_id: string }[],
887
- message?: MessageRequest,
888
- options: ChannelUpdateOptions = {},
889
- ) {
890
- return await this.update({ assign_roles: roles, message, ...options });
918
+ return await this.update(
919
+ { remove_filter_tags: tags, message, ...options },
920
+ requestOptions,
921
+ );
891
922
  }
892
923
 
893
924
  /**
@@ -896,20 +927,26 @@ export class Channel extends ChannelApi {
896
927
  * @param members - An array of members to invite to the channel.
897
928
  * @param message - Message object for channel members notification (optional).
898
929
  * @param options - Configuration to control the behavior while updating (optional, defaults to `{}`).
930
+ * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
931
+ * into the request (optional).
899
932
  * @returns The server response.
900
933
  */
901
934
  async inviteMembers(
902
935
  members: string[] | Required<Omit<Gen_ChannelMemberRequest, 'channel_role'>>[],
903
936
  message?: MessageRequest,
904
937
  options: ChannelUpdateOptions = {},
938
+ requestOptions?: StreamRequestOptions,
905
939
  ) {
906
- return await this.update({
907
- invites: members.map((member) =>
908
- typeof member === 'string' ? { user_id: member } : member,
909
- ),
910
- message,
911
- ...options,
912
- });
940
+ return await this.update(
941
+ {
942
+ invites: members.map((member) =>
943
+ typeof member === 'string' ? { user_id: member } : member,
944
+ ),
945
+ message,
946
+ ...options,
947
+ },
948
+ requestOptions,
949
+ );
913
950
  }
914
951
 
915
952
  /**
@@ -918,30 +955,20 @@ export class Channel extends ChannelApi {
918
955
  * @param members - An array of member identifiers.
919
956
  * @param message - Message object for channel members notification (optional).
920
957
  * @param options - Configuration to control the behavior while updating (optional, defaults to `{}`).
958
+ * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
959
+ * into the request (optional).
921
960
  * @returns The server response.
922
961
  */
923
962
  async removeMembers(
924
963
  members: string[],
925
964
  message?: MessageRequest,
926
965
  options: ChannelUpdateOptions = {},
966
+ requestOptions?: StreamRequestOptions,
927
967
  ) {
928
- return await this.update({ remove_members: members, message, ...options });
929
- }
930
-
931
- /**
932
- * Removes the moderator role from channel members.
933
- *
934
- * @param members - An array of member identifiers.
935
- * @param message - Message object for channel members notification (optional).
936
- * @param options - Configuration to control the behavior while updating (optional, defaults to `{}`).
937
- * @returns The server response.
938
- */
939
- async demoteModerators(
940
- members: string[],
941
- message?: MessageRequest,
942
- options: ChannelUpdateOptions = {},
943
- ) {
944
- return await this.update({ demote_moderators: members, message, ...options });
968
+ return await this.update(
969
+ { remove_members: members, message, ...options },
970
+ requestOptions,
971
+ );
945
972
  }
946
973
 
947
974
  /**
@@ -957,13 +984,20 @@ export class Channel extends ChannelApi {
957
984
  *
958
985
  * @param options - Mute options (optional, defaults to `{}`).
959
986
  * @param options.expiration - Expiration in minutes (optional).
987
+ * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
988
+ * into the request (optional).
960
989
  * @returns The server response.
961
990
  */
962
- async mute(options?: Gen_MuteChannelRequest) {
963
- return await this.getClient().muteChannel({
964
- channel_cids: [this.cid],
965
- ...options,
966
- });
991
+ async mute(options?: Gen_MuteChannelRequest, requestOptions?: StreamRequestOptions) {
992
+ this._checkHasId();
993
+
994
+ return await this.getClient().muteChannel(
995
+ {
996
+ channel_cids: [this.cid],
997
+ ...options,
998
+ },
999
+ requestOptions,
1000
+ );
967
1001
  }
968
1002
 
969
1003
  /**
@@ -975,13 +1009,23 @@ export class Channel extends ChannelApi {
975
1009
  *
976
1010
  * @param options - Unmute options (optional, defaults to `{}`).
977
1011
  * @param options.user_id - User ID (optional).
1012
+ * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
1013
+ * into the request (optional).
978
1014
  * @returns The server response.
979
1015
  */
980
- async unmute(options?: Gen_UnmuteChannelRequest) {
981
- return await this.getClient().unmuteChannel({
982
- channel_cids: [this.cid],
983
- ...options,
984
- });
1016
+ async unmute(
1017
+ options?: Gen_UnmuteChannelRequest,
1018
+ requestOptions?: StreamRequestOptions,
1019
+ ) {
1020
+ this._checkHasId();
1021
+
1022
+ return await this.getClient().unmuteChannel(
1023
+ {
1024
+ channel_cids: [this.cid],
1025
+ ...options,
1026
+ },
1027
+ requestOptions,
1028
+ );
985
1029
  }
986
1030
 
987
1031
  /**
@@ -990,10 +1034,14 @@ export class Channel extends ChannelApi {
990
1034
  * @example
991
1035
  * await channel.archive();
992
1036
  *
1037
+ * @param _request - Unused. Holds the request position so `requestOptions` stays the
1038
+ * second argument, as on the generated methods; pass `undefined`.
1039
+ * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
1040
+ * into the request (optional).
993
1041
  * @returns The server response.
994
1042
  */
995
- async archive() {
996
- return await this.updateMemberPartial({ set: { archived: true } });
1043
+ async archive(_request?: Record<string, never>, requestOptions?: StreamRequestOptions) {
1044
+ return await this.updateMemberPartial({ set: { archived: true } }, requestOptions);
997
1045
  }
998
1046
 
999
1047
  /**
@@ -1002,10 +1050,17 @@ export class Channel extends ChannelApi {
1002
1050
  * @example
1003
1051
  * await channel.unarchive();
1004
1052
  *
1053
+ * @param _request - Unused. Holds the request position so `requestOptions` stays the
1054
+ * second argument, as on the generated methods; pass `undefined`.
1055
+ * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
1056
+ * into the request (optional).
1005
1057
  * @returns The server response.
1006
1058
  */
1007
- async unarchive() {
1008
- return await this.updateMemberPartial({ set: { archived: false } });
1059
+ async unarchive(
1060
+ _request?: Record<string, never>,
1061
+ requestOptions?: StreamRequestOptions,
1062
+ ) {
1063
+ return await this.updateMemberPartial({ set: { archived: false } }, requestOptions);
1009
1064
  }
1010
1065
 
1011
1066
  /**
@@ -1014,10 +1069,14 @@ export class Channel extends ChannelApi {
1014
1069
  * @example
1015
1070
  * await channel.pin();
1016
1071
  *
1072
+ * @param _request - Unused. Holds the request position so `requestOptions` stays the
1073
+ * second argument, as on the generated methods; pass `undefined`.
1074
+ * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
1075
+ * into the request (optional).
1017
1076
  * @returns The server response.
1018
1077
  */
1019
- async pin() {
1020
- return await this.updateMemberPartial({ set: { pinned: true } });
1078
+ async pin(_request?: Record<string, never>, requestOptions?: StreamRequestOptions) {
1079
+ return await this.updateMemberPartial({ set: { pinned: true } }, requestOptions);
1021
1080
  }
1022
1081
 
1023
1082
  /**
@@ -1026,31 +1085,59 @@ export class Channel extends ChannelApi {
1026
1085
  * @example
1027
1086
  * await channel.unpin();
1028
1087
  *
1088
+ * @param _request - Unused. Holds the request position so `requestOptions` stays the
1089
+ * second argument, as on the generated methods; pass `undefined`.
1090
+ * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
1091
+ * into the request (optional).
1029
1092
  * @returns The server response.
1030
1093
  */
1031
- async unpin() {
1032
- return await this.updateMemberPartial({ set: { pinned: false } });
1094
+ async unpin(_request?: Record<string, never>, requestOptions?: StreamRequestOptions) {
1095
+ return await this.updateMemberPartial({ set: { pinned: false } }, requestOptions);
1033
1096
  }
1034
1097
 
1035
1098
  /**
1036
1099
  * Returns the mute status for the current channel.
1037
1100
  *
1038
- * @returns An object of the form `{ muted: true | false, createdAt: Date | null, expiresAt: Date | null }`.
1101
+ * @returns An object of the form `{ muted: true | false, createdAt: TimestampNS | null, expiresAt: TimestampNS | null }`,
1102
+ * where the timestamps are unix nanoseconds as the API sends them.
1039
1103
  */
1040
1104
  muteStatus() {
1041
- this._checkInitialized();
1105
+ this._checkHasId();
1042
1106
  return this.getClient()._muteStatus(this.cid);
1043
1107
  }
1044
1108
 
1045
- sendAction(messageId: string, formData: Record<string, string>) {
1046
- this._checkInitialized();
1047
- if (!messageId) {
1048
- throw Error(`Message ID is missing`);
1049
- }
1050
- return this.getClient().runMessageAction({
1051
- id: messageId,
1052
- form_data: formData,
1053
- });
1109
+ /**
1110
+ * Recomputes this channel's reactive `state.muteStatus` from the client's current `mutedChannels`
1111
+ * and publishes it only when it actually changed — so the frequent `health.check` fan-out does not
1112
+ * churn subscribers. Called from the constructor and by the client whenever `mutedChannels`
1113
+ * updates. Unlike `muteStatus()`, this does not require the channel to be initialized.
1114
+ */
1115
+ _syncMuteStatus() {
1116
+ if (this.pendingDisposal) return;
1117
+
1118
+ const next = this.getClient()._muteStatus(this.cid);
1119
+ const previous = this.state.getLatestValue().muteStatus;
1120
+ const unchanged =
1121
+ previous.muted === next.muted &&
1122
+ (previous.createdAt ?? null) === (next.createdAt ?? null) &&
1123
+ (previous.expiresAt ?? null) === (next.expiresAt ?? null);
1124
+
1125
+ if (unchanged) return;
1126
+
1127
+ this.state.partialNext({ muteStatus: next });
1128
+ }
1129
+
1130
+ async sendAction(
1131
+ messageId: string,
1132
+ formData: Record<string, string>,
1133
+ requestOptions?: StreamRequestOptions,
1134
+ ) {
1135
+ this._checkHasId();
1136
+ return await this.getClient().runMessageAction(
1137
+ { id: messageId },
1138
+ { form_data: formData },
1139
+ requestOptions,
1140
+ );
1054
1141
  }
1055
1142
 
1056
1143
  /**
@@ -1061,8 +1148,14 @@ export class Channel extends ChannelApi {
1061
1148
  *
1062
1149
  * @param parentId - Set this field to `message.id` to indicate that the typing event is happening in a thread (optional).
1063
1150
  * @param options - Optional override carrying a `user_id` (optional).
1151
+ * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
1152
+ * into the request (optional).
1064
1153
  */
1065
- async keystroke(parentId?: string, options?: { user_id: string }) {
1154
+ async keystroke(
1155
+ parentId?: string,
1156
+ options?: { user_id: string },
1157
+ requestOptions?: StreamRequestOptions,
1158
+ ) {
1066
1159
  if (!this._isTypingIndicatorsEnabled()) {
1067
1160
  return;
1068
1161
  }
@@ -1073,15 +1166,18 @@ export class Channel extends ChannelApi {
1073
1166
  // send a typing.start every 2 seconds
1074
1167
  if (diff === null || diff > 2000) {
1075
1168
  this.lastTypingEvent = new Date();
1076
- await this.sendEvent({
1077
- event: {
1078
- type: 'typing.start',
1079
- parent_id: parentId,
1080
- ...(options || {}),
1081
- created_at: new Date(),
1082
- custom: {},
1169
+ await this.sendEvent(
1170
+ {
1171
+ event: {
1172
+ type: 'typing.start',
1173
+ parent_id: parentId,
1174
+ ...(options || {}),
1175
+ created_at: nowNs(),
1176
+ custom: {},
1177
+ },
1083
1178
  },
1084
- });
1179
+ requestOptions,
1180
+ );
1085
1181
  }
1086
1182
  }
1087
1183
 
@@ -1093,50 +1189,78 @@ export class Channel extends ChannelApi {
1093
1189
  * @param state - The new state of the AI process, e.g. thinking, generating.
1094
1190
  * @param options - Parameters such as `ai_message` to include additional details in the event (optional, defaults to `{}`).
1095
1191
  * @param options.ai_message - Additional message detail to include in the event (optional).
1192
+ * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
1193
+ * into the request (optional).
1096
1194
  */
1097
1195
  async updateAIState(
1098
1196
  messageId: string,
1099
1197
  state: AIState,
1100
1198
  options: { ai_message?: string } = {},
1199
+ requestOptions?: StreamRequestOptions,
1101
1200
  ) {
1102
- await this.sendEvent({
1103
- event: {
1104
- ...options,
1105
- type: 'ai_indicator.update',
1106
- message_id: messageId,
1107
- ai_state: state,
1108
- created_at: new Date(),
1109
- custom: {},
1201
+ await this.sendEvent(
1202
+ {
1203
+ event: {
1204
+ ...options,
1205
+ type: 'ai_indicator.update',
1206
+ message_id: messageId,
1207
+ ai_state: state,
1208
+ created_at: nowNs(),
1209
+ custom: {},
1210
+ },
1110
1211
  },
1111
- });
1212
+ requestOptions,
1213
+ );
1112
1214
  }
1113
1215
 
1114
1216
  /**
1115
1217
  * Sends an event to notify watchers to clear the typing/thinking UI when the AI response starts streaming.
1116
1218
  * Typically used by the server connected to the AI service to inform clients that the AI response has started.
1219
+ *
1220
+ * @param _request - Unused. Holds the request position so `requestOptions` stays the
1221
+ * second argument, as on the generated methods; pass `undefined`.
1222
+ * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
1223
+ * into the request (optional).
1117
1224
  */
1118
- async clearAIIndicator() {
1119
- await this.sendEvent({
1120
- event: {
1121
- type: 'ai_indicator.clear',
1122
- created_at: new Date(),
1123
- custom: {},
1225
+ async clearAIIndicator(
1226
+ _request?: Record<string, never>,
1227
+ requestOptions?: StreamRequestOptions,
1228
+ ) {
1229
+ await this.sendEvent(
1230
+ {
1231
+ event: {
1232
+ type: 'ai_indicator.clear',
1233
+ created_at: nowNs(),
1234
+ custom: {},
1235
+ },
1124
1236
  },
1125
- });
1237
+ requestOptions,
1238
+ );
1126
1239
  }
1127
1240
 
1128
1241
  /**
1129
1242
  * Sends an event to stop AI response generation, leaving the message in its current state.
1130
1243
  * Triggered by the user to halt the AI response process.
1244
+ *
1245
+ * @param _request - Unused. Holds the request position so `requestOptions` stays the
1246
+ * second argument, as on the generated methods; pass `undefined`.
1247
+ * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
1248
+ * into the request (optional).
1131
1249
  */
1132
- async stopAIResponse() {
1133
- await this.sendEvent({
1134
- event: {
1135
- type: 'ai_indicator.stop',
1136
- created_at: new Date(),
1137
- custom: {},
1250
+ async stopAIResponse(
1251
+ _request?: Record<string, never>,
1252
+ requestOptions?: StreamRequestOptions,
1253
+ ) {
1254
+ await this.sendEvent(
1255
+ {
1256
+ event: {
1257
+ type: 'ai_indicator.stop',
1258
+ created_at: nowNs(),
1259
+ custom: {},
1260
+ },
1138
1261
  },
1139
- });
1262
+ requestOptions,
1263
+ );
1140
1264
  }
1141
1265
 
1142
1266
  /**
@@ -1146,81 +1270,287 @@ export class Channel extends ChannelApi {
1146
1270
  *
1147
1271
  * @param parentId - Set this field to `message.id` to indicate that the typing event is happening in a thread (optional).
1148
1272
  * @param options - Optional override carrying a `user_id` (optional).
1273
+ * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
1274
+ * into the request (optional).
1275
+ */
1276
+ async stopTyping(
1277
+ parentId?: string,
1278
+ options?: { user_id: string },
1279
+ requestOptions?: StreamRequestOptions,
1280
+ ) {
1281
+ if (!this._isTypingIndicatorsEnabled()) {
1282
+ return;
1283
+ }
1284
+ this.lastTypingEvent = null;
1285
+ this.isTyping = false;
1286
+ await this.sendEvent(
1287
+ {
1288
+ event: {
1289
+ type: 'typing.stop',
1290
+ parent_id: parentId,
1291
+ ...(options || {}),
1292
+ created_at: nowNs(),
1293
+ custom: {},
1294
+ },
1295
+ },
1296
+ requestOptions,
1297
+ );
1298
+ }
1299
+
1300
+ _isTypingIndicatorsEnabled(): boolean {
1301
+ // nobody to tell about a channel the server hasn't assigned an id yet
1302
+ if (this.isProvisional) return false;
1303
+ // The resolved value, not the raw server flag: it already ANDs the channel type's `typing_events`
1304
+ // with what the integrator registered, so a client-side `typingEvents.enabled: false` is honoured
1305
+ // too. The other two axes are runtime facts no configuration can express.
1306
+ const { typingEvents } = this.configController.value;
1307
+ if (!typingEvents.enabled || !this.getClient().wsConnection?.isHealthy) {
1308
+ return false;
1309
+ }
1310
+ return this.getClient().user?.privacy_settings?.typing_indicators?.enabled ?? true;
1311
+ }
1312
+
1313
+ /**
1314
+ * Run this user's mark-read reporter for this channel. Delegates to
1315
+ * `MessageDeliveryReporter`, which batches the underlying `markRead` request
1316
+ * with the user's read receipts state.
1317
+ *
1318
+ * Use the inherited `markRead()` from `ChannelApi` for a direct, unbatched call.
1319
+ *
1320
+ * @param data - Mark read options (optional, defaults to `{}`).
1321
+ */
1322
+ async markReadViaReporter(data: MarkReadRequest = {}) {
1323
+ return await this.getClient().messageDeliveryReporter.markRead(this, data);
1324
+ }
1325
+
1326
+ /**
1327
+ * Override of the inherited `markRead()` from `ChannelApi` that requires the
1328
+ * channel to be initialized and respects the `read_events` channel config.
1329
+ *
1330
+ * @param ...args - `[data, requestOptions]`. `data` holds the mark-read options;
1331
+ * `requestOptions` carries per-request options such as an abort `signal` and is never
1332
+ * serialized into the request.
1333
+ * @returns The server response, or `null` if the request was skipped.
1334
+ */
1335
+ override async markRead(...args: Parameters<ChannelApi['markRead']>) {
1336
+ this._checkInitialized();
1337
+
1338
+ if (!this.configController.value.readEvents.enabled) {
1339
+ throw new Error(
1340
+ "Read events are disabled — either by the channel type's `read_events` setting or by `channel.readEvents.enabled` in your configuration",
1341
+ );
1342
+ }
1343
+
1344
+ return await super.markRead(...args);
1345
+ }
1346
+
1347
+ /**
1348
+ * Whether a live server response was applied to this instance since it was created — see
1349
+ * {@link ChannelLifecycleState.initialized}. Store-backed and reactive: subscribe via
1350
+ * `useStateStore(channel.state, (s) => ({ initialized: s.initialized }))`.
1351
+ */
1352
+ get initialized() {
1353
+ return this.state.getLatestValue().initialized;
1354
+ }
1355
+
1356
+ set initialized(initialized: boolean) {
1357
+ this.state.partialNext({ initialized });
1358
+ }
1359
+
1360
+ /**
1361
+ * Whether the channel has no id yet: it was built from members, and the server assigns its id when
1362
+ * its query is answered. Until then no request but that query can be sent for it, and its cid is
1363
+ * the temporary one built from the members. A channel with an id is never provisional, whether or
1364
+ * not the server has it: requests for it go to the server, which answers for it.
1365
+ *
1366
+ * Not reactive, as `id` is not kept in `channel.state`. To react to it, subscribe to
1367
+ * {@link Channel.initialized}: the response that sets `id` sets `initialized` to `true` too.
1368
+ */
1369
+ get isProvisional() {
1370
+ return !this.id;
1371
+ }
1372
+
1373
+ /**
1374
+ * The stored instance that replaced this one, if any — see
1375
+ * {@link ChannelLifecycleState.supersededBy}. Store-backed and reactive.
1376
+ *
1377
+ * A superseded instance receives no events (they go to the stored instance under its cid) and
1378
+ * reports `watchStatus: NotWatching`. Use the successor from then on: switch a UI showing this
1379
+ * instance to it, as `ChatView` does. `ensureWatched()` resolves with it.
1380
+ *
1381
+ * The SDK never disconnects a superseded instance on its own before logout, as the app may still
1382
+ * hold it. Call {@link Channel.disconnect} on it once nothing uses it.
1383
+ */
1384
+ get supersededBy() {
1385
+ return this.state.getLatestValue().supersededBy;
1386
+ }
1387
+
1388
+ /**
1389
+ * Whether the channel was initialized by manually populating its state (offline hydration) rather
1390
+ * than a live watch. Store-backed and reactive.
1391
+ */
1392
+ get offlineMode() {
1393
+ return this.state.getLatestValue().offlineMode;
1394
+ }
1395
+
1396
+ set offlineMode(offlineMode: boolean) {
1397
+ this.state.partialNext({ offlineMode });
1398
+ }
1399
+
1400
+ /**
1401
+ * The channel's server-provided data, read from `state.data`. Assigning publishes `data`,
1402
+ * `memberCount` and `ownCapabilities` in one state update. An assigned object that omits
1403
+ * `member_count` or `own_capabilities` gets the last known value carried over onto a copy, so a
1404
+ * partial update doesn't wipe them and raw readers (e.g. `channelHasReadEvents`) stay consistent
1405
+ * with the store. The assigned object itself is never changed; editing `channel.data.x` in place
1406
+ * doesn't reach the state.
1407
+ */
1408
+ get data(): Partial<ChannelResponse> | undefined {
1409
+ return this.state.getLatestValue().data;
1410
+ }
1411
+
1412
+ set data(next: Partial<ChannelResponse> | undefined) {
1413
+ const previous = this.state.getLatestValue().data;
1414
+ const carriedMemberCount =
1415
+ typeof next?.member_count !== 'number' && typeof previous?.member_count === 'number'
1416
+ ? previous.member_count
1417
+ : undefined;
1418
+ // `own_capabilities` stays undefined until known, so "not loaded" isn't read as "none" (#1732)
1419
+ const carriedCapabilities =
1420
+ !Array.isArray(next?.own_capabilities) && Array.isArray(previous?.own_capabilities)
1421
+ ? [...previous.own_capabilities]
1422
+ : undefined;
1423
+
1424
+ const data =
1425
+ next && (carriedMemberCount !== undefined || carriedCapabilities)
1426
+ ? {
1427
+ ...next,
1428
+ ...(carriedMemberCount !== undefined && { member_count: carriedMemberCount }),
1429
+ ...(carriedCapabilities && { own_capabilities: carriedCapabilities }),
1430
+ }
1431
+ : next;
1432
+
1433
+ const memberCount = data?.member_count ?? carriedMemberCount;
1434
+ const ownCapabilities = data?.own_capabilities ?? carriedCapabilities;
1435
+ this.state.partialNext({
1436
+ data,
1437
+ memberCount: memberCount ?? this.state.getLatestValue().memberCount,
1438
+ ownCapabilities: ownCapabilities ? [...ownCapabilities] : [],
1439
+ });
1440
+ }
1441
+
1442
+ /**
1443
+ * Whether {@link Channel.disconnect} has run: the channel was deleted, the current user removed
1444
+ * from it, the client disconnected, or nothing used it any more. Store-backed and reactive.
1445
+ *
1446
+ * One-way and terminal — read-only, set only by {@link Channel.disconnect}, and nothing revives
1447
+ * the instance. Its resources are already released ({@link Channel.disconnect} disposes the
1448
+ * paginators and unregisters the subscriptions), so nothing should touch it. It stays in the
1449
+ * channel store until `client.channelManager.releaseUnusedChannels()` drops it, and until then the
1450
+ * SDK treats it as not stored: `client.channelManager.ensure(…)` gives a fresh instance for its
1451
+ * cid, lists refuse it, and recovery never re-watches it. The offline DB refuses it as a source of
1452
+ * `channel.data`, and `getClient()` throws on it, so a reference held across a `disconnectUser()`
1453
+ * fails loudly instead of quietly requesting on a client with no user.
1454
+ */
1455
+ get pendingDisposal() {
1456
+ return this.state.getLatestValue().pendingDisposal;
1457
+ }
1458
+
1459
+ /**
1460
+ * Whether this client holds a server-side watch on the channel, and if not, whether it should be
1461
+ * restored — see {@link ChannelWatchStatus}. Store-backed and reactive: subscribe via
1462
+ * `useStateStore(channel.state, (s) => ({ watchStatus: s.watchStatus }))`.
1149
1463
  */
1150
- async stopTyping(parentId?: string, options?: { user_id: string }) {
1151
- if (!this._isTypingIndicatorsEnabled()) {
1152
- return;
1153
- }
1154
- this.lastTypingEvent = null;
1155
- this.isTyping = false;
1156
- await this.sendEvent({
1157
- event: {
1158
- type: 'typing.stop',
1159
- parent_id: parentId,
1160
- ...(options || {}),
1161
- created_at: new Date(),
1162
- custom: {},
1163
- },
1164
- });
1464
+ get watchStatus() {
1465
+ return this.state.getLatestValue().watchStatus;
1165
1466
  }
1166
1467
 
1167
- _isTypingIndicatorsEnabled(): boolean {
1168
- if (!this.getConfig()?.typing_events || !this.getClient().wsConnection?.isHealthy) {
1169
- return false;
1170
- }
1171
- return this.getClient().user?.privacy_settings?.typing_indicators?.enabled ?? true;
1468
+ set watchStatus(watchStatus: ChannelWatchStatus) {
1469
+ this.state.partialNext({ watchStatus });
1172
1470
  }
1173
1471
 
1174
1472
  /**
1175
- * Run this user's mark-read reporter for this channel. Delegates to
1176
- * `MessageDeliveryReporter`, which batches the underlying `markRead` request
1177
- * with the user's read receipts state.
1178
- *
1179
- * Use the inherited `markRead()` from `ChannelApi` for a direct, unbatched call.
1473
+ * Whether a query for this channel (`watch()`, `query()`, `create()`) is waiting for its response.
1474
+ * The channel store keeps a channel while it is loaded.
1180
1475
  *
1181
- * @param data - Mark read options (optional, defaults to `{}`).
1476
+ * @internal
1182
1477
  */
1183
- async markReadViaReporter(data: MarkReadRequest = {}) {
1184
- return await this.getClient().messageDeliveryReporter.markRead(this, data);
1478
+ get isQueryingChannel() {
1479
+ return this._channelQueriesInFlight > 0;
1185
1480
  }
1186
1481
 
1187
1482
  /**
1188
- * Override of the inherited `markRead()` from `ChannelApi` that requires the
1189
- * channel to be initialized and respects the `read_events` channel config.
1190
- *
1191
- * @param data - Mark read options (optional, defaults to `{}`).
1192
- * @returns The server response, or `null` if the request was skipped.
1483
+ * Whether a consumer has declared this channel as the one it is currently consuming (see
1484
+ * {@link Channel.activate}). Reactive — subscribe via
1485
+ * `useStateStore(channel.state, (s) => ({ active: s.active }))`.
1193
1486
  */
1194
- override async markRead(data?: MarkReadRequest) {
1195
- this._checkInitialized();
1487
+ get active() {
1488
+ return this.state.getLatestValue().active;
1489
+ }
1196
1490
 
1197
- if (!this.getConfig()?.read_events) {
1198
- throw new Error('Read events are disabled for this application');
1491
+ /**
1492
+ * Declares that a consumer is now consuming this channel's own state, and returns the function
1493
+ * that ends it. Refcounted, as a single `Channel` instance can be held by several consumers at
1494
+ * once, so it stays active until the last one releases. Calling a release function again does
1495
+ * nothing.
1496
+ *
1497
+ * While active, the channel's own state takes precedence over bulk state writes: channel-list
1498
+ * hydration does not re-seed its message list (its own `channel.reload()` owns that window).
1499
+ *
1500
+ * An active channel also stays in the channel store. Once the last consumer releases it, it is
1501
+ * kept only while something else uses it (a watch, a channel list, a claim). A superseded channel
1502
+ * (see {@link ChannelLifecycleState.supersededBy}) is never disconnected by its release: the app
1503
+ * may still hold it. It ends at logout, or when the app calls {@link Channel.disconnect}.
1504
+ *
1505
+ * A disposed channel (`pendingDisposal`) isn't activated: it is not stored, gets no events and
1506
+ * recovery skips it. A warning points at `client.channelManager.ensure()` for a live instance, and
1507
+ * the returned release does nothing, so the caller's cleanup still runs.
1508
+ */
1509
+ activate = (): (() => void) => {
1510
+ if (this.pendingDisposal) {
1511
+ logger.withExtraTags('activate', this.cid).warn(this.disposedError().message);
1512
+ return () => undefined;
1513
+ }
1514
+ this._activeRefCount += 1;
1515
+ if (this._activeRefCount === 1) {
1516
+ this.state.partialNext({ active: true });
1199
1517
  }
1200
1518
 
1201
- return await super.markRead(data);
1202
- }
1519
+ let released = false;
1520
+ return () => {
1521
+ if (released) return;
1522
+ released = true;
1523
+ this._activeRefCount -= 1;
1524
+ if (this._activeRefCount === 0) {
1525
+ this.state.partialNext({ active: false });
1526
+ }
1527
+ };
1528
+ };
1203
1529
 
1204
1530
  /**
1205
1531
  * Marks the channel as unread from `messageId`. Only works when the `read_events` setting is enabled.
1206
1532
  *
1207
- * @param data - Mark unread options.
1533
+ * @param ...args - `[data, requestOptions]`. `data` holds the mark-unread options;
1534
+ * `requestOptions` carries per-request options such as an abort `signal` and is never
1535
+ * serialized into the request.
1208
1536
  * @returns An API response, or `null` if the request was skipped.
1209
1537
  */
1210
- override async markUnread(data?: MarkUnreadRequest) {
1538
+ override async markUnread(...args: Parameters<ChannelApi['markUnread']>) {
1211
1539
  this._checkInitialized();
1212
1540
 
1213
- if (!this.getConfig()?.read_events) {
1214
- throw new Error('Read events are disabled for this application');
1541
+ if (!this.configController.value.readEvents.enabled) {
1542
+ throw new Error(
1543
+ "Read events are disabled — either by the channel type's `read_events` setting or by `channel.readEvents.enabled` in your configuration",
1544
+ );
1215
1545
  }
1216
1546
 
1217
- return await super.markUnread(data);
1547
+ return await super.markUnread(...args);
1218
1548
  }
1219
1549
 
1220
1550
  /**
1221
1551
  * Resets this user's unread count locally, without any backend call. Intended for
1222
1552
  * channels that have read events disabled (e.g. livestreams) when the client is created with the
1223
- * `isLocalUnreadCountEnabled` option. Dispatches a dedicated, client-only `message.read_locally` event
1553
+ * `readEvents.localUnreadCountEnabled` configuration. Dispatches a dedicated, client-only `message.read_locally` event
1224
1554
  * that runs through the same `_handleChannelEvent` read logic as a real `message.read` (minus the
1225
1555
  * delivery-report network sync), so the read-state update lives in one place. When offline support
1226
1556
  * is enabled, the offline DB persists the reset for read-events-disabled channels, so the local
@@ -1236,7 +1566,7 @@ export class Channel extends ChannelApi {
1236
1566
  channel_id: this.id,
1237
1567
  channel_type: this.type,
1238
1568
  cid: this.cid,
1239
- created_at: new Date(),
1569
+ created_at: nowNs(),
1240
1570
  last_read_message_id: this.messagePaginator.headmostItem?.id,
1241
1571
  team: this.data?.team,
1242
1572
  type: 'message.read_locally',
@@ -1260,34 +1590,95 @@ export class Channel extends ChannelApi {
1260
1590
  }
1261
1591
 
1262
1592
  this.state.clean();
1593
+
1594
+ // Clear a stuck AI indicator when we're offline (we'd miss the ending clear/stop). The cleaning
1595
+ // interval keeps ticking through transient/internet drops; closeConnection stops it, and that
1596
+ // path clears the indicator itself. Gate on health, not staleness — a healthy connection must
1597
+ // never cut off a long-running response.
1598
+ const client = this.getClient();
1599
+ if (!client.wsConnection?.isHealthy) {
1600
+ this.state.resetAIState();
1601
+ }
1602
+ }
1603
+
1604
+ /**
1605
+ * Watches the channel unless it is watched already, without duplicating a request: a call made
1606
+ * while an earlier `ensureWatched()` with the same options is still in flight waits for that one
1607
+ * instead of sending another. For callers that may ask for the same channel at the same time, such
1608
+ * as several events naming it, or a click while an event already restores its watch.
1609
+ *
1610
+ * {@link Channel.watch} and {@link Channel.query} are not affected: they always send their request,
1611
+ * and are not joined by this method. A channel already watched sends nothing, so `options` such as
1612
+ * a message window apply only when the call watches it; use the message paginator to load a window.
1613
+ *
1614
+ * Resolves with the instance to use from now on: this one, or the one that superseded it
1615
+ * ({@link Channel.supersededBy}). A channel created from members is superseded when its watch
1616
+ * answers with a cid another instance is already stored under; that instance is the one stored,
1617
+ * listed and receiving events, so it is the one this ensures watched and resolves with.
1618
+ *
1619
+ * Rejects as the watch does, and every caller waiting for that watch gets its rejection. The next
1620
+ * call sends a new request.
1621
+ *
1622
+ * @param options - Options for the watch request (optional). Calls join only a watch with the same
1623
+ * options.
1624
+ * @returns The instance to use, so it can follow `client.channelManager.ensure(...)` in one
1625
+ * expression.
1626
+ */
1627
+ async ensureWatched(options?: ChannelGetOrCreateRequest): Promise<Channel> {
1628
+ if (this.supersededBy) return this.supersededBy.ensureWatched(options);
1629
+ if (this.watchStatus === ChannelWatchStatus.Watching) return this;
1630
+ const requested = options ?? {};
1631
+ // deep equality, as for query shapes: key order doesn't matter
1632
+ if (
1633
+ this._ensureWatchedInFlight &&
1634
+ isEqual(this._ensureWatchedInFlight.options, requested)
1635
+ ) {
1636
+ await this._ensureWatchedInFlight.promise;
1637
+ return this.afterEnsuredWatch(options);
1638
+ }
1639
+ const promise = this.watch(options);
1640
+ this._ensureWatchedInFlight = { options: requested, promise };
1641
+ try {
1642
+ await promise;
1643
+ } finally {
1644
+ if (this._ensureWatchedInFlight?.promise === promise)
1645
+ this._ensureWatchedInFlight = undefined;
1646
+ }
1647
+ return this.afterEnsuredWatch(options);
1648
+ }
1649
+
1650
+ /** This instance, or its successor if the watch just superseded it (see `ensureWatched`). */
1651
+ private afterEnsuredWatch(options?: ChannelGetOrCreateRequest) {
1652
+ return this.supersededBy ? this.supersededBy.ensureWatched(options) : this;
1263
1653
  }
1264
1654
 
1265
1655
  /**
1266
1656
  * Loads the initial channel state and watches for changes.
1267
1657
  *
1268
1658
  * @param options - Additional options for the query endpoint (optional).
1659
+ * @param requestOptions - Per-request options such as an abort `signal` (optional). The signal
1660
+ * reaches the wait for a live socket as well as the request, so abandoning the call abandons the
1661
+ * wait with it.
1269
1662
  * @returns The server response.
1270
1663
  */
1271
- async watch(options?: ChannelGetOrCreateRequest) {
1664
+ async watch(
1665
+ options?: ChannelGetOrCreateRequest,
1666
+ requestOptions?: StreamRequestOptions,
1667
+ ) {
1272
1668
  const defaultOptions = {
1273
1669
  state: true,
1274
1670
  watch: true,
1275
1671
  presence: false,
1276
1672
  };
1277
1673
 
1278
- // Make sure we wait for the connect promise if there is a pending one
1279
- await this.getClient().wsPromise;
1280
-
1281
- if (!this.getClient()._hasConnectionID()) {
1282
- defaultOptions.watch = false;
1283
- }
1284
-
1285
1674
  const combined = { ...defaultOptions, ...options };
1286
- const state = await this.query(combined, 'latest');
1287
- this.initialized = true;
1288
- const previousData = this.data;
1675
+
1676
+ // No wait here. `ApiClient` holds any request that watches or subscribes to presence until the
1677
+ // handshake has produced a connection id, so `watch: true` always binds to a current one and
1678
+ // `watchStatus = Watching` is truthful by construction — while a call asking for neither goes out
1679
+ // with no socket at all.
1680
+ const state = await this.query(combined, 'latest', requestOptions);
1289
1681
  this.data = state.channel;
1290
- this._syncStateFromChannelData(this.data, previousData);
1291
1682
 
1292
1683
  // The message paginator is seeded synchronously inside query() (before read-state hydration),
1293
1684
  // so a channel opened via watch() alone — a deep-link restore, a search result, a freshly
@@ -1298,84 +1689,105 @@ export class Channel extends ChannelApi {
1298
1689
  }
1299
1690
 
1300
1691
  /**
1301
- * Stops watching the channel.
1692
+ * Re-watch the channel and refresh its FULL loaded message window — the channel analog of
1693
+ * {@link Thread.reload}. Used on reconnect to catch up AND reconcile hard deletes that happened
1694
+ * while offline: a hard delete reaches other clients via no event, so an offline client only learns
1695
+ * of it by diffing the re-queried page.
1302
1696
  *
1303
- * @param request - The stop-watching request payload (optional).
1304
- * @returns The server response.
1697
+ * This is intentionally thin: it only re-issues `watch()` with a limit sized to the loaded window
1698
+ * (`items.length`, so the whole loaded window is refreshed — not the smaller channel-list page). The
1699
+ * actual fold + destructive reconciliation happens inside `query()` → `seedFirstPageSync`
1700
+ * (the same path the channel-list re-hydrate and connection recovery use), driven by the loaded-id
1701
+ * snapshot `query()` captures before its await. Owning that single path is what lets the SDK stop
1702
+ * passing the reconciliation window/snapshot itself.
1703
+ *
1704
+ * Preserves failed (unsent) messages: an overlap merge keeps them (the reconcile's provenance guard
1705
+ * never prunes a non-server message); only a disjoint rebuild can drop them, so any that actually
1706
+ * fell out are re-ingested below. The offline DB is consulted alongside the in-memory window, because
1707
+ * a failed message can be absent from memory and still be the user's unsent work — a cold boot starts
1708
+ * with an empty paginator, and an eviction can drop it mid-session. v9 got this from a second, lagging
1709
+ * copy of the list (the React SDK's own state); with one reactive source of truth the persisted row is
1710
+ * that buffer.
1305
1711
  */
1306
- override async stopWatching(request?: Gen_ChannelStopWatchingRequest) {
1307
- const response = await super.stopWatching(request);
1308
-
1309
- logger.withExtraTags('stopWatching', this.cid).info('Stopped watching the channel.');
1310
-
1311
- return response;
1712
+ async reload() {
1713
+ if (this._reloading || (!this.initialized && !this.offlineMode)) return;
1714
+ this._reloading = true;
1715
+ try {
1716
+ const paginator = this.messagePaginator;
1717
+ const headItems = paginator.headItems;
1718
+ const requestedLimit =
1719
+ Math.max(headItems.length, paginator.pageSize ?? 0) || undefined;
1720
+ const offlineDb = this.getClient().offlineDb;
1721
+ const failedInMemory = headItems.filter((message) => message.status === 'failed');
1722
+ // Read before the await, so this cannot pick up a message that failed DURING the reload — that
1723
+ // one is already in the paginator and does not need re-ingesting.
1724
+ const failedInDb = offlineDb
1725
+ ? await offlineDb.getFailedMessages({ cid: this.cid })
1726
+ : [];
1727
+ const failedById = new Map<string, LocalMessage>();
1728
+ for (const message of [...failedInDb, ...failedInMemory]) {
1729
+ // In-memory wins on a collision: it is at least as fresh as the row it was mirrored from.
1730
+ failedById.set(message.id, message);
1731
+ }
1732
+ const failedBefore = [...failedById.values()];
1733
+
1734
+ await this.watch({ messages: { limit: requestedLimit } });
1735
+ this.offlineMode = false;
1736
+
1737
+ if (failedBefore.length) {
1738
+ // Make sure the messages that failed to be sent before the watch() request are
1739
+ // reingested after the watch() query.
1740
+ const visible = new Set((paginator.items ?? []).map((message) => message.id));
1741
+ paginator.batch(
1742
+ () => {
1743
+ for (const failed of failedBefore) {
1744
+ if (!visible.has(failed.id)) paginator.ingestItem(failed);
1745
+ }
1746
+ },
1747
+ { coalesce: true },
1748
+ );
1749
+ }
1750
+ } finally {
1751
+ this._reloading = false;
1752
+ }
1312
1753
  }
1313
1754
 
1314
1755
  /**
1315
- * List the message replies for a parent message.
1316
- *
1317
- * The recommended way of working with threads is to use the `Thread` class.
1756
+ * Stops watching the channel.
1318
1757
  *
1319
- * @param request - The get-replies request payload, including the parent message ID, pagination
1320
- * params, and optional sort directions for `created_at`.
1321
- * @returns A response with a list of messages.
1758
+ * @param ...args - `[request, requestOptions]`. `request` is the stop-watching payload;
1759
+ * `requestOptions` carries per-request options such as an abort `signal` and is never
1760
+ * serialized into the request.
1761
+ * @returns The server response.
1322
1762
  */
1323
- async getReplies(request: GetRepliesRequest) {
1324
- const data = await this.getClient().getReplies(request);
1763
+ override async stopWatching(...args: Parameters<ChannelApi['stopWatching']>) {
1764
+ const response = await super.stopWatching(...args);
1325
1765
 
1326
- // Thread reply state is owned by the Thread object (Thread.messagePaginator); the returned
1327
- // replies are consumed there. The channel message list is owned by channel.messagePaginator.
1328
- return data;
1329
- }
1766
+ // Deliberate: unlike a connection loss this must NOT be restored on reconnect.
1767
+ this.watchStatus = ChannelWatchStatus.NotWatching;
1330
1768
 
1331
- // TODO: find out v2 equivalent
1332
- /**
1333
- * List pinned messages of the channel.
1334
- *
1335
- * @param options - Pagination params, e.g. `{ limit: 10, id_lte: 10 }`.
1336
- * @param sort - Defines sorting direction of pinned messages (optional, defaults to `[]`).
1337
- * @returns A response with a list of messages.
1338
- */
1339
- async getPinnedMessages(
1340
- options: PinnedMessagePaginationOptions,
1341
- sort: PinnedMessagesSort = [],
1342
- ) {
1343
- return await this.getClient().api.get<GetRepliesAPIResponse>(
1344
- this._channelURL() + '/pinned_messages',
1345
- {
1346
- payload: {
1347
- ...options,
1348
- sort,
1349
- },
1350
- },
1351
- );
1352
- }
1769
+ logger.withExtraTags('stopWatching', this.cid).info('Stopped watching the channel.');
1353
1770
 
1354
- /**
1355
- * List the reactions; supports pagination.
1356
- *
1357
- * @param request - The request payload, including the target message ID and
1358
- * pagination options (`limit`, `offset`).
1359
- * @returns The server response.
1360
- */
1361
- getReactions(request: Parameters<ChatApi['getReactions']>[0]) {
1362
- return this.getClient().getReactions(request);
1771
+ return response;
1363
1772
  }
1364
1773
 
1365
1774
  /**
1366
1775
  * Retrieves a list of messages by ID.
1367
1776
  *
1368
1777
  * @param messageIds - The IDs of the messages to retrieve from this channel.
1778
+ * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
1779
+ * into the request (optional).
1369
1780
  * @returns Server response.
1370
1781
  */
1371
- getMessagesById(messageIds: string[]) {
1372
- return this.getManyMessages({ ids: messageIds });
1782
+ getMessagesById(messageIds: string[], requestOptions?: StreamRequestOptions) {
1783
+ return this.getManyMessages({ ids: messageIds }, requestOptions);
1373
1784
  }
1374
1785
 
1375
1786
  /**
1376
1787
  * Returns the last time the user marked the channel as read. If the user never marked the channel as read, this will return `null`.
1377
1788
  *
1378
- * @returns The last-read `Date`, `null` if never read, or `undefined` if the user is unset.
1789
+ * @returns The last-read timestamp in unix nanoseconds, `null` if never read, or `undefined` if
1790
+ * the user is unset.
1379
1791
  */
1380
1792
  lastRead() {
1381
1793
  const { userId } = this.getClient();
@@ -1392,19 +1804,15 @@ export class Channel extends ChannelApi {
1392
1804
  if (message.user?.id && this.getClient().userMuteStatus(message.user.id))
1393
1805
  return false;
1394
1806
 
1395
- // Return false if channel doesn't allow read events, unless the client opted into a local
1396
- // unread count (e.g. livestreams where read events are disabled). See `isLocalUnreadCountEnabled`.
1397
- if (
1398
- !this.getClient().options.isLocalUnreadCountEnabled &&
1399
- !channelHasReadEvents(this)
1400
- ) {
1807
+ // Return false if channel doesn't allow read events, unless the integrator opted into a local
1808
+ // unread count (e.g. livestreams where read events are disabled). See
1809
+ // `readEvents.localUnreadCountEnabled`.
1810
+ if (!this.config.readEvents.localUnreadCountEnabled && !channelHasReadEvents(this)) {
1401
1811
  return false;
1402
1812
  }
1403
1813
 
1404
1814
  // FIXME: see #1265, adjust and count new messages even when the channel is muted
1405
- // Read mute state directly from the client to avoid _checkInitialized() — this method
1406
- // is invoked from _handleChannelEvent (e.g. message.new) before .watch() resolves.
1407
- if (this.getClient()._muteStatus(this.cid).muted) return false;
1815
+ if (this.muteStatus().muted) return false;
1408
1816
 
1409
1817
  return true;
1410
1818
  }
@@ -1412,11 +1820,13 @@ export class Channel extends ChannelApi {
1412
1820
  /**
1413
1821
  * Count of unread messages.
1414
1822
  *
1415
- * @param lastRead - The time that the user read a message (optional, defaults to the current user's read state).
1823
+ * @param lastRead - The time that the user read a message, in unix nanoseconds (optional,
1824
+ * defaults to the current user's read state).
1416
1825
  * @returns Unread count.
1417
1826
  */
1418
- countUnread(lastRead?: Date | null) {
1419
- if (!lastRead) return this.state.unreadCount;
1827
+ countUnread(lastRead?: TimestampNS | null) {
1828
+ // Nullish, not truthy: `0` is a legitimate wire timestamp (the epoch).
1829
+ if (lastRead == null) return this.state.unreadCount;
1420
1830
  let count = 0;
1421
1831
  const latestMessages = this.messagePaginator.headItems;
1422
1832
  for (let i = 0; i < latestMessages.length; i += 1) {
@@ -1443,7 +1853,7 @@ export class Channel extends ChannelApi {
1443
1853
  const message = latestMessages[i];
1444
1854
  if (
1445
1855
  this._countMessageAsUnread(message) &&
1446
- (!lastRead || message.created_at > lastRead) &&
1856
+ (lastRead == null || message.created_at > lastRead) &&
1447
1857
  message.mentioned_users?.some((user) => user.id === userId)
1448
1858
  ) {
1449
1859
  count++;
@@ -1468,6 +1878,54 @@ export class Channel extends ChannelApi {
1468
1878
  return await this.query(defaultOptions, 'latest');
1469
1879
  };
1470
1880
 
1881
+ /**
1882
+ * Stores this channel, created without an id, under the cid the server gave it. It is stored under
1883
+ * `this.cid` until then: the temporary cid built from its members ({@link generateChannelTempCid}),
1884
+ * or nowhere for a channel with neither id nor members. The entry moves to the server's cid. When
1885
+ * another instance already holds that cid (stored by an event or a list while this one was in
1886
+ * flight), that instance stays the one stored, since something may be using it, and takes over
1887
+ * from this one ({@link ChannelManager.supersedeChannel}), which also drops this one's entry.
1888
+ */
1889
+ private storeUnderServerCid(
1890
+ response: ChannelStateResponseFields,
1891
+ { watch }: { watch?: boolean },
1892
+ ) {
1893
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1894
+ const serverCid = response.channel!.cid;
1895
+ const { channelManager } = this.getClient();
1896
+ const storedUnder = this.cid;
1897
+ this.cid = serverCid;
1898
+ const isStoredUnderOldCid =
1899
+ storedUnder !== serverCid && channelManager.get(storedUnder) === this;
1900
+ // A channel the app disconnected is done with: this instance takes its place rather than being
1901
+ // superseded by it, as `ensure()` would give a fresh instance for its cid.
1902
+ if (channelManager.get(serverCid)?.pendingDisposal) {
1903
+ channelManager.removeChannel(serverCid);
1904
+ }
1905
+ const stored = channelManager.get(serverCid);
1906
+
1907
+ if (!stored) {
1908
+ if (
1909
+ !isStoredUnderOldCid ||
1910
+ !channelManager.changeChannelId(storedUnder, serverCid)
1911
+ ) {
1912
+ channelManager.getOrCreateChannel(serverCid, () => this);
1913
+ }
1914
+ return;
1915
+ }
1916
+
1917
+ if (stored === this) return;
1918
+ logger
1919
+ .withExtraTags('query', serverCid)
1920
+ .warn(
1921
+ 'Another instance of this channel is stored and takes over from this one (see channel.supersededBy).',
1922
+ );
1923
+ channelManager.supersedeChannel(this, stored, response, {
1924
+ storedUnder: isStoredUnderOldCid ? storedUnder : undefined,
1925
+ watch,
1926
+ });
1927
+ }
1928
+
1471
1929
  /**
1472
1930
  * Queries the API to load messages, members, or other channel fields.
1473
1931
  *
@@ -1476,27 +1934,81 @@ export class Channel extends ChannelApi {
1476
1934
  * messages into state. Use `current` to load the initial channel state or to extend the
1477
1935
  * currently displayed messages; use `latest` to load/extend the latest messages; `new` is
1478
1936
  * used for loading a specific message and its surroundings (optional, defaults to `'current'`).
1937
+ * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
1938
+ * into the request (optional).
1479
1939
  * @returns A query response.
1480
1940
  */
1481
1941
  async query(
1482
1942
  options: ChannelGetOrCreateRequest = {},
1483
1943
  messageSetToAddToIfDoesNotExist: MessageSetType = 'current',
1944
+ requestOptions?: StreamRequestOptions,
1945
+ ) {
1946
+ // A disposed instance is done for good: its query would load it again and, for a watch, register
1947
+ // a watch whose events go to the instance now stored for the cid. Refused before it is sent.
1948
+ if (this.pendingDisposal) throw this.disposedError();
1949
+ // counted until the response is applied, watch status included, so the channel store keeps a
1950
+ // channel that is being loaded
1951
+ this._channelQueriesInFlight += 1;
1952
+ try {
1953
+ return await this.runQuery(
1954
+ options,
1955
+ messageSetToAddToIfDoesNotExist,
1956
+ requestOptions,
1957
+ );
1958
+ } finally {
1959
+ this._channelQueriesInFlight -= 1;
1960
+ }
1961
+ }
1962
+
1963
+ private async runQuery(
1964
+ options: ChannelGetOrCreateRequest,
1965
+ messageSetToAddToIfDoesNotExist: MessageSetType,
1966
+ requestOptions?: StreamRequestOptions,
1484
1967
  ) {
1485
- // Make sure we wait for the connect promise if there is a pending one
1486
- await this.getClient().wsPromise;
1968
+ // Snapshot the loaded message ids BEFORE the network await, for a latest-window (re)seed only.
1969
+ // When this query re-seeds an already-loaded window (reconnect / re-hydrate), seedFirstPageSync
1970
+ // reconciles the fresh page against what is loaded, and the snapshot lets it tell an offline
1971
+ // hard-delete (in the snapshot, absent from the page) from a message that arrives live
1972
+ // during the fetch (not in the snapshot). Captured here — the only place with the pre-await state —
1973
+ // so callers (channel.reload, watch) need not thread it. Empty on a cold open, so it is harmless.
1974
+ // TODO(perf/cleanup): `headItems` materializes full message objects (intervalToItems) just to map
1975
+ // them down to ids. A cheaper, clearer equivalent is a straight copy of the paginator index's own
1976
+ // id set — expose `memberIds` on StoreBackedItemIndex (e.g. `snapshotMembers()` returning
1977
+ // `new Set(this.memberIds)`) and use it here AND in client.queryChannelsAndHydrate. The broader
1978
+ // scope (all intervals vs just the head) is inert: the reconcile only consults head ids, older
1979
+ // island ids are never at/above-newest, and local messages are guarded by isServerConfirmedMessage.
1980
+ const candidateIds =
1981
+ messageSetToAddToIfDoesNotExist === 'latest'
1982
+ ? new Set(this.messagePaginator.headItems.map((message) => message.id))
1983
+ : undefined;
1984
+
1985
+ // The INITIAL channel-open query honors the paginator's OWN pageSize (light on native, 25) rather
1986
+ // than the server's larger default — opening loads the same page size it paginates by. A caller
1987
+ // that already knows how much to fetch passes an explicit messages.limit, which is respected as-is:
1988
+ // a reconnect/re-hydrate sizes it to the loaded window (channel.reload → items.length), and
1989
+ // pagination/around pass their own cursors + limit.
1990
+ const requestedPageSize = options?.messages?.limit ?? this.messagePaginator.pageSize;
1487
1991
 
1488
1992
  const queryPayload: ChannelGetOrCreateRequest = {
1489
1993
  data: this._data,
1490
1994
  state: true,
1491
1995
  ...options,
1996
+ // Ask the server for exactly the initial-open page size (not its default), so the loaded window
1997
+ // matches the paginator's pageSize. Explicit messages (reconnect/around/pagination) pass through.
1998
+ messages:
1999
+ options?.messages ??
2000
+ (messageSetToAddToIfDoesNotExist === 'latest'
2001
+ ? { limit: requestedPageSize }
2002
+ : undefined),
1492
2003
  };
1493
2004
 
1494
2005
  const state = this.id
1495
- ? await this.getOrCreate(queryPayload)
1496
- : await this.getClient().getOrCreateDistinctChannel({
1497
- type: this.type,
1498
- ...queryPayload,
1499
- });
2006
+ ? await this.getOrCreate(queryPayload, requestOptions)
2007
+ : await this.getClient().getOrCreateDistinctChannel(
2008
+ { type: this.type },
2009
+ queryPayload,
2010
+ requestOptions,
2011
+ );
1500
2012
 
1501
2013
  // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1502
2014
  const channel = state.channel!;
@@ -1504,36 +2016,20 @@ export class Channel extends ChannelApi {
1504
2016
  // update the channel id if it was missing
1505
2017
  if (!this.id) {
1506
2018
  this.id = channel.id;
1507
- this.cid = channel.cid;
1508
- // set the channel as active...
1509
-
1510
- const tempChannelCid = generateChannelTempCid(
1511
- this.type,
1512
- state.members.map((member) => member.user_id || member.user?.id || ''),
1513
- );
1514
-
1515
- if (tempChannelCid && tempChannelCid in this.getClient().activeChannels) {
1516
- // This gets set in `client.channel()` function, when channel is created
1517
- // using members, not id.
1518
- delete this.getClient().activeChannels[tempChannelCid];
1519
- }
1520
-
1521
- if (
1522
- !(this.cid in this.getClient().activeChannels) &&
1523
- this.getClient()._cacheEnabled()
1524
- ) {
1525
- this.getClient().activeChannels[this.cid] = this;
1526
- }
2019
+ this.storeUnderServerCid(state, { watch: queryPayload.watch });
1527
2020
  }
1528
2021
 
1529
2022
  this.getClient()._addChannelConfig(channel);
1530
2023
 
1531
- // the only config param that is necessary to be updated based on server config soon as the config is delivered
1532
- if (typeof channel.config?.shared_locations !== 'undefined') {
1533
- this.messageComposer.updateConfig({
1534
- location: { enabled: channel.config.shared_locations },
1535
- });
1536
- }
2024
+ // The composer derives part of its configuration from this channel's server-side config, which for
2025
+ // a channel opened via `client.channelManager.ensure({ type, id })` arrives only now — after the
2026
+ // composer was built. A composer with registered subscriptions hears about it through the store;
2027
+ // one without has no other route, so it is told here.
2028
+ //
2029
+ // Restrictions, not a request: passing the server's value to `updateConfig` would record a server
2030
+ // *permission* as something the client asked for, and so re-enable a feature an integrator had
2031
+ // deliberately turned off (**DV-18**).
2032
+ this.messageComposer.applyServerRestrictions();
1537
2033
 
1538
2034
  // Seed the message paginator with the first (latest) page BEFORE _initializeState, which
1539
2035
  // hydrates the read state and (via MessageReceiptsTracker) resolves read/delivered cursors
@@ -1542,8 +2038,6 @@ export class Channel extends ChannelApi {
1542
2038
  // latest-page open paths (watch/create) pass 'latest' — the paginator's own pagination queries
1543
2039
  // use 'current' and must not be reseeded as a first page here.
1544
2040
  if (messageSetToAddToIfDoesNotExist === 'latest' && Array.isArray(state.messages)) {
1545
- const requestedPageSize =
1546
- options?.messages?.limit ?? DEFAULT_QUERY_CHANNEL_MESSAGE_LIST_PAGE_SIZE;
1547
2041
  // Pass the query's message pagination options through: a channel can be opened AROUND a
1548
2042
  // message (id_around / created_at_around), in which case the fetched page is a jump window,
1549
2043
  // not the latest page — the paginator must reconcile it with jump semantics.
@@ -1551,16 +2045,29 @@ export class Channel extends ChannelApi {
1551
2045
  state.messages.map(formatMessage),
1552
2046
  requestedPageSize,
1553
2047
  options?.messages,
2048
+ // Re-seed of an already-loaded window folds + reconciles instead of blanking (see above).
2049
+ { candidateIds, reconcile: true },
1554
2050
  );
1555
2051
  }
1556
2052
 
2053
+ if (this.supersededBy) {
2054
+ // This response superseded the instance: events for the cid go to the stored instance, which
2055
+ // took over the watch (`supersedeChannel`), so this one receives none.
2056
+ this.watchStatus = ChannelWatchStatus.NotWatching;
2057
+ } else if (queryPayload.watch) {
2058
+ // The request carrying `watch: true` came back, so the server has registered this connection
2059
+ // as a watcher. Only ever set here because a `watch: false` query does NOT unwatch
2060
+ // server-side, so it must not clear the flag.
2061
+ this.watchStatus = ChannelWatchStatus.Watching;
2062
+ }
2063
+
1557
2064
  // Seed read/members/pinned/thread-cleanup state; the message list is in the paginator.
1558
2065
  this._initializeState(state);
1559
2066
  // The queried page is the latest set unless this was a jump/around query.
1560
2067
  const isLatestMessageSet =
1561
2068
  messageSetToAddToIfDoesNotExist === 'latest' &&
1562
2069
  !options?.messages?.id_around &&
1563
- !(options?.messages as MessagePaginationOptions | undefined)?.created_at_around;
2070
+ !(options?.messages as MessagePaginationParams | undefined)?.created_at_around;
1564
2071
 
1565
2072
  this.getClient().polls.hydratePollCache(state.messages, true);
1566
2073
  this.getClient().reminders.hydrateState(state.messages);
@@ -1576,11 +2083,10 @@ export class Channel extends ChannelApi {
1576
2083
  ]
1577
2084
  .sort()
1578
2085
  .join();
1579
- const previousData = this.data;
1580
2086
  this.data = channel;
1581
- this._syncStateFromChannelData(this.data, previousData);
1582
- this.offlineMode = false;
1583
- this.cooldownTimer.refresh();
2087
+ // A live response is applied, in one update before the events below, which the offline database
2088
+ // handles by reading it.
2089
+ this.state.partialNext({ initialized: true, offlineMode: false });
1584
2090
 
1585
2091
  if (areCapabilitiesChanged) {
1586
2092
  this.getClient().dispatchEvent({
@@ -1617,12 +2123,13 @@ export class Channel extends ChannelApi {
1617
2123
  * @param options - Ban options.
1618
2124
  * @returns The server response.
1619
2125
  */
1620
- async banUser(targetUserId: string, options: BanUserOptions) {
1621
- this._checkInitialized();
1622
- return await this.getClient().banUser(targetUserId, {
2126
+ async banUser(targetUserId: string, options: Omit<BanUserOptions, 'channel_cid'>) {
2127
+ this._checkHasId();
2128
+
2129
+ return await this.getClient().moderation.ban({
1623
2130
  ...options,
1624
- type: this.type,
1625
- id: this.id,
2131
+ target_user_id: targetUserId,
2132
+ channel_cid: this.cid,
1626
2133
  });
1627
2134
  }
1628
2135
 
@@ -1630,24 +2137,25 @@ export class Channel extends ChannelApi {
1630
2137
  * Hides the channel from `queryChannels` for the user until a message is added.
1631
2138
  * If `clear_history` is set to `true`, all messages will be removed for the user.
1632
2139
  *
1633
- * @param request - The hide channel request payload (optional). Pass `{ clear_history: true }`
1634
- * to clear message history for the user.
2140
+ * @param ...args - `[request, requestOptions]`. Pass `request: { clear_history: true }` to clear
2141
+ * message history for the user; `requestOptions` carries per-request options such as an abort
2142
+ * `signal` and is never serialized into the request.
1635
2143
  * @returns The server response.
1636
2144
  */
1637
- override async hide(request?: Gen_HideChannelRequest) {
1638
- this._checkInitialized();
1639
- return await super.hide(request);
2145
+ override async hide(...args: Parameters<ChannelApi['hide']>) {
2146
+ return await super.hide(...args);
1640
2147
  }
1641
2148
 
1642
2149
  /**
1643
2150
  * Removes the hidden status for a channel. Ensures the channel is initialized first.
1644
2151
  *
1645
- * @param request - The show channel request payload (optional).
2152
+ * @param ...args - `[request, requestOptions]`. `request` is the show-channel payload;
2153
+ * `requestOptions` carries per-request options such as an abort `signal` and is never
2154
+ * serialized into the request.
1646
2155
  * @returns The server response.
1647
2156
  */
1648
- override async show(request?: Gen_ShowChannelRequest) {
1649
- this._checkInitialized();
1650
- return await super.show(request);
2157
+ override async show(...args: Parameters<ChannelApi['show']>) {
2158
+ return await super.show(...args);
1651
2159
  }
1652
2160
 
1653
2161
  /**
@@ -1658,119 +2166,84 @@ export class Channel extends ChannelApi {
1658
2166
  * @returns The server response.
1659
2167
  */
1660
2168
  async unbanUser(targetUserId: string, options?: UnBanUserOptions) {
1661
- this._checkInitialized();
1662
- return await this.getClient().unbanUser(targetUserId, {
1663
- ...options,
1664
- type: this.type,
1665
- id: this.id,
1666
- });
1667
- }
2169
+ this._checkHasId();
1668
2170
 
1669
- /**
1670
- * Shadow bans a user from a channel.
1671
- *
1672
- * @param targetUserId - The user to shadow ban.
1673
- * @param options - Ban options.
1674
- * @returns The server response.
1675
- */
1676
- async shadowBan(targetUserId: string, options: BanUserOptions) {
1677
- this._checkInitialized();
1678
- return await this.getClient().shadowBan(targetUserId, {
2171
+ return await this.getClient().unbanUser(targetUserId, {
1679
2172
  ...options,
1680
2173
  type: this.type,
1681
2174
  id: this.id,
1682
2175
  });
1683
2176
  }
1684
2177
 
1685
- /**
1686
- * Removes the shadow ban for a user on a channel.
1687
- *
1688
- * @param targetUserId - The user to remove the shadow ban for.
1689
- * @returns The server response.
1690
- */
1691
- async removeShadowBan(targetUserId: string) {
1692
- this._checkInitialized();
1693
- return await this.getClient().removeShadowBan(targetUserId, {
1694
- type: this.type,
1695
- id: this.id,
1696
- });
1697
- }
1698
-
1699
2178
  /**
1700
2179
  * Casts or cancels one or more votes on a poll.
1701
2180
  *
1702
- * @param request - The cast-poll-vote request payload, including the target message ID, poll ID,
1703
- * and the vote to cast (or an empty payload to cancel).
2181
+ * @param ...args - `[pathParams, request, requestOptions]`. `pathParams` holds the target
2182
+ * `message_id` and `poll_id`; `request` holds the vote to cast (or an empty payload to cancel);
2183
+ * `requestOptions` carries per-request options such as an abort `signal` and is never
2184
+ * serialized into the request.
1704
2185
  * @returns The poll vote response.
1705
2186
  */
1706
- async vote(request: Parameters<ChatApi['castPollVote']>[0]) {
1707
- return await this.getClient().castPollVote(request);
2187
+ async vote(...args: Parameters<ChatApi['castPollVote']>) {
2188
+ this._checkHasId();
2189
+ return await this.getClient().castPollVote(...args);
1708
2190
  }
1709
2191
 
1710
- async removeVote(request: Parameters<ChatApi['deletePollVote']>[0]) {
1711
- return await this.getClient().deletePollVote(request);
2192
+ async removeVote(...args: Parameters<ChatApi['deletePollVote']>) {
2193
+ this._checkHasId();
2194
+ return await this.getClient().deletePollVote(...args);
1712
2195
  }
1713
2196
 
1714
- async _createDraft(request: Gen_CreateDraftRequest) {
1715
- return await super.createDraft(request);
2197
+ async _createDraft(...args: Parameters<ChannelApi['createDraft']>) {
2198
+ return await super.createDraft(...args);
1716
2199
  }
1717
2200
 
1718
2201
  /**
1719
2202
  * Creates or updates a draft message in a channel. If offline support is enabled, the
1720
2203
  * call is queued so it is replayed on reconnect.
1721
2204
  */
1722
- override async createDraft(request: Gen_CreateDraftRequest) {
1723
- try {
1724
- const offlineDb = this.getClient().offlineDb;
1725
- if (offlineDb) {
1726
- return (await offlineDb.queueTask<CreateDraftResponse>({
1727
- task: {
1728
- channelId: this.id as string,
1729
- channelType: this.type,
1730
- threadId: request.message?.parent_id,
1731
- payload: [request],
1732
- type: 'create-draft',
1733
- },
1734
- })) as Awaited<ReturnType<ChannelApi['createDraft']>>;
1735
- }
1736
- } catch (error) {
1737
- offlineDbLogger
1738
- .withExtraTags('createDraft', this.cid)
1739
- .error('Creating the draft in the offline database failed.', { error });
1740
- }
2205
+ override async createDraft(...args: Parameters<ChannelApi['createDraft']>) {
2206
+ this._checkHasId();
2207
+
2208
+ const [request] = args;
1741
2209
 
1742
- return this._createDraft(request);
2210
+ return await queueOrRun({
2211
+ channel: this,
2212
+ client: this.getClient(),
2213
+ task: {
2214
+ channelId: this.id,
2215
+ channelType: this.type,
2216
+ threadId: request.message?.parent_id,
2217
+ payload: args,
2218
+ type: 'create-draft',
2219
+ },
2220
+ });
1743
2221
  }
1744
2222
 
1745
- async _deleteDraft(request?: Parameters<ChannelApi['deleteDraft']>[0]) {
1746
- return await super.deleteDraft(request);
2223
+ async _deleteDraft(...args: Parameters<ChannelApi['deleteDraft']>) {
2224
+ return await super.deleteDraft(...args);
1747
2225
  }
1748
2226
 
1749
2227
  /**
1750
2228
  * Deletes a draft message from a channel or a thread. If offline support is enabled, the
1751
2229
  * call is queued so it is replayed on reconnect.
1752
2230
  */
1753
- override async deleteDraft(request?: Parameters<ChannelApi['deleteDraft']>[0]) {
1754
- try {
1755
- const offlineDb = this.getClient().offlineDb;
1756
- if (offlineDb) {
1757
- return (await offlineDb.queueTask<APIResponse>({
1758
- task: {
1759
- channelId: this.id as string,
1760
- channelType: this.type,
1761
- threadId: request?.parent_id,
1762
- payload: [request],
1763
- type: 'delete-draft',
1764
- },
1765
- })) as Awaited<ReturnType<ChannelApi['deleteDraft']>>;
1766
- }
1767
- } catch (error) {
1768
- offlineDbLogger
1769
- .withExtraTags('deleteDraft', this.cid)
1770
- .error('Deleting the draft from the offline database failed.', { error });
1771
- }
2231
+ override async deleteDraft(...args: Parameters<ChannelApi['deleteDraft']>) {
2232
+ this._checkHasId();
2233
+
2234
+ const [request] = args;
1772
2235
 
1773
- return this._deleteDraft(request);
2236
+ return await queueOrRun({
2237
+ channel: this,
2238
+ client: this.getClient(),
2239
+ task: {
2240
+ channelId: this.id,
2241
+ channelType: this.type,
2242
+ threadId: request?.parent_id,
2243
+ payload: args,
2244
+ type: 'delete-draft',
2245
+ },
2246
+ });
1774
2247
  }
1775
2248
 
1776
2249
  /**
@@ -1862,16 +2335,16 @@ export class Channel extends ChannelApi {
1862
2335
  let hasStateChanged = false;
1863
2336
  this.messageReceiptsTracker.setPendingReadStoreReconcileMeta(reconcileMeta);
1864
2337
 
1865
- this.state.readStore.next((currentReadStoreState) => {
1866
- const nextReadState = patch(currentReadStoreState.read);
2338
+ this.state.next((currentState) => {
2339
+ const nextReadState = patch(currentState.read);
1867
2340
 
1868
- if (nextReadState === currentReadStoreState.read) {
1869
- return currentReadStoreState;
2341
+ if (nextReadState === currentState.read) {
2342
+ return currentState;
1870
2343
  }
1871
2344
  hasStateChanged = true;
1872
2345
 
1873
2346
  return {
1874
- ...currentReadStoreState,
2347
+ ...currentState,
1875
2348
  read: nextReadState,
1876
2349
  };
1877
2350
  });
@@ -1905,6 +2378,34 @@ export class Channel extends ChannelApi {
1905
2378
  return nextUserReadState;
1906
2379
  }
1907
2380
 
2381
+ /**
2382
+ * Sets the current user's unread count. The count lives in exactly one place — the reactive
2383
+ * `read[userId].unread_messages`, which is what the unread badge reads and what
2384
+ * `state.unreadCount` derives from — so channel-wide resets (`channel.truncated`, "all channels
2385
+ * read") must route through here rather than writing a count of their own.
2386
+ */
2387
+ /** @returns whether the count actually changed, so callers can react only to the channels it did. */
2388
+ _setOwnUnreadCount(unreadCount: number): boolean {
2389
+ if (this.pendingDisposal) return false;
2390
+
2391
+ const userId = this.getClient().userId;
2392
+ if (!userId) return false;
2393
+
2394
+ const currentUserReadState = this.state.read[userId];
2395
+ // only reconcile an existing read entry; never fabricate one just to store a count
2396
+ if (!currentUserReadState || currentUserReadState.unread_messages === unreadCount) {
2397
+ return false;
2398
+ }
2399
+
2400
+ this._upsertReadState(
2401
+ userId,
2402
+ () => ({ ...currentUserReadState, unread_messages: unreadCount }),
2403
+ { changedUserIds: [userId] },
2404
+ );
2405
+
2406
+ return true;
2407
+ }
2408
+
1908
2409
  _handleChannelEvent(event: Event) {
1909
2410
  // eslint-disable-next-line @typescript-eslint/no-this-alias
1910
2411
  const channel = this;
@@ -1924,39 +2425,51 @@ export class Channel extends ChannelApi {
1924
2425
  channelState.removeTypingEvent(event.user.id);
1925
2426
  }
1926
2427
  break;
1927
- // `message.read_locally` is the client-only event dispatched by `markReadLocally()` when read
1928
- // events are disabled (e.g. livestreams with `isLocalUnreadCountEnabled`). It reuses the exact
1929
- // `message.read` state logic so the read-state update lives in one place — only the
1930
- // delivery-report network sync below is skipped for it.
2428
+ case 'ai_indicator.update':
2429
+ channelState.partialNext({
2430
+ aiState: (event.ai_state as AIState) ?? AIStates.Idle,
2431
+ });
2432
+ break;
2433
+ case 'ai_indicator.clear':
2434
+ channelState.partialNext({ aiState: AIStates.Idle });
2435
+ break;
2436
+ case 'ai_indicator.stop':
2437
+ channelState.partialNext({ aiState: AIStates.Stop });
2438
+ break;
2439
+ // `notification.mark_read` is the only read signal for a channel the user is not watching, since
2440
+ // `message.read` goes to watchers only. `message.read_locally` is the local stand-in when read
2441
+ // events are disabled (livestreams). Both reuse the `message.read` logic, minus its delivery sync.
2442
+ case 'notification.mark_read':
1931
2443
  case 'message.read_locally':
1932
2444
  case 'message.read':
1933
- if (event.user?.id && event.created_at) {
2445
+ if (
2446
+ event.user?.id &&
2447
+ event.created_at != null &&
2448
+ // A thread read says nothing about the channel, and is handled by the reactive
2449
+ // `thread` object instead. `notification.mark_read` announces one with `thread_id`,
2450
+ // `message.read` with the thread itself; reading the channel off either would reset
2451
+ // its unread count.
2452
+ !(event.type === 'notification.mark_read' && event.thread_id) &&
2453
+ !('thread' in event && event.thread)
2454
+ ) {
1934
2455
  const eventUser = event.user;
1935
- const readAtDate = new Date(event.created_at);
1936
- const toDate = (value?: string | Date) =>
1937
- value ? (value instanceof Date ? value : new Date(value)) : undefined;
2456
+ const readAt = event.created_at;
1938
2457
  const userReadState = this._upsertReadState(
1939
2458
  eventUser.id,
1940
2459
  (currentUserReadState) => {
1941
- const currentDeliveredAt = toDate(currentUserReadState?.last_delivered_at);
2460
+ const currentDeliveredAt = currentUserReadState?.last_delivered_at;
1942
2461
 
1943
2462
  return {
1944
2463
  // preserve delivery information already known for user
1945
2464
  ...currentUserReadState,
1946
- ...(currentUserReadState?.last_read
1947
- ? { last_read: toDate(currentUserReadState.last_read) }
1948
- : null),
1949
- ...(currentDeliveredAt
1950
- ? { last_delivered_at: currentDeliveredAt }
1951
- : null),
1952
- last_read: readAtDate,
2465
+ last_read: readAt,
1953
2466
  last_read_message_id: event.last_read_message_id,
1954
2467
  last_delivered_at:
1955
- !currentDeliveredAt || currentDeliveredAt < readAtDate
1956
- ? readAtDate
2468
+ !currentDeliveredAt || currentDeliveredAt < readAt
2469
+ ? readAt
1957
2470
  : currentDeliveredAt,
1958
2471
  last_delivered_message_id:
1959
- !currentDeliveredAt || currentDeliveredAt < readAtDate
2472
+ !currentDeliveredAt || currentDeliveredAt < readAt
1960
2473
  ? (event.last_read_message_id ??
1961
2474
  currentUserReadState?.last_delivered_message_id)
1962
2475
  : currentUserReadState?.last_delivered_message_id,
@@ -1973,7 +2486,6 @@ export class Channel extends ChannelApi {
1973
2486
  const isOwnEvent = event.user?.id === client.user?.id;
1974
2487
 
1975
2488
  if (isOwnEvent) {
1976
- channelState.unreadCount = 0;
1977
2489
  // Delivery reporting buffers a `markChannelsDelivered` network request; the local read
1978
2490
  // must not hit the backend, so only sync for the real server `message.read`.
1979
2491
  if (event.type === 'message.read') {
@@ -1984,24 +2496,29 @@ export class Channel extends ChannelApi {
1984
2496
  break;
1985
2497
  case 'message.delivered':
1986
2498
  // todo: update also on thread
1987
- if (event.user?.id && event.created_at) {
2499
+ if (event.user?.id && event.created_at != null) {
1988
2500
  const eventUser = event.user;
1989
2501
  const createdAt = event.created_at;
1990
- const toDate = (value?: string | Date) =>
1991
- value ? (value instanceof Date ? value : new Date(value)) : undefined;
1992
- const resolvedDeliveredAt = new Date(event.last_delivered_at ?? createdAt);
2502
+ // `last_delivered_at` is the one timestamp the spec still declares as a bare `type:
2503
+ // string` with no `format: date-time`, so it arrives as RFC3339 while `created_at` on the
2504
+ // very same event arrives as unix nanoseconds. Normalize it into the wire unit so the
2505
+ // comparisons below are unit-consistent; an absent or unparseable value falls back to
2506
+ // `created_at`, which is already in that unit.
2507
+ // TODO: report upstream — this field should be a `date-time` like every other timestamp.
2508
+ const parsedDeliveredAt = event.last_delivered_at
2509
+ ? Date.parse(event.last_delivered_at)
2510
+ : NaN;
2511
+ const resolvedDeliveredAt = Number.isFinite(parsedDeliveredAt)
2512
+ ? msToNs(parsedDeliveredAt)
2513
+ : createdAt;
1993
2514
  const userReadState = this._upsertReadState(
1994
2515
  eventUser.id,
1995
2516
  (currentUserReadState) => {
1996
- const currentDeliveredAt = toDate(currentUserReadState?.last_delivered_at);
1997
- const currentReadAt = toDate(currentUserReadState?.last_read);
2517
+ const currentDeliveredAt = currentUserReadState?.last_delivered_at;
2518
+ const currentReadAt = currentUserReadState?.last_read;
1998
2519
 
1999
2520
  return {
2000
2521
  ...currentUserReadState,
2001
- ...(currentReadAt ? { last_read: currentReadAt } : null),
2002
- ...(currentDeliveredAt
2003
- ? { last_delivered_at: currentDeliveredAt }
2004
- : null),
2005
2522
  last_delivered_at:
2006
2523
  currentDeliveredAt && currentDeliveredAt > resolvedDeliveredAt
2007
2524
  ? currentDeliveredAt
@@ -2012,7 +2529,7 @@ export class Channel extends ChannelApi {
2012
2529
  : event.last_delivered_message_id,
2013
2530
  user: eventUser,
2014
2531
  // delivery events can be received before read events
2015
- last_read: currentReadAt ?? new Date(createdAt),
2532
+ last_read: currentReadAt ?? createdAt,
2016
2533
  unread_messages: currentUserReadState?.unread_messages ?? 0,
2017
2534
  };
2018
2535
  },
@@ -2034,6 +2551,7 @@ export class Channel extends ChannelApi {
2034
2551
  case 'user.updated':
2035
2552
  if (event.user?.id) {
2036
2553
  channelState.watchers[event.user.id] = event.user;
2554
+ channel.getClient().state.updateUserReference(event.user, channel.cid);
2037
2555
  }
2038
2556
  break;
2039
2557
  case 'user.watching.stop':
@@ -2053,8 +2571,12 @@ export class Channel extends ChannelApi {
2053
2571
  this.messagePaginator.removeItem({ id: event.message.id });
2054
2572
  this.pinnedMessagesPaginator.removeItem({ id: event.message.id });
2055
2573
  } else {
2056
- this.messagePaginator.ingestItem(formattedMessage);
2057
- this.pinnedMessagesPaginator.ingestItem(formattedMessage);
2574
+ // A soft delete changes content only — it moves neither `created_at` nor `pinned`, so
2575
+ // no collection's membership or sort position changes. One id-addressed write
2576
+ // therefore reaches every holder through the store, where an `ingestItem` per
2577
+ // collection would make each of them re-emit its own window on top of the fan-out.
2578
+ const store = this.getClient().messageStore;
2579
+ if (store.has(event.message.id)) store.upsert(formattedMessage);
2058
2580
  }
2059
2581
  }
2060
2582
  this.messagePaginator.reflectQuotedMessageUpdate(formattedMessage);
@@ -2063,7 +2585,7 @@ export class Channel extends ChannelApi {
2063
2585
  break;
2064
2586
  case 'user.messages.deleted':
2065
2587
  if (event.user) {
2066
- const deletedAt = new Date(event.created_at ?? Date.now());
2588
+ const deletedAt = event.created_at ?? nowNs();
2067
2589
  const hardDelete = !!event.hard_delete;
2068
2590
  this.messagePaginator.applyMessageDeletionForUser({
2069
2591
  userId: event.user.id,
@@ -2089,29 +2611,38 @@ export class Channel extends ChannelApi {
2089
2611
  // ingestItem advances the paginator's tracked latest message (→ last_message_at). A
2090
2612
  // message that arrives while the viewer has scrolled to an older window lands in the
2091
2613
  // head interval, not the active one, so the view is preserved without an isUpToDate flag.
2092
- this.messagePaginator.ingestItem(formatMessage(event.message));
2614
+ const formattedMessage = formatMessage(event.message);
2615
+ this.messagePaginator.ingestItem(formattedMessage);
2093
2616
  // ingestItem auto-adds when pinned (matchesFilter { pinned: true }).
2094
- this.pinnedMessagesPaginator.ingestItem(formatMessage(event.message));
2617
+ this.pinnedMessagesPaginator.ingestItem(formattedMessage);
2095
2618
  }
2096
2619
 
2097
2620
  // do not increase the unread count - the back-end does not increase the count neither in the following cases:
2098
2621
  // 1. the message is mine
2099
2622
  // 2. the message is a thread reply from any user
2100
2623
  const preventUnreadCountUpdate = ownMessage || isThreadMessage;
2101
- if (ownMessage) {
2102
- this.cooldownTimer.refresh();
2103
- }
2104
2624
  if (preventUnreadCountUpdate) break;
2105
2625
 
2626
+ // The own unread count IS `read[ownUserId].unread_messages` (see
2627
+ // `ChannelState.unreadCount`), so the own row is what carries the own-unread gating: a
2628
+ // message that does not count as unread (silent/shadowed/muted) never bumps it, and neither
2629
+ // does one arriving while the user is viewing the latest messages — the SDK is about to mark
2630
+ // it read itself, and the count/snapshot would flash until it does. The other users' rows
2631
+ // are receipt bookkeeping and keep their blanket bump.
2632
+ const countsAsOwnUnread =
2633
+ !this.messagePaginator.isViewingLive &&
2634
+ this._countMessageAsUnread(event.message);
2635
+
2106
2636
  if (event.user?.id) {
2107
2637
  const eventUser = event.user;
2108
2638
  const eventUserId = eventUser.id;
2109
- const createdAt = new Date(event.created_at ?? Date.now());
2639
+ const createdAt = event.created_at ?? nowNs();
2110
2640
  const eventMessageId = event.message.id;
2641
+ const ownUserId = client.userId;
2111
2642
  this._patchReadState(
2112
2643
  (currentReadState) => {
2113
2644
  const userIds = Object.keys(currentReadState);
2114
- if (!userIds.length) return currentReadState;
2645
+ if (!userIds.length && !countsAsOwnUnread) return currentReadState;
2115
2646
 
2116
2647
  const nextReadState = { ...currentReadState };
2117
2648
 
@@ -2124,6 +2655,9 @@ export class Channel extends ChannelApi {
2124
2655
  last_delivered_at: createdAt,
2125
2656
  last_delivered_message_id: eventMessageId,
2126
2657
  };
2658
+ } else if (userId === ownUserId && !countsAsOwnUnread) {
2659
+ // does not count towards the own unread count — leave the row untouched
2660
+ continue;
2127
2661
  } else {
2128
2662
  nextReadState[userId] = {
2129
2663
  ...currentReadState[userId],
@@ -2133,22 +2667,26 @@ export class Channel extends ChannelApi {
2133
2667
  }
2134
2668
  }
2135
2669
 
2670
+ // Seed the own row when the channel has none yet — an uninitialized channel (see
2671
+ // regression #1732) or one queried with `state: false`, where `_initializeState`
2672
+ // never ran to seed it. Without this the own count has nowhere to live and stops
2673
+ // accumulating. `last_read` is epoch: nothing has been read, which is exactly how
2674
+ // every "no last read" consumer already treats a missing value.
2675
+ if (ownUserId && countsAsOwnUnread && !currentReadState[ownUserId]) {
2676
+ nextReadState[ownUserId] = {
2677
+ last_read: asTimestampNS(0),
2678
+ unread_messages: 1,
2679
+ user: (client.user ?? { id: ownUserId }) as UserResponse,
2680
+ };
2681
+ }
2682
+
2136
2683
  return nextReadState;
2137
2684
  },
2138
2685
  { changedUserIds: Object.keys(channelState.read) },
2139
2686
  );
2140
2687
  }
2141
2688
 
2142
- // Skip the own-unread bump when the user is actively viewing the latest messages (app
2143
- // foregrounded + newest message on screen). Without this, a message read in real time
2144
- // momentarily bumps `unreadCount`/the snapshot — the "N new" separator/banner + the
2145
- // channel-list badge would flash until the SDK's mark-read resets it. The SDK reports the
2146
- // viewing state via `messagePaginator.setViewingLive` and marks the message read itself.
2147
- // Only the OWN unread accounting is gated; the per-user read/receipt tracking above is
2148
- // intentionally left intact.
2149
- const isViewingLive = this.messagePaginator.isViewingLive;
2150
- if (!isViewingLive && this._countMessageAsUnread(event.message)) {
2151
- channelState.unreadCount = channelState.unreadCount + 1;
2689
+ if (countsAsOwnUnread) {
2152
2690
  this.messagePaginator.setUnreadSnapshot({
2153
2691
  unreadCount: channelState.unreadCount,
2154
2692
  });
@@ -2171,31 +2709,32 @@ export class Channel extends ChannelApi {
2171
2709
  }
2172
2710
  }
2173
2711
  break;
2174
- case 'channel.truncated':
2175
- if (event.channel?.truncated_at) {
2176
- const truncatedAtDate = new Date(event.channel.truncated_at);
2177
-
2178
- channelState.unreadCount = this.countUnread(truncatedAtDate);
2712
+ case 'channel.truncated': {
2713
+ const truncatedAt = event.channel?.truncated_at;
2714
+ if (truncatedAt != null) {
2715
+ this._setOwnUnreadCount(this.countUnread(truncatedAt));
2179
2716
  // Partial truncation: keep messages newer than the cutoff. clearStateAndCache would wipe
2180
2717
  // the whole paginator (readers now source from it), so use the partial truncate. The
2181
2718
  // channel-wide read/unread context is reset by the truncation, so drop the unread snapshot
2182
2719
  // too (clearStateAndCache did this for the full-truncate branch).
2183
- this.messagePaginator.truncate({ truncatedAt: truncatedAtDate });
2720
+ this.messagePaginator.truncate({ truncatedAt });
2184
2721
  this.messagePaginator.clearUnreadSnapshot();
2185
- this.pinnedMessagesPaginator.truncate({ truncatedAt: truncatedAtDate });
2722
+ this.pinnedMessagesPaginator.truncate({ truncatedAt });
2186
2723
  } else {
2187
- channelState.unreadCount = 0;
2724
+ this._setOwnUnreadCount(0);
2188
2725
  this.messagePaginator.clearStateAndCache();
2189
2726
  this.pinnedMessagesPaginator.clearStateAndCache();
2190
2727
  }
2191
2728
 
2192
2729
  // system messages don't increment unread counts
2193
2730
  if (event.message) {
2194
- this.messagePaginator.ingestItem(formatMessage(event.message));
2195
- this.pinnedMessagesPaginator.ingestItem(formatMessage(event.message));
2731
+ const formattedMessage = formatMessage(event.message);
2732
+ this.messagePaginator.ingestItem(formattedMessage);
2733
+ this.pinnedMessagesPaginator.ingestItem(formattedMessage);
2196
2734
  }
2197
2735
 
2198
2736
  break;
2737
+ }
2199
2738
  case 'member.added':
2200
2739
  case 'member.updated': {
2201
2740
  const memberCopy: ChannelMemberResponse = {
@@ -2215,6 +2754,7 @@ export class Channel extends ChannelApi {
2215
2754
  ...channelState.members,
2216
2755
  [memberCopy.user.id]: memberCopy,
2217
2756
  };
2757
+ channel.getClient().state.updateUserReference(memberCopy.user, channel.cid);
2218
2758
  }
2219
2759
 
2220
2760
  const currentUserId = this.getClient().userId;
@@ -2242,7 +2782,7 @@ export class Channel extends ChannelApi {
2242
2782
  break;
2243
2783
  case 'notification.mark_unread': {
2244
2784
  const ownMessage = event.user?.id === this.getClient().user?.id;
2245
- if (!ownMessage || !event.user || !event.last_read_at) break;
2785
+ if (!ownMessage || !event.user || event.last_read_at == null) break;
2246
2786
  const eventUser = event.user;
2247
2787
  const lastReadAt = event.last_read_at;
2248
2788
  const unreadCount = event.unread_messages ?? 0;
@@ -2252,7 +2792,7 @@ export class Channel extends ChannelApi {
2252
2792
  // keep the message delivery info
2253
2793
  ...currentUserReadState,
2254
2794
  first_unread_message_id: event.first_unread_message_id,
2255
- last_read: new Date(lastReadAt),
2795
+ last_read: lastReadAt,
2256
2796
  last_read_message_id: event.last_read_message_id,
2257
2797
  user: eventUser,
2258
2798
  unread_messages: unreadCount,
@@ -2267,8 +2807,6 @@ export class Channel extends ChannelApi {
2267
2807
  lastReadMessageId: channelState.read[event.user.id].last_read_message_id,
2268
2808
  unreadCount,
2269
2809
  });
2270
-
2271
- channelState.unreadCount = unreadCount;
2272
2810
  break;
2273
2811
  }
2274
2812
  case 'channel.updated':
@@ -2279,7 +2817,6 @@ export class Channel extends ChannelApi {
2279
2817
  if (isFrozenChanged) {
2280
2818
  this.query({ state: false, messages: { limit: 0 }, watchers: { limit: 0 } });
2281
2819
  }
2282
- const previousChannelData = channel.data;
2283
2820
  const newChannelData = {
2284
2821
  ...event.channel,
2285
2822
  hidden: event.channel?.hidden ?? channel.data?.hidden,
@@ -2288,71 +2825,28 @@ export class Channel extends ChannelApi {
2288
2825
  event.channel?.own_capabilities ?? channel.data?.own_capabilities,
2289
2826
  };
2290
2827
  channel.data = newChannelData;
2291
- channel._syncStateFromChannelData(channel.data, previousChannelData);
2292
- this.cooldownTimer.refresh();
2293
2828
  }
2294
2829
  break;
2295
2830
  case 'reaction.new':
2296
- if (event.message && event.reaction) {
2297
- const { reaction } = event;
2298
- // Reflect main messages AND show_in_channel replies (both live in these paginators);
2299
- // pure replies are handled by the thread's own reaction subscription.
2300
- if (!event.message?.parent_id || event.message.show_in_channel) {
2301
- this.messagePaginator.reflectReaction({ message: event.message, reaction });
2302
- this.pinnedMessagesPaginator.reflectReaction({
2303
- message: event.message,
2304
- reaction,
2305
- });
2306
- }
2307
- }
2308
- break;
2309
- case 'reaction.deleted':
2310
- if (event.message && event.reaction) {
2311
- const { reaction } = event;
2312
- if (
2313
- event.message &&
2314
- (!event.message.parent_id || event.message.show_in_channel)
2315
- ) {
2316
- this.messagePaginator.reflectReaction({
2317
- message: event.message,
2318
- reaction,
2319
- removed: true,
2320
- });
2321
- this.pinnedMessagesPaginator.reflectReaction({
2322
- message: event.message,
2323
- reaction,
2324
- removed: true,
2325
- });
2326
- }
2327
- }
2328
- break;
2329
2831
  case 'reaction.updated':
2832
+ case 'reaction.deleted':
2330
2833
  if (event.message && event.reaction) {
2331
- const { reaction } = event;
2332
- // assuming reaction.updated is only called if enforce_unique is true
2333
- if (!event.message?.parent_id || event.message.show_in_channel) {
2334
- this.messagePaginator.reflectReaction({
2335
- enforceUnique: true,
2336
- message: event.message,
2337
- reaction,
2338
- });
2339
- this.pinnedMessagesPaginator.reflectReaction({
2340
- enforceUnique: true,
2341
- message: event.message,
2342
- reaction,
2343
- });
2344
- }
2834
+ reflectReactionEvent(this.getClient(), {
2835
+ // reaction.updated is only sent when enforce_unique is set
2836
+ enforceUnique: event.type === 'reaction.updated',
2837
+ message: event.message,
2838
+ reaction: event.reaction,
2839
+ removed: event.type === 'reaction.deleted',
2840
+ });
2345
2841
  }
2346
2842
  break;
2347
2843
  case 'channel.hidden': {
2348
- const previousChannelData = channel.data;
2349
2844
  channel.data = {
2350
2845
  // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2351
2846
  ...channel.data!,
2352
2847
  blocked: event.channel?.blocked ?? false,
2353
2848
  hidden: true,
2354
2849
  };
2355
- channel._syncStateFromChannelData(channel.data, previousChannelData);
2356
2850
  if (event.clear_history) {
2357
2851
  this.messagePaginator.clearStateAndCache();
2358
2852
  this.pinnedMessagesPaginator.clearStateAndCache();
@@ -2360,14 +2854,12 @@ export class Channel extends ChannelApi {
2360
2854
  break;
2361
2855
  }
2362
2856
  case 'channel.visible': {
2363
- const previousChannelData = channel.data;
2364
2857
  channel.data = {
2365
2858
  // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2366
2859
  ...channel.data!,
2367
2860
  blocked: event.channel?.blocked ?? false,
2368
2861
  hidden: false,
2369
2862
  };
2370
- channel._syncStateFromChannelData(channel.data, previousChannelData);
2371
2863
  this.getClient().offlineDb?.handleChannelVisibilityEvent({ event });
2372
2864
  break;
2373
2865
  }
@@ -2400,28 +2892,36 @@ export class Channel extends ChannelApi {
2400
2892
  }
2401
2893
 
2402
2894
  _callChannelListeners = (event: WSEvent) => {
2403
- const allSet = this.listeners.get('all');
2404
- const targetSet = this.listeners.get(event.type);
2405
-
2406
- [allSet, targetSet].forEach((set) =>
2407
- set?.forEach((handleEvent) => handleEvent(event)),
2408
- );
2895
+ // Snapshot before dispatching: `on` adds to these sets in place and `Set.forEach` visits
2896
+ // entries appended mid-iteration, so a listener that subscribes while handling an event
2897
+ // must not be invoked for it.
2898
+ const listeners = [
2899
+ ...(this.listeners.get('all') ?? []),
2900
+ ...(this.listeners.get(event.type) ?? []),
2901
+ ];
2902
+
2903
+ for (const listener of listeners) {
2904
+ invokeEventListener(listener, event, logger);
2905
+ }
2409
2906
  };
2410
2907
 
2411
2908
  /**
2412
- * Returns the channel url.
2909
+ * Asserts that the channel has an id. Throws an error if not (happens when we init channel with members only and not id).
2910
+ * Call this before calling any API method reading this.id or this.cid directly
2413
2911
  *
2414
- * @returns The channel url.
2912
+ * Note: only id is optional, cid is defined as string, so TS won't complain about a missing check there.
2415
2913
  */
2416
- _channelURL = () => {
2914
+ _checkHasId(): asserts this is this & { id: string } {
2417
2915
  if (!this.id) {
2418
- throw new Error('channel id is not defined');
2916
+ throw new Error(
2917
+ `Channel isn't yet created, call getOrCreateDistinctChannel() before this operation`,
2918
+ );
2419
2919
  }
2420
- return `${this.getClient().baseURL}/channels/${encodeURIComponent(
2421
- this.type,
2422
- )}/${encodeURIComponent(this.id)}`;
2423
- };
2920
+ }
2424
2921
 
2922
+ /**
2923
+ * Checks if channel has been queried/initialized. Call this when a method relies on data only available after channel is queried from API.
2924
+ */
2425
2925
  _checkInitialized() {
2426
2926
  if (!this.initialized && !this.offlineMode) {
2427
2927
  throw Error(
@@ -2430,34 +2930,24 @@ export class Channel extends ChannelApi {
2430
2930
  }
2431
2931
  }
2432
2932
 
2433
- _syncStateFromChannelData(
2434
- data: Channel['data'],
2435
- fallbackData: Channel['data'] = this.data,
2436
- ) {
2437
- this.state.syncOwnCapabilitiesFromChannelData(data, fallbackData);
2438
- this.state.syncMemberCountFromChannelData(data, fallbackData);
2439
- }
2440
-
2441
2933
  _initializeState(state: ChannelStateResponseFields) {
2442
2934
  const { state: clientState, user, userID } = this.getClient();
2443
2935
 
2444
2936
  // add the members and users
2445
2937
  if (state.members) {
2446
2938
  this._hydrateMembers({ members: state.members });
2447
-
2448
- for (const member of state.members) {
2449
- if (member.user) {
2450
- clientState.updateUserReference(member.user, this.cid);
2451
- }
2452
- }
2453
2939
  }
2454
2940
 
2455
2941
  if (state.membership) {
2456
2942
  this.state.membership = state.membership;
2943
+ // the members page of a large channel may leave out the current user, so register them here
2944
+ if (state.membership.user) {
2945
+ clientState.updateUserReference(state.membership.user, this.cid);
2946
+ }
2457
2947
  }
2458
2948
 
2459
2949
  // Seed the message paginator's `lastMessageAt` aggregate from the server's authoritative
2460
- // `last_message_at`. The first-page seed (Channel.query / client.hydrateActiveChannels) also
2950
+ // `last_message_at`. The first-page seed (Channel.query / client.hydrateChannels) also
2461
2951
  // advances it from ingested messages; both feed the same monotonic max, so this additionally
2462
2952
  // covers the path where the paginator seed is skipped (an already-loaded channel the viewer has
2463
2953
  // jumped away from, where re-seeding would clobber their window).
@@ -2489,7 +2979,7 @@ export class Channel extends ChannelApi {
2489
2979
  // that everything up to this point is not marked as unread
2490
2980
  const readUpdates: ChannelState['read'] = {};
2491
2981
  if (userID != null) {
2492
- const last_read = this.messagePaginator.lastMessageAt || new Date();
2982
+ const last_read = this.messagePaginator.lastMessageAt ?? nowNs();
2493
2983
  if (user) {
2494
2984
  readUpdates[user.id] = {
2495
2985
  user: user as UserResponse,
@@ -2503,19 +2993,13 @@ export class Channel extends ChannelApi {
2503
2993
  if (state.read) {
2504
2994
  for (const read of state.read) {
2505
2995
  readUpdates[read.user.id] = {
2506
- last_delivered_at: read.last_delivered_at
2507
- ? new Date(read.last_delivered_at)
2508
- : undefined,
2996
+ last_delivered_at: read.last_delivered_at ?? undefined,
2509
2997
  last_delivered_message_id: read.last_delivered_message_id,
2510
- last_read: new Date(read.last_read),
2998
+ last_read: read.last_read,
2511
2999
  last_read_message_id: read.last_read_message_id,
2512
3000
  unread_messages: read.unread_messages ?? 0,
2513
3001
  user: read.user,
2514
3002
  };
2515
-
2516
- if (read.user.id === user?.id) {
2517
- this.state.unreadCount = readUpdates[read.user.id].unread_messages;
2518
- }
2519
3003
  }
2520
3004
  }
2521
3005
 
@@ -2567,10 +3051,13 @@ export class Channel extends ChannelApi {
2567
3051
  */
2568
3052
  overrideCurrentState?: boolean;
2569
3053
  }) {
3054
+ const clientState = this.getClient().state;
2570
3055
  const newMembersById = members.reduce<ChannelState['members']>(
2571
3056
  (membersById, member) => {
2572
3057
  if (member.user) {
2573
3058
  membersById[member.user.id] = member;
3059
+ // lets `user.updated` and `user.presence.changed` reach this member
3060
+ clientState.updateUserReference(member.user, this.cid);
2574
3061
  }
2575
3062
  return membersById;
2576
3063
  },
@@ -2587,16 +3074,52 @@ export class Channel extends ChannelApi {
2587
3074
  }
2588
3075
  }
2589
3076
 
2590
- _disconnect() {
2591
- logger.withExtraTags('_disconnect', this.cid).info('Disconnecting the channel.');
3077
+ /**
3078
+ * Stops the instance for good and marks it for disposal: it unsubscribes from the client's
3079
+ * configuration and the server config, stops the receipts tracker and the cooldown timer, disposes
3080
+ * the message and pinned-message paginators (which unlinks them from the shared message store), and
3081
+ * then sets `pendingDisposal: true` and `watchStatus: NotWatching`. It sends no request, so the
3082
+ * server keeps a watch this connection held until the connection ends. Calling it again does
3083
+ * nothing, and nothing revives the instance.
3084
+ *
3085
+ * The SDK calls it when a channel ends: deleted, the current user removed from it, the user
3086
+ * logged out, or released as unused. Call it yourself to finish an instance you are done with.
3087
+ *
3088
+ * It doesn't remove the channel from the channel store, as parts of the app may still use the
3089
+ * instance: a stored instance stays there, and in the lists showing it, finished, until the next
3090
+ * `client.channelManager.releaseUnusedChannels()` removes it (or an end the SDK handles: deleted,
3091
+ * removed from it, logout). Meanwhile `client.channelManager.ensure(…)` gives a fresh instance
3092
+ * for its cid.
3093
+ *
3094
+ * It doesn't free memory itself: the instance is garbage collected once nothing refers to it.
3095
+ */
3096
+ disconnect() {
3097
+ // once only: a second run would drop subscription counts other consumers hold
3098
+ if (this.pendingDisposal) return;
3099
+ logger.withExtraTags('disconnect', this.cid).info('Disconnecting the channel.');
3100
+
3101
+ // Release the channel.state subscriptions BEFORE flipping `pendingDisposal` — that publishes to
3102
+ // the store, so no subscriber handler runs against a half-disconnected channel.
2592
3103
 
2593
- this.disconnected = true;
3104
+ // Runs the `'channel'` setup function's teardown and removes this channel from the configuration
3105
+ // store's subscribers. Cleared so a repeated `disconnect` cannot double-run it.
3106
+ this.unsubscribeConfiguration?.();
3107
+ this.unsubscribeConfiguration = undefined;
3108
+ this.unsubscribeServerConfig?.();
3109
+ this.unsubscribeServerConfig = undefined;
2594
3110
  this.messageReceiptsTracker.unregisterSubscriptions();
2595
- this.cooldownTimer.clearTimeout();
3111
+ this.cooldownTimer.unregisterSubscriptions();
2596
3112
  // Release the store-backed paginators so the message store no longer pins this removed channel
2597
3113
  // (and its whole message graph) through its subscriber registry. The channel is being discarded
2598
- // here (disconnected + deleted from activeChannels, never reused), mirroring Thread teardown.
3114
+ // here (pending disposal + removed from the channel store, never reused), mirroring Thread teardown.
2599
3115
  this.messagePaginator.dispose();
2600
3116
  this.pinnedMessagesPaginator.dispose();
3117
+
3118
+ // One update, last, so subscribers see both together. A deleted channel (or one the user was
3119
+ // removed from) must not be re-watched — see #2599.
3120
+ this.state.partialNext({
3121
+ pendingDisposal: true,
3122
+ watchStatus: ChannelWatchStatus.NotWatching,
3123
+ });
2601
3124
  }
2602
3125
  }