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,11 +1,12 @@
1
1
  import type {
2
+ AnyInterval,
2
3
  ItemCoordinates,
3
4
  PaginationQueryParams,
4
5
  PaginationQueryReturnValue,
5
6
  PaginationQueryShapeChangeIdentifier,
6
7
  PaginatorOptions,
7
8
  PaginatorState,
8
- PostQueryReconcileParams,
9
+ PlaceQueryPageParams,
9
10
  SetPaginatorItemsParams,
10
11
  } from './BasePaginator';
11
12
  import { BasePaginator } from './BasePaginator';
@@ -16,7 +17,8 @@ import { FilterBuilder } from '../FilterBuilder';
16
17
  import { makeComparator } from '../sortCompiler';
17
18
  import { filterConstrainsField, itemMatchesFilter } from '../filterCompiler';
18
19
  import { StoreBackedItemIndex } from '../../entityStore/StoreBackedItemIndex';
19
- import { generateUUIDv4 } from '../../utils';
20
+ import type { EntityStore } from '../../entityStore/EntityStore';
21
+ import { generateUUIDv4, runDetached } from '../../utils';
20
22
  import type { StreamChat } from '../../client';
21
23
  import type { Channel } from '../../channel';
22
24
  import type {
@@ -31,44 +33,54 @@ import type { FieldToDataResolver, PathResolver } from '../types.normalization';
31
33
  import { resolveDotPathValue } from '../utility.normalization';
32
34
  import { isEqual } from '../../utils/mergeWith/mergeWithCore';
33
35
 
36
+ const hasSameItems = (current: Channel[] | undefined, next: Channel[] | undefined) => {
37
+ if (current === next) return false;
38
+ if (!current || !next || current.length !== next.length) return false;
39
+ for (let i = 0; i < next.length; i++) if (current[i] !== next[i]) return false;
40
+ return true;
41
+ };
42
+
43
+ /**
44
+ * The most loaded channels a reconnect re-queries (`recoverLoadedItems`). Those loaded past it are
45
+ * kept as they are, unverified.
46
+ */
47
+ const MAX_RECOVERED_ITEMS = 150;
48
+
34
49
  const DEFAULT_BACKEND_SORT: SortParamRequest[] = [
35
50
  { direction: -1, field: 'last_message_at' },
36
51
  { direction: -1, field: 'updated_at' },
37
52
  ];
38
53
 
39
54
  /**
40
- * The `queryChannels` request this paginator will send, plus the client-only `stateOptions`.
41
- *
42
- * Deliberately the request's own shape (`filter_conditions`, `sort`, `limit`, `predefined_filter`, …)
43
- * rather than a `{ filters, sort, options }` wrapper: the same object goes on the wire, keys the
44
- * offline-db cache and is compared for query-shape changes, so any field mapping in between would be a
45
- * place for those three to drift apart. `MessageQueryShape` is likewise the request params themselves.
55
+ * The `queryChannels` request this paginator sends, plus the client-only `stateOptions`. It is the
56
+ * request's own shape because the same object goes on the wire, keys the offline-db cache and is
57
+ * compared for query-shape changes.
46
58
  */
47
59
  export type ChannelQueryShape = QueryChannelsRequest & {
48
- /** Not part of the request — controls how the response is applied to client state. */
60
+ /** Not part of the request: controls how the response is applied to client state. */
49
61
  stateOptions?: ChannelStateOptions;
50
62
  };
51
63
 
52
64
  export type ChannelPaginatorState = PaginatorState<Channel>;
53
65
 
66
+ /**
67
+ * Request options sent with every page query (`state`, `watch`, `presence`, `message_limit`, ...).
68
+ * `limit` and `offset` belong to the paginator: set the page size with `paginatorOptions.pageSize`.
69
+ */
54
70
  export type ChannelPaginatorRequestOptions = Partial<
55
71
  Omit<ChannelOptions, 'offset' | 'limit'>
56
72
  >;
57
73
 
58
74
  export type ChannelSortComparatorFactoryParams = {
59
- /** Sort the comparator is being built for — the effective sort, so a backend-resolved sort template. */
75
+ /** The effective sort the comparator is built for (a backend-resolved template, if any). */
60
76
  sort: SortParamRequest[];
61
- /**
62
- * The comparator `ChannelPaginator` would use for this sort. Delegate to it for the fields you do not
63
- * want to handle yourself instead of reimplementing channel field resolution and the cid tiebreaker.
64
- */
77
+ /** The comparator `ChannelPaginator` would use: delegate to it for the fields you do not handle. */
65
78
  defaultComparator: (a: Channel, b: Channel) => number;
66
79
  };
67
80
 
68
81
  /**
69
- * Produces the comparator that orders this paginator's channels. Consulted on **every** comparator
70
- * rebuild (construction, `sort` change, backend-resolved predefined sort), so unlike assigning
71
- * `sortComparator` directly, a factory is not overwritten by later sort changes.
82
+ * Produces the comparator that orders the channels. Consulted on every rebuild (construction,
83
+ * `sort` change, backend-resolved predefined sort), so later sort changes do not overwrite it.
72
84
  */
73
85
  export type ChannelSortComparatorFactory = (
74
86
  params: ChannelSortComparatorFactoryParams,
@@ -84,12 +96,16 @@ export type ChannelPaginatorOptions = {
84
96
  requestOptions?: ChannelPaginatorRequestOptions;
85
97
  sort?: SortParamRequest[];
86
98
  sortComparatorFactory?: ChannelSortComparatorFactory;
99
+ /**
100
+ * The channel store backing the list's index. Defaults to `client.channelManager`'s store, shared
101
+ * by every list.
102
+ *
103
+ * @internal
104
+ */
105
+ store?: EntityStore<Channel>;
87
106
  };
88
107
 
89
- /**
90
- * What identifies the query itself, as opposed to which page of it is being requested. Two shapes with
91
- * the same identity continue one pagination; a different identity restarts it from the first page.
92
- */
108
+ /** The query without its page: shapes with the same identity continue one pagination. */
93
109
  const getQueryIdentity = (queryShape: ChannelQueryShape | undefined) => {
94
110
  if (!queryShape) return queryShape;
95
111
  const {
@@ -110,13 +126,18 @@ const hasPaginationQueryShapeChanged: PaginationQueryShapeChangeIdentifier<
110
126
 
111
127
  const archivedFilterResolver: FieldToDataResolver<Channel> = {
112
128
  matchesField: (field) => field === 'archived',
113
- resolve: (channel) => !!channel.state.membership.archived_at,
129
+ resolve: (channel) => channel.state.membership.archived_at != null,
114
130
  };
115
131
 
116
- const appBannedFilterResolver: FieldToDataResolver<Channel> = {
132
+ // Resolvers needing the user or the mute list use the list's client, not `channel.getClient()`: that
133
+ // throws on a disposed channel, which must still sort and filter so a list can locate and drop it.
134
+
135
+ const createAppBannedFilterResolver = (
136
+ client: StreamChat,
137
+ ): FieldToDataResolver<Channel> => ({
117
138
  matchesField: (field) => field === 'app_banned',
118
139
  resolve: (channel) => {
119
- const ownUserId = channel.getClient().user?.id;
140
+ const ownUserId = client.userId;
120
141
  const otherMembers = Object.values(channel.state.members).filter(
121
142
  ({ user }) => user?.id !== ownUserId,
122
143
  );
@@ -125,53 +146,53 @@ const appBannedFilterResolver: FieldToDataResolver<Channel> = {
125
146
  const otherMember = otherMembers[0];
126
147
  return otherMember.user?.banned ? 'only' : 'excluded';
127
148
  },
128
- };
149
+ });
129
150
 
130
- const hasUnreadFilterResolver: FieldToDataResolver<Channel> = {
151
+ const createHasUnreadFilterResolver = (
152
+ client: StreamChat,
153
+ ): FieldToDataResolver<Channel> => ({
131
154
  matchesField: (field) => field === 'has_unread',
132
155
  resolve: (channel) => {
133
- const ownUserId = channel.getClient().user?.id;
156
+ const ownUserId = client.userId;
134
157
  return (
135
158
  ownUserId &&
136
159
  channel.state.read[ownUserId] &&
137
160
  channel.state.read[ownUserId].unread_messages > 0
138
161
  );
139
162
  },
140
- };
163
+ });
141
164
 
142
165
  const hiddenFilterResolver: FieldToDataResolver<Channel> = {
143
166
  matchesField: (field) => field === 'hidden',
144
- // `hidden` is optional on ChannelResponse, so a response that omits it (and a channel that was never
145
- // hidden or shown) leaves `channel.data.hidden` undefined. Coerce to a boolean so `{ hidden: false }`
146
- // matches those channels instead of comparing undefined against false.
167
+ // `hidden` is optional on the response: coerce so `{ hidden: false }` matches channels without it.
147
168
  resolve: (channel) => !!channel.data?.hidden,
148
169
  };
149
170
 
150
171
  const lastUpdatedFilterResolver: FieldToDataResolver<Channel> = {
151
172
  matchesField: (field) => field === 'last_updated',
152
- resolve: (channel) => {
153
- // combination of last_message_at and updated_at
154
- const lastMessageAt = channel.messagePaginator.lastMessageAt?.getTime() ?? null;
155
- const updatedAt = channel.data?.updated_at
156
- ? new Date(channel.data?.updated_at).getTime()
157
- : undefined;
158
- return lastMessageAt !== null && updatedAt !== undefined
159
- ? Math.max(lastMessageAt, updatedAt)
160
- : (lastMessageAt ?? updatedAt);
161
- },
173
+ // the server uses the creation time for a channel without messages
174
+ resolve: (channel) =>
175
+ channel.messagePaginator.latestMessageAt ?? channel.data?.created_at,
162
176
  };
163
177
 
164
178
  const membersFilterResolver: FieldToDataResolver<Channel> = {
165
179
  matchesField: (field) => field === 'members',
166
- resolve: (channel) =>
167
- channel.state.members
180
+ resolve: (channel) => {
181
+ const ids = channel.state.members
168
182
  ? Object.values(channel.state.members).reduce<string[]>((ids, member) => {
169
183
  if (member.user?.id) {
170
184
  ids.push(member.user?.id);
171
185
  }
172
186
  return ids;
173
187
  }, [])
174
- : [],
188
+ : [];
189
+ // Only a page of a large channel's members may be loaded, but the own membership always is, so
190
+ // `members: { $in: [ownId] }` holds.
191
+ const { membership } = channel.state;
192
+ const ownId = membership?.user?.id ?? membership?.user_id;
193
+ if (ownId && !ids.includes(ownId)) ids.push(ownId);
194
+ return ids;
195
+ },
175
196
  };
176
197
 
177
198
  const memberUserNameFilterResolver: FieldToDataResolver<Channel> = {
@@ -187,67 +208,97 @@ const memberUserNameFilterResolver: FieldToDataResolver<Channel> = {
187
208
  : [],
188
209
  };
189
210
 
211
+ /** The own invite's status: `pending`, `accepted` or `rejected`, or `undefined` without an invite. */
212
+ const resolveOwnInviteStatus = (channel: Channel) => {
213
+ const { membership } = channel.state;
214
+ if (membership?.invite_accepted_at != null) return 'accepted';
215
+ if (membership?.invite_rejected_at != null) return 'rejected';
216
+ if (membership?.invited) return 'pending';
217
+ return undefined;
218
+ };
219
+
220
+ const inviteFilterResolver: FieldToDataResolver<Channel> = {
221
+ matchesField: (field) => field === 'invite',
222
+ resolve: resolveOwnInviteStatus,
223
+ };
224
+
225
+ const joinedFilterResolver: FieldToDataResolver<Channel> = {
226
+ matchesField: (field) => field === 'joined',
227
+ // A member, unless the membership is a pending or rejected invite.
228
+ resolve: (channel) => {
229
+ const { membership } = channel.state;
230
+ const isMember = !!(membership?.user?.id ?? membership?.user_id);
231
+ const inviteStatus = resolveOwnInviteStatus(channel);
232
+ return isMember && inviteStatus !== 'pending' && inviteStatus !== 'rejected';
233
+ },
234
+ };
235
+
190
236
  const pinnedFilterResolver: FieldToDataResolver<Channel> = {
191
237
  matchesField: (field) => field === 'pinned',
192
- resolve: (channel) => !!channel.state.membership.pinned_at,
238
+ resolve: (channel) => channel.state.membership.pinned_at != null,
193
239
  };
194
240
 
195
- const mutedFilterResolver: FieldToDataResolver<Channel> = {
241
+ const createMutedFilterResolver = (client: StreamChat): FieldToDataResolver<Channel> => ({
196
242
  matchesField: (field) => field === 'muted',
197
- // UserMuteResponse state lives on the client (client.mutedChannels), not on channel.data — resolve it via
198
- // the client so `{ muted: true/false }` matches client-side, rather than letting the generic
199
- // data resolver read a non-existent `channel.data.muted` (which would resolve to undefined and
200
- // never equal a boolean filter value).
201
- resolve: (channel) => channel.getClient()._muteStatus(channel.cid).muted,
243
+ // Mute state lives on the client (`client.mutedChannels`), not in `channel.data`.
244
+ resolve: (channel) => client._muteStatus(channel.cid).muted,
245
+ });
246
+
247
+ /**
248
+ * A channel field by path: from `channel.data`, else from `channel.data.custom` (where a response
249
+ * keeps `name` and custom fields). `type`, `id` and `cid` come from the instance, since
250
+ * `channel.data` has them only after a query.
251
+ */
252
+ const resolveChannelDataValue = (channel: Channel, path: string) => {
253
+ if (path === 'type' || path === 'id' || path === 'cid') return channel[path];
254
+ const value = resolveDotPathValue(channel.data, path);
255
+ return value !== undefined ? value : resolveDotPathValue(channel.data?.custom, path);
202
256
  };
203
257
 
204
258
  const dataFieldFilterResolver: FieldToDataResolver<Channel> = {
205
259
  matchesField: () => true,
206
- resolve: (channel, path) => resolveDotPathValue(channel.data, path),
260
+ resolve: resolveChannelDataValue,
207
261
  };
208
262
 
209
- // very, very unfortunately channel data is dispersed btw Channel.data and Channel.state
210
- const channelSortPathResolver: PathResolver<Channel> = (channel, path) => {
211
- switch (path) {
212
- case 'last_message_at':
213
- return channel.messagePaginator.lastMessageAt;
214
- case 'has_unread': {
215
- return hasUnreadFilterResolver.resolve(channel, path);
216
- }
217
- case 'last_updated': {
218
- return lastUpdatedFilterResolver.resolve(channel, path) ?? 0;
219
- }
220
- case 'pinned_at':
221
- return channel.state.membership.pinned_at;
222
- case 'unread_count': {
223
- const userId = channel.getClient().user?.id;
224
- return userId ? channel.state.read[userId].unread_messages : 0;
263
+ // Channel data is split between `Channel.data` and `Channel.state`.
264
+ const createChannelSortPathResolver = (client: StreamChat): PathResolver<Channel> => {
265
+ const hasUnreadResolver = createHasUnreadFilterResolver(client);
266
+ return (channel, path) => {
267
+ switch (path) {
268
+ case 'last_message_at':
269
+ return channel.messagePaginator.latestMessageAt;
270
+ case 'has_unread': {
271
+ return hasUnreadResolver.resolve(channel, path);
272
+ }
273
+ case 'last_updated': {
274
+ return lastUpdatedFilterResolver.resolve(channel, path) ?? 0;
275
+ }
276
+ case 'pinned_at':
277
+ return channel.state.membership.pinned_at;
278
+ case 'unread_count': {
279
+ const userId = client.userId;
280
+ // a channel without a read entry for the user has nothing unread
281
+ return userId ? (channel.state.read[userId]?.unread_messages ?? 0) : 0;
282
+ }
283
+ default:
284
+ return resolveChannelDataValue(channel, path);
225
285
  }
226
- default:
227
- return resolveDotPathValue(channel.data, path);
228
- }
286
+ };
229
287
  };
230
288
 
231
- // todo: maybe items could be just an array of {cid: string} and the data would be retrieved from client.activeChannels
232
- // todo: maybe we should introduce client._cache.channels that would be reactive and orchestrator would subscribe to client._cache.channels state to keep all the dependent state in sync
233
289
  /**
234
- * A paginated channel list. Filters are described along three independent axes — the names follow them:
290
+ * A paginated channel list. `staticFilters` are the filters this client asked for, `filterBuilder`
291
+ * adds dynamic ones from its reactive context (merged over the static ones on every build). For a
292
+ * `predefined_filter` query the backend reports what it applied (`predefinedFilter`), which wins
293
+ * over `staticFilters` in `effectiveFilters` (and over `sort` in `effectiveSort`).
235
294
  *
236
- * - origin: `staticFilters` are supplied at construction and fixed; `filterBuilder` generates the
237
- * dynamic ones from its reactive context on every build. Every build merges dynamic over static.
238
- * - authority: `staticFilters` are what this client asked for; `predefinedFilter` is what the backend
239
- * reports it actually applied for a `predefined_filter` query. `effectiveFilters` is the winner of the
240
- * two (and `effectiveSort` likewise for ordering).
241
- * - purpose: `buildQueryFilters()` produces the filters sent to the server (and the offline-db query
242
- * key), built from the local filters only; `buildMatchFilters()` produces the filters items are
243
- * matched against locally, built from `effectiveFilters`. They are not interchangeable: sending the
244
- * resolved filter back changes the query shape mid-pagination, and matching against the local filter
245
- * admits channels the queried list excludes.
295
+ * `buildQueryFilters()` (sent to the server, offline-db query key) uses the local filters only and
296
+ * `buildMatchFilters()` (local matching) uses `effectiveFilters`. Do not swap them: sending the
297
+ * resolved filter back changes the query shape mid-pagination, and matching on the local filter
298
+ * admits channels the list excludes.
246
299
  *
247
- * Ordering follows the same authority rule: `sortComparator` is derived from `effectiveSort` and is
248
- * rebuilt whenever that changes, so it must not be assigned to. Customize it through
249
- * `sortComparatorFactory` (constructor option or setter, consulted on every rebuild) or by overriding
250
- * `buildSortComparator` in a subclass.
300
+ * `sortComparator` is derived from `effectiveSort` and rebuilt when it changes, so do not assign
301
+ * it: use `sortComparatorFactory` or override `buildSortComparator`.
251
302
  */
252
303
  export class ChannelPaginator extends BasePaginator<Channel, ChannelQueryShape> {
253
304
  private readonly _id: string;
@@ -256,14 +307,29 @@ export class ChannelPaginator extends BasePaginator<Channel, ChannelQueryShape>
256
307
  protected _sort: SortParamRequest[] | undefined;
257
308
  protected _options: ChannelPaginatorRequestOptions | undefined;
258
309
  protected _channelStateOptions: ChannelStateOptions | undefined;
259
- protected _nextQueryShape: ChannelQueryShape | undefined;
260
310
  /** Backend-reported metadata of the last `predefined_filter` query (see `predefinedFilter`). */
261
311
  protected _predefinedFilter: ParsedPredefinedFilterResponse | undefined;
312
+ /** Metadata of the in-flight response, committed by `placeQueryPage` on a first page only. */
313
+ private _pendingPredefinedFilter: ParsedPredefinedFilterResponse | undefined;
262
314
  /**
263
- * Predefined-filter metadata from the response of the query currently in flight. Held until
264
- * `postQueryReconcile` decides whether it should be committed (first page only).
315
+ * True while the loaded items came only from the offline cache (seeded by `setItems`, never
316
+ * confirmed by a query). The seed's offset and query shape would make the next query a
317
+ * continuation, but a cache has no pagination position, so `executeQuery` forces a first page that
318
+ * keeps the items.
265
319
  */
266
- private _pendingPredefinedFilter: ParsedPredefinedFilterResponse | undefined;
320
+ private _itemsLoadedFromOfflineDB = false;
321
+ /** The query in flight refreshes a cache-only interval, so its response replaces the interval. */
322
+ private _replaceOfflineSeedOnResponse = false;
323
+ /** The query handed to the sync manager, from the cache read until it runs. See `executeQuery`. */
324
+ private _queryAwaitingSync: ChannelQueryShape | undefined;
325
+ /** The cids of the page the latest query returned, `undefined` when it failed. */
326
+ private _lastPageCids: string[] | undefined;
327
+ /** Whether `recoverLoadedItems` runs: its pages own the list's position until it ends. */
328
+ private _isRecoveringLoadedItems = false;
329
+ /** A recovery asked for while one runs: the running pass stops and a new one starts. */
330
+ private _recoveryRequestedAgain = false;
331
+ /** A next page refused while recovering, queried once the recovery ends. See `executeQuery`. */
332
+ private _tailQueryAwaitingRecovery = false;
267
333
  protected _sortComparatorFactory: ChannelSortComparatorFactory | undefined;
268
334
  sortComparator: (a: Channel, b: Channel) => number;
269
335
  filterBuilder: FilterBuilder<ChannelFilters>;
@@ -278,16 +344,22 @@ export class ChannelPaginator extends BasePaginator<Channel, ChannelQueryShape>
278
344
  requestOptions,
279
345
  sort,
280
346
  sortComparatorFactory,
347
+ store,
281
348
  }: ChannelPaginatorOptions) {
282
349
  super({
283
350
  hasPaginationQueryShapeChanged,
284
- itemIndex: new StoreBackedItemIndex<Channel>({
285
- getEntityId: (channel) => channel.cid,
286
- }),
351
+ // the index is this list's holder in the store: a channel stays stored while the list lists it
352
+ createItemIndex: (owner) =>
353
+ new StoreBackedItemIndex<Channel>({
354
+ getEntityId: (channel) => channel.cid,
355
+ holderName: 'channel-paginator',
356
+ owner: owner as ChannelPaginator,
357
+ store: store ?? client.channelManager?.channelStore,
358
+ }),
287
359
  retryCount: DEFAULT_QUERY_CHANNELS_RETRY_COUNT,
288
360
  ...paginatorOptions,
289
361
  });
290
- const definedSort = sort ?? DEFAULT_BACKEND_SORT;
362
+ const definedSort = sort?.length ? sort : DEFAULT_BACKEND_SORT;
291
363
  this.client = client;
292
364
  this._id = id ?? `channel-paginator-${generateUUIDv4()}`;
293
365
  this._sort = definedSort;
@@ -299,33 +371,35 @@ export class ChannelPaginator extends BasePaginator<Channel, ChannelQueryShape>
299
371
  this.sortComparator = this.buildSortComparator(definedSort);
300
372
  this.setFilterResolvers([
301
373
  archivedFilterResolver,
302
- appBannedFilterResolver,
303
- hasUnreadFilterResolver,
374
+ createAppBannedFilterResolver(client),
375
+ createHasUnreadFilterResolver(client),
304
376
  hiddenFilterResolver,
377
+ inviteFilterResolver,
378
+ joinedFilterResolver,
305
379
  lastUpdatedFilterResolver,
306
380
  pinnedFilterResolver,
307
- mutedFilterResolver,
381
+ createMutedFilterResolver(client),
308
382
  membersFilterResolver,
309
383
  memberUserNameFilterResolver,
310
384
  dataFieldFilterResolver,
311
385
  ]);
386
+ // Channels are reactive objects: republish only when the list's membership or order changes.
387
+ this.state.addPreprocessor((next, previous) => {
388
+ if (previous && hasSameItems(previous.items, next.items))
389
+ next.items = previous.items;
390
+ });
312
391
  }
313
392
 
314
393
  /**
315
- * Builds the comparator for the given sort — the single construction point, so every rebuild (the
316
- * `sort` setter, a backend-resolved predefined sort) keeps the channel-specific path resolver and the
317
- * cid tiebreaker; omitting either makes ordering fall back to raw `channel.data` lookups and become
318
- * non-deterministic for equal sort values.
319
- *
320
- * `sortComparator` is derived state and is therefore reassigned on every rebuild — assigning to it
321
- * directly does not survive a sort change or a predefined-filter response. To customize ordering,
322
- * supply `sortComparatorFactory` (it is consulted on every rebuild and may delegate to
323
- * `defaultComparator`), or override this method in a subclass.
394
+ * The single construction point of `sortComparator`, so every rebuild keeps the channel path
395
+ * resolver and the cid tiebreaker. Customize it with `sortComparatorFactory` (which may delegate
396
+ * to `defaultComparator`) or by overriding this method: assigning `sortComparator` directly is
397
+ * lost on the next rebuild.
324
398
  */
325
399
  protected buildSortComparator(sort: SortParamRequest[]) {
326
400
  const defaultComparator = makeComparator<Channel>({
327
401
  sort,
328
- resolvePathValue: channelSortPathResolver,
402
+ resolvePathValue: createChannelSortPathResolver(this.client),
329
403
  tiebreaker: (l, r) => {
330
404
  const leftId = this.getItemId(l);
331
405
  const rightId = this.getItemId(r);
@@ -351,35 +425,26 @@ export class ChannelPaginator extends BasePaginator<Channel, ChannelQueryShape>
351
425
  }
352
426
 
353
427
  get sort(): SortParamRequest[] {
354
- return this._sort ?? DEFAULT_BACKEND_SORT;
428
+ return this._sort?.length ? this._sort : DEFAULT_BACKEND_SORT;
355
429
  }
356
430
 
357
431
  /**
358
- * What the backend reported it actually filtered and sorted by for the last first-page query —
359
- * `QueryChannelsResponse.predefined_filter` (`name`, `filter`, and `sort` when the stored filter
360
- * carries its own sort template). Set only for `predefined_filter` queries: the raw `filter_conditions`
361
- * of a normal query are not echoed back.
432
+ * What the backend reported it filtered and sorted by for the last first-page query
433
+ * (`QueryChannelsResponse.predefined_filter`: `name`, `filter`, and `sort` when the stored filter
434
+ * has a sort template). Set only for `predefined_filter` queries.
362
435
  */
363
436
  get predefinedFilter(): ParsedPredefinedFilterResponse | undefined {
364
437
  return this._predefinedFilter;
365
438
  }
366
439
 
367
- /**
368
- * Filters this paginator matches items against client-side. A predefined filter resolved by the backend
369
- * wins over the locally configured one: for such a query the local `filters` are not what the server
370
- * applied, so matching against them would admit items the queried list excludes.
371
- */
440
+ /** Filters items are matched against locally: the backend-resolved one, else `staticFilters`. */
372
441
  get effectiveFilters(): ChannelFilters | undefined {
373
442
  return (
374
443
  (this._predefinedFilter?.filter as ChannelFilters | undefined) ?? this.staticFilters
375
444
  );
376
445
  }
377
446
 
378
- /**
379
- * Sort this paginator orders items by. Mirrors `effectiveFilters`: a sort template carried by a
380
- * backend-resolved predefined filter takes precedence over the requested sort, matching backend
381
- * precedence rules.
382
- */
447
+ /** The sort items are ordered by: the backend-resolved predefined sort template, else `sort`. */
383
448
  get effectiveSort(): SortParamRequest[] {
384
449
  return (this._predefinedFilter?.sort as SortParamRequest[] | undefined) ?? this.sort;
385
450
  }
@@ -414,10 +479,8 @@ export class ChannelPaginator extends BasePaginator<Channel, ChannelQueryShape>
414
479
  }
415
480
 
416
481
  /**
417
- * Take over channel ordering at any point in the paginator's life. The comparator is rebuilt
418
- * immediately and the factory is consulted again on every later rebuild, so — unlike assigning
419
- * `sortComparator` — a sort change or a backend-resolved predefined sort will not discard it. Set to
420
- * `undefined` to go back to the built-in ordering.
482
+ * Rebuilds the comparator immediately; later rebuilds consult the factory again, so a sort change
483
+ * does not discard it. `undefined` restores the built-in ordering.
421
484
  */
422
485
  set sortComparatorFactory(factory: ChannelSortComparatorFactory | undefined) {
423
486
  this._sortComparatorFactory = factory;
@@ -429,21 +492,16 @@ export class ChannelPaginator extends BasePaginator<Channel, ChannelQueryShape>
429
492
  }
430
493
 
431
494
  /**
432
- * Filters sent to the server with the next query (and used as the offline-db query key). Deliberately
433
- * built from the locally configured filters only — feeding the backend-resolved filter back in would
434
- * change the query shape after the first response and make the following page look like a new first
435
- * page to `hasPaginationQueryShapeChanged`.
495
+ * Filters sent with the next query and used as the offline-db query key. Built from the local
496
+ * filters only: the backend-resolved filter would change the query shape after the first response,
497
+ * so the next page would look like a first page.
436
498
  */
437
499
  buildQueryFilters = (): ChannelFilters =>
438
500
  this.filterBuilder.buildFilters({
439
501
  baseFilters: { ...this.staticFilters },
440
502
  });
441
503
 
442
- /**
443
- * Filters items are matched against locally — the `BasePaginator.buildMatchFilters` hook consumed by
444
- * `matchesFilter`. Built from `effectiveFilters`, so a `predefined_filter` list matches what the
445
- * backend applied rather than the local filters, which are not what produced the list.
446
- */
504
+ /** Filters items are matched against locally (`matchesFilter`), built from `effectiveFilters`. */
447
505
  buildMatchFilters = (): ChannelFilters =>
448
506
  this.filterBuilder.buildFilters({
449
507
  baseFilters: { ...this.effectiveFilters },
@@ -452,22 +510,16 @@ export class ChannelPaginator extends BasePaginator<Channel, ChannelQueryShape>
452
510
  matchesFilter(channel: Channel): boolean {
453
511
  const filters = this.buildMatchFilters();
454
512
 
455
- // Mirror `queryChannels`, which excludes hidden channels unless the filter asks for them —
456
- // otherwise a channel hidden while the list is open keeps matching and stays visible until the next
457
- // query. Applied here rather than as a synthetic `hidden: false` filter entry so the default also
458
- // holds for a paginator whose filter resolvers were replaced (`setFilterResolvers`), which would
459
- // otherwise leave `hidden` unresolvable and reject every channel.
513
+ // Like `queryChannels`, exclude hidden channels unless the filter asks for them. Not a synthetic
514
+ // `hidden: false` entry: with replaced resolvers (`setFilterResolvers`) `hidden` would be
515
+ // unresolvable and reject every channel.
460
516
  if (channel.data?.hidden && !filterConstrainsField(filters, 'hidden')) return false;
461
517
  return itemMatchesFilter<Channel>(channel, filters, {
462
518
  resolvers: this._filterFieldToDataResolvers,
463
519
  });
464
520
  }
465
521
 
466
- /**
467
- * Commits the `predefined_filter` metadata of the response, or clears it when the response carried
468
- * none (a plain `filter_conditions` query), so a switch away from a predefined filter cannot leave
469
- * stale matching/ordering semantics behind.
470
- */
522
+ /** Commits the response's `predefined_filter` metadata, or clears it when there is none. */
471
523
  protected applyPredefinedFilterResponse(
472
524
  predefinedFilter: ParsedPredefinedFilterResponse | undefined,
473
525
  ) {
@@ -476,28 +528,41 @@ export class ChannelPaginator extends BasePaginator<Channel, ChannelQueryShape>
476
528
  }
477
529
 
478
530
  /**
479
- * The response metadata describes the query as a whole, so it is (re)committed only when a first page
480
- * lands — matching the legacy `ChannelManager`, which kept it untouched while paginating. A failed
481
- * query (`results === null`) must not drop the metadata of the already loaded list either.
531
+ * The metadata describes the query as a whole, so it is committed only when a first page lands (a
532
+ * failed query keeps the loaded list's). It is committed before `super`, which filters and ingests
533
+ * the page using `matchesFilter` and the comparator this metadata feeds.
482
534
  *
483
- * Committing before `super` matters: the base implementation filters and ingests the page using
484
- * `matchesFilter` and the comparators this metadata feeds.
535
+ * A recovery page (see `recoverLoadedItems`) starts where the one before it ended, so it extends
536
+ * the shown interval, though a page at a caller's shape would otherwise start one of its own.
485
537
  */
486
- postQueryReconcile(params: PostQueryReconcileParams<Channel, ChannelQueryShape>) {
538
+ override placeQueryPage(params: PlaceQueryPageParams<Channel, ChannelQueryShape>) {
539
+ if (this._isRecoveringLoadedItems && params.startsSeparateInterval) {
540
+ params = { ...params, startsSeparateInterval: false };
541
+ }
542
+ this._lastPageCids = params.results?.items.map((channel) => channel.cid);
487
543
  const pendingPredefinedFilter = this._pendingPredefinedFilter;
488
544
  this._pendingPredefinedFilter = undefined;
489
545
  if (params.isFirstPage && params.results) {
490
546
  this.applyPredefinedFilterResponse(pendingPredefinedFilter);
491
547
  }
492
- return super.postQueryReconcile(params);
548
+ const replaceOfflineSeed = this._replaceOfflineSeedOnResponse;
549
+ this._replaceOfflineSeedOnResponse = false;
550
+ if (replaceOfflineSeed && params.results) {
551
+ // The cache can be arbitrarily old and hold channels the server dropped (hidden, deleted,
552
+ // left): the page replaces the seed instead of merging into it.
553
+ this.clearItemStorage();
554
+ return super.placeQueryPage({ ...params, keepPreviousItems: false });
555
+ }
556
+ return super.placeQueryPage(params);
493
557
  }
494
558
 
495
- // invoked inside BasePaginator.executeQuery() to keep it as a query descriptor;
496
- protected getNextQueryShape(): ChannelQueryShape {
559
+ protected getNextQueryShape({
560
+ pageSize,
561
+ }: { pageSize?: number } = {}): ChannelQueryShape {
497
562
  const shape: ChannelQueryShape = {
498
563
  filter_conditions: this.buildQueryFilters(),
499
564
  ...this.options,
500
- limit: this.pageSize,
565
+ limit: pageSize ?? this.pageSize,
501
566
  offset: this.offset,
502
567
  };
503
568
 
@@ -519,14 +584,11 @@ export class ChannelPaginator extends BasePaginator<Channel, ChannelQueryShape>
519
584
  }
520
585
 
521
586
  /**
522
- * Writes a cid order into the offline cache under the query that produced it.
523
- *
524
- * `filters` and `sort` are passed separately even though `options` already contains them: the concrete
525
- * (RN) DB implementation derives the cache row key from those two top-level arguments in
526
- * `convertFilterSortToQuery`, while `options` carries the full request — the only place
527
- * `predefined_filter` / `filter_values` / `sort_values` appear, without which two predefined-filter
528
- * lists cannot be told apart. The duplication goes away once `convertFilterSortToQuery` derives the
529
- * key from `options` (a change in that implementation plus a schema-version bump to flush stale rows).
587
+ * Writes a cid order into the offline cache under the query that produced it. `filters` and `sort`
588
+ * are passed apart from `options` (which already holds them) because the DB implementation derives
589
+ * the cache row key from them, while `options` carries the full request (`predefined_filter`, ...)
590
+ * that tells predefined-filter lists apart. The resolved `predefinedFilter` is stored with the
591
+ * order: a cache-seeded list has no response to learn it from.
530
592
  */
531
593
  protected cacheCidsForQuery({
532
594
  cids,
@@ -538,9 +600,10 @@ export class ChannelPaginator extends BasePaginator<Channel, ChannelQueryShape>
538
600
  this.client.offlineDb?.executeQuerySafely(
539
601
  (db) =>
540
602
  db.upsertCidsForQuery({
541
- cids,
603
+ cids: cids.slice(0, this.pageSize),
542
604
  filters: request.filter_conditions,
543
605
  options: request,
606
+ predefinedFilter: this._predefinedFilter,
544
607
  sort: request.sort,
545
608
  }),
546
609
  { method: 'upsertCidsForQuery' },
@@ -548,15 +611,18 @@ export class ChannelPaginator extends BasePaginator<Channel, ChannelQueryShape>
548
611
  }
549
612
 
550
613
  /**
551
- * Persists the current cid order under the query that produced it. Called after every mutation of the
552
- * loaded list — including live WS-driven inserts/removals, which reorder the list without any query
553
- * running; skipping those would leave the cached order stale until the next full re-query.
614
+ * Persists the current cid order under the query that produced it. Runs after every mutation of
615
+ * the loaded list, including live inserts and removals that reorder it without a query.
554
616
  */
555
617
  protected persistLoadedCids() {
556
- if (!this.client.offlineDb) return;
618
+ // Without a user the list is being emptied by `disconnectUser()`: what stays in the offline DB
619
+ // is the app's call (`resetDB()`).
620
+ if (!this.client.offlineDb || !this.client.userId) return;
557
621
 
558
622
  this.cacheCidsForQuery({
559
- cids: (this.items ?? []).map((channel) => channel.cid),
623
+ cids: (this.items ?? [])
624
+ .filter((channel) => !channel.isProvisional)
625
+ .map((channel) => channel.cid),
560
626
  request: this.loadedQueryRequest,
561
627
  });
562
628
  }
@@ -574,16 +640,20 @@ export class ChannelPaginator extends BasePaginator<Channel, ChannelQueryShape>
574
640
  const { stateOptions: _, ...request } = queryShape;
575
641
 
576
642
  try {
577
- const channelsFromDB = await this.client.offlineDb.getChannelsForQuery({
643
+ const cachedQuery = await this.client.offlineDb.getChannelsForQuery({
578
644
  userId: this.client.user.id,
579
645
  options: request,
580
646
  });
581
647
 
582
- if (channelsFromDB) {
583
- return this.client.hydrateActiveChannels(channelsFromDB, {
584
- offlineMode: true,
585
- skipInitialization: [], // passing empty array will clear out the existing messages from channel state, this removes the possibility of duplicate messages
586
- });
648
+ if (cachedQuery) {
649
+ if (cachedQuery.predefinedFilter) {
650
+ this.applyPredefinedFilterResponse(cachedQuery.predefinedFilter);
651
+ }
652
+ return this.client.hydrateChannels(
653
+ cachedQuery.channels,
654
+ { offlineMode: true },
655
+ request,
656
+ );
587
657
  }
588
658
  } catch (error) {
589
659
  chatLoggerSystem.getLogger('channel').error((error as Error).message);
@@ -609,73 +679,102 @@ export class ChannelPaginator extends BasePaginator<Channel, ChannelQueryShape>
609
679
  };
610
680
 
611
681
  /**
612
- * Postpones a first-page query while the offline sync is still in progress: the cached page is
613
- * surfaced right away and the network query is handed to the sync manager, which re-runs it once
614
- * reconciliation finished — querying (and persisting cids) against unsynced local state would race
615
- * with the replay of pending local mutations. Mirrors `ChannelManager.queryChannels`, which deferred
616
- * on every unsynced call and read the cache only when it had nothing loaded yet.
617
- *
618
- * Only first-page queries defer; paginating an already loaded list is unaffected (as was the legacy
619
- * `loadNext`).
682
+ * Defers a first-page query (or a page of a cache-seeded list) while the offline sync is in
683
+ * progress: the cached page is shown right away and the network query is handed to the sync
684
+ * manager, which re-runs it after reconciliation. Querying and persisting cids against unsynced
685
+ * local state would race the replay of pending mutations. Paginating a list loaded from the
686
+ * network is not deferred.
620
687
  */
621
688
  async executeQuery(params: PaginationQueryParams<ChannelQueryShape> = {}) {
689
+ // The recovery's pages hold the position (`offset` restarts at 0 until the last one lands), so
690
+ // a page queried in between would fetch the wrong one. A refresh still runs.
691
+ if (this._isRecoveringLoadedItems && params.direction && params.reset !== 'yes') {
692
+ if (params.direction === 'tailward') this._tailQueryAwaitingRecovery = true;
693
+ return;
694
+ }
622
695
  const { offlineDb } = this.client;
623
- const queryShape = params.queryShape ?? this.getNextQueryShape();
696
+
697
+ const effectiveParams: PaginationQueryParams<ChannelQueryShape> =
698
+ this._itemsLoadedFromOfflineDB && params.reset !== 'yes'
699
+ ? { ...params, keepPreviousItems: true, reset: 'yes' as const }
700
+ : params;
701
+
702
+ const queryShape = effectiveParams.queryShape ?? this.getNextQueryShape();
624
703
  const shouldDeferUntilSynced =
625
704
  !!offlineDb?.getChannelsForQuery &&
626
705
  !!this.client.user?.id &&
627
- !offlineDb.syncManager.syncStatus &&
628
- this.isFirstPageQuery({ queryShape, reset: params.reset });
706
+ !offlineDb.syncManager.isSynced &&
707
+ // A cache-seeded list is not a loaded one, so paginating it defers too.
708
+ (this._itemsLoadedFromOfflineDB ||
709
+ this.isFirstPageQuery({ queryShape, reset: effectiveParams.reset }));
629
710
 
630
- if (!shouldDeferUntilSynced) return await super.executeQuery(params);
711
+ if (!shouldDeferUntilSynced) return await super.executeQuery(effectiveParams);
712
+
713
+ if (
714
+ this._queryAwaitingSync &&
715
+ !this.config.hasPaginationQueryShapeChanged(this._queryAwaitingSync, queryShape)
716
+ ) {
717
+ return;
718
+ }
719
+ this._queryAwaitingSync = queryShape;
631
720
 
632
721
  if (!this.isInitialized) {
633
- const cachedChannels = await this.preloadFirstPageFromOfflineDb({
634
- ...params,
635
- queryShape,
636
- });
722
+ let cachedChannels: Channel[] | undefined;
723
+ try {
724
+ cachedChannels = await this.preloadFirstPageFromOfflineDb({
725
+ ...effectiveParams,
726
+ queryShape,
727
+ });
728
+ } catch (error) {
729
+ this._queryAwaitingSync = undefined;
730
+ throw error;
731
+ }
637
732
  if (cachedChannels?.length) {
638
- // Seed via `setItems` (which ingests the page into the interval/index storage), so that the items
639
- // actually appear within the adequate index.
733
+ // Seed via `setItems`, which ingests the page into the interval/index storage.
640
734
  // TODO: Maybe find a better way to do this rather than 2 partialNext invocations
641
735
  // running. This all happens so fast it should never be noticeable but it's
642
736
  // a microoptimization.
643
737
  this.setItems({ valueOrFactory: cachedChannels, isFirstPage: true });
738
+ this._itemsLoadedFromOfflineDB = true;
644
739
  }
645
- // Nothing is in flight while we wait for the sync; leaving `isLoading` true would make
646
- // `canExecuteQuery` reject the query scheduled below.
740
+ // Nothing is in flight while waiting for the sync: `isLoading` would make `canExecuteQuery`
741
+ // reject the query scheduled below.
647
742
  this.state.partialNext({ isLoading: false });
648
743
  }
649
744
 
650
- // Check if everything is synced up already and if so, just run the actual queryChannels request.
651
- // Otherwise, the sync status change will never fire and so `executeQuery` will never really be
652
- // run.
653
- if (offlineDb.syncManager.syncStatus) {
654
- return await super.executeQuery({ ...params, keepPreviousItems: true });
745
+ const refreshParams: PaginationQueryParams<ChannelQueryShape> = {
746
+ ...effectiveParams,
747
+ keepPreviousItems: true,
748
+ ...(this._itemsLoadedFromOfflineDB ? { reset: 'yes' as const } : {}),
749
+ };
750
+
751
+ // Already synced: the sync-status callback would never fire, so run the query now.
752
+ if (offlineDb.syncManager.isSynced) {
753
+ this._queryAwaitingSync = undefined;
754
+ return await super.executeQuery(refreshParams);
655
755
  }
656
756
 
657
- // When the sync completes, run the real query — but as a NON-DESTRUCTIVE refresh
658
- // (`keepPreviousItems`) so the channels we already surfaced from the offline DB stay visible while it
659
- // runs. Without this the re-run goes through the first-page reset path and re-preloads from the DB;
660
- // if the sync invalidated the offline query cache (i.e. a channel changed while the app was closed),
661
- // that re-preload returns nothing and the list blanks to a second skeleton before the fresh page lands.
662
757
  offlineDb.syncManager.scheduleSyncStatusChangeCallback(this.id, async () => {
663
- await this.executeQuery({ ...params, keepPreviousItems: true });
758
+ this._queryAwaitingSync = undefined;
759
+ await this.executeQuery(refreshParams);
664
760
  });
665
761
  }
666
762
 
667
- query = async (): Promise<PaginationQueryReturnValue<Channel>> => {
668
- // get the params only if they were not generated previously
669
- if (!this._nextQueryShape) {
670
- this._nextQueryShape = this.getNextQueryShape();
671
- }
672
- const { stateOptions, ...request } = this._nextQueryShape;
763
+ protected override fetchQueryResponse = async ({
764
+ queryShape: preparedQueryShape,
765
+ }: PaginationQueryParams<ChannelQueryShape> = {}): Promise<
766
+ PaginationQueryReturnValue<Channel>
767
+ > => {
768
+ if (this._itemsLoadedFromOfflineDB) this._replaceOfflineSeedOnResponse = true;
769
+ // A query is going out: the items stop being cache-only, whatever the response.
770
+ this._itemsLoadedFromOfflineDB = false;
771
+ const queryShape = preparedQueryShape ?? this.getNextQueryShape();
772
+ const { stateOptions, ...request } = queryShape;
673
773
  let items: Channel[];
674
774
  if (this.config.doRequest) {
675
- items = (await this.config.doRequest(this._nextQueryShape)).items;
775
+ items = (await this.config.doRequest(queryShape)).items;
676
776
  } else {
677
- // withResponse gives access to response-level metadata (`predefined_filter`) which a
678
- // predefined-filter list needs to know what the backend actually filtered and sorted by.
777
+ // `withResponse` exposes `predefined_filter`, which a predefined-filter list needs.
679
778
  const response = await this.client.queryChannelsAndHydrate(request, {
680
779
  ...stateOptions,
681
780
  withResponse: true,
@@ -686,19 +785,182 @@ export class ChannelPaginator extends BasePaginator<Channel, ChannelQueryShape>
686
785
  return { items };
687
786
  };
688
787
 
689
- filterQueryResults = (items: Channel[]) => items;
788
+ private getLastPageCids() {
789
+ return this._lastPageCids;
790
+ }
791
+
792
+ /**
793
+ * The reconnect refresh. Re-queries every loaded page, then drops the loaded channels no page
794
+ * returned that sort within the re-queried range: they were deleted, left, hidden, or no longer
795
+ * match the filter. Those sorting below it were not re-queried and stay.
796
+ *
797
+ * Each page asks for everything still to cover and the next one starts where it ended, so the
798
+ * server's page cap decides the step. A failed page removes nothing. At most
799
+ * {@link MAX_RECOVERED_ITEMS} channels are re-queried.
800
+ *
801
+ * Paging is held meanwhile: a next page asked for is queried once the recovery ends, as the list
802
+ * end that asked for it does not ask again when the recovery changed nothing. A query of the
803
+ * list's own already in flight is waited for, as it would make the recovery's refused.
804
+ *
805
+ * A call while a recovery runs returns at once and the running pass starts over from the first page
806
+ * once its page in flight lands, as the pages before were watched on a connection that is gone.
807
+ */
808
+ recoverLoadedItems = async () => {
809
+ if (this._isRecoveringLoadedItems) {
810
+ this._recoveryRequestedAgain = true;
811
+ return;
812
+ }
813
+ this._isRecoveringLoadedItems = true;
814
+ try {
815
+ do {
816
+ this._recoveryRequestedAgain = false;
817
+ await this.waitForQueryToSettle();
818
+ await this.recoverLoadedPages();
819
+ } while (this._recoveryRequestedAgain);
820
+ } finally {
821
+ this._isRecoveringLoadedItems = false;
822
+ }
823
+ if (!this._tailQueryAwaitingRecovery) return;
824
+ this._tailQueryAwaitingRecovery = false;
825
+ runDetached(this.toTail(), { context: 'ChannelPaginator.recoverLoadedItems' });
826
+ };
827
+
828
+ /** Resolves once the list has no query of its own in flight. */
829
+ private waitForQueryToSettle = () =>
830
+ new Promise<void>((resolve) => {
831
+ if (!this.isLoading) {
832
+ resolve();
833
+ return;
834
+ }
835
+ const unsubscribe = this.state.subscribeWithSelector(
836
+ ({ isLoading }) => ({ isLoading }),
837
+ ({ isLoading }) => {
838
+ if (isLoading) return;
839
+ unsubscribe();
840
+ resolve();
841
+ },
842
+ );
843
+ });
844
+
845
+ private recoverLoadedPages = async () => {
846
+ const loadedCids = new Set((this.items ?? []).map((channel) => channel.cid));
847
+ const recoveredCount = Math.min(loadedCids.size, MAX_RECOVERED_ITEMS);
848
+ const returnedCids = new Set<string>();
849
+ let lastReturnedCid: string | undefined;
850
+ let reachedEnd = false;
851
+ const shape = this.getNextQueryShape();
852
+ let interval: AnyInterval | null = null;
853
+ let offset = 0;
854
+ let pageCount = 0;
855
+ do {
856
+ this._lastPageCids = undefined;
857
+ // the list's own query path, without publishing as the list is published once, below
858
+ const result = await this.executeQuery({
859
+ keepPreviousItems: true,
860
+ queryShape:
861
+ offset === 0 ? undefined : { ...shape, offset, limit: recoveredCount - offset },
862
+ reset: offset === 0 ? 'yes' : undefined,
863
+ silent: true,
864
+ updateState: false,
865
+ });
866
+ const page = this.getLastPageCids();
867
+ if (!result || !page || this._recoveryRequestedAgain) {
868
+ // the first page reset the position and no page commits one, so hand it back
869
+ this.state.partialNext({ offset: this.items?.length ?? 0 });
870
+ return;
871
+ }
872
+ if (result.targetInterval) {
873
+ interval = result.targetInterval;
874
+ // we update immediately for the first page as most of the stuff that is going
875
+ // to move is going to do it to this page
876
+ this.setActiveInterval(interval, { updateState: offset === 0 });
877
+ }
878
+ // a page shorter than asked for, and than a page, is the end of the list
879
+ const requested =
880
+ offset === 0 ? Math.max(this.pageSize, loadedCids.size) : recoveredCount - offset;
881
+ if (page.length < Math.min(this.pageSize, requested)) reachedEnd = true;
882
+ if (!page.length) break;
883
+ pageCount++;
884
+ for (const channel of result.stateCandidate.items ?? [])
885
+ returnedCids.add(channel.cid);
886
+ lastReturnedCid = page[page.length - 1];
887
+ offset += page.length;
888
+ } while (offset < recoveredCount);
889
+
890
+ const lastReturned = lastReturnedCid
891
+ ? this.client.channelManager.get(lastReturnedCid)
892
+ : undefined;
893
+ const isWithinRecoveredRange = (cid: string) => {
894
+ if (reachedEnd) return true;
895
+ const channel = this.getItem(cid);
896
+ if (!channel || !lastReturned) return false;
897
+ return this.sortComparator(channel, lastReturned) < 0;
898
+ };
899
+ this.batch(
900
+ () => {
901
+ for (const cid of loadedCids) {
902
+ if (!returnedCids.has(cid) && isWithinRecoveredRange(cid)) {
903
+ this.removeItem({ id: cid });
904
+ }
905
+ }
906
+ },
907
+ { coalesce: true },
908
+ );
909
+ // the first page was published as it landed, so only later pages are left to show
910
+ if (interval && pageCount > 1) this.setActiveInterval(interval);
911
+ this.state.partialNext({
912
+ offset: this.items?.length ?? 0,
913
+ // optimistically assume we have more pages, at worst it's one extra pagination attempt
914
+ hasMoreTail: true,
915
+ });
916
+ };
917
+
918
+ /** The extracting step of the query pipeline: the response is the page. */
919
+ protected override extractQueryPage(
920
+ response: PaginationQueryReturnValue<Channel>,
921
+ _params: PaginationQueryParams<ChannelQueryShape>,
922
+ ) {
923
+ return response;
924
+ }
690
925
 
691
926
  setItems(params: SetPaginatorItemsParams<Channel>) {
692
927
  super.setItems(params);
693
928
  this.persistLoadedCids();
694
929
  }
695
930
 
696
- ingestItem(channel: Channel): boolean {
931
+ /**
932
+ * Places `channel` in the list if it matches, or drops it when it stops matching. A provisional
933
+ * channel (created from members, no ID yet) is refused: it is stored under a temporary cid. Another
934
+ * instance for a stored cid is replaced by the stored one (`ChannelManager.resolveListedChannel`).
935
+ */
936
+ ingestItem(input: Channel): boolean {
937
+ if (input.isProvisional) return false;
938
+ const channel = this.client.channelManager.resolveListedChannel(input);
939
+ if (!channel) return false;
697
940
  const changed = super.ingestItem(channel);
941
+ // A channel outside the result set is not held.
942
+ if (!this.matchesFilter(channel)) this._itemIndex.remove(channel.cid);
698
943
  if (changed) this.persistLoadedCids();
699
944
  return changed;
700
945
  }
701
946
 
947
+ /** Entity-store subscriber. A channel publishes changes via `channel.state`: nothing to do. */
948
+ onEntitiesChanged(): void {
949
+ return;
950
+ }
951
+
952
+ /** Entity-store subscriber: the store removed a channel this list holds (e.g. logout). */
953
+ onEntityRemoved(id: string, channel: unknown): void {
954
+ this.removeItem({ id, item: channel as Channel });
955
+ }
956
+
957
+ resetState() {
958
+ super.resetState();
959
+ this._itemIndex.clear();
960
+ this._queryAwaitingSync = undefined;
961
+ this._tailQueryAwaitingRecovery = false;
962
+ }
963
+
702
964
  removeItem(params: { id?: string; item?: Channel }): ItemCoordinates {
703
965
  const coordinates = super.removeItem(params);
704
966
  if ((coordinates.state?.currentIndex ?? -1) > -1 || coordinates.interval) {