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

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 (269) hide show
  1. package/dist/cjs/index.browser.js +2196 -3902
  2. package/dist/cjs/index.browser.js.map +3 -3
  3. package/dist/cjs/index.node.js +2197 -3902
  4. package/dist/cjs/index.node.js.map +3 -3
  5. package/dist/esm/index.mjs +2199 -3905
  6. package/dist/esm/index.mjs.map +4 -4
  7. package/dist/types/ChannelManager.d.ts +120 -233
  8. package/dist/types/CooldownTimer.d.ts +8 -23
  9. package/dist/types/EventHandlerPipeline.d.ts +17 -37
  10. package/dist/types/LiveLocationManager.d.ts +22 -50
  11. package/dist/types/api-client.d.ts +9 -14
  12. package/dist/types/channel.d.ts +253 -448
  13. package/dist/types/channel_state.d.ts +48 -95
  14. package/dist/types/client.d.ts +245 -370
  15. package/dist/types/client_state.d.ts +1 -3
  16. package/dist/types/configuration/ConfigController.d.ts +30 -124
  17. package/dist/types/configuration/InstanceConfigurationRegistry.d.ts +31 -123
  18. package/dist/types/configuration/keys.d.ts +5 -19
  19. package/dist/types/configuration/shape.d.ts +12 -29
  20. package/dist/types/configuration/types.d.ts +59 -87
  21. package/dist/types/configuration/utils/applyInstanceConfiguration.d.ts +13 -35
  22. package/dist/types/configuration/utils/copyConfigPatch.d.ts +8 -0
  23. package/dist/types/configuration/utils/declarativeSlices.d.ts +5 -16
  24. package/dist/types/configuration/utils/deepFreezeConfig.d.ts +3 -17
  25. package/dist/types/configuration/utils/serverAuthority.d.ts +9 -29
  26. package/dist/types/connection/ConnectionIdManager.d.ts +18 -40
  27. package/dist/types/connection/ConnectionRecoveryManager.d.ts +29 -120
  28. package/dist/types/connection/networkConnection/NetworkConnectionObserver.d.ts +32 -103
  29. package/dist/types/connection/networkConnection/reporters.d.ts +9 -32
  30. package/dist/types/connection/networkConnection/types.d.ts +12 -27
  31. package/dist/types/connection/wsConnection/StableWSConnection.d.ts +37 -116
  32. package/dist/types/connection/wsConnection/WSConnection.d.ts +41 -104
  33. package/dist/types/connection/wsConnection/WSConnectionFallback.d.ts +8 -16
  34. package/dist/types/connection/wsConnection/config.d.ts +8 -28
  35. package/dist/types/connection/wsConnection/types.d.ts +17 -70
  36. package/dist/types/entityStore/EntityStore.d.ts +153 -113
  37. package/dist/types/entityStore/StoreBackedItemIndex.d.ts +13 -46
  38. package/dist/types/errors.d.ts +7 -19
  39. package/dist/types/gen/chat/ChannelApi.d.ts +2 -1
  40. package/dist/types/gen/chat/ChatApi.d.ts +28 -14
  41. package/dist/types/gen/models/index.d.ts +769 -86
  42. package/dist/types/gen/moderation/ModerationApi.d.ts +4 -4
  43. package/dist/types/index.d.ts +2 -4
  44. package/dist/types/languageNames.d.ts +9 -24
  45. package/dist/types/logger.d.ts +1 -3
  46. package/dist/types/messageComposer/LocationComposer.d.ts +1 -1
  47. package/dist/types/messageComposer/attachmentIdentity.d.ts +1 -6
  48. package/dist/types/messageComposer/attachmentManager.d.ts +10 -32
  49. package/dist/types/messageComposer/attachmentUtils.d.ts +3 -14
  50. package/dist/types/messageComposer/configuration/configuration.d.ts +2 -5
  51. package/dist/types/messageComposer/configuration/types.d.ts +29 -56
  52. package/dist/types/messageComposer/linkPreviewsManager.d.ts +6 -9
  53. package/dist/types/messageComposer/messageComposer.d.ts +30 -164
  54. package/dist/types/messageComposer/middleware/attachmentManager/postUpload/attachmentEnrichment.d.ts +4 -14
  55. package/dist/types/messageComposer/middleware/messageComposer/attachments.d.ts +2 -9
  56. package/dist/types/messageComposer/middleware/pollComposer/types.d.ts +2 -4
  57. package/dist/types/messageComposer/middleware/pollComposer/validation.d.ts +7 -19
  58. package/dist/types/messageComposer/middleware/textComposer/commands.d.ts +9 -0
  59. package/dist/types/messageComposer/middleware/textComposer/mentions.d.ts +11 -18
  60. package/dist/types/messageComposer/middleware/textComposer/textMiddlewareUtils.d.ts +9 -3
  61. package/dist/types/messageComposer/middleware/textComposer/types.d.ts +1 -6
  62. package/dist/types/messageComposer/pollComposer.d.ts +8 -4
  63. package/dist/types/messageComposer/textComposer.d.ts +3 -9
  64. package/dist/types/messageComposer/types.d.ts +5 -8
  65. package/dist/types/messageDelivery/MessageDeliveryReporter.d.ts +25 -79
  66. package/dist/types/messageDelivery/MessageReceiptsTracker.d.ts +15 -82
  67. package/dist/types/messageOperations/FailedSendCache.d.ts +4 -9
  68. package/dist/types/messageOperations/MessageOperationStatePolicy.d.ts +10 -20
  69. package/dist/types/messageOperations/MessageOperations.d.ts +20 -40
  70. package/dist/types/messageOperations/applyReactionLocally.d.ts +5 -22
  71. package/dist/types/messageOperations/createMessageOperations.d.ts +3 -5
  72. package/dist/types/messageOperations/reflectReactionEvent.d.ts +5 -13
  73. package/dist/types/messageOperations/sendOrdering.d.ts +4 -7
  74. package/dist/types/messageOperations/settlePendingAttachmentUploads.d.ts +7 -15
  75. package/dist/types/messageOperations/types.d.ts +15 -30
  76. package/dist/types/middleware.d.ts +7 -5
  77. package/dist/types/moderation.d.ts +21 -14
  78. package/dist/types/notifications/NotificationManager.d.ts +8 -31
  79. package/dist/types/notifications/types.d.ts +19 -59
  80. package/dist/types/offline-support/offline_support_api.d.ts +145 -539
  81. package/dist/types/offline-support/offline_sync_manager.d.ts +18 -42
  82. package/dist/types/offline-support/queueableOperations.d.ts +24 -52
  83. package/dist/types/offline-support/types.d.ts +24 -187
  84. package/dist/types/pagination/ItemIndex.d.ts +4 -12
  85. package/dist/types/pagination/cursorDerivation/aroundPaginationFlags.d.ts +13 -0
  86. package/dist/types/pagination/cursorDerivation/createdAtAroundPaginationFlags.d.ts +2 -4
  87. package/dist/types/pagination/cursorDerivation/linearPaginationFlags.d.ts +2 -3
  88. package/dist/types/pagination/paginators/BasePaginator.d.ts +235 -622
  89. package/dist/types/pagination/paginators/ChannelPaginator.d.ts +67 -125
  90. package/dist/types/pagination/paginators/MessageIntervalPaginator.d.ts +133 -292
  91. package/dist/types/pagination/paginators/MessagePaginator.d.ts +69 -118
  92. package/dist/types/pagination/paginators/PinnedMessagePaginator.d.ts +7 -26
  93. package/dist/types/pagination/paginators/ReminderPaginator.d.ts +2 -2
  94. package/dist/types/pagination/paginators/ThreadPaginator.d.ts +15 -23
  95. package/dist/types/pagination/paginators/UserGroupPaginator.d.ts +2 -6
  96. package/dist/types/pagination/sortCompiler.d.ts +11 -22
  97. package/dist/types/pagination/utility.normalization.d.ts +5 -23
  98. package/dist/types/pagination/utility.search.d.ts +3 -8
  99. package/dist/types/poll.d.ts +14 -14
  100. package/dist/types/poll_manager.d.ts +11 -2
  101. package/dist/types/poll_optimistic_votes.d.ts +10 -14
  102. package/dist/types/reminders/Reminder.d.ts +4 -4
  103. package/dist/types/reminders/ReminderManager.d.ts +7 -20
  104. package/dist/types/search/BaseSearchSource.d.ts +7 -12
  105. package/dist/types/search/ChannelSearchSource.d.ts +7 -7
  106. package/dist/types/search/MessageSearchSource.d.ts +7 -9
  107. package/dist/types/search/SearchController.d.ts +17 -22
  108. package/dist/types/search/types.d.ts +6 -10
  109. package/dist/types/signing.d.ts +12 -3
  110. package/dist/types/thread.d.ts +23 -71
  111. package/dist/types/thread_manager.d.ts +45 -70
  112. package/dist/types/token_manager.d.ts +8 -13
  113. package/dist/types/types.d.ts +64 -125
  114. package/dist/types/types.utility.d.ts +3 -3
  115. package/dist/types/upload-utils.d.ts +5 -10
  116. package/dist/types/uploadManager.d.ts +17 -45
  117. package/dist/types/utils/FixedSizeQueueCache.d.ts +6 -11
  118. package/dist/types/utils/WithSubscriptions.d.ts +5 -15
  119. package/dist/types/utils/concurrency.d.ts +11 -19
  120. package/dist/types/utils/mergeWith/mergeWith.d.ts +8 -11
  121. package/dist/types/utils/mergeWith/mergeWithCore.d.ts +5 -13
  122. package/dist/types/utils/mergeWith/mergeWithDiff.d.ts +22 -0
  123. package/dist/types/utils/objectPath.d.ts +6 -41
  124. package/dist/types/utils/retryable.d.ts +8 -12
  125. package/dist/types/utils/throttling/throttle.d.ts +8 -23
  126. package/dist/types/utils/time.d.ts +24 -64
  127. package/dist/types/utils.d.ts +40 -86
  128. package/package.json +7 -2
  129. package/src/ChannelManager.ts +159 -300
  130. package/src/CooldownTimer.ts +11 -29
  131. package/src/EventHandlerPipeline.ts +21 -44
  132. package/src/LiveLocationManager.ts +35 -74
  133. package/src/api-client.ts +43 -61
  134. package/src/campaign.ts +1 -1
  135. package/src/channel.ts +396 -749
  136. package/src/channel_batch_updater.ts +1 -1
  137. package/src/channel_state.ts +50 -105
  138. package/src/client.ts +360 -588
  139. package/src/client_state.ts +1 -6
  140. package/src/configuration/ConfigController.ts +41 -157
  141. package/src/configuration/InstanceConfigurationRegistry.ts +42 -171
  142. package/src/configuration/index.ts +1 -1
  143. package/src/configuration/keys.ts +13 -32
  144. package/src/configuration/shape.ts +67 -70
  145. package/src/configuration/types.ts +60 -100
  146. package/src/configuration/utils/applyInstanceConfiguration.ts +21 -53
  147. package/src/configuration/utils/copyConfigPatch.ts +11 -32
  148. package/src/configuration/utils/declarativeSlices.ts +9 -39
  149. package/src/configuration/utils/deepFreezeConfig.ts +3 -17
  150. package/src/configuration/utils/index.ts +2 -4
  151. package/src/configuration/utils/serverAuthority.ts +20 -68
  152. package/src/connection/ConnectionIdManager.ts +20 -49
  153. package/src/connection/ConnectionRecoveryManager.ts +51 -178
  154. package/src/connection/networkConnection/NetworkConnectionObserver.ts +37 -114
  155. package/src/connection/networkConnection/reporters.ts +9 -36
  156. package/src/connection/networkConnection/types.ts +12 -27
  157. package/src/connection/wsConnection/StableWSConnection.ts +73 -193
  158. package/src/connection/wsConnection/WSConnection.ts +56 -131
  159. package/src/connection/wsConnection/WSConnectionFallback.ts +22 -31
  160. package/src/connection/wsConnection/config.ts +13 -48
  161. package/src/connection/wsConnection/types.ts +17 -70
  162. package/src/constants.ts +4 -4
  163. package/src/entityStore/EntityStore.ts +162 -167
  164. package/src/entityStore/StoreBackedItemIndex.ts +14 -47
  165. package/src/errors.ts +7 -19
  166. package/src/formatMessageMemo.ts +3 -9
  167. package/src/gen/chat/ChannelApi.ts +19 -0
  168. package/src/gen/chat/ChatApi.ts +87 -13
  169. package/src/gen/models/index.ts +793 -71
  170. package/src/gen/moderation/ModerationApi.ts +0 -4
  171. package/src/index.ts +10 -14
  172. package/src/languageNames.ts +9 -24
  173. package/src/logger.ts +1 -3
  174. package/src/messageComposer/LocationComposer.ts +7 -23
  175. package/src/messageComposer/MessageComposerEffectHandlers.ts +1 -2
  176. package/src/messageComposer/attachmentIdentity.ts +2 -13
  177. package/src/messageComposer/attachmentManager.ts +17 -63
  178. package/src/messageComposer/attachmentUtils.ts +3 -17
  179. package/src/messageComposer/configuration/configuration.ts +5 -8
  180. package/src/messageComposer/configuration/types.ts +29 -56
  181. package/src/messageComposer/fileUtils.ts +1 -1
  182. package/src/messageComposer/linkPreviewsManager.ts +8 -20
  183. package/src/messageComposer/messageComposer.ts +54 -222
  184. package/src/messageComposer/middleware/attachmentManager/postUpload/attachmentEnrichment.ts +4 -16
  185. package/src/messageComposer/middleware/attachmentManager/postUpload/uploadErrorHandler.ts +1 -2
  186. package/src/messageComposer/middleware/messageComposer/attachments.ts +14 -40
  187. package/src/messageComposer/middleware/messageComposer/linkPreviews.ts +3 -4
  188. package/src/messageComposer/middleware/messageComposer/textComposer.ts +1 -1
  189. package/src/messageComposer/middleware/messageComposer/userDataInjection.ts +4 -11
  190. package/src/messageComposer/middleware/pollComposer/state.ts +2 -2
  191. package/src/messageComposer/middleware/pollComposer/types.ts +2 -4
  192. package/src/messageComposer/middleware/pollComposer/validation.ts +8 -26
  193. package/src/messageComposer/middleware/textComposer/TextComposerMiddlewareExecutor.ts +1 -6
  194. package/src/messageComposer/middleware/textComposer/commandUtils.ts +1 -2
  195. package/src/messageComposer/middleware/textComposer/commands.ts +11 -16
  196. package/src/messageComposer/middleware/textComposer/mentions.ts +32 -70
  197. package/src/messageComposer/middleware/textComposer/textMiddlewareUtils.ts +10 -4
  198. package/src/messageComposer/middleware/textComposer/types.ts +1 -6
  199. package/src/messageComposer/pollComposer.ts +11 -8
  200. package/src/messageComposer/textComposer.ts +9 -59
  201. package/src/messageComposer/types.ts +9 -12
  202. package/src/messageDelivery/MessageDeliveryReporter.ts +60 -113
  203. package/src/messageDelivery/MessageReceiptsTracker.ts +21 -105
  204. package/src/messageOperations/FailedSendCache.ts +4 -9
  205. package/src/messageOperations/MessageOperationStatePolicy.ts +40 -67
  206. package/src/messageOperations/MessageOperations.ts +33 -62
  207. package/src/messageOperations/applyReactionLocally.ts +9 -28
  208. package/src/messageOperations/createMessageOperations.ts +17 -33
  209. package/src/messageOperations/reflectReactionEvent.ts +5 -13
  210. package/src/messageOperations/sendOrdering.ts +4 -7
  211. package/src/messageOperations/settlePendingAttachmentUploads.ts +10 -21
  212. package/src/messageOperations/types.ts +15 -30
  213. package/src/middleware.ts +7 -10
  214. package/src/moderation.ts +25 -21
  215. package/src/notifications/NotificationManager.ts +11 -35
  216. package/src/notifications/types.ts +19 -59
  217. package/src/offline-support/offline_support_api.ts +178 -608
  218. package/src/offline-support/offline_sync_manager.ts +25 -69
  219. package/src/offline-support/queueableOperations.ts +31 -84
  220. package/src/offline-support/types.ts +25 -188
  221. package/src/pagination/ItemIndex.ts +4 -12
  222. package/src/pagination/cursorDerivation/aroundPaginationFlags.ts +29 -0
  223. package/src/pagination/cursorDerivation/createdAtAroundPaginationFlags.ts +13 -62
  224. package/src/pagination/cursorDerivation/idAroundPaginationFlags.ts +11 -39
  225. package/src/pagination/cursorDerivation/linearPaginationFlags.ts +4 -6
  226. package/src/pagination/filterCompiler.ts +11 -25
  227. package/src/pagination/paginators/BasePaginator.ts +422 -976
  228. package/src/pagination/paginators/ChannelPaginator.ts +130 -190
  229. package/src/pagination/paginators/MessageIntervalPaginator.ts +226 -457
  230. package/src/pagination/paginators/MessagePaginator.ts +135 -175
  231. package/src/pagination/paginators/PinnedMessagePaginator.ts +13 -38
  232. package/src/pagination/paginators/ReminderPaginator.ts +12 -15
  233. package/src/pagination/paginators/ThreadPaginator.ts +16 -26
  234. package/src/pagination/paginators/UserGroupPaginator.ts +6 -17
  235. package/src/pagination/paginators/stateThrottling.ts +5 -10
  236. package/src/pagination/sortCompiler.ts +23 -50
  237. package/src/pagination/utility.normalization.ts +8 -30
  238. package/src/pagination/utility.search.ts +4 -11
  239. package/src/poll.ts +19 -19
  240. package/src/poll_manager.ts +16 -20
  241. package/src/poll_optimistic_votes.ts +17 -22
  242. package/src/reminders/Reminder.ts +5 -6
  243. package/src/reminders/ReminderManager.ts +9 -34
  244. package/src/reminders/ReminderTimer.ts +1 -2
  245. package/src/search/BaseSearchSource.ts +14 -29
  246. package/src/search/ChannelSearchSource.ts +8 -8
  247. package/src/search/MessageSearchSource.ts +19 -25
  248. package/src/search/SearchController.ts +18 -24
  249. package/src/search/types.ts +6 -10
  250. package/src/segment.ts +1 -1
  251. package/src/signing.ts +23 -3
  252. package/src/thread.ts +72 -173
  253. package/src/thread_manager.ts +59 -76
  254. package/src/token_manager.ts +11 -21
  255. package/src/types.ts +78 -126
  256. package/src/types.utility.ts +3 -3
  257. package/src/upload-utils.ts +5 -10
  258. package/src/uploadManager.ts +22 -54
  259. package/src/utils/FixedSizeQueueCache.ts +13 -21
  260. package/src/utils/WithSubscriptions.ts +5 -15
  261. package/src/utils/concurrency.ts +16 -55
  262. package/src/utils/mergeWith/mergeWith.ts +10 -13
  263. package/src/utils/mergeWith/mergeWithCore.ts +24 -81
  264. package/src/utils/mergeWith/mergeWithDiff.ts +15 -33
  265. package/src/utils/objectPath.ts +6 -41
  266. package/src/utils/retryable.ts +10 -14
  267. package/src/utils/throttling/throttle.ts +9 -25
  268. package/src/utils/time.ts +26 -66
  269. package/src/utils.ts +72 -128
