stream-chat 10.0.0-rc.8 → 10.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (366) hide show
  1. package/README.md +7 -6
  2. package/dist/cjs/index.browser.js +22095 -22290
  3. package/dist/cjs/index.browser.js.map +4 -4
  4. package/dist/cjs/index.node.js +22143 -22298
  5. package/dist/cjs/index.node.js.map +4 -4
  6. package/dist/esm/index.mjs +22093 -22288
  7. package/dist/esm/index.mjs.map +4 -4
  8. package/dist/types/ChannelManager.d.ts +216 -135
  9. package/dist/types/CooldownTimer.d.ts +16 -27
  10. package/dist/types/EventHandlerPipeline.d.ts +18 -38
  11. package/dist/types/LiveLocationManager.d.ts +25 -47
  12. package/dist/types/api-client.d.ts +17 -5
  13. package/dist/types/channel.d.ts +435 -500
  14. package/dist/types/channel_state.d.ts +72 -112
  15. package/dist/types/client.d.ts +323 -440
  16. package/dist/types/client_state.d.ts +1 -3
  17. package/dist/types/configuration/ConfigController.d.ts +31 -125
  18. package/dist/types/configuration/InstanceConfigurationRegistry.d.ts +32 -124
  19. package/dist/types/configuration/keys.d.ts +5 -19
  20. package/dist/types/configuration/shape.d.ts +12 -29
  21. package/dist/types/configuration/types.d.ts +64 -79
  22. package/dist/types/configuration/utils/applyInstanceConfiguration.d.ts +14 -36
  23. package/dist/types/configuration/utils/copyConfigPatch.d.ts +8 -0
  24. package/dist/types/configuration/utils/declarativeSlices.d.ts +5 -16
  25. package/dist/types/configuration/utils/deepFreezeConfig.d.ts +3 -17
  26. package/dist/types/configuration/utils/serverAuthority.d.ts +9 -29
  27. package/dist/types/connection/ConnectionIdManager.d.ts +45 -0
  28. package/dist/types/connection/ConnectionRecoveryManager.d.ts +84 -0
  29. package/dist/types/connection/index.d.ts +4 -0
  30. package/dist/types/connection/networkConnection/NetworkConnectionObserver.d.ts +82 -0
  31. package/dist/types/connection/networkConnection/index.d.ts +3 -0
  32. package/dist/types/connection/networkConnection/reporters.d.ts +20 -0
  33. package/dist/types/connection/networkConnection/types.d.ts +40 -0
  34. package/dist/types/connection/wsConnection/StableWSConnection.d.ts +137 -0
  35. package/dist/types/connection/wsConnection/WSConnection.d.ts +105 -0
  36. package/dist/types/connection/wsConnection/WSConnectionFallback.d.ts +47 -0
  37. package/dist/types/connection/wsConnection/config.d.ts +31 -0
  38. package/dist/types/connection/wsConnection/index.d.ts +4 -0
  39. package/dist/types/connection/wsConnection/types.d.ts +46 -0
  40. package/dist/types/constants.d.ts +3 -1
  41. package/dist/types/custom_types.d.ts +0 -2
  42. package/dist/types/entityStore/EntityStore.d.ts +226 -65
  43. package/dist/types/entityStore/StoreBackedItemIndex.d.ts +19 -33
  44. package/dist/types/entityStore/index.d.ts +0 -1
  45. package/dist/types/errors.d.ts +16 -19
  46. package/dist/types/formatMessageMemo.d.ts +5 -0
  47. package/dist/types/gen/chat/ChannelApi.d.ts +5 -1
  48. package/dist/types/gen/chat/ChatApi.d.ts +149 -105
  49. package/dist/types/gen/models/index.d.ts +2540 -698
  50. package/dist/types/gen/models/timestamp-guard.d.ts +22 -0
  51. package/dist/types/gen/moderation/ModerationApi.d.ts +37 -14
  52. package/dist/types/index.d.ts +10 -5
  53. package/dist/types/{i18n/languageNames.d.ts → languageNames.d.ts} +9 -24
  54. package/dist/types/logger.d.ts +1 -3
  55. package/dist/types/messageComposer/CustomDataManager.d.ts +7 -1
  56. package/dist/types/messageComposer/LocationComposer.d.ts +8 -2
  57. package/dist/types/messageComposer/attachmentIdentity.d.ts +24 -0
  58. package/dist/types/messageComposer/attachmentManager.d.ts +52 -24
  59. package/dist/types/messageComposer/attachmentUtils.d.ts +23 -0
  60. package/dist/types/messageComposer/configuration/configuration.d.ts +2 -5
  61. package/dist/types/messageComposer/configuration/types.d.ts +38 -50
  62. package/dist/types/messageComposer/index.d.ts +1 -0
  63. package/dist/types/messageComposer/linkPreviewsManager.d.ts +12 -9
  64. package/dist/types/messageComposer/messageComposer.d.ts +60 -123
  65. package/dist/types/messageComposer/middleware/attachmentManager/postUpload/attachmentEnrichment.d.ts +10 -1
  66. package/dist/types/messageComposer/middleware/messageComposer/attachments.d.ts +4 -0
  67. package/dist/types/messageComposer/middleware/messageComposer/commandInjection.d.ts +5 -0
  68. package/dist/types/messageComposer/middleware/messageComposer/index.d.ts +2 -0
  69. package/dist/types/messageComposer/middleware/messageComposer/pollOnly.d.ts +6 -0
  70. package/dist/types/messageComposer/middleware/messageComposer/userDataInjection.d.ts +5 -0
  71. package/dist/types/messageComposer/middleware/pollComposer/types.d.ts +2 -4
  72. package/dist/types/messageComposer/middleware/pollComposer/validation.d.ts +7 -19
  73. package/dist/types/messageComposer/middleware/textComposer/commandUtils.d.ts +4 -0
  74. package/dist/types/messageComposer/middleware/textComposer/commands.d.ts +11 -2
  75. package/dist/types/messageComposer/middleware/textComposer/mentions.d.ts +20 -19
  76. package/dist/types/messageComposer/middleware/textComposer/textMiddlewareUtils.d.ts +9 -3
  77. package/dist/types/messageComposer/middleware/textComposer/types.d.ts +1 -6
  78. package/dist/types/messageComposer/pollComposer.d.ts +15 -5
  79. package/dist/types/messageComposer/textComposer.d.ts +14 -7
  80. package/dist/types/messageComposer/types.d.ts +27 -7
  81. package/dist/types/messageDelivery/MessageDeliveryReporter.d.ts +27 -80
  82. package/dist/types/messageDelivery/MessageReceiptsTracker.d.ts +43 -73
  83. package/dist/types/messageOperations/FailedSendCache.d.ts +29 -0
  84. package/dist/types/messageOperations/MessageOperationStatePolicy.d.ts +16 -22
  85. package/dist/types/messageOperations/MessageOperations.d.ts +63 -34
  86. package/dist/types/messageOperations/applyReactionLocally.d.ts +15 -0
  87. package/dist/types/messageOperations/createMessageOperations.d.ts +9 -0
  88. package/dist/types/messageOperations/index.d.ts +6 -4
  89. package/dist/types/messageOperations/reflectReactionEvent.d.ts +16 -0
  90. package/dist/types/messageOperations/sendOrdering.d.ts +14 -0
  91. package/dist/types/messageOperations/settlePendingAttachmentUploads.d.ts +20 -0
  92. package/dist/types/messageOperations/types.d.ts +43 -14
  93. package/dist/types/middleware.d.ts +10 -0
  94. package/dist/types/moderation.d.ts +21 -14
  95. package/dist/types/notifications/NotificationManager.d.ts +10 -23
  96. package/dist/types/notifications/types.d.ts +21 -57
  97. package/dist/types/offline-support/offline_support_api.d.ts +150 -528
  98. package/dist/types/offline-support/offline_sync_manager.d.ts +21 -42
  99. package/dist/types/offline-support/queueableOperations.d.ts +35 -37
  100. package/dist/types/offline-support/types.d.ts +40 -185
  101. package/dist/types/pagination/FilterBuilder.d.ts +1 -18
  102. package/dist/types/pagination/ItemIndex.d.ts +4 -12
  103. package/dist/types/pagination/cursorDerivation/aroundPaginationFlags.d.ts +13 -0
  104. package/dist/types/pagination/cursorDerivation/createdAtAroundPaginationFlags.d.ts +4 -5
  105. package/dist/types/pagination/cursorDerivation/linearPaginationFlags.d.ts +19 -5
  106. package/dist/types/pagination/index.d.ts +1 -0
  107. package/dist/types/pagination/paginators/BasePaginator.d.ts +604 -550
  108. package/dist/types/pagination/paginators/ChannelPaginator.d.ts +123 -106
  109. package/dist/types/pagination/paginators/MessageIntervalPaginator.d.ts +576 -327
  110. package/dist/types/pagination/paginators/MessagePaginator.d.ts +237 -131
  111. package/dist/types/pagination/paginators/PinnedMessagePaginator.d.ts +15 -26
  112. package/dist/types/pagination/paginators/ReminderPaginator.d.ts +4 -3
  113. package/dist/types/pagination/paginators/ThreadPaginator.d.ts +44 -0
  114. package/dist/types/pagination/paginators/UserGroupPaginator.d.ts +5 -8
  115. package/dist/types/pagination/paginators/index.d.ts +1 -0
  116. package/dist/types/pagination/sortCompiler.d.ts +11 -22
  117. package/dist/types/pagination/utility.normalization.d.ts +8 -13
  118. package/dist/types/pagination/utility.search.d.ts +3 -8
  119. package/dist/types/poll.d.ts +35 -8
  120. package/dist/types/poll_manager.d.ts +12 -2
  121. package/dist/types/poll_optimistic_votes.d.ts +57 -0
  122. package/dist/types/reminders/Reminder.d.ts +17 -7
  123. package/dist/types/reminders/ReminderManager.d.ts +13 -25
  124. package/dist/types/search/BaseSearchSource.d.ts +10 -8
  125. package/dist/types/search/ChannelSearchSource.d.ts +16 -0
  126. package/dist/types/search/MessageSearchSource.d.ts +17 -0
  127. package/dist/types/search/SearchController.d.ts +26 -28
  128. package/dist/types/search/types.d.ts +6 -10
  129. package/dist/types/signing.d.ts +12 -3
  130. package/dist/types/thread.d.ts +67 -129
  131. package/dist/types/thread_manager.d.ts +95 -66
  132. package/dist/types/token_manager.d.ts +8 -13
  133. package/dist/types/types.d.ts +81 -197
  134. package/dist/types/types.utility.d.ts +3 -3
  135. package/dist/types/upload-utils.d.ts +5 -10
  136. package/dist/types/uploadManager.d.ts +31 -11
  137. package/dist/types/utils/FixedSizeQueueCache.d.ts +8 -11
  138. package/dist/types/utils/WithSubscriptions.d.ts +6 -16
  139. package/dist/types/utils/abort.d.ts +17 -0
  140. package/dist/types/utils/concurrency.d.ts +12 -20
  141. package/dist/types/utils/mergeWith/mergeWith.d.ts +8 -11
  142. package/dist/types/utils/mergeWith/mergeWithCore.d.ts +5 -13
  143. package/dist/types/utils/mergeWith/mergeWithDiff.d.ts +22 -0
  144. package/dist/types/utils/objectPath.d.ts +6 -41
  145. package/dist/types/utils/retryable.d.ts +8 -12
  146. package/dist/types/utils/throttling/throttle.d.ts +8 -23
  147. package/dist/types/utils/time.d.ts +45 -0
  148. package/dist/types/utils.d.ts +74 -93
  149. package/package.json +14 -40
  150. package/src/ChannelManager.ts +494 -303
  151. package/src/CooldownTimer.ts +46 -59
  152. package/src/EventHandlerPipeline.ts +22 -45
  153. package/src/LiveLocationManager.ts +99 -91
  154. package/src/api-client.ts +113 -50
  155. package/src/campaign.ts +1 -1
  156. package/src/channel.ts +1098 -1351
  157. package/src/channel_batch_updater.ts +1 -1
  158. package/src/channel_state.ts +81 -174
  159. package/src/client.ts +755 -970
  160. package/src/client_state.ts +3 -8
  161. package/src/configuration/ConfigController.ts +42 -158
  162. package/src/configuration/InstanceConfigurationRegistry.ts +43 -172
  163. package/src/configuration/index.ts +1 -1
  164. package/src/configuration/keys.ts +13 -32
  165. package/src/configuration/shape.ts +169 -59
  166. package/src/configuration/types.ts +69 -92
  167. package/src/configuration/utils/applyInstanceConfiguration.ts +22 -54
  168. package/src/configuration/utils/copyConfigPatch.ts +11 -32
  169. package/src/configuration/utils/declarativeSlices.ts +9 -39
  170. package/src/configuration/utils/deepFreezeConfig.ts +3 -17
  171. package/src/configuration/utils/index.ts +2 -4
  172. package/src/configuration/utils/serverAuthority.ts +20 -68
  173. package/src/connection/ConnectionIdManager.ts +111 -0
  174. package/src/connection/ConnectionRecoveryManager.ts +257 -0
  175. package/src/connection/index.ts +4 -0
  176. package/src/connection/networkConnection/NetworkConnectionObserver.ts +204 -0
  177. package/src/connection/networkConnection/index.ts +3 -0
  178. package/src/connection/networkConnection/reporters.ts +58 -0
  179. package/src/connection/networkConnection/types.ts +45 -0
  180. package/src/{connection.ts → connection/wsConnection/StableWSConnection.ts} +230 -231
  181. package/src/connection/wsConnection/WSConnection.ts +270 -0
  182. package/src/connection/wsConnection/WSConnectionFallback.ts +250 -0
  183. package/src/connection/wsConnection/config.ts +73 -0
  184. package/src/connection/wsConnection/index.ts +4 -0
  185. package/src/connection/wsConnection/types.ts +48 -0
  186. package/src/constants.ts +7 -5
  187. package/src/custom_types.ts +0 -1
  188. package/src/entityStore/EntityStore.ts +415 -79
  189. package/src/entityStore/StoreBackedItemIndex.ts +37 -41
  190. package/src/entityStore/index.ts +0 -1
  191. package/src/errors.ts +39 -20
  192. package/src/formatMessageMemo.ts +17 -0
  193. package/src/gen/chat/ChannelApi.ts +122 -36
  194. package/src/gen/chat/ChatApi.ts +578 -1752
  195. package/src/gen/models/index.ts +2566 -3440
  196. package/src/gen/models/timestamp-guard.ts +27 -0
  197. package/src/gen/moderation/ModerationApi.ts +183 -406
  198. package/src/index.ts +32 -10
  199. package/src/languageNames.ts +88 -0
  200. package/src/logger.ts +1 -3
  201. package/src/messageComposer/CustomDataManager.ts +19 -6
  202. package/src/messageComposer/LocationComposer.ts +49 -9
  203. package/src/messageComposer/MessageComposerEffectHandlers.ts +1 -2
  204. package/src/messageComposer/attachmentIdentity.ts +54 -0
  205. package/src/messageComposer/attachmentManager.ts +170 -185
  206. package/src/messageComposer/attachmentUtils.ts +44 -0
  207. package/src/messageComposer/configuration/configuration.ts +15 -8
  208. package/src/messageComposer/configuration/types.ts +38 -50
  209. package/src/messageComposer/fileUtils.ts +1 -1
  210. package/src/messageComposer/index.ts +1 -0
  211. package/src/messageComposer/linkPreviewsManager.ts +18 -21
  212. package/src/messageComposer/messageComposer.ts +234 -179
  213. package/src/messageComposer/middleware/attachmentManager/postUpload/AttachmentPostUploadMiddlewareExecutor.ts +1 -1
  214. package/src/messageComposer/middleware/attachmentManager/postUpload/attachmentEnrichment.ts +46 -33
  215. package/src/messageComposer/middleware/attachmentManager/postUpload/uploadErrorHandler.ts +4 -1
  216. package/src/messageComposer/middleware/attachmentManager/preUpload/blockedUploadNotification.ts +1 -1
  217. package/src/messageComposer/middleware/messageComposer/MessageComposerMiddlewareExecutor.ts +6 -0
  218. package/src/messageComposer/middleware/messageComposer/attachments.ts +76 -5
  219. package/src/messageComposer/middleware/messageComposer/commandInjection.ts +10 -4
  220. package/src/messageComposer/middleware/messageComposer/customData.ts +17 -5
  221. package/src/messageComposer/middleware/messageComposer/index.ts +2 -0
  222. package/src/messageComposer/middleware/messageComposer/linkPreviews.ts +22 -12
  223. package/src/messageComposer/middleware/messageComposer/pollOnly.ts +9 -1
  224. package/src/messageComposer/middleware/messageComposer/sharedLocation.ts +7 -2
  225. package/src/messageComposer/middleware/messageComposer/textComposer.ts +1 -1
  226. package/src/messageComposer/middleware/messageComposer/userDataInjection.ts +12 -12
  227. package/src/messageComposer/middleware/pollComposer/state.ts +2 -2
  228. package/src/messageComposer/middleware/pollComposer/types.ts +2 -4
  229. package/src/messageComposer/middleware/pollComposer/validation.ts +8 -26
  230. package/src/messageComposer/middleware/textComposer/TextComposerMiddlewareExecutor.ts +8 -6
  231. package/src/messageComposer/middleware/textComposer/commandUtils.ts +10 -3
  232. package/src/messageComposer/middleware/textComposer/commands.ts +11 -16
  233. package/src/messageComposer/middleware/textComposer/mentions.ts +32 -70
  234. package/src/messageComposer/middleware/textComposer/textMiddlewareUtils.ts +10 -4
  235. package/src/messageComposer/middleware/textComposer/types.ts +1 -6
  236. package/src/messageComposer/pollComposer.ts +21 -9
  237. package/src/messageComposer/textComposer.ts +37 -57
  238. package/src/messageComposer/types.ts +39 -11
  239. package/src/messageDelivery/MessageDeliveryReporter.ts +86 -124
  240. package/src/messageDelivery/MessageReceiptsTracker.ts +122 -139
  241. package/src/messageOperations/FailedSendCache.ts +85 -0
  242. package/src/messageOperations/MessageOperationStatePolicy.ts +124 -116
  243. package/src/messageOperations/MessageOperations.ts +297 -175
  244. package/src/{entityStore → messageOperations}/applyReactionLocally.ts +13 -25
  245. package/src/messageOperations/createMessageOperations.ts +176 -0
  246. package/src/messageOperations/index.ts +6 -14
  247. package/src/messageOperations/reflectReactionEvent.ts +43 -0
  248. package/src/messageOperations/sendOrdering.ts +25 -0
  249. package/src/messageOperations/settlePendingAttachmentUploads.ts +98 -0
  250. package/src/messageOperations/types.ts +51 -13
  251. package/src/middleware.ts +13 -5
  252. package/src/moderation.ts +25 -21
  253. package/src/notifications/NotificationManager.ts +19 -28
  254. package/src/notifications/types.ts +21 -57
  255. package/src/offline-support/offline_support_api.ts +231 -681
  256. package/src/offline-support/offline_sync_manager.ts +51 -90
  257. package/src/offline-support/queueableOperations.ts +98 -73
  258. package/src/offline-support/types.ts +43 -185
  259. package/src/pagination/FilterBuilder.ts +1 -22
  260. package/src/pagination/ItemIndex.ts +4 -12
  261. package/src/pagination/cursorDerivation/aroundPaginationFlags.ts +29 -0
  262. package/src/pagination/cursorDerivation/createdAtAroundPaginationFlags.ts +17 -62
  263. package/src/pagination/cursorDerivation/idAroundPaginationFlags.ts +11 -39
  264. package/src/pagination/cursorDerivation/linearPaginationFlags.ts +53 -33
  265. package/src/pagination/filterCompiler.ts +11 -25
  266. package/src/pagination/index.ts +1 -0
  267. package/src/pagination/paginators/BasePaginator.ts +1415 -1041
  268. package/src/pagination/paginators/ChannelPaginator.ts +481 -219
  269. package/src/pagination/paginators/MessageIntervalPaginator.ts +1362 -775
  270. package/src/pagination/paginators/MessagePaginator.ts +521 -240
  271. package/src/pagination/paginators/PinnedMessagePaginator.ts +32 -40
  272. package/src/pagination/paginators/ReminderPaginator.ts +21 -16
  273. package/src/pagination/paginators/ThreadPaginator.ts +170 -0
  274. package/src/pagination/paginators/UserGroupPaginator.ts +18 -15
  275. package/src/pagination/paginators/index.ts +1 -0
  276. package/src/pagination/paginators/stateThrottling.ts +5 -10
  277. package/src/pagination/sortCompiler.ts +23 -50
  278. package/src/pagination/utility.normalization.ts +17 -24
  279. package/src/pagination/utility.search.ts +4 -11
  280. package/src/poll.ts +183 -102
  281. package/src/poll_manager.ts +24 -22
  282. package/src/poll_optimistic_votes.ts +335 -0
  283. package/src/reminders/Reminder.ts +33 -16
  284. package/src/reminders/ReminderManager.ts +23 -56
  285. package/src/reminders/ReminderTimer.ts +6 -6
  286. package/src/search/BaseSearchSource.ts +19 -25
  287. package/src/search/ChannelSearchSource.ts +43 -1
  288. package/src/search/MessageSearchSource.ts +77 -13
  289. package/src/search/SearchController.ts +39 -36
  290. package/src/search/types.ts +6 -10
  291. package/src/segment.ts +1 -1
  292. package/src/signing.ts +23 -3
  293. package/src/thread.ts +430 -712
  294. package/src/thread_manager.ts +300 -234
  295. package/src/token_manager.ts +12 -22
  296. package/src/types.ts +102 -214
  297. package/src/types.utility.ts +3 -3
  298. package/src/upload-utils.ts +5 -10
  299. package/src/uploadManager.ts +64 -18
  300. package/src/utils/FixedSizeQueueCache.ts +18 -21
  301. package/src/utils/WithSubscriptions.ts +6 -16
  302. package/src/utils/abort.ts +45 -0
  303. package/src/utils/concurrency.ts +16 -55
  304. package/src/utils/mergeWith/mergeWith.ts +10 -13
  305. package/src/utils/mergeWith/mergeWithCore.ts +24 -81
  306. package/src/utils/mergeWith/mergeWithDiff.ts +15 -33
  307. package/src/utils/objectPath.ts +6 -41
  308. package/src/utils/retryable.ts +10 -14
  309. package/src/utils/throttling/throttle.ts +9 -25
  310. package/src/utils/time.ts +64 -0
  311. package/src/utils.ts +227 -174
  312. package/codegen/i18n/callSites.ts +0 -126
  313. package/codegen/i18n/generate.ts +0 -226
  314. package/codegen/i18n/guards.ts +0 -178
  315. package/codegen/i18n/index.ts +0 -29
  316. package/codegen/i18n/stringMaps.ts +0 -91
  317. package/codegen/i18n/types.ts +0 -100
  318. package/dist/cjs/i18n.browser.js +0 -1131
  319. package/dist/cjs/i18n.browser.js.map +0 -7
  320. package/dist/cjs/i18n.node.js +0 -1160
  321. package/dist/cjs/i18n.node.js.map +0 -7
  322. package/dist/esm/i18n-codegen.mjs +0 -409
  323. package/dist/esm/i18n-codegen.mjs.map +0 -7
  324. package/dist/esm/i18n.mjs +0 -1098
  325. package/dist/esm/i18n.mjs.map +0 -7
  326. package/dist/types/ConnectionRecoveryManager.d.ts +0 -156
  327. package/dist/types/connection.d.ts +0 -139
  328. package/dist/types/entityStore/applyReactionLocally.d.ts +0 -26
  329. package/dist/types/gen/model-decoders/decoders.d.ts +0 -3
  330. package/dist/types/gen/model-decoders/event-decoder-mapping.d.ts +0 -6
  331. package/dist/types/i18n/Streami18n.d.ts +0 -168
  332. package/dist/types/i18n/TranslationBuilder.d.ts +0 -70
  333. package/dist/types/i18n/TranslationStore.d.ts +0 -57
  334. package/dist/types/i18n/dayjs.d.ts +0 -104
  335. package/dist/types/i18n/formatters.d.ts +0 -91
  336. package/dist/types/i18n/index.d.ts +0 -15
  337. package/dist/types/i18n/translator.d.ts +0 -29
  338. package/dist/types/i18n/types.d.ts +0 -262
  339. package/dist/types/i18n-codegen/callSites.d.ts +0 -10
  340. package/dist/types/i18n-codegen/generate.d.ts +0 -15
  341. package/dist/types/i18n-codegen/guards.d.ts +0 -61
  342. package/dist/types/i18n-codegen/index.d.ts +0 -29
  343. package/dist/types/i18n-codegen/stringMaps.d.ts +0 -14
  344. package/dist/types/i18n-codegen/types.d.ts +0 -94
  345. package/dist/types/insights.d.ts +0 -56
  346. package/dist/types/messageOperations/optimistic.d.ts +0 -118
  347. package/dist/types/messageOperations/persistence.d.ts +0 -21
  348. package/dist/types/pagination/utility.queryChannel.d.ts +0 -26
  349. package/dist/types/store.d.ts +0 -125
  350. package/src/ConnectionRecoveryManager.ts +0 -293
  351. package/src/gen/model-decoders/decoders.ts +0 -2710
  352. package/src/gen/model-decoders/event-decoder-mapping.ts +0 -198
  353. package/src/i18n/Streami18n.ts +0 -520
  354. package/src/i18n/TranslationBuilder.ts +0 -176
  355. package/src/i18n/TranslationStore.ts +0 -96
  356. package/src/i18n/dayjs.ts +0 -228
  357. package/src/i18n/formatters.ts +0 -461
  358. package/src/i18n/index.ts +0 -15
  359. package/src/i18n/languageNames.ts +0 -103
  360. package/src/i18n/translator.ts +0 -76
  361. package/src/i18n/types.ts +0 -375
  362. package/src/insights.ts +0 -82
  363. package/src/messageOperations/optimistic.ts +0 -249
  364. package/src/messageOperations/persistence.ts +0 -40
  365. package/src/pagination/utility.queryChannel.ts +0 -84
  366. package/src/store.ts +0 -304
