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
@@ -1,70 +1,68 @@
1
- import WebSocket from 'isomorphic-ws';
2
- import {
3
- addConnectionEventListeners,
4
- chatCodes,
5
- convertErrorToJson,
6
- randomId,
7
- removeConnectionEventListeners,
8
- retryInterval,
9
- sleep,
10
- } from './utils';
11
- import {
12
- buildWsFatalInsight,
13
- buildWsSuccessAfterFailureInsight,
14
- postInsights,
15
- } from './insights';
16
- import { chatLoggerSystem } from './logger';
17
- import type { ConnectAPIResponse, ConnectionOpen, EventPayload } from './types';
18
- import type { StreamChat } from './client';
19
- import type { APIError } from './errors';
20
- import { decodeWSEvent } from './gen/model-decoders/event-decoder-mapping';
21
- import type { WSEvent } from './gen/models';
1
+ import { chatCodes, randomId, retryInterval, sleep } from '../../utils';
2
+ import { chatLoggerSystem } from '../../logger';
3
+ import { WS_NETWORK_RECOVERY_RETRY_MS } from './config';
4
+ import type { ConnectAPIResponse, ConnectionOpen } from '../../types';
5
+ import type { WSConnection } from './WSConnection';
6
+ import type { StreamChat } from '../../client';
7
+ import type { APIError } from '../../errors';
8
+ import type { WSEvent } from '../../gen/models';
9
+ import type { WSConnectionConfig } from './types';
22
10
 
23
11
  const logger = chatLoggerSystem.getLogger('connection');
24
12
 
25
13
  // Type guards to check WebSocket error type
26
14
  const isCloseEvent = (
27
- res: WebSocket.CloseEvent | WebSocket.Data | WebSocket.ErrorEvent,
28
- ): res is WebSocket.CloseEvent => (res as WebSocket.CloseEvent).code !== undefined;
15
+ res: CloseEvent | MessageEvent | ErrorEvent | Event,
16
+ ): res is CloseEvent => (res as CloseEvent).code !== undefined;
29
17
 
30
18
  const isErrorEvent = (
31
- res: WebSocket.CloseEvent | WebSocket.Data | WebSocket.ErrorEvent,
32
- ): res is WebSocket.ErrorEvent => (res as WebSocket.ErrorEvent).error !== undefined;
19
+ res: CloseEvent | MessageEvent | ErrorEvent | Event,
20
+ ): res is ErrorEvent => (res as ErrorEvent).error !== undefined;
21
+
22
+ class WSCloseError extends Error {
23
+ public reason?: string;
24
+ public wasClean?: boolean;
25
+ public code?: number;
26
+ public target?: EventTarget | null;
27
+ constructor(message?: string, errorOptions?: ErrorOptions) {
28
+ super(message, errorOptions);
29
+ }
30
+ }
33
31
 
34
32
  /**
35
33
  * A WS connection that reconnects upon failure.
36
34
  *
37
- * - the browser will sometimes report that you're online or offline
38
- * - the WS connection can break and fail (there is a 30s health check)
39
- * - sometimes your WS connection will seem to work while the user is in fact offline
40
- * - to speed up online/offline detection you can use the `window.addEventListener('offline')`
35
+ * - the WS connection can break and fail; a ping goes out every 25s (`pingInterval`)
36
+ * - sometimes the WS connection seems to work while the device is in fact offline
37
+ * - the device's own network status is a separate fact, owned by `client.networkConnection` and fed by a
38
+ * platform listener the integrator registers; this class consumes it, it does not detect it
41
39
  *
42
- * There are 4 ways in which a connection can become unhealthy:
40
+ * There are 4 ways in which this connection can go down:
43
41
  * - WebSocket.onerror is called
44
42
  * - WebSocket.onclose is called
45
- * - the health check fails and no event is received for ~40 seconds
46
- * - the browser indicates the connection is now offline
43
+ * - no frame arrives for 35s, so the health-check loop gives up (`connectionCheckTimeout`)
44
+ * - the device reports its network went offline
47
45
  *
48
46
  * There are 2 assumptions we make about the server:
49
47
  * - state can be recovered by querying the channel again
50
48
  * - if the servers fails to publish a message to the client, the WS connection is destroyed
51
49
  */