package/src/utils.ts CHANGED
@@ -20,11 +20,10 @@ import { nowNs, nsToDate } from './utils/time';
20
20
  const logger = chatLoggerSystem.getLogger('utils');
21
21
 
22
22
  /**
23
- * Logs the execution of a promise. Use this when you want to run the promise and handle errors by
24
- * logging a warning.
23
+ * Runs a promise fire-and-forget and logs an error when it rejects.
25
24
  *
26
- * @param promise - The promise you want to run and log.
27
- * @param name - A descriptive name of what the promise does for log output.
25
+ * @param promise - The promise to run.
26
+ * @param name - What the promise does, for the log output.
28
27
  */
29
28
  export function logChatPromiseExecution<T>(promise: Promise<T>, name: string) {
30
29
  promise.then().catch((error) => {
@@ -40,12 +39,8 @@ const logListenerError = <T>(scopedLogger: ScopedLogger, error: unknown, event:
40
39
  .error('Unhandled error in event listener', { error, event });
41
40
 
42
41
  /**
43
- * Invokes a single event listener in isolation, so that a faulty listener cannot
44
- * abort the dispatch loop or the bookkeeping that follows it.
45
- *
46
- * Reports two failure modes: a synchronous throw, and a rejected promise from an `async`
47
- * listener — async handlers are assignable to the void-returning `EventHandler` type, so
48
- * without this they would be silent unhandled rejections.
42
+ * Invokes one event listener in isolation: a synchronous throw or a rejected promise (from an
43
+ * `async` listener) is logged and cannot abort the dispatch loop.
49
44
  */
50
45
  export const invokeEventListener = <T>(
51
46
  listener: (event: T) => unknown,
@@ -106,27 +101,19 @@ export function isOwnUserBaseProperty(property: string) {
106
101
  return ownUserBaseProperties[property as keyof OwnUserBase];
107
102
  }
108
103
 
109
- /**
110
- * channelHasReadEvents - Whether read events are enabled for the current user on a channel.
111
- */
104
+ /** Whether `read-events` is among the own capabilities (true while they are not loaded). */
112
105
  export const channelHasReadEvents = (channel?: Channel) => {
113
106
  const ownCapabilities = channel?.data?.own_capabilities;
114
107
  return !(Array.isArray(ownCapabilities) && !ownCapabilities.includes('read-events'));
115
108
  };
116
109
 
117
- /**
118
- * channelTracksReadLocally - Whether a channel maintains a client local unread count.
119
- */
110
+ /** Whether read events are off and the channel keeps a client-local unread count. */
120
111
  export const channelTracksReadLocally = (channel?: Channel) =>
121
112
  !channelHasReadEvents(channel) && !!channel?.config.readEvents.localUnreadCountEnabled;
122
113
 
123
- /**
124
- * retryInterval - A retry interval which increases acc to number of failures
125
- *
126
- * @returns Duration to wait in milliseconds
127
- */
114
+ /** A random retry delay in milliseconds that grows with `numberOfFailures`. */
128
115
  export function retryInterval(numberOfFailures: number) {
129
- // try to reconnect in 0.25-25 seconds (random to spread out the load from failures)
116
+ // 0.25 to 25 seconds, random to spread out the load from failures
130
117
  const max = Math.min(500 + numberOfFailures * 2000, 25000);
131
118
  const min = Math.min(Math.max(250, (numberOfFailures - 1) * 2000), 25000);
132
119
  return Math.floor(Math.random() * (max - min) + min);
@@ -187,14 +174,20 @@ function getRandomBytes(length: number): Uint8Array {
187
174
  return bytes;
188
175
  }
189
176
 
177
+ const isScalarParam = (value: unknown) =>
178
+ typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean';
179
+
190
180
  export const axiosParamsSerializer: AxiosRequestConfig['paramsSerializer'] = (params) => {
191
181
  const newParams = [];
192
182
  for (const k in params) {
193
- // Stream backend doesn't treat "undefined" value same as value not being present.
194
- // So, we need to skip the undefined values.
183
+ // The backend does not treat an "undefined" value as absent, so skip it.
195
184
  if (params[k] === undefined) continue;
196
185
 
197
- if (Array.isArray(params[k]) || typeof params[k] === 'object') {
186
+ // Scalar arrays are comma-separated (`ids=a,b`), as the API parses list params; a JSON array
187
+ // there silently matches nothing.
188
+ if (Array.isArray(params[k]) && params[k].every(isScalarParam)) {
189
+ newParams.push(`${k}=${encodeURIComponent(params[k].join(','))}`);
190
+ } else if (Array.isArray(params[k]) || typeof params[k] === 'object') {
198
191
  newParams.push(`${k}=${encodeURIComponent(JSON.stringify(params[k]))}`);
199
192
  } else {
200
193
  newParams.push(`${k}=${encodeURIComponent(params[k])}`);
@@ -205,14 +198,14 @@ export const axiosParamsSerializer: AxiosRequestConfig['paramsSerializer'] = (pa
205
198
  };
206
199
 
207
200
  /**
208
- * Takes the message object, adds SDK-specific fields (status, error),
209
- * and returns a new LocalMessage object.
201
+ * Adds the SDK-specific fields (`status`, `error`) to a message. Memoized per source object: callers
202
+ * share the result, so do not mutate it.
210
203
  *
211
- * @param message - message object
204
+ * @param message - The message from the API, or a local one.
205
+ * @returns The `LocalMessage`.
212
206
  */
213
207
  export function formatMessage(message: MessageResponse | LocalMessage): LocalMessage {
214
- // Every consumer of one source object gets the same `LocalMessage`, so the message store's
215
- // reference bail fires and siblings are not re-projected once per consumer.
208
+ // Memoized per source object: every consumer gets the same `LocalMessage`.
216
209
  const memoized = getMemoizedFormat(message);
217
210
  if (memoized) return memoized;
218
211
 
@@ -222,9 +215,8 @@ export function formatMessage(message: MessageResponse | LocalMessage): LocalMes
222
215
  if (!msg) return null;
223
216
  return {
224
217
  ...msg,
225
- // Timestamps are the wire's unix-nanosecond numbers and stay that way — there is no
226
- // conversion left to do here. `created_at` / `updated_at` still default, because a locally
227
- // composed message has none until the server answers.
218
+ // Timestamps stay unix nanoseconds. A locally composed message has no `created_at` /
219
+ // `updated_at` until the server answers.
228
220
  created_at: msg.created_at ?? nowNs(),
229
221
  deleted_at: msg.deleted_at ?? undefined,
230
222
  pinned_at: msg.pinned_at ?? undefined,
@@ -250,18 +242,15 @@ export function formatMessage(message: MessageResponse | LocalMessage): LocalMes
250
242
  }
251
243
 
252
244
  /**
253
- * Computes the current user's `own_reactions` after applying a single reaction change, off a
254
- * `current` base. A WS reaction/edit event carries `own_reactions: []` (or stale), so consumers
255
- * must recompute from the copy they already hold rather than trusting the event — this is the
256
- * shared core used by both the message paginator (`reflectReaction`) and the thread's parent
257
- * message (which is not held in any paginator, so it needs the same logic directly).
245
+ * Computes the current user's `own_reactions` after one reaction change, from the `current` copy. A
246
+ * WS reaction event carries `own_reactions: []` (or stale), so it cannot be trusted. Used by
247
+ * `applyReactionLocally` and `reflectReactionEvent`.
258
248
  *
259
249
  * - `removed`: drop the current user's reaction of this type.
260
- * - `enforceUnique`: replace any existing own reaction with the incoming one (used by
261
- * `reaction.updated`, where a user's reaction supersedes their previous one).
250
+ * - `enforceUnique`: replace any own reaction with the incoming one (`reaction.updated`).
262
251
  * - otherwise: add the reaction, de-duped by type.
263
252
  *
264
- * A reaction by another user never changes the current user's `own_reactions`.
253
+ * A reaction by another user never changes `own_reactions`.
265
254
  */
266
255
  export function computeOwnReactions({
267
256
  current,
@@ -286,10 +275,7 @@ export function computeOwnReactions({
286
275
 
287
276
  /**
288
277
  * Returns a copy of `message` with `reaction` folded into its `reaction_groups` /
289
- * `latest_reactions`. Does not touch `own_reactions` — the reaction entry points
290
- * ({@link MessageIntervalPaginator.reflectReaction} / `Thread.applyParentReactionLocally`) own that
291
- * via {@link computeOwnReactions}. Shared so both the paginator and the (paginator-less) thread
292
- * parent compute counts identically.
278
+ * `latest_reactions`. `own_reactions` is left to {@link computeOwnReactions}.
293
279
  */
294
280
  export function messageWithReactionAdded(
295
281
  message: LocalMessage,
@@ -301,7 +287,7 @@ export function messageWithReactionAdded(
301
287
  ...(message.reaction_groups ?? {}),
302
288
  };
303
289
 
304
- // When enforcing uniqueness, first back the current user's existing reactions out of the groups
290
+ // With `enforceUnique`, first back the current user's existing reactions out of the groups.
305
291
  if (enforceUnique) {
306
292
  for (const ownReaction of message.own_reactions ?? []) {
307
293
  const group = reactionGroups[ownReaction.type];
@@ -380,12 +366,9 @@ export function messageWithReactionRemoved(
380
366
  }
381
367
 
382
368
  /**
383
- * Wire timestamps into the `Date` objects `MessageRequest` declares. Sub-millisecond precision is
384
- * lost, which is inherent to the declared request type.
385
- *
386
- * `shared_location` is listed field by field so only what `SharedLocation` declares can reach the
387
- * API — a location read off a message also carries `channel_cid`, `user_id`, `created_at`,
388
- * `updated_at` and `message_id`.
369
+ * Converts wire timestamps into the `Date` objects `MessageRequest` declares (sub-millisecond
370
+ * precision is lost). `shared_location` is copied field by field so only what `SharedLocation`
371
+ * declares reaches the API.
389
372
  */
390
373
  const toRequestDateFields = ({
391
374
  pinned_at,
@@ -411,21 +394,14 @@ const toRequestDateFields = ({
411
394
  : {}),
412
395
  });
413
396
 
414
- /**
415
- * Whether a URL points at something the API and other devices can actually fetch.
416
- */
397
+ /** Whether a URL is HTTP(S), so the API and other devices can fetch it. */
417
398
  const isRemoteUrl = (url?: string) => !!url && /^https?:\/\//i.test(url.trim());
418
399
 
419
400
  /**
420
- * Strips composer-internal state from a message's attachments, and drops any whose upload never
421
- * resolved.
422
- *
423
- * `localMetadata` is how `AttachmentManager` tracks an upload (its id, the `File`, the local
424
- * preview); it must never reach the API. An attachment that still carries it and has no remote
425
- * URL was never settled, which means something bypassed the send path that awaits those uploads.
426
- * Sending it would store an attachment pointing at nothing, so it is dropped and logged instead.
427
- *
428
- * Returns the same message object when there was nothing to change.
401
+ * Strips `localMetadata` (`AttachmentManager`'s upload state, never sent to the API) from a
402
+ * message's attachments. Of those that carried it, drops with a warning the ones with no remote URL:
403
+ * their upload never settled, so something bypassed the send path that awaits uploads. Returns the
404
+ * same message object when nothing changed.
429
405
  */
430
406
  export const sanitizeOutgoingAttachments = <T extends { attachments?: Attachment[] }>(
431
407
  message: T,
@@ -448,8 +424,7 @@ export const sanitizeOutgoingAttachments = <T extends { attachments?: Attachment
448
424
 
449
425
  changed = true;
450
426
 
451
- // Any of these pointing at a remote URL means the attachment resolved to something the API
452
- // can store and other devices can load.
427
+ // A remote URL in any of these means the upload resolved.
453
428
  const hasRemoteSource =
454
429
  isRemoteUrl(rest.asset_url) ||
455
430
  isRemoteUrl(rest.image_url) ||
@@ -481,8 +456,7 @@ export const localMessageToNewMessagePayload = (
481
456
  localMessage: LocalMessage,
482
457
  ): MessageRequest => {
483
458
  const {
484
- // Remove all timestamp fields and client-specific fields.
485
- // Field pinned_at can therefore be earlier than created_at as new message payload can hold it.
459
+ // Timestamp and client-specific fields are removed, so `pinned_at` can precede `created_at`.
486
460
  created_at: _created_at,
487
461
  updated_at: _updated_at,
488
462
  deleted_at: _deleted_at,
@@ -490,30 +464,27 @@ export const localMessageToNewMessagePayload = (
490
464
  pinned_at,
491
465
  pin_expires,
492
466
  shared_location,
493
- // Client-specific fields
494
467
  error: _error,
495
468
  status: _status,
496
- // Reaction related fields
497
469
  latest_reactions: _latest_reactions,
498
470
  own_reactions: _own_reactions,
499
471
  reaction_counts: _reaction_counts,
500
472
  reaction_scores: _reaction_scores,
501
473
  reply_count: _reply_count,
502
- // MessageRequest text related fields that shouldn't be in update
474
+ // Text-related fields that are not sent as-is (`mentioned_users` goes out as IDs)
503
475
  command: _command,
504
476
  html: _html,
505
477
  i18n: _i18n,
506
478
  mentioned_groups: _mentioned_groups,
507
479
  quoted_message: _quoted_message,
508
480
  mentioned_users,
509
- // MessageRequest content related fields
510
481
  ...messageFields
511
482
  } = localMessage;
512
483
 
513
484
  const requestDates = toRequestDateFields({ pinned_at, pin_expires, shared_location });
514
485
 
515
- // `messageFields` still carries LocalMessage-only fields (cid, deleted_reply_count, mentioned_*,
516
- // pinned, shadowed, …) that the stricter OpenAPI `MessageRequest` omits; the server ignores them.
486
+ // `messageFields` carries LocalMessage-only fields (cid, pinned, shadowed, ...) that
487
+ // `MessageRequest` omits; the server ignores them.
517
488
  return {
518
489
  ...(messageFields as MessageRequest),
519
490
  mentioned_users: mentioned_users?.map((user) => user.id),
@@ -560,8 +531,8 @@ export const toDeletedMessage = ({
560
531
  }) => {
561
532
  if (hardDelete) {
562
533
  /**
563
- * In case of hard delete, we need to strip down all text, html, attachments and all the custom properties on message
564
- * The hard-deleted message is kept in the UI until the messages are re-queried
534
+ * On hard delete, strip text, html, attachments and custom properties. The message stays in the
535
+ * UI until messages are re-queried.
565
536
  * FIXME: we are returning an object that does not match LocalMessage
566
537
  */
567
538
  return {
@@ -601,9 +572,8 @@ export const findIndexInSortedArray = <T, L>({
601
572
  needle: T;
602
573
  sortedArray: readonly T[];
603
574
  /**
604
- * In an array of objects (like messages), pick a unique property identifying
605
- * an element. It will be used to find a direct match for the needle element
606
- * in case compare values are not unique.
575
+ * Picks a unique property identifying an element, used to find a direct match for the needle when
576
+ * compare values are not unique.
607
577
  *
608
578
  * @example
609
579
  * ```ts
@@ -612,8 +582,7 @@ export const findIndexInSortedArray = <T, L>({
612
582
  */
613
583
  selectKey?: (arrayElement: T) => string;
614
584
  /**
615
- * In an array of objects (like messages), pick a specific
616
- * property to compare the needle value to.
585
+ * Picks the property to compare the needle to.
617
586
  *
618
587
  * @example
619
588
  * ```ts
@@ -621,14 +590,7 @@ export const findIndexInSortedArray = <T, L>({
621
590
  * ```
622
591
  */
623
592
  selectValueToCompare?: (arrayElement: T) => L | T;
624
- /**
625
- * @default ascending
626
- * @description
627
- * ```md
628
- * ascending - [1,2,3,4,5...]
629
- * descending - [...5,4,3,2,1]
630
- * ```
631
- */
593
+ /** @default 'ascending' */
632
594
  sortDirection?: 'ascending' | 'descending';
633
595
  }) => {
634
596
  if (!sortedArray.length) return 0;
@@ -658,9 +620,8 @@ export const findIndexInSortedArray = <T, L>({
658
620
  }
659
621
  }
660
622
 
661
- // In case there are several array elements with the same comparable value, search around the insertion
662
- // point to possibly find an element with the same key. If found, prefer it.
663
- // This, for example, prevents duplication of messages with the same creation date.
623
+ // With several elements of the same comparable value, search around the insertion point for one
624
+ // with the same key and prefer it (prevents duplicating messages with the same creation date).
664
625
  if (selectKey) {
665
626
  const needleKey = selectKey(needle);
666
627
  const step = sortDirection === 'ascending' ? -1 : +1;
@@ -693,8 +654,8 @@ function maybeGetReactionGroupsFallback(
693
654
  const fallback: { [key: string]: ReactionGroupResponse } = {};
694
655
 
695
656
  for (const type of Object.keys(counts)) {
696
- // Best-effort fallback derived from counts/scores; the richer OpenAPI `ReactionGroupResponse`
697
- // fields (first/last_reaction_at, latest_reactions_by) are not available here.
657
+ // Best effort: `first_reaction_at`, `last_reaction_at` and `latest_reactions_by` cannot be
658
+ // derived.
698
659
  fallback[type] = {
699
660
  count: counts[type],
700
661
  sum_scores: scores[type],
@@ -709,34 +670,22 @@ function maybeGetReactionGroupsFallback(
709
670
 
710
671
  export interface DebouncedFunc<T extends (...args: any[]) => any> {
711
672
  /**
712
- * Call the original function, but applying the debounce rules.
713
- *
714
- * If the debounced function can be run immediately, this calls it and returns its return
715
- * value.
716
- *
717
- * Otherwise, it returns the return value of the last invocation, or undefined if the debounced
718
- * function was not invoked yet.
673
+ * Calls the function under the debounce rules. Returns its value when it runs immediately, else
674
+ * the last invocation's value (`undefined` before the first).
719
675
  */
720
676
  (...args: Parameters<T>): ReturnType<T> | undefined;
721
677
 
722
- /**
723
- * Throw away any pending invocation of the debounced function.
724
- */
725
678
  cancel(): void;
726
679
 
727
680
  /**
728
- * If there is a pending invocation of the debounced function, invoke it immediately and return
729
- * its return value.
730
- *
731
- * Otherwise, return the value from the last invocation, or undefined if the debounced function
732
- * was never invoked.
681
+ * Runs the pending invocation immediately and returns its value; otherwise returns the last
682
+ * invocation's value (`undefined` if never invoked).
733
683
  */
734
684
  flush(): ReturnType<T> | undefined;
735
685
  }
736
686
 
737
- // works exactly the same as lodash.debounce, except that the timeout can also be
738
- // a function of the call arguments, resolved on every call (e.g. to debounce short,
739
- // low-selectivity search queries harder than long ones)
687
+ // Like lodash.debounce, except `timeout` can be a function of the call arguments, resolved on every
688
+ // call.
740
689
  export const debounce = <T extends (...args: any[]) => any>(
741
690
  fn: T,
742
691
  timeout: number | ((...args: Parameters<T>) => number) = 0,
@@ -784,8 +733,6 @@ export const debounce = <T extends (...args: any[]) => any>(
784
733
  return debouncedFn;
785
734
  };
786
735
 
787
- // The single throttle implementation lives in ./utils/throttling/throttle; re-exported here so
788
- // `import { throttle } from './utils'` keeps working (lodash.throttle-style leading/trailing).
789
736
  export { throttle } from './utils/throttling/throttle';
790
737
  export type {
791
738
  Throttled,
@@ -801,7 +748,7 @@ const get = <T>(obj: T, path: string): unknown =>
801
748
  return undefined;
802
749
  }, obj);
803
750
 
804
- // works exactly the same as lodash.uniqBy
751
+ // Like lodash.uniqBy.
805
752
  export const uniqBy = <T>(
806
753
  array: T[] | unknown,
807
754
  iteratee: ((item: T) => unknown) | keyof T,
@@ -819,19 +766,19 @@ export const uniqBy = <T>(
819
766
  };
820
767
 
821
768
  /**
822
- * The user id of a member as `ChannelInput.members` lists it: a user id, `{ user_id }` or
823
- * `{ user: { id } }`.
769
+ * Reads the user ID of a member.
770
+ *
771
+ * @param member - A user ID, a member request or a member response.
772
+ * @returns The user ID, or `''` if there is none.
824
773
  */
825
774
  export const getMemberUserId = (
826
775
  member: string | { user_id?: string; user?: { id?: string } },
827
776
  ) => (typeof member === 'string' ? member : member.user_id || member.user?.id || '');
828
777
 
829
778
  /**
830
- * The id a channel created from members, without an id, has until the server answers: the sorted
831
- * member user ids joined by `,`, after `!members-`. It is the same for the same members whatever
832
- * their order. `undefined` when there are no members.
833
- *
834
- * @param memberIds - The member user ids.
779
+ * The temporary ID of a channel created from members without an ID, until the server answers:
780
+ * `!members-` plus the sorted member IDs joined by `,`, so it is order-independent. `undefined`
781
+ * when there are no members.
835
782
  */
836
783
  export const generateChannelTempId = (memberIds: string[]) => {
837
784
  const membersStr = [...memberIds].filter(Boolean).sort().join(',');
@@ -840,12 +787,9 @@ export const generateChannelTempId = (memberIds: string[]) => {
840
787
  };
841
788
 
842
789
  /**
843
- * The cid a channel created from members, without an id, has until the server answers: its
844
- * {@link generateChannelTempId} under its type. It stands in for the cid the server assigns, so the
845
- * channel is stored once under it. `undefined` when there are no members.
846
- *
847
- * @param channelType - The channel type.
848
- * @param memberIds - The member user ids.
790
+ * The temporary cid of a channel created from members without an ID: its
791
+ * {@link generateChannelTempId} under its type, so the channel is stored once under it until the
792
+ * server assigns the real cid. `undefined` when there are no members.
849
793
  */
850
794
  export const generateChannelTempCid = (channelType: string, memberIds: string[]) => {
851
795
  const tempId = generateChannelTempId(memberIds);