@@ -1,22 +1,21 @@
1
- import type {
2
- BasePaginatorConfig,
3
- ExecuteQueryReturnValue,
4
- Interval,
5
- PostQueryReconcileParams,
6
- } from './BasePaginator';
1
+ import type { BasePaginatorConfig, Interval, QueryPagePlacement } from './BasePaginator';
2
+ import { isLogicalInterval } from './BasePaginator';
7
3
  import {
8
4
  type MessagePaginatorOptions as BaseMessagePaginatorOptions,
9
5
  getMessageCreatedAtTimestamp,
10
6
  type JumpToMessageOptions,
11
7
  MessageIntervalPaginator,
8
+ type MessageQueryResponse,
12
9
  type MessageQueryShape,
13
10
  } from './MessageIntervalPaginator';
14
- import type { LocalMessage } from '../../types';
15
- import { StateStore } from '../../store';
11
+ import type { LocalMessage, TimestampNS, UserResponse } from '../../types';
12
+ import type { EntityStoreChangeBatch } from '../../entityStore/EntityStore';
13
+ import { asTimestampNS, nsToDate } from '../../utils/time';
14
+ import { isThreadOnlyReply } from '../../utils';
15
+ import { StateStore } from '@stream-io/state-store';
16
16
 
17
17
  export type {
18
18
  JumpToMessageOptions,
19
- MergeNewestPageOptions,
20
19
  MessageFocusReason,
21
20
  MessageFocusSignal,
22
21
  MessageFocusSignalState,
@@ -24,105 +23,101 @@ export type {
24
23
  MessagePaginatorSort,
25
24
  MessagePaginatorState,
26
25
  MessageQueryShape,
27
- SeedFirstPageOptions,
26
+ PreparedExternalQuery,
27
+ ReconcileNewestMessagesOptions,
28
28
  } from './MessageIntervalPaginator';
29
29
  export { MessageIntervalPaginator } from './MessageIntervalPaginator';
30
30
 
31
31
  /**
32
- * Auxiliary (non-pagination) state for the message paginator: whole-collection aggregates that are
33
- * independent of the active pagination window (the dual of pagination — values over the entire set,
34
- * not a page of it). `lastMessageAt` is effectively `MAX(created_at)` over the channel-relevant
35
- * messages and is the source of truth for channel-list ordering
36
- * (`channel.messagePaginator.lastMessageAt`): seeded from `ChannelResponse.last_message_at`, then
37
- * advanced monotonically as newer messages are ingested.
32
+ * Whole-collection aggregates, independent of the active pagination interval. `latestMessageAt` is
33
+ * the time of the channel's latest message and orders the channel list
34
+ * (`channel.messagePaginator.latestMessageAt`): the later of
35
+ * {@link MessagePaginatorAggregateState.latestMessage}'s `created_at` and the `last_message_at` of
36
+ * the latest channel or thread response.
38
37
  */
39
38
  export type MessagePaginatorAggregateState = {
40
39
  /**
41
- * The newest channel-relevant message, for display (e.g. a channel/thread list item's last-message
42
- * preview or latest-reply avatar). A LIVE reference: it advances to a strictly newer message, is
43
- * refreshed in place when that message is edited/soft-deleted/reacted-to, and is recomputed to the
44
- * next newest when it is hard-removed. Respects `shouldAdvanceLastMessage` (skips system messages
45
- * per `skip_last_msg_update_for_system_msgs`, and thread-only replies). `null` until one is ingested.
40
+ * The newest message the client holds that counts as the channel's latest, from any loaded
41
+ * interval or from an event. Not necessarily the server's latest message: when the client does
42
+ * not hold that one, {@link MessagePaginator.latestMessageAt} is later than its `created_at` (see
43
+ * {@link MessagePaginator.latestMessage}). For display (latest-message preview, latest-reply
44
+ * avatar). A live reference: it advances to a strictly newer message, is refreshed in place on
45
+ * edit, soft-delete or reaction, and is recomputed when hard-removed. Follows
46
+ * `shouldAdvanceLatestMessage` (skips `error` and `ephemeral` messages and thread-only replies).
47
+ * `null` until one is ingested.
46
48
  *
47
- * Lives here, NOT derived from pagination `state`, so it stays reactive when a WS message lands in
48
- * the head interval while an older window is active — the pagination store only emits when the
49
- * active* interval is impacted (see `BasePaginator.ingestItem`), so a `state`-derived latest would
50
- * go stale in that case.
49
+ * It lives outside pagination `state`, which only emits when the active interval is affected: a
50
+ * message landing in the head interval while an older interval is active would go stale there.
51
51
  */
52
- lastMessage: LocalMessage | null;
52
+ latestMessage: LocalMessage | null;
53
53
  /**
54
- * Server-provided `ChannelResponse.last_message_at` floor, for channels whose newest message is not
55
- * loaded (e.g. surfaced by a channel-list query). Kept SEPARATE from {@link lastMessage} so it can
56
- * outrank a stale/absent loaded message for sorting without overwriting the display message. The
57
- * sort key {@link MessagePaginator.lastMessageAt} is derived as the max of the two, so the two can
58
- * never drift out of sync.
54
+ * The `last_message_at` of the latest channel or thread query result (`ChannelResponse` or
55
+ * `ThreadStateResponse`). It comes with the channel or thread data rather than with a message, so
56
+ * the message it refers to may not be loaded. Each query result that carries it replaces it (see
57
+ * {@link MessagePaginator.setQueriedLatestMessageAt}); events never set it, as a new message from
58
+ * an event updates {@link latestMessage} instead. When the newest message is hard-deleted, it
59
+ * moves back to the previous loaded message; a truncation clears it. `null` when the query
60
+ * reported no messages.
61
+ *
62
+ * {@link MessagePaginator.latestMessageAt} is the later of this and {@link latestMessage}'s
63
+ * `created_at`, so it can be later than the message shown as the latest.
59
64
  */
60
- seededLastMessageAt: Date | null;
65
+ queriedLatestMessageAt: TimestampNS | null;
61
66
  };
62
67
 
63
68
  export type MessagePaginatorOptions = BaseMessagePaginatorOptions & {
64
69
  /**
65
- * Controls whether `jumpToTheFirstUnreadMessage()` should prefer the `unreadStateSnapshot`
66
- * state over `channel.state.read[...]`.
67
- *
68
- * - 'snapshot' (default): retrieve the first unread message id from the unreadStateSnapshot state when jumping to the first unread message
69
- * - 'read-state-only': retrieve the last read message id from the channel read state when jumping to the first unread message
70
+ * Where `jumpToTheFirstUnreadMessage()` reads the unread reference from: `'snapshot'`
71
+ * prefers `unreadStateSnapshot`, `'read-state-only'` uses only `channel.state.read[...]`.
72
+ * Defaults to `'snapshot'`.
70
73
  */
71
74
  unreadReferencePolicy?: 'snapshot' | 'read-state-only';
72
75
  };
73
76
 
74
77
  export type UnreadSnapshotState = {
75
- lastReadAt: Date | null;
78
+ lastReadAt: TimestampNS | null;
76
79
  unreadCount: number;
77
80
  /**
78
- * Snapshot of the first unread message id for the user.
79
- * This is intentionally decoupled from `channel.state.read[...]` because apps
80
- * may mark the channel read immediately on open, while still wanting to render
81
- * UI indicators that jump to the previously-unread location.
81
+ * First unread message ID. Decoupled from `channel.state.read[...]` because apps may mark the
82
+ * channel read on open yet still want UI that jumps to the previously unread location.
82
83
  */
83
84
  firstUnreadMessageId: string | null;
84
- /**
85
- * Snapshot of the last read message id for the user (fallback when first unread
86
- * is not known).
87
- */
85
+ /** Last read message ID, a fallback when the first unread is unknown. */
88
86
  lastReadMessageId: string | null;
89
87
  };
90
88
 
91
89
  /**
92
- * External, UI-driven signal: `true` while the user is actively viewing the latest messages of
93
- * this collection (app foregrounded AND the newest message on screen). The owning SDK sets it — the
94
- * state layer has no viewport. When live, an incoming message is NOT counted as unread (the count /
95
- * snapshot bump is skipped), so the "N new" separator/banner never flash for a message the user is
96
- * already looking at. Defaults to `false` (assume not viewing until the SDK proves otherwise).
90
+ * Set by the owning SDK (the state layer has no viewport): `true` while the user views the latest
91
+ * messages (app foregrounded and newest message on screen). While live, an incoming message does
92
+ * not bump the unread count or snapshot. Defaults to `false`.
97
93
  */
98
94
  export type LiveViewState = {
99
95
  isViewingLive: boolean;
100
96
  };
101
97
 
102
98
  /**
103
- * MessagePaginator extends {@link MessageIntervalPaginator} with the unread/live-view concern:
104
- * an independent unread reference snapshot, the UI-driven "viewing the latest messages" signal, and
105
- * the "jump to first unread" navigation built on top of them.
99
+ * Adds the unread snapshot, the UI-driven live-view signal and "jump to first unread" navigation to
100
+ * {@link MessageIntervalPaginator}.
106
101
  */
107
102
  export class MessagePaginator extends MessageIntervalPaginator {
103
+ protected get holderName() {
104
+ return 'message-paginator';
105
+ }
108
106
  private unreadReferencePolicy: 'snapshot' | 'read-state-only';
109
107
  /**
110
- * Independent unread reference state (not tied to `channel.state.read`).
111
- * Consumers may set this right before calling markRead / when opening a channel.
108
+ * Unread reference state, independent of `channel.state.read`. Seeded on each first page;
109
+ * consumers may also set it before `markRead`.
112
110
  */
113
111
  readonly unreadStateSnapshot: StateStore<UnreadSnapshotState>;
114
112
  /**
115
- * UI-driven "viewing the latest messages" signal (see {@link LiveViewState}). Set by the SDK via
116
- * {@link setViewingLive}; read by the channel to gate the unread bump on `message.new`. Subscribe to
117
- * this store for reactivity, or read the current boolean directly via the {@link isViewingLive} getter.
113
+ * The "viewing the latest messages" signal ({@link LiveViewState}), set via {@link setViewingLive}
114
+ * and read by the channel to gate the unread bump on `message.new`.
118
115
  */
119
116
  readonly liveViewState: StateStore<LiveViewState>;
120
117
  /**
121
- * Auxiliary (non-pagination) state — see {@link MessagePaginatorAggregateState}. A store separate
122
- * from `state` so `lastMessageAt` can be advanced from inside a `state.next` updater
123
- * (`ingestPage`) without being clobbered, and so consumers subscribe to a quiet signal that only
124
- * emits when the aggregate actually changes (not on every scroll/pagination emission). This is
125
- * distinct from the base's `intervalViews` interval-projection store.
118
+ * {@link MessagePaginatorAggregateState}, in a store apart from `state` so `latestMessage` can
119
+ * advance from inside a `state.next` updater (`ingestPage`) and subscribers only see aggregate
120
+ * changes.
126
121
  */
127
122
  readonly aggregateState: StateStore<MessagePaginatorAggregateState>;
128
123
 
@@ -130,21 +125,14 @@ export class MessagePaginator extends MessageIntervalPaginator {
130
125
  { unreadReferencePolicy = 'snapshot', ...options }: MessagePaginatorOptions,
131
126
  builtInDefaults: Partial<BasePaginatorConfig<LocalMessage, MessageQueryShape>> = {},
132
127
  ) {
133
- super(
134
- // NB: the store-backed item index is provided by MessageIntervalPaginator (the common
135
- // ancestor), so both the main list and the pinned list share the client-global message store.
136
- options,
137
- {
138
- // Throttle message-list `state` publishes to at most once per 500ms (leading + trailing), so a
139
- // burst of events coalesces into ~2 renders/sec instead of one per event. Optimistic
140
- // (local-user) writes bypass the throttle via EntityStore.flushSubscribers → flushState.
141
- // A default rather than a construction argument, so `paginatorOptions.stateThrottleMs` and a
142
- // declarative registration both override it — and so a re-derivation restores it without the
143
- // subclass having to re-inject it, which is what the old `initializeConfig` override existed for.
144
- stateThrottleMs: 500,
145
- ...builtInDefaults,
146
- },
147
- );
128
+ super(options, {
129
+ // Coalesce live `state.items` publishes to one per 500ms (leading + trailing). Optimistic
130
+ // (local-user) writes bypass it via `EntityStore.flushSubscribers`. A default, so
131
+ // `stateThrottleMs` options and declarative registrations override it and a re-derivation
132
+ // restores it.
133
+ stateThrottleMs: 500,
134
+ ...builtInDefaults,
135
+ });
148
136
  this.unreadReferencePolicy = unreadReferencePolicy;
149
137
  this.unreadStateSnapshot = new StateStore<UnreadSnapshotState>({
150
138
  lastReadAt: null,
@@ -156,157 +144,476 @@ export class MessagePaginator extends MessageIntervalPaginator {
156
144
  isViewingLive: false,
157
145
  });
158
146
  this.aggregateState = new StateStore<MessagePaginatorAggregateState>({
159
- lastMessage: null,
160
- seededLastMessageAt: null,
147
+ latestMessage: null,
148
+ queriedLatestMessageAt: null,
161
149
  });
162
150
  }
163
151
 
164
152
  /**
165
- * Channel-list sort key: the later of the newest loaded message's `created_at` and the server seed.
166
- * **Derived** (never stored) so it cannot drift from {@link lastMessage}. `null` until seeded or a
167
- * message is ingested.
153
+ * The time of the channel's latest message as far as the client knows: the later of
154
+ * {@link latestMessage}'s `created_at` and the `last_message_at` of the latest response (see
155
+ * {@link setQueriedLatestMessageAt}). Later than {@link latestMessage} when the server has newer
156
+ * messages the client does not hold. The channel-list sort key. **Derived** (never stored) so it
157
+ * cannot drift from {@link latestMessage}. A system message that does not move `last_message_at`
158
+ * (see {@link isSkippedSystemMessage}) does not count: the newest loaded message that does is
159
+ * used instead. `null` until a query sets it or a message is ingested.
168
160
  */
169
- get lastMessageAt(): Date | null {
170
- const { lastMessage, seededLastMessageAt } = this.aggregateState.getLatestValue();
171
- const fromMessage =
172
- lastMessage?.created_at instanceof Date ? lastMessage.created_at : null;
173
- if (fromMessage && seededLastMessageAt) {
174
- return fromMessage >= seededLastMessageAt ? fromMessage : seededLastMessageAt;
161
+ get latestMessageAt(): TimestampNS | null {
162
+ return this.latestMessageAtIncluding(this.latestMessageAtSource);
163
+ }
164
+
165
+ /** The newest loaded message that moves `last_message_at`, which {@link latestMessageAt} reads. */
166
+ private get latestMessageAtSource(): LocalMessage | null {
167
+ const { latestMessage } = this.aggregateState.getLatestValue();
168
+ return this.isSkippedSystemMessage(latestMessage)
169
+ ? this.recomputeLatestMessage({ counts: this.movesLastMessageAt })
170
+ : latestMessage;
171
+ }
172
+
173
+ /**
174
+ * {@link latestMessageAt} as the server knows it (see {@link pageReachesHead}): an unsent latest
175
+ * message carries the device's clock, so the latest server-known message counts in its place.
176
+ */
177
+ private get latestServerMessageAt(): TimestampNS | null {
178
+ const { latestMessage } = this.aggregateState.getLatestValue();
179
+ const isUnsent = !!latestMessage && !this.isServerConfirmedMessage(latestMessage);
180
+ return this.latestMessageAtIncluding(
181
+ isUnsent || this.isSkippedSystemMessage(latestMessage)
182
+ ? this.recomputeLatestMessage({
183
+ counts: this.movesLastMessageAt,
184
+ serverConfirmedOnly: true,
185
+ })
186
+ : latestMessage,
187
+ );
188
+ }
189
+
190
+ /** The later of `message`'s `created_at` and the queried `last_message_at`. */
191
+ private latestMessageAtIncluding(message: LocalMessage | null): TimestampNS | null {
192
+ const { queriedLatestMessageAt } = this.aggregateState.getLatestValue();
193
+ const fromMessage = getMessageCreatedAtTimestamp(message);
194
+ if (fromMessage !== null && queriedLatestMessageAt !== null) {
195
+ return asTimestampNS(Math.max(fromMessage, queriedLatestMessageAt));
175
196
  }
176
- return fromMessage ?? seededLastMessageAt;
197
+ return fromMessage ?? queriedLatestMessageAt;
177
198
  }
178
199
 
179
200
  /**
180
- * The newest channel-relevant message (the monotonic tracked latest), for display. Convenience read
181
- * of {@link aggregateState}; subscribe to `aggregateState` for reactivity. `null` until a message is
182
- * ingested (a server-only seed advances {@link lastMessageAt} but leaves this `null`).
201
+ * The newest message the client holds that counts as the channel's latest (see
202
+ * {@link shouldAdvanceLatestMessage}), from any loaded interval or from an event. Not necessarily
203
+ * the server's latest message: {@link latestMessageAt} is later than its `created_at` when the
204
+ * server has newer messages the client does not hold. `null` until a message is ingested (a
205
+ * `last_message_at` from a query sets {@link latestMessageAt} but leaves this `null`).
206
+ * Convenience read of {@link aggregateState}; subscribe to `aggregateState` for reactivity.
207
+ *
208
+ * It differs from {@link anchoredHeadItem}, the newest message of the interval known to reach the
209
+ * server's latest message, in two ways:
210
+ * - It skips messages that do not count: an `error` message can be `anchoredHeadItem` but never
211
+ * `latestMessage`.
212
+ * - It does not need that interval. A channel opened at its first unread message loads m40–m60
213
+ * while the server's newest is m95: `latestMessage` is m60, `latestMessageAt` is m95's time and
214
+ * `anchoredHeadItem` is `undefined`.
183
215
  */
184
- get lastMessage(): LocalMessage | null {
185
- return this.aggregateState.getLatestValue().lastMessage;
216
+ get latestMessage(): LocalMessage | null {
217
+ return this.aggregateState.getLatestValue().latestMessage;
186
218
  }
187
219
 
188
220
  /**
189
- * The main channel list's notion of "latest message" for `channel.state.last_message_at`: on top of
190
- * the base rule (not shadowed) this excludes thread-only replies (a reply with a `parent_id` that is
191
- * not shown in the channel is not part of the channel list) and, when the channel is configured with
192
- * `skip_last_msg_update_for_system_msgs`, system messages. Mirrors the legacy
193
- * `Channel._trackLastMessage` skip logic.
221
+ * The newest server-confirmed message of the interval that reaches the newest message (see
222
+ * {@link anchoredHeadItems}). Any message the interval holds counts, system messages included, but
223
+ * not an unsent one: its id is local. `undefined` while that interval is not loaded or holds no
224
+ * server-confirmed message.
194
225
  *
195
- * These exclusions are specific to the MAIN channel list. A reply list (thread paginator, which has
196
- * a `parentMessageId`) is made ENTIRELY of thread replies — there the newest reply is exactly the
197
- * "latest message", so the exclusions are skipped and only the base rule applies.
226
+ * @internal
227
+ */
228
+ get anchoredHeadServerConfirmedItem(): LocalMessage | undefined {
229
+ const head = this.anchoredHeadInterval;
230
+ return head ? this.getServerKnownEdges(head).head : undefined;
231
+ }
232
+
233
+ /**
234
+ * Whether `message` counts as the channel's latest message: not shadowed, not an `error` or
235
+ * `ephemeral` message (only the current user sees those, e.g. a failed command or a giphy preview)
236
+ * and, in the main list, not a thread-only reply. A reply list (`parentMessageId` set) holds only
237
+ * thread replies, so the thread-only rule does not apply there.
198
238
  */
199
- protected shouldAdvanceLastMessage(message: LocalMessage): boolean {
239
+ protected shouldAdvanceLatestMessage(message: LocalMessage): boolean {
200
240
  if (message.shadowed) return false;
241
+ if (message.type === 'error' || message.type === 'ephemeral') return false;
201
242
  if (this.parentMessageId) return true;
202
- const isThreadOnlyReply = !!message.parent_id && !message.show_in_channel;
203
- if (isThreadOnlyReply) return false;
204
- const skipSystemMessage =
205
- !!this.channel.serverConfig?.skip_last_msg_update_for_system_msgs &&
206
- message.type === 'system';
207
- return !skipSystemMessage;
243
+ return !isThreadOnlyReply(message);
208
244
  }
209
245
 
210
246
  /**
211
- * Monotonically advance {@link lastMessageAt} to `message.created_at` when it is newer than the
212
- * current value and {@link shouldAdvanceLastMessage} permits it. Writes the dedicated
213
- * {@link aggregateState} store (not `state`), so it is safe to call from inside a `state.next`
214
- * updater (`ingestPage`). Returns `true` when the value moved.
215
- *
216
- * Called internally on ingest; also public for callers that advance the aggregate without a normal
217
- * in-window ingest — e.g. offline pending-message replay, where the sent message has not yet been
218
- * ingested via the `message.new` event.
247
+ * Whether `message` is a main-list system message that, with
248
+ * `skip_last_msg_update_for_system_msgs`, does not move the channel's `last_message_at` on the
249
+ * server. It is still shown as the {@link latestMessage}, but {@link latestMessageAt} skips it.
219
250
  */
220
- trackLastMessage(message: LocalMessage): boolean {
221
- if (!this.shouldAdvanceLastMessage(message)) return false;
251
+ private isSkippedSystemMessage(message: LocalMessage | null): boolean {
252
+ return (
253
+ !!message &&
254
+ !this.parentMessageId &&
255
+ message.type === 'system' &&
256
+ !!this.channel.serverConfig?.skip_last_msg_update_for_system_msgs
257
+ );
258
+ }
259
+
260
+ /** Whether `message` counts for {@link latestMessageAt}. */
261
+ private movesLastMessageAt = (message: LocalMessage) =>
262
+ this.shouldAdvanceLatestMessage(message) && !this.isSkippedSystemMessage(message);
263
+
264
+ /**
265
+ * Advances {@link latestMessage} (and so {@link latestMessageAt}) to `message` when it is newer
266
+ * and {@link shouldAdvanceLatestMessage} permits. Writes {@link aggregateState} only, so it is
267
+ * safe inside a `state.next` updater (`ingestPage`). Returns `true` when the value moved. Public
268
+ * for callers that advance it without an in-interval ingest, e.g. offline pending-message replay.
269
+ */
270
+ trackLatestMessage(message: LocalMessage): boolean {
271
+ const current = this.aggregateState.getLatestValue().latestMessage;
272
+ if (!this.shouldAdvanceLatestMessage(message)) {
273
+ if (current?.id !== message.id) return false;
274
+ this.aggregateState.partialNext({
275
+ latestMessage: this.recomputeLatestMessage({ excludeId: message.id }),
276
+ });
277
+ return true;
278
+ }
222
279
  const incoming = getMessageCreatedAtTimestamp(message);
223
280
  if (incoming === null) return false;
224
- const current = this.aggregateState.getLatestValue().lastMessage;
225
- // Refresh in place when this IS the current latest being updated — an edit, soft-delete,
226
- // reaction, or quoted-message update all re-ingest the same id (same `created_at`). This keeps
227
- // `lastMessage` a LIVE reference (so a preview shows "deleted"/edited text), and because
228
- // `aggregateState` emits regardless of the active interval, it stays reactive off-window.
281
+ // An edit, soft-delete, reaction or quote update re-ingests the current latest (same ID and
282
+ // `created_at`): refresh it in place so `latestMessage` stays live.
229
283
  if (current && current.id === message.id) {
230
- this.aggregateState.partialNext({ lastMessage: message });
284
+ this.aggregateState.partialNext({ latestMessage: message });
231
285
  return true;
232
286
  }
233
- // Otherwise only advance to a strictly newer message. Guard against the current message's own
234
- // timestamp — NOT `lastMessageAt` (which the server seed can inflate); otherwise a seed newer than
235
- // the loaded window would reject the very message it was derived from.
287
+ // Otherwise only a strictly newer message advances. Compare against the current message's own
288
+ // timestamp, not `latestMessageAt`: a queried `last_message_at` newer than the loaded interval
289
+ // would reject the message.
236
290
  const currentTs = current ? getMessageCreatedAtTimestamp(current) : null;
237
291
  if (currentTs !== null && incoming <= currentTs) return false;
238
- this.aggregateState.partialNext({ lastMessage: message });
292
+ this.aggregateState.partialNext({ latestMessage: message });
239
293
  return true;
240
294
  }
241
295
 
242
296
  /**
243
- * Seed {@link lastMessageAt} from the server-provided `ChannelResponse.last_message_at`, the
244
- * authoritative whole-channel aggregate. Monotonic: a no-op when the paginator already advanced
245
- * past it (e.g. from ingested messages), so seed order does not matter.
297
+ * Sets {@link MessagePaginatorAggregateState.queriedLatestMessageAt} from a query result's
298
+ * `last_message_at` (a channel's, or a thread's for a reply list), which {@link latestMessageAt}
299
+ * then takes into account. Each result replaces the previous value, even with an earlier one:
300
+ * the newest message may have been hard-deleted, which no event reports with the new value. A
301
+ * message ingested after the result was produced, such as a new one from an event, still counts,
302
+ * through {@link latestMessage}. `null` clears it (no messages); `undefined` (not in the result)
303
+ * leaves it.
304
+ */
305
+ setQueriedLatestMessageAt(value: TimestampNS | null | undefined) {
306
+ if (value === undefined) return;
307
+ const next = value !== null && Number.isFinite(value) ? value : null;
308
+ if (next === this.aggregateState.getLatestValue().queriedLatestMessageAt) return;
309
+ this.aggregateState.partialNext({ queriedLatestMessageAt: next });
310
+ }
311
+
312
+ /**
313
+ * Clears the head mark of the head interval when it is stale (see {@link unmarkHead}). It is stale
314
+ * when its newest message is older than the `last_message_at` the latest query returned (see
315
+ * {@link setQueriedLatestMessageAt}): the channel has newer messages the interval lacks. The
316
+ * interval then stops being the head interval ({@link anchoredHeadItem} becomes `undefined`) and
317
+ * can load newer messages, and a message that then arrives from an event starts a separate head
318
+ * interval instead of joining it across the gap. Messages that exist only locally, such as a
319
+ * failed send, are left out of the comparison: they carry the device's clock.
320
+ *
321
+ * For example, the interval holds m1–m20 and the channel is not watched while m21–m25 are sent. A
322
+ * query returns m25's time: the interval can now load m21–m25, and m26 from an event does not land
323
+ * right after m20.
324
+ *
325
+ * Call it with each response that does not bring the newest messages up to date, before any page
326
+ * the response carries is placed: a page that reaches the newest message marks its own interval as
327
+ * the head. Call it only when no events were arriving before the response and nothing else
328
+ * brings the newest messages: while the channel is watched, a message the interval lacks is still
329
+ * on its way, and a re-watch that places the newest page settles the interval itself.
330
+ */
331
+ unmarkStaleHead() {
332
+ const head = this.anchoredHeadInterval;
333
+ const { queriedLatestMessageAt } = this.aggregateState.getLatestValue();
334
+ if (!head || queriedLatestMessageAt === null) return;
335
+ let headNewestAt: TimestampNS | null = null;
336
+ for (const message of this.intervalToItems(head)) {
337
+ if (!this.isServerConfirmedMessage(message)) continue;
338
+ const createdAt = getMessageCreatedAtTimestamp(message);
339
+ if (createdAt !== null && (headNewestAt === null || createdAt > headNewestAt))
340
+ headNewestAt = createdAt;
341
+ }
342
+ if (headNewestAt !== null && headNewestAt >= queriedLatestMessageAt) return;
343
+ this.unmarkHead(head);
344
+ }
345
+
346
+ /**
347
+ * A page reaches the newest message when its newest message is at or after
348
+ * {@link latestServerMessageAt}, as known before the page is ingested; one older than that is not
349
+ * the newest. That value comes from the latest response (`ChannelResponse` for a channel,
350
+ * `ThreadStateResponse` for a reply list, through {@link setQueriedLatestMessageAt}) and from the
351
+ * messages ingested since, such as new ones from events. `undefined` while it is not known.
246
352
  */
247
- seedLastMessageAt(value: string | Date | null | undefined) {
248
- if (!value) return;
249
- const date = value instanceof Date ? value : new Date(value);
250
- const timestamp = date.getTime();
251
- if (!Number.isFinite(timestamp)) return;
252
- const current = this.aggregateState.getLatestValue().seededLastMessageAt;
253
- if (current && timestamp <= current.getTime()) return;
254
- this.aggregateState.partialNext({ seededLastMessageAt: date });
353
+ protected override pageReachesHead(page: LocalMessage[]): boolean | undefined {
354
+ const latestServerMessageAt = this.latestServerMessageAt;
355
+ if (latestServerMessageAt === null) return undefined;
356
+ // the page's newest message is at its head edge
357
+ const createdAt = getMessageCreatedAtTimestamp(
358
+ this.getPagePaginationEdges(page).head,
359
+ );
360
+ return createdAt !== null && createdAt >= latestServerMessageAt;
255
361
  }
256
362
 
363
+ /**
364
+ * Ingests a single message, from an event or an operation such as a send. A message that starts
365
+ * the newest interval is placed by {@link ingestAsNewestInterval}. Any other goes into the
366
+ * interval it belongs to and the active interval stays active, except for the current user's new
367
+ * send (see {@link isOwnSendWhileOlderIntervalIsActive}): the newest interval holding it is
368
+ * shown, so the user sees what they sent.
369
+ */
257
370
  ingestItem(item: LocalMessage): boolean {
258
- // Only items that survive the filter advance the aggregate (`ingestItem` also handles removals
259
- // of items that no longer match). The advance writes the separate `aggregateState` store, so it
260
- // is independent of `super`'s `state`/index mutations.
371
+ // Only items passing the filter advance the aggregate (`ingestItem` also removes the others).
261
372
  if (this.matchesFilter(item)) {
262
- this.trackLastMessage(item);
373
+ if (this.isNewNewestMessage(item)) return this.ingestAsNewestInterval(item);
374
+ this.trackLatestMessage(item);
375
+ }
376
+ // judged before ingesting, while the message is not held yet
377
+ const showsNewestInterval = this.isOwnSendWhileOlderIntervalIsActive(item);
378
+ const ingested = super.ingestItem(item);
379
+ const newest = this.anchoredHeadInterval;
380
+ if (ingested && showsNewestInterval && newest?.itemIds.includes(item.id)) {
381
+ this.showIntervalOfOwnSend(newest);
382
+ }
383
+ return ingested;
384
+ }
385
+
386
+ /**
387
+ * Whether `message` is the current user's own send (see {@link isOwnSend}) that the paginator
388
+ * does not hold yet, while the newest interval is loaded but another interval is active. A message
389
+ * already held (a retry of a failed send, a replayed send, its server confirmation) is not new.
390
+ */
391
+ private isOwnSendWhileOlderIntervalIsActive(message: LocalMessage): boolean {
392
+ const newest = this.anchoredHeadInterval;
393
+ return (
394
+ !!newest &&
395
+ !this.isActiveInterval(newest) &&
396
+ !this.getItem(message.id) &&
397
+ this.isOwnSend(message)
398
+ );
399
+ }
400
+
401
+ /**
402
+ * Shows the interval holding the current user's own send. The send decides the interval shown, so
403
+ * it claims the active interval as a jump does: a page a query claimed earlier is then only
404
+ * stored.
405
+ */
406
+ private showIntervalOfOwnSend(interval: Interval) {
407
+ this.claimActiveInterval();
408
+ this.showLoadedInterval(interval);
409
+ }
410
+
411
+ /**
412
+ * A message the paginator does not hold yet, at or after {@link latestMessageAt} (as known before
413
+ * it arrives), while no loaded interval reaches the newest message. It is then the newest message,
414
+ * so it starts the newest interval, as a page holding it would (see {@link pageReachesHead}).
415
+ */
416
+ private isNewNewestMessage(message: LocalMessage): boolean {
417
+ if (this.anchoredHeadItem !== undefined || this.getItem(message.id)) return false;
418
+ const latestMessageAt = this.latestMessageAt;
419
+ const createdAt = getMessageCreatedAtTimestamp(message);
420
+ return latestMessageAt !== null && createdAt !== null && createdAt >= latestMessageAt;
421
+ }
422
+
423
+ /**
424
+ * The logical-head items (ingested one by one, usually from events, rather than as part of a
425
+ * page) not older than `queriedLatestMessageAt`, the `last_message_at` of the latest channel or
426
+ * thread response; all of them when no response has set it. They were ingested after that
427
+ * response, one after another, so nothing is missing between them. Items older than that, such as
428
+ * a message arriving out of order, are left out.
429
+ */
430
+ private get logicalHeadItemsSinceQueriedLatestMessageAt(): LocalMessage[] {
431
+ const { queriedLatestMessageAt } = this.aggregateState.getLatestValue();
432
+ return this.logicalHeadItems.filter((item) => {
433
+ const createdAt = getMessageCreatedAtTimestamp(item);
434
+ return (
435
+ queriedLatestMessageAt === null ||
436
+ (createdAt !== null && createdAt >= queriedLatestMessageAt)
437
+ );
438
+ });
439
+ }
440
+
441
+ /**
442
+ * Starts the newest interval with `message`, together with the
443
+ * {@link logicalHeadItemsSinceQueriedLatestMessageAt} ingested before it. It can load older
444
+ * messages unless none are left to load (see {@link hasNoMessagesBeforeLiveMessages}). It becomes
445
+ * the active interval when no interval was active, when the logical head it takes items from was,
446
+ * or when `message` is the current user's own send (see {@link isOwnSend}), as every own send
447
+ * shows the newest interval (see {@link ingestItem}).
448
+ */
449
+ private ingestAsNewestInterval(message: LocalMessage): boolean {
450
+ const liveHead = this.liveHeadLogical;
451
+ const interval = this.ingestPage({
452
+ page: [...this.logicalHeadItemsSinceQueriedLatestMessageAt, message],
453
+ isHead: true,
454
+ isTail: this.hasNoMessagesBeforeLiveMessages,
455
+ setActive: false,
456
+ });
457
+ if (!interval) return false;
458
+
459
+ if (this.isOwnSend(message)) {
460
+ this.showIntervalOfOwnSend(interval);
461
+ } else if (
462
+ !this._activeIntervalId ||
463
+ (!!liveHead && this.isActiveInterval(liveHead))
464
+ ) {
465
+ this.showLoadedInterval(interval);
263
466
  }
264
- return super.ingestItem(item);
467
+ return true;
468
+ }
469
+
470
+ /**
471
+ * Whether no message older than the live messages is left to load: no interval of queried messages
472
+ * is loaded and the list reports no older messages, as after a newest page that came back empty.
473
+ * A list never queried, or one holding an interval (a jumped-to one, or one whose head mark was
474
+ * cleared), has older messages to load.
475
+ */
476
+ private get hasNoMessagesBeforeLiveMessages(): boolean {
477
+ return (
478
+ this.hasMoreTail === false &&
479
+ this.itemIntervals.every((interval) => isLogicalInterval(interval))
480
+ );
481
+ }
482
+
483
+ /**
484
+ * Whether `message` is one the current user is sending from this device: status `sending` and
485
+ * authored by the client's user. The same user's message from another device arrives
486
+ * server-confirmed and is not one.
487
+ */
488
+ private isOwnSend(message: LocalMessage): boolean {
489
+ return message.status === 'sending' && this.isOwnMessage(message);
490
+ }
491
+
492
+ /** Whether the client's user wrote `message`; never for a paginator without a client. */
493
+ private isOwnMessage(message: LocalMessage): boolean {
494
+ const userId = this.channel.getClient?.()?.userId;
495
+ return !!userId && message.user?.id === userId;
265
496
  }
266
497
 
267
498
  ingestPage(
268
499
  params: Parameters<MessageIntervalPaginator['ingestPage']>[0],
269
500
  ): Interval | null {
270
501
  const interval = super.ingestPage(params);
271
- // Advance from each page item; the monotonic max over the page yields the newest. Comparison is
272
- // by `created_at` against `aggregateState` (no index lookup), so order vs `super` is irrelevant.
273
502
  if (params.page?.length) {
274
- for (const item of params.page) this.trackLastMessage(item);
503
+ for (const item of params.page) this.trackLatestMessage(item);
275
504
  }
276
505
  return interval;
277
506
  }
278
507
 
508
+ onEntitiesChanged(batch: EntityStoreChangeBatch) {
509
+ super.onEntitiesChanged(batch);
510
+ const { latestMessage } = this.aggregateState.getLatestValue();
511
+ if (!latestMessage || !batch.changedIds.has(latestMessage.id)) return;
512
+ const stored = this.getItem(latestMessage.id);
513
+ if (!stored) return;
514
+ this.aggregateState.partialNext({
515
+ latestMessage: this.shouldAdvanceLatestMessage(stored)
516
+ ? stored
517
+ : this.recomputeLatestMessage({ excludeId: stored.id }),
518
+ });
519
+ }
520
+
521
+ reflectUserUpdate(user: UserResponse) {
522
+ super.reflectUserUpdate(user);
523
+ const { latestMessage } = this.aggregateState.getLatestValue();
524
+ if (latestMessage?.user?.id !== user.id) return;
525
+ this.aggregateState.partialNext({ latestMessage: { ...latestMessage, user } });
526
+ }
527
+
279
528
  removeItem(
280
529
  params: Parameters<MessageIntervalPaginator['removeItem']>[0],
281
530
  ): ReturnType<MessageIntervalPaginator['removeItem']> {
282
531
  const removedId =
283
532
  params.id ?? (params.item ? this.getItemId(params.item) : undefined);
284
- const wasLatest =
285
- !!removedId && this.aggregateState.getLatestValue().lastMessage?.id === removedId;
533
+ const { latestMessage, queriedLatestMessageAt } =
534
+ this.aggregateState.getLatestValue();
535
+ const wasLatest = !!removedId && latestMessage?.id === removedId;
536
+ // A skipped system message can be the latest without moving `last_message_at`, so the message
537
+ // that did can be another one.
538
+ const latestMessageAtSource = removedId ? this.latestMessageAtSource : null;
539
+ const wasLatestMessageAtSource =
540
+ !!removedId && latestMessageAtSource?.id === removedId;
286
541
  const result = super.removeItem(params);
287
- if (wasLatest) {
288
- // The tracked latest was hard-removed; fall back to the newest still-loaded message that
289
- // passes the filter. `trackLastMessage` cannot do this (it only advances), so recompute here.
290
- this.aggregateState.partialNext({ lastMessage: this.recomputeLastMessage() });
291
- }
542
+ if (!wasLatest && !wasLatestMessageAtSource) return result;
543
+ // A tracked message was hard-removed; fall back to the newest still-loaded message that counts,
544
+ // which `trackLatestMessage` cannot do (it only advances).
545
+ const previousAt = wasLatestMessageAtSource
546
+ ? getMessageCreatedAtTimestamp(
547
+ this.recomputeLatestMessage({ counts: this.movesLastMessageAt }),
548
+ )
549
+ : null;
550
+ const removedAt = getMessageCreatedAtTimestamp(latestMessageAtSource);
551
+ const isQueriedFromRemovedMessage =
552
+ wasLatestMessageAtSource &&
553
+ queriedLatestMessageAt !== null &&
554
+ removedAt !== null &&
555
+ queriedLatestMessageAt <= removedAt;
556
+ // The server moves `last_message_at` back to the previous message without sending it, so the
557
+ // queried value takes the previous loaded message's time. With none loaded the new value is
558
+ // unknown, and it stays.
559
+ this.aggregateState.partialNext({
560
+ latestMessage: wasLatest ? this.recomputeLatestMessage() : latestMessage,
561
+ queriedLatestMessageAt:
562
+ isQueriedFromRemovedMessage && previousAt !== null
563
+ ? previousAt
564
+ : queriedLatestMessageAt,
565
+ });
292
566
  return result;
293
567
  }
294
568
 
569
+ truncate(params: Parameters<MessageIntervalPaginator['truncate']>[0]) {
570
+ super.truncate(params);
571
+ const { latestMessage, queriedLatestMessageAt } =
572
+ this.aggregateState.getLatestValue();
573
+ const isTruncated = (timestamp: TimestampNS | null) =>
574
+ timestamp !== null && timestamp < params.truncatedAt;
575
+ const isLatestMessageTruncated = isTruncated(
576
+ getMessageCreatedAtTimestamp(latestMessage),
577
+ );
578
+ const isQueriedLatestMessageAtTruncated = isTruncated(queriedLatestMessageAt);
579
+ if (!isLatestMessageTruncated && !isQueriedLatestMessageAtTruncated) return;
580
+ this.aggregateState.partialNext({
581
+ latestMessage: isLatestMessageTruncated
582
+ ? this.recomputeLatestMessage()
583
+ : latestMessage,
584
+ queriedLatestMessageAt: isQueriedLatestMessageAtTruncated
585
+ ? null
586
+ : queriedLatestMessageAt,
587
+ });
588
+ }
589
+
295
590
  /**
296
- * The still-loaded message with the greatest `created_at` that passes
297
- * {@link shouldAdvanceLastMessage} (skips system / thread-only per config), from the newest-loaded
298
- * window. Used to recompute the tracked latest after the current one is removed. `null` when nothing
299
- * loaded qualifies.
300
- *
301
- * "Latest" is defined by `created_at` (matching {@link trackLastMessage}), NOT by the paginator's
302
- * display order — so this compares timestamps rather than assuming a position, and stays correct
303
- * whatever `itemOrder` / `requestSort` are configured to.
591
+ * The still-loaded message with the greatest `created_at` that `counts` (by default
592
+ * {@link shouldAdvanceLatestMessage}), from the interval that reaches the newest message and the
593
+ * {@link logicalHeadItemsSinceQueriedLatestMessageAt}. An interval reached by a jump is not
594
+ * searched, nor an out-of-order older message: neither is the channel's previous message. Used to
595
+ * recompute the tracked latest after the current one is removed or stops counting;
596
+ * `serverConfirmedOnly` skips unsent messages and `excludeId` skips that message. `null` when
597
+ * nothing loaded qualifies. It compares timestamps rather than positions, so it holds for any
598
+ * `itemOrder` / `requestSort`.
304
599
  */
305
- private recomputeLastMessage(): LocalMessage | null {
600
+ private recomputeLatestMessage({
601
+ counts = (message) => this.shouldAdvanceLatestMessage(message),
602
+ excludeId,
603
+ serverConfirmedOnly = false,
604
+ }: {
605
+ counts?: (message: LocalMessage) => boolean;
606
+ excludeId?: string;
607
+ serverConfirmedOnly?: boolean;
608
+ } = {}): LocalMessage | null {
306
609
  let latest: LocalMessage | null = null;
307
610
  let latestTimestamp = -Infinity;
308
- for (const item of this.headItems) {
309
- if (!this.shouldAdvanceLastMessage(item)) continue;
611
+ for (const item of [
612
+ ...this.anchoredHeadItems,
613
+ ...this.logicalHeadItemsSinceQueriedLatestMessageAt,
614
+ ]) {
615
+ if (item.id === excludeId || !counts(item)) continue;
616
+ if (serverConfirmedOnly && !this.isServerConfirmedMessage(item)) continue;
310
617
  const timestamp = getMessageCreatedAtTimestamp(item);
311
618
  if (timestamp === null || timestamp <= latestTimestamp) continue;
312
619
  latest = item;
@@ -316,23 +623,18 @@ export class MessagePaginator extends MessageIntervalPaginator {
316
623
  }
317
624
 
318
625
  /**
319
- * (Re)seed the unread state snapshot from the current own read state.
320
- *
321
- * Called after the first-page query, and can be called again by the SDK whenever a channel is
322
- * (re)opened from a cached paginator — where no fresh first-page query runs — so the snapshot
323
- * reflects the CURRENT read boundary rather than one frozen at the very first open. Without a
324
- * re-seed the separator position, unread count and "jump to first unread" target all go stale
325
- * across reopens.
626
+ * (Re)seeds the unread snapshot from the own read state. Runs once a first page and the rest of
627
+ * its response are in (the paginator's own first-page queries, `watch()` and the channel-list
628
+ * hydrate, when these place one), and the SDK calls it again when a channel is reopened from a
629
+ * cached paginator (no first-page query), so the separator, unread count and jump target follow
630
+ * the current read boundary.
326
631
  *
327
- * `firstUnreadMessageId` is intentionally reset to `null`: it represents an EXPLICIT mark-unread
328
- * (set by `notification.mark_unread`), not a live/computed boundary. Persisting a computed value
329
- * here would make the channel look explicitly marked-unread and suppress auto-mark-read.
632
+ * `firstUnreadMessageId` is reset to `null`: it holds only an explicit mark-unread
633
+ * (`notification.mark_unread`), and a computed value would suppress auto-mark-read.
330
634
  */
331
635
  seedUnreadSnapshot = () => {
332
- // A paginator query (BasePaginator.executeQuery) awaits the network before running its
333
- // synchronous postQueryReconcile, which calls this on the first page. If the channel was
334
- // torn down while that request was in flight, reading the client below throws (the channel is
335
- // pending disposal), so guard against that.
636
+ // The query awaits the network before this runs: the channel may be pending disposal by then,
637
+ // and `getClient()` throws.
336
638
  if (this.channel.pendingDisposal) return;
337
639
  const ownUserId = this.channel.getClient().user?.id;
338
640
  const ownReadState = ownUserId ? this.channel.state.read[ownUserId] : undefined;
@@ -346,38 +648,30 @@ export class MessagePaginator extends MessageIntervalPaginator {
346
648
  };
347
649
 
348
650
  /**
349
- * Invokes super.postQueryReconcile() and takes an unread state snapshot on the first-page query.
350
- * The snapshot has to be taken immediately after the query as the viewed channel is marked read
351
- * immediately after opening it. The snapshot can be used to display unread UI indicators.
651
+ * Applies the rest of the response, then takes the unread snapshot after a first-page query, from
652
+ * the read state the response brought. A viewed channel is marked read right after it opens, so
653
+ * the snapshot keeps the unread state from before, for unread UI indicators.
352
654
  */
353
- postQueryReconcile(
354
- params: PostQueryReconcileParams<LocalMessage, MessageQueryShape>,
355
- ): ExecuteQueryReturnValue<LocalMessage> {
356
- const result = super.postQueryReconcile(params);
357
-
358
- if (params.isFirstPage) {
359
- this.seedUnreadSnapshot();
360
- }
361
- return result;
655
+ protected override applyQueryResponseRest(
656
+ response: MessageQueryResponse,
657
+ placeParams: QueryPagePlacement<MessageQueryShape>,
658
+ ) {
659
+ super.applyQueryResponseRest(response, placeParams);
660
+ if (placeParams.isFirstPage) this.seedUnreadSnapshot();
362
661
  }
363
662
 
364
663
  /**
365
- * Jumps to the unread reference message.
366
- *
367
- * IMPORTANT: This intentionally does *not* rely on `channel.state.read[ownUserId]` only,
368
- * because apps may mark a channel read immediately after opening it, while still
369
- * wanting to keep "jump to unread" UI indicators alive (based on a snapshot).
664
+ * Jumps to the unread reference message. It does not rely on `channel.state.read` alone, since
665
+ * apps may mark a channel read on open yet keep "jump to unread" UI alive from the snapshot.
370
666
  *
371
667
  * Resolution order:
372
- * 1) explicit first-unread id from snapshot/read-state (mark-unread) — jump straight to it
373
- * 2) last-read timestamp: infer the FIRST UNREAD message from it — using the already-loaded
374
- * window when it straddles the boundary, otherwise a `created_at_around` query — and jump there
375
- * 3) last read id from snapshot/read-state (last-resort fallback when no timestamp is available)
668
+ * 1. an explicit first-unread ID (snapshot or read state): jump to it;
669
+ * 2. the last-read timestamp: infer the first unread message from the loaded interval, or from a
670
+ * `created_at_around` query when the interval does not straddle the boundary, and jump to it;
671
+ * 3. the last-read ID, when no timestamp is known.
376
672
  *
377
- * The timestamp inference (2) is preferred over jumping to the last-read id so that the jump lands
378
- * ON (and highlights) the first unread message rather than the last read one. The last-read id is
379
- * only used as a fallback when we cannot infer an unread boundary. The inference is NOT persisted
380
- * back into the snapshot (that is reserved for explicit mark-unread).
673
+ * The inference is not written to the snapshot: `firstUnreadMessageId` is reserved for an explicit
674
+ * mark-unread (it would suppress auto-mark-read).
381
675
  */
382
676
  jumpToTheFirstUnreadMessage = async (options?: JumpToMessageOptions) => {
383
677
  const ownUserId = this.channel.getClient().user?.id;
@@ -396,8 +690,6 @@ export class MessagePaginator extends MessageIntervalPaginator {
396
690
  const lastReadAtFromReadState = ownReadState?.last_read ?? null;
397
691
  const lastReadIdFromReadState = ownReadState?.last_read_message_id ?? null;
398
692
 
399
- // 1) A stable first-unread id is known (mark-unread, or a previously persisted inference):
400
- // jump straight to it.
401
693
  const firstUnreadMessageId = firstUnreadFromSnapshot ?? firstUnreadFromReadState;
402
694
  if (firstUnreadMessageId) {
403
695
  return await this.jumpToMessage(firstUnreadMessageId, {
@@ -407,47 +699,41 @@ export class MessagePaginator extends MessageIntervalPaginator {
407
699
  }
408
700
 
409
701
  const lastReadMessageId = lastReadIdFromSnapshot ?? lastReadIdFromReadState;
410
- // Prefer the SNAPSHOT timestamp over the fresh read-state one. The snapshot is the frozen UI
411
- // boundary the "N new" separator/banner render from, so a banner tap must jump to where that
412
- // indicator points. On (re)open the SDK marks the channel read (`markReadOnMount`) which advances
413
- // the read-state `last_read` to ~now and clears the server unread — so preferring read-state
414
- // would make a later banner tap infer "nothing unread" and jump to the latest message. The
415
- // snapshot is kept fresh on genuine catch-up (the SDK's mark-read resets it), so it is only
416
- // "frozen" precisely while there are unreads to jump to.
702
+ // The snapshot timestamp wins over the read state's: the snapshot is the frozen boundary the
703
+ // "N new" banner renders from, while mark-read on open advances the read state to ~now, so a
704
+ // banner tap would infer nothing unread and jump to the latest message.
417
705
  const lastReadAt = lastReadAtFromSnapshot ?? lastReadAtFromReadState;
418
706
 
419
- // 2) No explicit first-unread id, but we know when the channel was last read. Infer the first
420
- // unread message from that timestamp so we land ON (and highlight) the first unread message
421
- // instead of the last read one. Prefer the already-loaded window (the common "a few unreads at
422
- // the bottom" case — no extra request); only query a page around last-read when the loaded
423
- // window does not straddle the boundary (i.e. every loaded message is newer than last-read).
424
- //
425
- // We deliberately do NOT persist the inferred boundary back into the snapshot: writing
426
- // `firstUnreadMessageId` would make the channel look explicitly marked-unread and suppress
427
- // auto-mark-read at the bottom. The separator reads the (re-seeded) snapshot directly.
428
- if (lastReadAt) {
707
+ const lastReadBoundary =
708
+ lastReadAt != null && Number.isFinite(lastReadAt) ? lastReadAt : null;
709
+
710
+ if (lastReadBoundary !== null) {
429
711
  let {
430
712
  firstUnreadMessageId: inferredFirstUnreadMessageId,
431
713
  lastReadMessageId: inferredLastReadMessageId,
432
714
  } = this.resolveUnreadBoundaryIdsByTimestamp({
433
- lastReadAt,
715
+ lastReadAt: lastReadBoundary,
434
716
  messages: this.state.getLatestValue().items ?? [],
435
717
  });
436
718
 
437
719
  if (!inferredLastReadMessageId) {
438
720
  const result = await this.executeQuery({
721
+ claimsActiveInterval: true,
439
722
  queryShape: {
440
- created_at_around: lastReadAt,
441
- limit: options?.pageSize,
723
+ // `created_at_around` is a request field and still takes a `Date`.
724
+ created_at_around: nsToDate(lastReadBoundary),
725
+ limit: options?.pageSize ?? this.pageSize,
442
726
  },
443
727
  updateState: false,
444
728
  });
729
+ // a later claim decides the active interval, and the page stays stored
730
+ if (result?.isSuperseded) return false;
445
731
  if (result) {
446
732
  ({
447
733
  firstUnreadMessageId: inferredFirstUnreadMessageId,
448
734
  lastReadMessageId: inferredLastReadMessageId,
449
735
  } = this.resolveUnreadBoundaryIdsByTimestamp({
450
- lastReadAt,
736
+ lastReadAt: lastReadBoundary,
451
737
  messages: result.stateCandidate.items ?? [],
452
738
  }));
453
739
  }
@@ -463,7 +749,6 @@ export class MessagePaginator extends MessageIntervalPaginator {
463
749
  }
464
750
  }
465
751
 
466
- // 3) Last resort: jump to the known last-read message when that is all we have.
467
752
  if (lastReadMessageId) {
468
753
  return await this.jumpToMessage(lastReadMessageId, {
469
754
  ...options,
@@ -479,18 +764,14 @@ export class MessagePaginator extends MessageIntervalPaginator {
479
764
  return this.unreadStateSnapshot.getLatestValue();
480
765
  };
481
766
 
482
- /**
483
- * Set the UI-driven "viewing the latest messages" signal (see {@link LiveViewState}). Called by
484
- * the SDK from its message-list viewability + app-state tracking. No-ops when unchanged.
485
- *
486
- * Intentionally NOT reset by `clearStateAndCache` — it is an external input owned by the SDK, not
487
- * derived pagination state.
488
- */
489
- /** Current "viewing the latest messages" boolean (convenience read of {@link liveViewState}). */
490
767
  get isViewingLive(): boolean {
491
768
  return this.liveViewState.getLatestValue().isViewingLive;
492
769
  }
493
770
 
771
+ /**
772
+ * Sets the live-view signal ({@link LiveViewState}). Not reset by `clearStateAndCache`: it is an
773
+ * external input owned by the SDK.
774
+ */
494
775
  setViewingLive = (isViewingLive: boolean) => {
495
776
  if (this.isViewingLive === isViewingLive) return;
496
777
  this.liveViewState.next({ isViewingLive });
@@ -508,6 +789,6 @@ export class MessagePaginator extends MessageIntervalPaginator {
508
789
  clearStateAndCache() {
509
790
  super.clearStateAndCache();
510
791
  this.clearUnreadSnapshot();
511
- this.aggregateState.next({ lastMessage: null, seededLastMessageAt: null });
792
+ this.aggregateState.next({ latestMessage: null, queriedLatestMessageAt: null });
512
793
  }
513
794
  }