52
50
  export class StableWSConnection {
53
- // global from constructor
54
- client: StreamChat;
51
+ /**
52
+ * The `WSConnection` this socket belongs to. Held instead of the client, because the status store
53
+ * lives here and everything the socket needs from the client is reachable through it.
54
+ */
55
+ wsConnection: WSConnection;
55
56
 
56
57
  // local vars
57
- connectionID?: string;
58
58
  connectionOpen?: ConnectAPIResponse;
59
59
  consecutiveFailures: number;
60
- pingInterval: number;
61
60
  healthCheckTimeoutRef?: NodeJS.Timeout;
62
61
  isConnecting: boolean;
63
62
  isDisconnected: boolean;
64
63
  isHealthy: boolean;
65
64
  isResolved?: boolean;
66
65
  lastEvent: Date | null;
67
- connectionCheckTimeout: number;
68
66
  connectionCheckTimeoutRef?: NodeJS.Timeout;
69
67
  rejectPromise?: (
70
68
  reason?: Error & {
@@ -79,9 +77,9 @@ export class StableWSConnection {
79
77
  ws?: WebSocket;
80
78
  wsID: number;
81
79
 
82
- constructor({ client }: { client: StreamChat }) {
83
- /** StreamChat client */
84
- this.client = client;
80
+ constructor({ wsConnection }: { wsConnection: WSConnection }) {
81
+ /** The `WSConnection` that owns this socket */
82
+ this.wsConnection = wsConnection;
85
83
  /** consecutive failures influence the duration of the timeout */
86
84
  this.consecutiveFailures = 0;
87
85
  /** keep track of the total number of failures */
@@ -98,24 +96,52 @@ export class StableWSConnection {
98
96
  this.wsID = 1;
99
97
  /** Store the last event time for health checks */
100
98
  this.lastEvent = null;
101
- /** Send a health check message every 25 seconds */
102
- this.pingInterval = 25 * 1000;
103
- this.connectionCheckTimeout = this.pingInterval + 10 * 1000;
99
+ }
100
+
101
+ /**
102
+ * The timing knobs, read from the parent **live** rather than snapshotted, so an `updateConfig`
103
+ * reaches the socket that is already open instead of only the next one.
104
+ */
105
+ private get config(): WSConnectionConfig {
106
+ return this.wsConnection.config;
107
+ }
104
108
 
105
- addConnectionEventListeners(this.onlineStatusChanged);
109
+ /** How often a health-check ping goes out. Configurable as `pingIntervalMs`. */
110
+ get pingInterval(): number {
111
+ return this.config.pingIntervalMs;
106
112
  }
107
113
 
108
- setClient(client: StreamChat) {
109
- this.client = client;
114
+ /**
115
+ * How long the connection check tolerates silence before tearing the socket down.
116
+ *
117
+ * Derived at read time rather than stored, so changing the ping interval moves the connection check
118
+ * with it instead of leaving the socket to kill itself between pings.
119
+ */
120
+ get connectionCheckTimeout(): number {
121
+ return this.config.pingIntervalMs + this.config.healthCheckGracePeriodMs;
122
+ }
123
+
124
+ /** The client, reached through the parent. See {@link wsConnection}. */
125
+ get client(): StreamChat {
126
+ return this.wsConnection.client;
127
+ }
128
+
129
+ /**
130
+ * Re-parents this socket, for one supplied through `config.connection` and built against a
131
+ * different `WSConnection` than the client adopting it.
132
+ */
133
+ setWSConnection(wsConnection: WSConnection) {
134
+ this.wsConnection = wsConnection;
110
135
  }
111
136
 
112
137
  /**
113
- * Connects to the WS URL. The default 15s timeout allows between 2 and 3 tries.
138
+ * Connects to the WS URL.
114
139
  *
115
- * @param timeout - Connect timeout in milliseconds (optional, defaults to `15000`).
116
- * @returns A promise that resolves once the first health check message is received.
140
+ * @param timeout - Connect timeout in milliseconds. Defaults to `config.connectTimeoutMs` (15s),
141
+ * which allows between 2 and 3 tries.
142
+ * @returns A promise that resolves once the server's `connection.ok` hello event arrives.
117
143
  */
118
- async connect(timeout = 15000) {
144
+ async connect(timeout: number = this.config.connectTimeoutMs) {
119
145
  if (this.isConnecting) {
120
146
  throw Error(
121
147
  `You've called connect twice, can only attempt 1 connection at the time`,
@@ -132,7 +158,7 @@ export class StableWSConnection {
132
158
  .withExtraTags('connect')
133
159
  .info(`Established a WebSocket connection. Health check: ${healthCheck}.`);
134
160
  } catch (error: any) {
135
- this.isHealthy = false;
161
+ this._applyHealth(false);
136
162
  this.consecutiveFailures += 1;
137
163
 
138
164
  const e = error as APIError;
@@ -161,12 +187,12 @@ export class StableWSConnection {
161
187
  }
162
188
 
163
189
  /**
164
- * _waitForHealthy polls the promise connection to see if its resolved until it times out
165
- * the default 15s timeout allows between 2~3 tries
190
+ * _waitForHealthy polls the promise connection to see if its resolved until it times out.
166
191
  *
167
- * @param timeout - duration (ms)
192
+ * @param timeout - duration (ms). Defaults to `config.connectTimeoutMs` (15s), which allows
193
+ * between 2~3 tries.
168
194
  */
169
- _waitForHealthy(timeout = 15000) {
195
+ _waitForHealthy(timeout: number = this.config.connectTimeoutMs) {
170
196
  return Promise.race([
171
197
  (async () => {
172
198
  const interval = 50; // ms
@@ -210,20 +236,14 @@ export class StableWSConnection {
210
236
  * @returns url string
211
237
  */
212
238
  _buildUrl = () => {
213
- const qs = this.client._buildWSPayload(this.requestID);
214
- const token = this.client.tokenManager.getToken();
215
- const wsUrlParams = this.client.options.wsUrlParams;
216
-
217
- const params = new URLSearchParams(wsUrlParams);
218
- params.set('json', qs);
239
+ const params = new URLSearchParams(this.config.urlParams);
219
240
  params.set('api_key', this.client.key);
220
- // it is expected that the autorization parameter exists even if
221
- // the token is undefined, so we interpolate it to be safe
222
- params.set('authorization', `${token}`);
223
241
  params.set('stream-auth-type', this.client.getAuthType());
242
+ // Browsers cannot set headers on the WS handshake, so the server reads this
243
+ // from the query string too.
224
244
  params.set('X-Stream-Client', this.client.getUserAgent());
225
245
 
226
- return `${this.client.wsBaseURL}/connect?${params.toString()}`;
246
+ return `${this.client.wsBaseURL}/api/v2/connect?${params.toString()}`;
227
247
  };
228
248
 
229
249
  /**
@@ -239,6 +259,10 @@ export class StableWSConnection {
239
259
  this.wsID += 1;
240
260
  this.isConnecting = false;
241
261
  this.isDisconnected = true;
262
+ // A deliberate close still expects a reopen - mobile backgrounding is the reason this method
263
+ // exists - so anything already waiting for a connection id keeps waiting. Invalidating drops the
264
+ // dead id and arms a fresh deferred for the socket `openConnection()` will build.
265
+ this.client.connectionIdManager.invalidate();
242
266
 
243
267
  // start by removing all the listeners
244
268
  if (this.healthCheckTimeoutRef) {
@@ -248,14 +272,9 @@ export class StableWSConnection {
248
272
  clearInterval(this.connectionCheckTimeoutRef);
249
273
  }
250
274
 
251
- removeConnectionEventListeners(this.onlineStatusChanged);
252
-
253
- this.isHealthy = false;
254
-
255
- // remove ws handlers...
256
- if (this.ws && this.ws.removeAllListeners) {
257
- this.ws.removeAllListeners();
258
- }
275
+ // Through `_applyHealth`, not a bare assignment: the store must tell the truth on this path too.
276
+ // It is what `closeConnection()` uses, and a deliberate shutdown is still a transition.
277
+ this._applyHealth(false);
259
278
 
260
279
  let isClosedPromise: Promise<void>;
261
280
  // and finally close...
@@ -264,7 +283,7 @@ export class StableWSConnection {
264
283
  const { ws } = this;
265
284
  if (ws && ws.close && ws.readyState === ws.OPEN) {
266
285
  isClosedPromise = new Promise((resolve) => {
267
- const onclose = (event: WebSocket.CloseEvent) => {
286
+ const onclose = (event: CloseEvent) => {
268
287
  logger
269
288
  .withExtraTags('disconnect')
270
289
  .debug(
@@ -303,17 +322,16 @@ export class StableWSConnection {
303
322
  /**
304
323
  * Connects to the WS endpoint.
305
324
  *
306
- * @returns A promise that resolves once the first health check message is received.
325
+ * @returns A promise that resolves once the server's `connection.ok` hello event arrives.
307
326
  */
308
327
  async _connect() {
309
- if (
310
- this.isConnecting ||
311
- (this.isDisconnected && this.client.options.enableWSFallback)
312
- )
313
- return; // simply ignore _connect if it's currently trying to connect
328
+ // simply ignore _connect if it's currently connecting, or if disconnect() was called
329
+ if (this.isConnecting || this.isDisconnected) return;
314
330
  this.isConnecting = true;
315
331
  this.requestID = randomId();
316
- this.client.insightMetrics.connectionStartTimestamp = new Date().getTime();
332
+ // Arm before anything can await a connection id. A no-op on a reconnect that still holds one -
333
+ // those requests keep flowing against the old id rather than blocking for the whole outage.
334
+ this.client.connectionIdManager.arm();
317
335
  let isTokenReady = false;
318
336
  try {
319
337
  logger.withExtraTags('_connect').debug('Waiting for the auth token.');
@@ -333,12 +351,19 @@ export class StableWSConnection {
333
351
 
334
352
  this._setupConnectionPromise();
335
353
  const wsURL = this._buildUrl();
354
+ // Built before the socket exists on purpose: the token is guaranteed loaded by
355
+ // this point, and a failure here must reject _connect rather than leave an open
356
+ // socket to die against the server's 10s auth-message deadline.
357
+ const authMessage = this.client._buildWSAuthMessage();
336
358
  logger.withExtraTags('_connect').info(`Connecting to ${wsURL}.`, {
337
359
  wsURL,
338
360
  requestID: this.requestID,
339
361
  });
340
- this.ws = new WebSocket(wsURL);
341
- this.ws.onopen = this.onopen.bind(this, this.wsID);
362
+
363
+ const WS = this.config.webSocketImpl ?? WebSocket;
364
+ this.ws = new WS(wsURL);
365
+
366
+ this.ws.onopen = this.onopen.bind(this, this.wsID, authMessage);
342
367
  this.ws.onclose = this.onclose.bind(this, this.wsID);
343
368
  this.ws.onerror = this.onerror.bind(this, this.wsID);
344
369
  this.ws.onmessage = this.onmessage.bind(this, this.wsID);
@@ -346,17 +371,10 @@ export class StableWSConnection {
346
371
  this.isConnecting = false;
347
372
 
348
373
  if (response) {
349
- this.connectionID = response.connection_id;
350
- if (
351
- this.client.insightMetrics.wsConsecutiveFailures > 0 &&
352
- this.client.options.enableInsights
353
- ) {
354
- postInsights(
355
- 'ws_success_after_failure',
356
- buildWsSuccessAfterFailureInsight(this as unknown as StableWSConnection),
357
- );
358
- this.client.insightMetrics.wsConsecutiveFailures = 0;
359
- }
374
+ // The id is published to the ConnectionIdManager and nowhere else. A copy kept here would
375
+ // outlive the socket it belongs to - `invalidate()` / `reset()` cannot reach it - which is
376
+ // exactly the staleness this manager exists to end.
377
+ this.client.connectionIdManager.resolveConnectionId(response.connection_id);
360
378
  return response;
361
379
  }
362
380
  } catch (error: any) {
@@ -364,16 +382,6 @@ export class StableWSConnection {
364
382
  logger
365
383
  .withExtraTags('_connect')
366
384
  .warn('An error occurred while connecting.', { error });
367
- if (this.client.options.enableInsights) {
368
- this.client.insightMetrics.wsConsecutiveFailures++;
369
- this.client.insightMetrics.wsTotalFailures++;
370
-
371
- const insights = buildWsFatalInsight(
372
- this as unknown as StableWSConnection,
373
- convertErrorToJson(error as Error),
374
- );
375
- postInsights?.('ws_fatal', insights);
376
- }
377
385
  throw error;
378
386
  }
379
387
  }
@@ -416,7 +424,7 @@ export class StableWSConnection {
416
424
  return;
417
425
  }
418
426
 
419
- if (this.isDisconnected && this.client.options.enableWSFallback) {
427
+ if (this.isDisconnected) {
420
428
  logger
421
429
  .withExtraTags('_reconnect')
422
430
  .debug('Aborting reconnect: disconnect() was called.');
@@ -436,13 +444,11 @@ export class StableWSConnection {
436
444
 
437
445
  try {
438
446
  await this._connect();
439
- logger.withExtraTags('_reconnect').debug('Waiting for the recover callback.');
440
- await this.client.recoverState();
441
- logger.withExtraTags('_reconnect').debug('Finished the recover callback.');
447
+ this.client._settleConnectPromises();
442
448
 
443
449
  this.consecutiveFailures = 0;
444
450
  } catch (error: any) {
445
- this.isHealthy = false;
451
+ this._applyHealth(false);
446
452
  this.consecutiveFailures += 1;
447
453
  if (
448
454
  error.code === chatCodes.TOKEN_EXPIRED &&
@@ -464,46 +470,101 @@ export class StableWSConnection {
464
470
  .warn('WebSocket connection failed. Retrying the reconnect.');
465
471
 
466
472
  this._reconnect();
473
+ } else {
474
+ // Giving up. Going down armed a deferred on the assumption that a reconnect would settle it,
475
+ // and nothing will now — leaving it pending hangs every request waiting for an id, with no
476
+ // retry coming and no error to show for it.
477
+ this.client.connectionIdManager.rejectConnectionId(error);
467
478
  }
468
479
  }
469
480
  logger.withExtraTags('_reconnect').debug('Reconnect attempt finished.');
470
481
  }
471
482
 
472
483
  /**
473
- * Called when the browser connects or disconnects from the internet.
484
+ * Handles a change reported for the `'network'` connection — the device's own — and applies it to
485
+ * the `'ws'` connection this class owns.
486
+ *
487
+ * The logs name both by their {@link ConnectionType} value rather than by prose, so a reader is
488
+ * never left guessing which connection a line is about. The effect clause is conditional because there may not be an effect: `_setHealth` returns
489
+ * early when the status is unchanged, and a `'network'` report commonly arrives after the socket has
490
+ * already died on its own.
474
491
  *
475
- * @param event - The DOM event whose `type` is `'online'` or `'offline'`.
492
+ * @deprecated Report network status through `client.networkConnection.setStatus(isOnline)` instead, or
493
+ * register a listener with `client.networkConnection.setStatusReporter(…)`. This entry point takes
494
+ * a DOM-shaped object and reaches into the socket, neither of which a caller should need. Kept
495
+ * for one major because `stream-chat-react-native` calls it directly.
496
+ *
497
+ * @param event - A DOM-shaped object whose `type` is `'online'` or `'offline'`. It carries no
498
+ * connection identifier and never has: it was fed by `window`'s own `online`/`offline` events,
499
+ * which are always about the device's network, and React Native synthesizes the same shape from
500
+ * `NetInfo`.
476
501
  */
477
502
  onlineStatusChanged = (event: Event) => {
478
- if (event.type === 'offline') {
479
- // mark the connection as down
503
+ if (event.type === 'offline') this._applyNetworkStatus(false);
504
+ else if (event.type === 'online') this._applyNetworkStatus(true);
505
+ };
506
+
507
+ /**
508
+ * Applies a reported change in the `'network'` connection to the `'ws'` connection this class owns.
509
+ *
510
+ * The single body behind both entry points — the network-store subscription the parent owns, and
511
+ * the deprecated {@link onlineStatusChanged} shim React Native still calls — so the two cannot
512
+ * drift.
513
+ *
514
+ * @internal
515
+ */
516
+ public _applyNetworkStatus(online: boolean) {
517
+ if (!online) {
480
518
  logger
481
519
  .withExtraTags('onlineStatusChanged')
482
- .info('Network status changed to offline.');
520
+ .info(`The 'network' connection went offline.`);
483
521
  this._setHealth(false);
484
- } else if (event.type === 'online') {
485
- // retry right now...
486
- // We check this.isHealthy, not sure if it's always
487
- // smart to create a new WS connection if the old one is still up and running.
488
- // it's possible we didn't miss any messages, so this process is just expensive and not needed.
489
- logger
490
- .withExtraTags('onlineStatusChanged')
491
- .info(`Network status changed to online. isHealthy: ${this.isHealthy}.`);
492
- if (!this.isHealthy) {
493
- this._reconnect({ interval: 10 });
494
- }
522
+ return;
495
523
  }
496
- };
497
524
 
498
- onopen = (wsId: number) => {
525
+ // A socket still carrying traffic has probably missed nothing, so replacing it would cost a
526
+ // handshake and a fresh connection ID for no gain. Only reconnect if it is actually down.
527
+ logger
528
+ .withExtraTags('onlineStatusChanged')
529
+ .info(
530
+ `The 'network' connection went online; ${
531
+ this.isHealthy
532
+ ? `leaving the 'ws' connection as it is`
533
+ : `reconnecting the 'ws' connection now`
534
+ }.`,
535
+ );
536
+
537
+ if (!this.isHealthy) {
538
+ this._reconnect({ interval: WS_NETWORK_RECOVERY_RETRY_MS });
539
+ }
540
+ }
541
+
542
+ onopen = (wsId: number, authMessage: string) => {
499
543
  if (this.wsID !== wsId) return;
500
544
 
501
545
  logger.withExtraTags('onopen').debug('WebSocket onopen callback fired.', {
502
546
  wsID: wsId,
503
547
  });
548
+
549
+ // `/api/v2/connect` authenticates off the first frame the client sends, not off
550
+ // the query string. The server closes the socket if it does not arrive in 10s.
551
+ const { ws } = this;
552
+ // disconnect() deletes this.ws synchronously; the wsID guard above covers
553
+ // reconnects, this covers a socket torn down before `open` was dispatched.
554
+ if (!ws || ws.readyState !== ws.OPEN) return;
555
+
556
+ try {
557
+ ws.send(authMessage);
558
+ } catch (error) {
559
+ logger
560
+ .withExtraTags('onopen')
561
+ .error('Failed to send the WebSocket auth message.', { error });
562
+ this.rejectPromise?.(this._errorFromWSEvent(error as Event));
563
+ this._destroyCurrentWSConnection();
564
+ }
504
565
  };
505
566
 
506
- onmessage = (wsId: number, event: WebSocket.MessageEvent) => {
567
+ onmessage = (wsId: number, event: MessageEvent) => {
507
568
  if (this.wsID !== wsId) return;
508
569
 
509
570
  logger.withExtraTags('onmessage').trace('WebSocket onmessage callback fired.', {
@@ -512,7 +573,7 @@ export class StableWSConnection {
512
573
  });
513
574
  if (typeof event.data !== 'string') return;
514
575
  const data = JSON.parse(event.data);
515
- const decodedData = decodeWSEvent(data) as WSEvent;
576
+ const decodedData = data as WSEvent;
516
577
 
517
578
  // we wait till the first message before we consider the connection open..
518
579
  // the reason for this is that auth errors and similar errors trigger a ws.onopen and immediately
@@ -524,14 +585,22 @@ export class StableWSConnection {
524
585
  return;
525
586
  }
526
587
 
527
- this.resolvePromise?.(decodedData as EventPayload<'health.check'>);
588
+ // Published before going online, so "the socket is up" implies "there is an id to watch on".
589
+ this.client.connectionIdManager.resolveConnectionId(
590
+ (decodedData as ConnectionOpen).connection_id,
591
+ );
592
+
593
+ this.resolvePromise?.(decodedData as ConnectionOpen);
528
594
  this._setHealth(true);
529
595
  }
530
596
 
531
597
  // trigger the event..
532
598
  this.lastEvent = new Date();
533
599
 
534
- if (data.type === 'health.check') {
600
+ // `connection.ok` is the v2 hello event. The server only echoes health checks in
601
+ // response to an inbound frame, so failing to schedule here means we never ping
602
+ // and scheduleConnectionCheck tears the socket down 35s later, in a loop.
603
+ if (data.type === 'health.check' || data.type === 'connection.ok') {
535
604
  this.scheduleNextPing();
536
605
  }
537
606
 
@@ -539,7 +608,7 @@ export class StableWSConnection {
539
608
  this.scheduleConnectionCheck();
540
609
  };
541
610
 
542
- onclose = (wsId: number, event: WebSocket.CloseEvent) => {
611
+ onclose = (wsId: number, event: CloseEvent) => {
543
612
  if (this.wsID !== wsId) return;
544
613
 
545
614
  logger
@@ -552,9 +621,7 @@ export class StableWSConnection {
552
621
  if (event.code === chatCodes.WS_CLOSED_SUCCESS) {
553
622
  // this is a permanent error raised by stream..
554
623
  // usually caused by invalid auth details
555
- const error = new Error(
556
- `WS connection reject with error ${event.reason}`,
557
- ) as Error & WebSocket.CloseEvent;
624
+ const error = new WSCloseError(`WS connection reject with error ${event.reason}`);
558
625
 
559
626
  error.reason = event.reason;
560
627
  error.code = event.code;
@@ -584,7 +651,7 @@ export class StableWSConnection {
584
651
  }
585
652
  };
586
653
 
587
- onerror = (wsId: number, event: WebSocket.ErrorEvent) => {
654
+ onerror = (wsId: number, event: Event) => {
588
655
  if (this.wsID !== wsId) return;
589
656
 
590
657
  this.consecutiveFailures += 1;
@@ -601,25 +668,50 @@ export class StableWSConnection {
601
668
  };
602
669
 
603
670
  /**
604
- * Sets the connection to healthy or unhealthy. Broadcasts an event if the connection status changed.
671
+ * Writes this connection's status to the field and to `client.wsConnection.state`, and drops the
672
+ * connection id when it goes down. Returns whether the status changed.
605
673
  *
606
- * @param healthy - Whether the connection is healthy.
674
+ * Every path that transitions the status goes through here — including `disconnect()`, which
675
+ * `closeConnection()` uses, and the two error paths. Covering all of them is why the store exists,
676
+ * and why invalidating the id belongs here rather than beside any one of those paths.
677
+ *
678
+ * Construction is not routed through here: initializing the field is not a transition, and stamping
679
+ * `lastUnhealthyAt` because a socket object was built would be a lie.
607
680
  */
608
- _setHealth = (healthy: boolean) => {
609
- if (healthy === this.isHealthy) return;
681
+ private _applyHealth(healthy: boolean): boolean {
682
+ if (healthy === this.isHealthy) return false;
610
683
 
611
684
  this.isHealthy = healthy;
612
685
 
613
- if (this.isHealthy) {
614
- this.client.dispatchEvent({ type: 'connection.changed', online: this.isHealthy });
615
- return;
686
+ if (!healthy) {
687
+ // The id those watches were keyed by is dead, so no further request may carry it. Invalidating
688
+ // arms a fresh deferred, so requests needing one wait for the reconnect instead of racing
689
+ // ahead with the old one.
690
+ this.client.connectionIdManager.invalidate();
616
691
  }
617
692
 
618
- // we're offline, wait few seconds and fire and event if still offline
619
- setTimeout(() => {
620
- if (this.isHealthy) return;
621
- this.client.dispatchEvent({ type: 'connection.changed', online: this.isHealthy });
622
- }, 5000);
693
+ this.wsConnection._setStatus({ isHealthy: healthy });
694
+
695
+ return true;
696
+ }
697
+
698
+ /**
699
+ * Applies a status change and does the bookkeeping that goes with it.
700
+ *
701
+ * Announcing it is not this class's job. The status lives in `client.wsConnection.state`, which
702
+ * {@link _applyHealth} writes on every transition — including the ones that were always silent —
703
+ * so a consumer subscribes there rather than waiting to be told.
704
+ *
705
+ * The five-second wait before announcing a drop moved to whoever renders the banner, its length
706
+ * configurable as `offlineNotificationDisplayDelayMs`. The timer here outlived the socket that
707
+ * armed it, so a replaced connection announced a drop its replacement had already recovered from.
708
+ */
709
+ _setHealth = (healthy: boolean) => {
710
+ if (!this._applyHealth(healthy)) return;
711
+ if (this.isHealthy) return;
712
+
713
+ // The server keys channel watches by connection ID, so they are gone the moment the socket is.
714
+ this.client.channelManager.markChannelsWatchInterrupted();
623
715
  };
624
716
 
625
717
  /**
@@ -630,7 +722,7 @@ export class StableWSConnection {
630
722
  * @returns A normalized error describing the WS failure.
631
723
  */
632
724
  _errorFromWSEvent = (
633
- event: WebSocket.CloseEvent | WebSocket.Data | WebSocket.ErrorEvent,
725
+ event: CloseEvent | MessageEvent | ErrorEvent | Event,
634
726
  isWSFailure = true,
635
727
  ) => {
636
728
  let code;
@@ -679,7 +771,6 @@ export class StableWSConnection {
679
771
  this.wsID += 1;
680
772
 
681
773
  try {
682
- this?.ws?.removeAllListeners();
683
774
  this?.ws?.close();
684
775
  } catch (e) {
685
776
  // we don't care
@@ -706,7 +797,7 @@ export class StableWSConnection {
706
797
  clearTimeout(this.healthCheckTimeoutRef);
707
798
  }
708
799
 
709
- // 30 seconds is the recommended interval (messenger uses this)
800
+ // Sent every `config.pingIntervalMs` (25s by default); the server answers with a health check event.
710
801
  this.healthCheckTimeoutRef = setTimeout(() => {
711
802
  // send the healthcheck.., server replies with a health check event
712
803
  const data = [{ type: 'health.check', client_id: this.client.clientId }];