stream-chat 10.0.0-rc.9 → 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 (361) hide show
  1. package/README.md +7 -6
  2. package/dist/cjs/index.browser.js +21650 -19790
  3. package/dist/cjs/index.browser.js.map +4 -4
  4. package/dist/cjs/index.node.js +21690 -19798
  5. package/dist/cjs/index.node.js.map +4 -4
  6. package/dist/esm/index.mjs +21755 -19895
  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 +13 -27
  10. package/dist/types/EventHandlerPipeline.d.ts +18 -38
  11. package/dist/types/LiveLocationManager.d.ts +24 -52
  12. package/dist/types/api-client.d.ts +17 -5
  13. package/dist/types/channel.d.ts +432 -470
  14. package/dist/types/channel_state.d.ts +68 -112
  15. package/dist/types/client.d.ts +321 -435
  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 +2 -0
  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 +2528 -690
  50. package/dist/types/gen/models/timestamp-guard.d.ts +22 -0
  51. package/dist/types/gen/moderation/ModerationApi.d.ts +33 -14
  52. package/dist/types/index.d.ts +10 -6
  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 +7 -1
  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 -128
  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 +19 -18
  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 +40 -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 -186
  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 -334
  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 +5 -23
  118. package/dist/types/pagination/utility.search.d.ts +3 -8
  119. package/dist/types/poll.d.ts +34 -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 +11 -11
  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 +63 -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 -199
  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 +33 -57
  148. package/dist/types/utils.d.ts +72 -91
  149. package/package.json +14 -40
  150. package/src/ChannelManager.ts +494 -303
  151. package/src/CooldownTimer.ts +28 -38
  152. package/src/EventHandlerPipeline.ts +22 -45
  153. package/src/LiveLocationManager.ts +37 -76
  154. package/src/api-client.ts +113 -50
  155. package/src/campaign.ts +1 -1
  156. package/src/channel.ts +1067 -1276
  157. package/src/channel_batch_updater.ts +1 -1
  158. package/src/channel_state.ts +73 -168
  159. package/src/client.ts +744 -974
  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 -232
  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 +6 -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 -1540
  195. package/src/gen/models/index.ts +2498 -3383
  196. package/src/gen/models/timestamp-guard.ts +27 -0
  197. package/src/gen/moderation/ModerationApi.ts +170 -367
  198. package/src/index.ts +22 -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 +19 -23
  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 +223 -174
  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/textComposer.ts +1 -1
  225. package/src/messageComposer/middleware/messageComposer/userDataInjection.ts +12 -12
  226. package/src/messageComposer/middleware/pollComposer/state.ts +2 -2
  227. package/src/messageComposer/middleware/pollComposer/types.ts +2 -4
  228. package/src/messageComposer/middleware/pollComposer/validation.ts +8 -26
  229. package/src/messageComposer/middleware/textComposer/TextComposerMiddlewareExecutor.ts +8 -6
  230. package/src/messageComposer/middleware/textComposer/commandUtils.ts +10 -3
  231. package/src/messageComposer/middleware/textComposer/commands.ts +11 -16
  232. package/src/messageComposer/middleware/textComposer/mentions.ts +32 -70
  233. package/src/messageComposer/middleware/textComposer/textMiddlewareUtils.ts +10 -4
  234. package/src/messageComposer/middleware/textComposer/types.ts +1 -6
  235. package/src/messageComposer/pollComposer.ts +21 -9
  236. package/src/messageComposer/textComposer.ts +37 -57
  237. package/src/messageComposer/types.ts +39 -11
  238. package/src/messageDelivery/MessageDeliveryReporter.ts +86 -125
  239. package/src/messageDelivery/MessageReceiptsTracker.ts +88 -101
  240. package/src/messageOperations/FailedSendCache.ts +85 -0
  241. package/src/messageOperations/MessageOperationStatePolicy.ts +121 -112
  242. package/src/messageOperations/MessageOperations.ts +297 -175
  243. package/src/{entityStore → messageOperations}/applyReactionLocally.ts +9 -28
  244. package/src/messageOperations/createMessageOperations.ts +176 -0
  245. package/src/messageOperations/index.ts +6 -14
  246. package/src/messageOperations/reflectReactionEvent.ts +43 -0
  247. package/src/messageOperations/sendOrdering.ts +25 -0
  248. package/src/messageOperations/settlePendingAttachmentUploads.ts +98 -0
  249. package/src/messageOperations/types.ts +51 -13
  250. package/src/middleware.ts +13 -5
  251. package/src/moderation.ts +25 -21
  252. package/src/notifications/NotificationManager.ts +19 -28
  253. package/src/notifications/types.ts +21 -57
  254. package/src/offline-support/offline_support_api.ts +226 -669
  255. package/src/offline-support/offline_sync_manager.ts +51 -80
  256. package/src/offline-support/queueableOperations.ts +98 -73
  257. package/src/offline-support/types.ts +43 -186
  258. package/src/pagination/FilterBuilder.ts +1 -22
  259. package/src/pagination/ItemIndex.ts +4 -12
  260. package/src/pagination/cursorDerivation/aroundPaginationFlags.ts +29 -0
  261. package/src/pagination/cursorDerivation/createdAtAroundPaginationFlags.ts +15 -63
  262. package/src/pagination/cursorDerivation/idAroundPaginationFlags.ts +11 -39
  263. package/src/pagination/cursorDerivation/linearPaginationFlags.ts +53 -33
  264. package/src/pagination/filterCompiler.ts +11 -25
  265. package/src/pagination/index.ts +1 -0
  266. package/src/pagination/paginators/BasePaginator.ts +1415 -1041
  267. package/src/pagination/paginators/ChannelPaginator.ts +479 -217
  268. package/src/pagination/paginators/MessageIntervalPaginator.ts +1351 -772
  269. package/src/pagination/paginators/MessagePaginator.ts +513 -233
  270. package/src/pagination/paginators/PinnedMessagePaginator.ts +32 -40
  271. package/src/pagination/paginators/ReminderPaginator.ts +21 -16
  272. package/src/pagination/paginators/ThreadPaginator.ts +170 -0
  273. package/src/pagination/paginators/UserGroupPaginator.ts +16 -19
  274. package/src/pagination/paginators/index.ts +1 -0
  275. package/src/pagination/paginators/stateThrottling.ts +5 -10
  276. package/src/pagination/sortCompiler.ts +23 -50
  277. package/src/pagination/utility.normalization.ts +8 -30
  278. package/src/pagination/utility.search.ts +4 -11
  279. package/src/poll.ts +177 -98
  280. package/src/poll_manager.ts +24 -22
  281. package/src/poll_optimistic_votes.ts +335 -0
  282. package/src/reminders/Reminder.ts +16 -12
  283. package/src/reminders/ReminderManager.ts +22 -55
  284. package/src/reminders/ReminderTimer.ts +1 -2
  285. package/src/search/BaseSearchSource.ts +19 -25
  286. package/src/search/ChannelSearchSource.ts +43 -1
  287. package/src/search/MessageSearchSource.ts +77 -13
  288. package/src/search/SearchController.ts +39 -36
  289. package/src/search/types.ts +6 -10
  290. package/src/segment.ts +1 -1
  291. package/src/signing.ts +23 -3
  292. package/src/thread.ts +418 -703
  293. package/src/thread_manager.ts +300 -234
  294. package/src/token_manager.ts +12 -22
  295. package/src/types.ts +102 -216
  296. package/src/types.utility.ts +3 -3
  297. package/src/upload-utils.ts +5 -10
  298. package/src/uploadManager.ts +64 -18
  299. package/src/utils/FixedSizeQueueCache.ts +18 -21
  300. package/src/utils/WithSubscriptions.ts +6 -16
  301. package/src/utils/abort.ts +45 -0
  302. package/src/utils/concurrency.ts +16 -55
  303. package/src/utils/mergeWith/mergeWith.ts +10 -13
  304. package/src/utils/mergeWith/mergeWithCore.ts +24 -81
  305. package/src/utils/mergeWith/mergeWithDiff.ts +15 -33
  306. package/src/utils/objectPath.ts +6 -41
  307. package/src/utils/retryable.ts +10 -14
  308. package/src/utils/throttling/throttle.ts +9 -25
  309. package/src/utils/time.ts +40 -60
  310. package/src/utils.ts +181 -174
  311. package/codegen/i18n/callSites.ts +0 -126
  312. package/codegen/i18n/generate.ts +0 -226
  313. package/codegen/i18n/guards.ts +0 -178
  314. package/codegen/i18n/index.ts +0 -29
  315. package/codegen/i18n/stringMaps.ts +0 -91
  316. package/codegen/i18n/types.ts +0 -100
  317. package/dist/cjs/i18n.browser.js +0 -1131
  318. package/dist/cjs/i18n.browser.js.map +0 -7
  319. package/dist/cjs/i18n.node.js +0 -1160
  320. package/dist/cjs/i18n.node.js.map +0 -7
  321. package/dist/esm/i18n-codegen.mjs +0 -409
  322. package/dist/esm/i18n-codegen.mjs.map +0 -7
  323. package/dist/esm/i18n.mjs +0 -1098
  324. package/dist/esm/i18n.mjs.map +0 -7
  325. package/dist/types/ConnectionRecoveryManager.d.ts +0 -156
  326. package/dist/types/connection.d.ts +0 -139
  327. package/dist/types/entityStore/applyReactionLocally.d.ts +0 -32
  328. package/dist/types/i18n/Streami18n.d.ts +0 -168
  329. package/dist/types/i18n/TranslationBuilder.d.ts +0 -70
  330. package/dist/types/i18n/TranslationStore.d.ts +0 -57
  331. package/dist/types/i18n/dayjs.d.ts +0 -104
  332. package/dist/types/i18n/formatters.d.ts +0 -91
  333. package/dist/types/i18n/index.d.ts +0 -15
  334. package/dist/types/i18n/translator.d.ts +0 -29
  335. package/dist/types/i18n/types.d.ts +0 -262
  336. package/dist/types/i18n-codegen/callSites.d.ts +0 -10
  337. package/dist/types/i18n-codegen/generate.d.ts +0 -15
  338. package/dist/types/i18n-codegen/guards.d.ts +0 -61
  339. package/dist/types/i18n-codegen/index.d.ts +0 -29
  340. package/dist/types/i18n-codegen/stringMaps.d.ts +0 -14
  341. package/dist/types/i18n-codegen/types.d.ts +0 -94
  342. package/dist/types/insights.d.ts +0 -56
  343. package/dist/types/messageOperations/optimistic.d.ts +0 -118
  344. package/dist/types/messageOperations/persistence.d.ts +0 -21
  345. package/dist/types/pagination/utility.queryChannel.d.ts +0 -26
  346. package/dist/types/store.d.ts +0 -125
  347. package/src/ConnectionRecoveryManager.ts +0 -293
  348. package/src/i18n/Streami18n.ts +0 -520
  349. package/src/i18n/TranslationBuilder.ts +0 -176
  350. package/src/i18n/TranslationStore.ts +0 -96
  351. package/src/i18n/dayjs.ts +0 -228
  352. package/src/i18n/formatters.ts +0 -461
  353. package/src/i18n/index.ts +0 -15
  354. package/src/i18n/languageNames.ts +0 -103
  355. package/src/i18n/translator.ts +0 -76
  356. package/src/i18n/types.ts +0 -375
  357. package/src/insights.ts +0 -82
  358. package/src/messageOperations/optimistic.ts +0 -257
  359. package/src/messageOperations/persistence.ts +0 -40
  360. package/src/pagination/utility.queryChannel.ts +0 -84
  361. package/src/store.ts +0 -304
@@ -1,5 +1,5 @@
1
1
  import type { ItemLocation } from '../sortCompiler';
2
- import { StateStore, type ValueOrPatch } from '../../store';
2
+ import { StateStore, type ValueOrPatch } from '@stream-io/state-store';
3
3
  import { type DebouncedFunc } from '../../utils';
4
4
  import type { FieldToDataResolver } from '../types.normalization';
5
5
  import type { ItemIndexApi } from '../ItemIndex';
@@ -22,27 +22,9 @@ export type Interval = {
22
22
  hasMoreTail: boolean;
23
23
  itemIds: string[];
24
24
  id: string;
25
- /**
26
- * True if this interval represents the global head of the dataset
27
- * under the current sortComparator.
28
- *
29
- * Cursor pagination:
30
- * headward === null
31
- *
32
- * Offset pagination:
33
- * offset === 0
34
- */
25
+ /** Reaches the dataset head (cursor: `headward === null`, offset: `offset === 0`). */
35
26
  isHead: boolean;
36
- /**
37
- * True if this interval represents the global tail of the dataset
38
- * under the current sortComparator.
39
- *
40
- * Cursor pagination:
41
- * tailward === null
42
- *
43
- * Offset pagination:
44
- * returnedItems.length < pageSize
45
- */
27
+ /** Reaches the dataset tail (cursor: `tailward === null`, offset: a short page). */
46
28
  isTail: boolean;
47
29
  };
48
30
  export type AnyInterval = Interval | LogicalInterval;
@@ -67,17 +49,9 @@ export type MakeIntervalParams<T> = {
67
49
  export type SetPaginatorItemsParams<T> = {
68
50
  valueOrFactory: ValueOrPatch<T[]>;
69
51
  cursor?: PaginatorCursor;
70
- /**
71
- * Relevant only is using item interval storage in the paginator.
72
- * Indicates that the page would be the head of pagination intervals array.
73
- * Items falling outside this intervals head bound will be merged into this interval.
74
- */
52
+ /** The page is the head interval: items beyond its head bound merge into it. */
75
53
  isFirstPage?: boolean;
76
- /**
77
- * Relevant only is using item interval storage in the paginator.
78
- * Indicates that the page would be the tail of pagination intervals array
79
- * Items falling outside this intervals tail bound will be merged into this interval.
80
- */
54
+ /** The page is the tail interval: items beyond its tail bound merge into it. */
81
55
  isLastPage?: boolean;
82
56
  };
83
57
  type MergeIntervalsResult = {
@@ -86,34 +60,21 @@ type MergeIntervalsResult = {
86
60
  logicalTail: LogicalInterval | null;
87
61
  };
88
62
  /**
89
- * headward - going from page X -> X-Y -> 0
90
- * tailward - goring from page 0 -> X -> X + Y ...
91
- *
92
- * Head is the place where new items are added - same as git.
93
- * Tail is the place where retrieved pages are appended.
63
+ * `headward` moves toward page 0, `tailward` away from it. New items are added at the head,
64
+ * retrieved pages are appended at the tail.
94
65
  */
95
66
  export type PaginationDirection = 'headward' | 'tailward';
96
67
  export type CursorDeriveContext<T, Q> = {
97
- /**
98
- * Current cursor to be merged with the newly derived cursor.
99
- * Allows to preserve the direction we have not paginated with the given request.
100
- */
68
+ /** Current cursor, merged with the derived one to keep the direction not paginated. */
101
69
  cursor: PaginatorCursor | undefined;
102
- /**
103
- * Direction we just paginated in.
104
- *
105
- * May be undefined for non-directional queries (e.g. jump-to / *_around).
106
- */
70
+ /** Direction just paginated in. Undefined for non-directional queries (jump-to, `*_around`). */
107
71
  direction: PaginationDirection | undefined;
108
72
  hasMoreTail: boolean;
109
73
  hasMoreHead: boolean;
110
- /** The parent interval the page was ingested into (if any) */
111
74
  interval: Interval;
112
- /** The page we just received after filtering */
75
+ /** The page received, after filtering. */
113
76
  page: T[];
114
- /** Last query shape (sometimes useful for bespoke logic) */
115
77
  queryShape: Q | undefined;
116
- /** Number we asked for */
117
78
  requestedPageSize: number;
118
79
  };
119
80
  export type PaginationFlags = {
@@ -137,58 +98,112 @@ export declare const ZERO_PAGE_CURSOR: PaginatorCursor;
137
98
  type StateResetPolicy = 'auto' | 'yes' | 'no' | (string & {});
138
99
  export type PaginationQueryShapeChangeIdentifier<S> = (toHeadQueryShape?: S, toTailQueryShape?: S) => boolean;
139
100
  export type PaginationQueryParams<Q> = {
101
+ /**
102
+ * Whether the query claims the active interval (see `BasePaginator.claimActiveInterval`): after
103
+ * a later claim, its page is only stored and the result reports `isSuperseded`. Default: see
104
+ * `BasePaginator.decidesActiveInterval`.
105
+ */
106
+ claimsActiveInterval?: boolean;
140
107
  direction?: PaginationDirection;
141
108
  /**
142
- * Keep the currently loaded items (and cursor/flags) visible while a first-page query runs
143
- * instead of blanking to the empty initial state. The freshly fetched page is merged into the
144
- * active interval by `postQueryReconcile` (upserting changed items, appending new ones), so the
145
- * list is refreshed in place with no loading-screen flash. Used by the non-destructive refresh.
109
+ * Keeps loaded items (and cursor/flags) visible during a first-page query instead of resetting;
110
+ * `placeQueryPage` merges the fetched page into the active interval.
146
111
  */
147
112
  keepPreviousItems?: boolean;
148
113
  /** Data that define the query (filters, sort, ...) */
149
114
  queryShape?: Q;
150
- /** Per-call override of the reset behavior. */
115
+ /** Per-call override: 'yes' forces a first page, 'no' continues, else the query shape decides. */
151
116
  reset?: StateResetPolicy;
152
117
  /**
153
- * How many times to **retry** a failed request, i.e. `retryCount + 1` attempts in total. Per-call
154
- * override of `PaginatorOptions.retryCount`, which defaults to 0 (no retry).
118
+ * Request options outside the query shape, so they never make the query a new first page. Each
119
+ * paginator reads the ones it documents. Resent on retries.
155
120
  */
121
+ requestOptions?: Record<string, unknown>;
122
+ /** Number of retries after a failure. Overrides `PaginatorOptions.retryCount`. */
156
123
  retryCount?: number;
157
124
  /**
158
- * Suppress `isLoading` transitions for this query (a silent, background refresh). When falsy
159
- * (default) the usual loading state is surfaced so the UI can show a spinner.
125
+ * Skips the `isLoading: true` publish for a non-first-page or `keepPreviousItems` query
126
+ * (background refresh). A first page without `keepPreviousItems` still surfaces loading.
160
127
  */
161
128
  silent?: boolean;
162
- /** Determines, whether the page loaded with the query will be committed to the paginator state. Default: true. */
129
+ /**
130
+ * Whether the page's interval becomes the active one and the state is published. Default: true.
131
+ * Otherwise the page is only stored; one landing in the active interval is still published. Even
132
+ * with it, the paginator's own page can be only stored (see `BasePaginator.isPageOnlyStored`).
133
+ */
163
134
  updateState?: boolean;
164
135
  };
165
- export type PostQueryReconcileParams<T, Q> = Pick<PaginationQueryParams<Q>, 'direction' | 'queryShape' | 'updateState' | 'keepPreviousItems'> & {
136
+ /**
137
+ * How a query's page is placed: what `BasePaginator.placeQueryPage` takes besides the page itself.
138
+ * The last step of the query pipeline gets it too (see `BasePaginator.applyQueryResponseRest`).
139
+ */
140
+ export type QueryPagePlacement<Q> = Pick<PaginationQueryParams<Q>, 'direction' | 'queryShape' | 'updateState' | 'keepPreviousItems'> & {
141
+ /**
142
+ * The query's claim on the active interval, for a query that claims it (see
143
+ * `PaginationQueryParams.claimsActiveInterval`). After a later claim, the page is only stored.
144
+ */
145
+ activeIntervalClaim?: number;
146
+ /**
147
+ * Whether the page starts a separate interval, merged only with intervals it overlaps, as its
148
+ * place relative to the active interval is unknown (queried elsewhere, or at a caller's shape).
149
+ * Otherwise it continues the active interval. Default: `false`, except for jump queries.
150
+ */
151
+ startsSeparateInterval?: boolean;
152
+ /**
153
+ * The interval active when a query from the paginator's own cursor was prepared. The page
154
+ * continues it only while it is still active (see `BasePaginator.isPageOnlyStored`).
155
+ */
156
+ continuesIntervalId?: string;
166
157
  isFirstPage: boolean;
158
+ /** The position a refresh keeping the items reset, restored when it places no page. */
159
+ positionBeforeReset?: Pick<PaginatorState<unknown>, 'cursor' | 'offset'>;
167
160
  requestedPageSize: number;
161
+ };
162
+ export type PlaceQueryPageParams<T, Q> = QueryPagePlacement<Q> & {
163
+ /** The page to place; `null` only ends the query. */
168
164
  results: PaginationQueryReturnValue<T> | null;
169
165
  };
170
166
  export type ExecuteQueryReturnValue<T> = {
171
167
  /**
172
- * State object resulting from the post query processing.
173
- * The object is committed to the state if PaginationQueryParams<Q>['updateState'] === true.
168
+ * State from the placing step (see `BasePaginator.placeQueryPage`), committed when `updateState`
169
+ * is true.
174
170
  */
175
171
  stateCandidate: Partial<PaginatorState<T>>;
176
- /** In case the items are kept in intervals, the interval into which the page has been merged, will be returned. */
172
+ /** The interval the page was merged into, when items are kept in intervals. */
177
173
  targetInterval: AnyInterval | null;
174
+ /**
175
+ * Set by `BasePaginator.executeQuery`: whether a later claim on the active interval overtook the
176
+ * query's own (see `PaginationQueryParams.claimsActiveInterval`).
177
+ */
178
+ isSuperseded?: boolean;
179
+ };
180
+ /**
181
+ * What a paginator's custom `doRequest` resolves to: a page of items, and its cursor with cursor
182
+ * pagination (see `BasePaginatorConfig.doRequest`).
183
+ */
184
+ export type DoRequestResponse<T> = {
185
+ items: T[];
186
+ cursor?: PaginatorCursor;
178
187
  };
179
188
  export type PaginationQueryReturnValue<T> = {
180
189
  items: T[];
181
190
  } & {
182
- headward?: string;
183
- tailward?: string;
184
191
  /**
185
- * @deprecated Use `tailward` instead.
192
+ * The cursor to the next page towards the head.
193
+ *
194
+ * - `null`: the page reaches the head of the dataset, so there is none. This holds for every
195
+ * paginator, including one that derives its cursors (`deriveCursor`).
196
+ * - `undefined` depends on where the paginator takes its cursors from. One that derives them reads it
197
+ * as not reported (a page queried towards the tail says nothing about the head side) and derives
198
+ * the cursor itself. One that takes them from the query reads it as no next page, as an API leaves
199
+ * out the cursor at the end.
186
200
  */
187
- next?: string;
201
+ headward?: string | null;
188
202
  /**
189
- * @deprecated Use `headward` instead.
203
+ * The cursor to the next page towards the tail; `null` and `undefined` as for {@link headward}, with
204
+ * `null` meaning the page reaches the tail of the dataset.
190
205
  */
191
- prev?: string;
206
+ tailward?: string | null;
192
207
  };
193
208
  export type PaginatorDebounceOptions = {
194
209
  debounceMs: number;
@@ -204,23 +219,21 @@ export type PaginatorState<T> = {
204
219
  offset?: number;
205
220
  };
206
221
  /**
207
- * Reactive projections of specific (fixed-identity) intervals, published independently of the
208
- * paginated `state` (which tracks only the *active* interval). See {@link BasePaginator.intervalViews}.
209
- * A field is rewritten only when its own interval changes, so a `useStateStore`/`subscribeWithSelector`
210
- * consumer selecting one field only wakes when *that* interval changes. (The head-most window that can
211
- * be either a logical or an anchored interval is a derived *role*, not a fixed interval, so it is not
212
- * published here — read it one-shot via {@link BasePaginator.headItems} / {@link BasePaginator.headmostItem}.)
222
+ * Projections of fixed-identity intervals, published independently of `state` (which tracks only
223
+ * the active interval; see {@link BasePaginator.intervalViews}). A field is rewritten only when its
224
+ * own interval changes. One-shot reads: {@link BasePaginator.anchoredHeadItems},
225
+ * {@link BasePaginator.logicalHeadItems}, {@link BasePaginator.logicalTailItems}.
213
226
  */
214
227
  export type PaginatorIntervalViews<T> = {
215
- /** Live logical-head interval — out-of-order items above the loaded window. */
216
- logicalHead: T[];
217
- /** Live logical-tail interval — out-of-order items below the loaded window. */
218
- logicalTail: T[];
219
228
  /**
220
- * Anchored head interval — the loaded page bounded at the dataset head (`isHead`), i.e. the newest
221
- * loaded page; empty when the head is not loaded. Its content updates when that page ingests/removes
222
- * an item, and its identity updates when a page's `isHead` flag flips during query reconciliation.
229
+ * Out-of-order items above the loaded interval. With no page loaded (before the first one, or after
230
+ * every loaded item left the list) the logical head can itself be the active interval, and then
231
+ * `state.items` lists the same items: a UI rendering both shows them twice.
223
232
  */
233
+ logicalHead: T[];
234
+ /** Out-of-order items below the loaded interval; can be the active interval too, as above. */
235
+ logicalTail: T[];
236
+ /** The loaded page bounded at the dataset head (`isHead`); empty when the head is not loaded. */
224
237
  anchoredHead: T[];
225
238
  };
226
239
  export type PaginatorItemsChangeProcessor<T> = (params: {
@@ -229,39 +242,16 @@ export type PaginatorItemsChangeProcessor<T> = (params: {
229
242
  }) => T[] | undefined;
230
243
  export interface PaginatorPlugin<T> {
231
244
  /**
232
- * Optional plugin hook invoked immediately before the paginator emits a new
233
- * `items` value to subscribers, but only when the `items` array has actually
234
- * changed by reference.
235
- *
236
- * This hook allows plugins to post-process the visible items—such as
237
- * deduplicating, normalizing, sorting, enriching, or otherwise transforming
238
- * the array—at the final stage of state emission. The processed value becomes
239
- * the `items` value delivered to subscribers.
240
- *
241
- * Return a new array to replace `nextState.items`, or return `undefined`
242
- * to leave the items unchanged.
243
- *
244
- * Executed in the order plugins are registered.
245
+ * Runs before `items` are emitted, only when the array changed by reference. Return a new array
246
+ * to replace `nextState.items`, or `undefined` to keep it. Runs in registration order.
245
247
  */
246
248
  onBeforeItemsEmitted?: PaginatorItemsChangeProcessor<T>;
247
249
  }
248
250
  /**
249
- * Optional list of plugins that can hook into paginator lifecycle events.
250
- *
251
- * Plugins allow you to encapsulate cross-cutting behavior (such as items
252
- * post-processing, analytics, offline caching, etc.) without modifying
253
- * the core paginator logic. Each plugin can register handlers like
254
- * `onItemsChange` that are invoked when relevant events occur.
255
- *
256
- * All registered plugins are executed in the order they appear in this array.
257
- */
258
- /**
259
- * The value-level subset of paginator configuration that can be supplied declaratively through
260
- * `client.config`. Structural inputs (`itemIndex`, `createItemIndex`) and subclass behaviour overrides
261
- * (`doRequest`, `itemOrderComparator`, `deriveCursor`) are deliberately absent — see
262
- * {@link BasePaginator.initializeConfig}.
263
- *
264
- * Declared standalone rather than derived from {@link PaginatorOptions} to avoid a circular type.
251
+ * The value-level subset of paginator options that `client.config` can supply declaratively.
252
+ * Structural inputs (`itemIndex`, `createItemIndex`) and subclass overrides (`doRequest`,
253
+ * `itemOrderComparator`, `deriveCursor`) are excluded. Declared standalone to avoid a circular type
254
+ * with `PaginatorOptions`.
265
255
  */
266
256
  export type DeclarativePaginatorConfig = {
267
257
  debounceMs?: number;
@@ -269,6 +259,7 @@ export type DeclarativePaginatorConfig = {
269
259
  initialCursor?: PaginatorCursor;
270
260
  initialOffset?: number;
271
261
  lockItemOrder?: boolean;
262
+ maxLoadedItems?: number;
272
263
  pageSize?: number;
273
264
  retryCount?: number;
274
265
  stateThrottleMs?: number;
@@ -276,170 +267,149 @@ export type DeclarativePaginatorConfig = {
276
267
  };
277
268
  export type PaginatorOptions<T, Q> = {
278
269
  /**
279
- * Declarative configuration for this paginator, supplied by whoever constructs it from
280
- * `client.config`. Kept separate from the other options so {@link BasePaginator.initializeConfig}
281
- * can re-derive with a *fresh* slice — a reset then drops declarative values while preserving
282
- * constructor-injected ones. Excluded from {@link BasePaginatorConfig}: it is an input, not part of
283
- * the resolved configuration.
270
+ * Declarative values from `client.config`, kept apart so a reset (`initializeConfig` with a fresh
271
+ * slice) drops them but keeps injected options. Not part of {@link BasePaginatorConfig}.
284
272
  */
285
273
  declarativeConfig?: DeclarativePaginatorConfig;
286
- /** The number of milliseconds to debounce the search query. The default interval is 300ms. */
274
+ /** Debounce of the search query in milliseconds. Defaults to 300. */
287
275
  debounceMs?: number;
288
276
  /**
289
- * When set (and not disabled for tests — see `stateThrottling.ts`), coalesces the paginator's own
290
- * live `state.items` publishes to at most once per `stateThrottleMs` (leading + trailing edge): a
291
- * burst of live mutations (WS `message.new`, reactions, reads) re-projects the active window and
292
- * publishes it ~2×/sec instead of once per event. Only the paginator's OWN writes to `state.items`
293
- * are batched — `state.getLatestValue()` is untouched (no `StateStore` change), pagination / jump /
294
- * query publishes stay immediate, and an immediate flush past it is available via
295
- * {@link flushPendingPublishes}. Unset ⇒ no throttle (default). Enabled at
296
- * 500ms for the message list — see {@link MessagePaginator}.
277
+ * Coalesces the paginator's own live `state.items` publishes to one per `stateThrottleMs`
278
+ * (leading and trailing edge). Pagination, jump and query publishes stay immediate. Disabled
279
+ * under test runners. Unset: no throttle.
297
280
  */
298
281
  stateThrottleMs?: number;
299
282
  /**
300
- * Function containing custom logic that decides, whether the next pagination query to be executed should be considered the first page query.
301
- * It makes sense to consider the next query as the first page query if filters, sort, options etc. (query params) excluding the page size have changed.
283
+ * Decides whether the next query is a first-page query. It should be when filters, sort or
284
+ * options (the query params except page size) changed.
302
285
  */
303
286
  hasPaginationQueryShapeChanged?: PaginationQueryShapeChangeIdentifier<any>;
304
287
  /**
305
- * Optional hook to fully control cursor + hasMore logic in 'derived' mode.
306
- * If not provided, BasePaginator uses its own default implementation.
288
+ * Derives the cursor and `hasMore` flags from the ingested interval. Without it, the cursor comes
289
+ * from the query response (`headward`/`tailward`, falsy meaning exhausted).
307
290
  */
308
291
  deriveCursor?: CursorDerivator<T, Q>;
309
- /** Custom function to retrieve items pages and optionally return a cursor in case of cursor pagination. */
310
- doRequest?: (queryParams: Q) => Promise<{
311
- items: T[];
312
- cursor?: PaginatorCursor;
313
- }>;
314
- /** In case of cursor pagination, specify the initial cursor value. */
292
+ /**
293
+ * Custom function to retrieve items pages and optionally return a cursor in case of cursor
294
+ * pagination. A `null` cursor side tells that the page reaches that end of the dataset; an
295
+ * `undefined` side is read as {@link PaginationQueryReturnValue.headward} describes for this
296
+ * paginator.
297
+ */
298
+ doRequest?: (queryParams: Q) => Promise<DoRequestResponse<T>>;
315
299
  initialCursor?: PaginatorCursor;
316
- /** In case of offset pagination, specify the initial offset value. */
317
300
  initialOffset?: number;
318
- /** If item index is provided, this index ensures updates in a single place and all consumers have access to a single source of data. */
301
+ /** Shared item index: a single source of data for all consumers. */
319
302
  itemIndex?: ItemIndexApi<T>;
320
303
  /**
321
- * Factory for the item index, invoked with the fully-constructed paginator as `owner`.
322
- * Lets a subclass back the paginator with an adapter that needs a reference to the
323
- * owner (e.g. a shared, client-global store) without the `this`-before-`super` problem.
324
- * Ignored when an explicit `itemIndex` is supplied.
304
+ * Builds the item index from the paginator (`owner`), for adapters that need it (e.g. a
305
+ * client-global store). Runs in the base constructor, before subclass fields are initialized.
306
+ * Ignored when `itemIndex` is supplied.
325
307
  */
326
- createItemIndex?: (owner: BasePaginator<T, Q>) => ItemIndexApi<T>;
308
+ createItemIndex?: (owner: BasePaginator<T, Q, unknown>) => ItemIndexApi<T>;
327
309
  /**
328
- * Comparator defining in-memory item ordering for interval math and visible list rendering.
329
- * Defaults to `sortComparator` to preserve existing paginator behavior.
310
+ * Orders items in memory for interval math and the visible list. Defaults to `sortComparator`.
330
311
  */
331
312
  itemOrderComparator?: (a: T, b: T) => number;
332
313
  /**
333
- * Will prevent changing the index of existing items in state.
334
- * If true, an item that is already visible keeps its relative position in the current items array when updated.
335
- * It does not guarantee global stability across interval changes or page jumps.
314
+ * An already visible item keeps its relative position in the current items array when updated.
315
+ * Does not hold across interval changes or page jumps.
336
316
  */
337
317
  lockItemOrder?: boolean;
338
- /** The item page size to be requested from the server. */
318
+ /**
319
+ * Caps the loaded items: when the head interval exceeds it, the oldest are released as new ones
320
+ * arrive and the tailward edge re-opens, so scrolling back re-fetches. Unset: unbounded. Values
321
+ * below `pageSize` are clamped up to it. See {@link BasePaginator.pruneTailToLimit}.
322
+ */
323
+ maxLoadedItems?: number;
324
+ /** Items requested per page. Defaults to 10. */
339
325
  pageSize?: number;
340
326
  /**
341
- * How many times to **retry** a failed request before giving up, i.e. `retryCount + 1` attempts in
342
- * total, with `DEFAULT_QUERY_CHANNELS_MS_BETWEEN_RETRIES` between them. Defaults to 0 (no retry);
327
+ * Retries after a failed request (`retryCount + 1` attempts),
328
+ * `DEFAULT_QUERY_CHANNELS_MS_BETWEEN_RETRIES` apart. Defaults to 0.
343
329
  * `PaginationQueryParams.retryCount` overrides it per call.
344
330
  */
345
331
  retryCount?: number;
346
- /** Prevent silencing the errors thrown during the pagination execution. Default is false. */
332
+ /** Rethrows errors from pagination execution instead of swallowing them. Defaults to false. */
347
333
  throwErrors?: boolean;
348
334
  };
349
- type OptionalPaginatorConfigFields = 'stateThrottleMs' | 'deriveCursor' | 'doRequest' | 'initialCursor' | 'initialOffset' | 'itemOrderComparator' | 'throwErrors';
335
+ type OptionalPaginatorConfigFields = 'stateThrottleMs' | 'maxLoadedItems' | 'deriveCursor' | 'doRequest' | 'initialCursor' | 'initialOffset' | 'itemOrderComparator' | 'throwErrors';
350
336
  /**
351
- * Construction-only inputs that are not part of the resolved configuration.
352
- *
353
- * `itemIndex` and `createItemIndex` are here rather than in {@link BasePaginatorConfig} because the
354
- * constructor destructures them out before building the config and resolves them once into
355
- * {@link BasePaginator._itemIndex}. They were typed as config members and never written, so
356
- * `paginator.config.itemIndex` compiled and returned `undefined` for every paginator ever built.
337
+ * Options minus the construction-only inputs: the constructor resolves `itemIndex` and
338
+ * `createItemIndex` once into {@link BasePaginator._itemIndex}, so they are not config.
357
339
  */
358
340
  type ResolvedPaginatorOptions<T, Q> = Omit<PaginatorOptions<T, Q>, 'createItemIndex' | 'declarativeConfig' | 'itemIndex'>;
359
341
  export type BasePaginatorConfig<T, Q> = Pick<ResolvedPaginatorOptions<T, Q>, OptionalPaginatorConfigFields> & Required<Omit<ResolvedPaginatorOptions<T, Q>, OptionalPaginatorConfigFields>>;
360
342
  export declare const DEFAULT_PAGINATION_OPTIONS: BasePaginatorConfig<any, any>;
361
- export declare abstract class BasePaginator<T, Q> {
343
+ /**
344
+ * Loads a sorted dataset page by page and keeps what it loaded as intervals.
345
+ *
346
+ * Terms used across the paginators, their names and their docs:
347
+ * - **interval**: a contiguous run of loaded items, with nothing missing between them
348
+ * ({@link Interval}). A page that connects to a loaded interval merges into it
349
+ * ({@link IntervalMergePolicy}); one that does not is kept as an interval of its own, so several
350
+ * intervals can be loaded at once.
351
+ * - **head / tail**: the two ends of the dataset in its sort order, and the matching ends of an
352
+ * interval. "Headward" and "tailward" are the directions toward them.
353
+ * - **active interval**: the interval whose items `state.items` exposes. The paginator's own
354
+ * navigation (loading toward the head or tail, jumping to an item) moves it; a page placed from
355
+ * outside moves it only where a subclass's placement rules say so.
356
+ * - **anchored head interval**: the loaded interval that reaches the head of the dataset
357
+ * (`isHead`); see {@link BasePaginator.anchoredHeadItems}. An interval reached by a jump is not
358
+ * anchored until it loads up to the head.
359
+ * - **logical head / tail interval**: items that arrived beyond the loaded head or tail and wait
360
+ * there until a page covers them ({@link LogicalInterval}).
361
+ *
362
+ * Say "interval", never "window": "window" is kept for the browser global and for time spans.
363
+ */
364
+ export declare abstract class BasePaginator<T, Q, R = PaginationQueryReturnValue<T>> {
362
365
  state: StateStore<PaginatorState<T>>;
363
366
  /**
364
- * Reactive projections of specific intervals — see {@link PaginatorIntervalViews}. Unlike `state`
365
- * (which only re-emits when the *active* interval is impacted), a field here is rewritten whenever
366
- * its own interval changes, regardless of which interval is active — so consumers can reactively
367
- * render off-window "sideloaded" content (`logicalHead`/`logicalTail`) and the newest loaded page
368
- * (`anchoredHead`). Kept separate from `state` so the paginated-list contract stays focused on the
369
- * active window + pagination status.
367
+ * Projections of specific intervals ({@link PaginatorIntervalViews}). Unlike `state`, a field is
368
+ * rewritten whenever its own interval changes, active or not.
370
369
  */
371
370
  intervalViews: StateStore<PaginatorIntervalViews<T>>;
372
- /** The shared configuration machinery — see {@link ConfigController}. */
373
371
  private readonly configController;
374
- /**
375
- * The paginator's resolved configuration, as a store so consumers can react to it.
376
- *
377
- * Every configurable class exposes its resolved configuration this way — `configState` for the store,
378
- * {@link config} for the current value. Before this, paginators held a plain object that changed
379
- * silently, so anything displaying a paginator's settings had to poll to notice a
380
- * `client.config.set()` or `reset()`.
381
- *
382
- * This is *resolved* configuration, distinct from `client.config`, which holds the configuration you
383
- * registered. The registered tree is an input to {@link initializeConfig}; this is its output.
384
- */
385
372
  get configState(): StateStore<BasePaginatorConfig<T, Q>>;
386
- /**
387
- * Options this paginator was constructed with, kept so {@link initializeConfig} can rebuild the
388
- * config from its real inputs instead of restoring a snapshot of the result. Excludes the
389
- * declarative slice, which is supplied fresh on every call — that is what lets a reset drop
390
- * declarative configuration while keeping constructor-injected options.
391
- */
373
+ /** Constructor options minus the declarative slice, for `initializeConfig` to rebuild from. */
392
374
  private readonly explicitOptions;
375
+ /** Throttle for the active-interval `state.items` publish. Set only with `stateThrottleMs`. */
376
+ private _activeIntervalPublishThrottle?;
393
377
  /**
394
- * Throttle for the active-window `state.items` publish (message list). Created only when
395
- * `config.stateThrottleMs` is set; drives {@link scheduleWindowPublish} / {@link flushPendingPublishes}. See
396
- * `stateThrottleMs` in {@link PaginatorOptions}.
397
- */
398
- private _windowPublishThrottle?;
399
- /**
400
- * Throttle for the interval-view publishes (`anchoredHead` / `logicalHead` / `logicalTail`) driven
401
- * by sibling store updates. Independent of {@link _windowPublishThrottle} so a view refresh lands on
402
- * its own trailing edge even when `state.items` stays quiet. Created alongside it (only when
403
- * `config.stateThrottleMs` is set); buffers changed ids in {@link _pendingViewChangedIds}.
378
+ * Throttle for interval-view publishes. Independent of {@link _activeIntervalPublishThrottle} so
379
+ * a view refresh lands on its own trailing edge even when `state.items` is quiet. Created with it.
404
380
  */
405
381
  private _viewPublishThrottle?;
406
- /** Changed ids buffered since the last {@link flushIntervalViewPublish} (throttled paginators only). */
382
+ /** Changed IDs buffered since the last {@link flushIntervalViewPublish} (throttled only). */
407
383
  private _pendingViewChangedIds;
408
384
  /**
409
- * Depth of active {@link batch} `coalesce` scopes. While > 0, `ingestItem` / `removeItem` record
410
- * that the active window changed (see {@link _suspendedWindowDirty}) instead of publishing it, so
411
- * the whole batch produces a single `state.items` emit — independent of state throttling.
385
+ * Depth of active {@link batch} `coalesce` scopes. While > 0, `ingestItem`/`removeItem` record
386
+ * the changed interval ({@link _staleActiveIntervalState}) instead of publishing.
412
387
  */
413
- private _windowPublishSuspendDepth;
414
- /** Set by a suspended op that changed the active window, so {@link batch} publishes once on exit. */
415
- private _suspendedWindowDirty;
388
+ private _activeIntervalPublishSuspendDepth;
416
389
  /**
417
- * Intervals keep items in disconnected ranges.
418
- * That is a scenario of jumping to non-sequential pages.
419
- * Intervals are populated only if itemIndex is provided.
390
+ * The interval a prune just shortened. Its `hasMoreTail` and `cursor` ride on the next
391
+ * `state.items` publish, which can be a throttle interval late, so
392
+ * {@link consumePendingPrunePaginationState} rereads them from the interval by ID when it fires.
420
393
  */
394
+ private _prunedIntervalId?;
395
+ /** The state shown when a suspended op last changed the active interval (see {@link batch}). */
396
+ private _staleActiveIntervalState?;
397
+ /** Disconnected ranges of items, e.g. after jumping to non-sequential pages. */
421
398
  protected _itemIntervals: Map<string, AnyInterval>;
422
399
  protected _activeIntervalId: string | undefined;
423
- /**
424
- * ItemIndex is a canonical, ID-addressable storage layer for domain items.
425
- * It serves as a single source of truth for all those that need to access the items
426
- * outside the paginator.
427
- */
400
+ /** How many claims on the active interval were made; the latest one decides it. */
401
+ private _activeIntervalClaimCount;
402
+ /** Canonical, ID-addressable item storage: the single source of truth outside the paginator. */
428
403
  protected _itemIndex: ItemIndexApi<T>;
429
404
  protected _executeQueryDebounced: DebouncedExecQueryFunction<Q>;
430
- /** Last effective query shape produced by subclass for the most recent request. */
405
+ /** Last effective query shape produced by the subclass for the most recent request. */
431
406
  protected _lastQueryShape?: Q;
432
- protected _nextQueryShape?: Q;
407
+ /** Set by `setItems`, which loads a page (even an empty one) without a query. */
408
+ private _pageSetWithoutQuery;
433
409
  /**
434
- * Stable, performs purely item data-driven (age, last_message_at, etc.) comparison.
435
- * Used under the hood
436
- * 1. as a fallback by effectiveComparator / boostComparator if boost comparison is not conclusive
437
- * 2. interval comparator
438
- *
439
- * Intervals cannot be sorted using boostComparator, because boosting the interval boundary (top item)
440
- * would lead to the boosting of the entire interval when sorting the intervals.
441
- *
442
- * Sorting within a single interval should be done using effectiveComparator, which by default uses boostComparator.
410
+ * Stable, purely data-driven comparison (age, timestamps, ...). Default for
411
+ * `itemOrderComparator`, which orders items and intervals and breaks `boostComparator` ties.
412
+ * Intervals never use the boost order: boosting a boundary item would boost its whole interval.
443
413
  */
444
414
  sortComparator: (a: T, b: T) => number;
445
415
  protected _filterFieldToDataResolvers: FieldToDataResolver<T>[];
@@ -449,92 +419,59 @@ export declare abstract class BasePaginator<T, Q> {
449
419
  }>;
450
420
  protected _maxBoostSeq: number;
451
421
  /**
452
- * Describes how `interval.itemIds` are oriented relative to pagination semantics.
453
- *
454
- * - `true` => `itemIds[0]` is the pagination head edge (default)
455
- * - `false` => `itemIds[itemIds.length - 1]` is the pagination head edge
456
- *
457
- * NOTE: This does not affect the *sorting* of `itemIds` (they are always kept
458
- * in `sortComparator` order). It only affects which side is considered
459
- * "head" for interval ordering and live ingestion decisions.
422
+ * Whether `itemIds[0]` (true) or the last ID (false) is the pagination head edge. Defaults to
423
+ * true. `itemIds` stay in `itemOrderComparator` order either way.
460
424
  */
461
425
  protected get intervalItemIdsAreHeadFirst(): boolean;
462
426
  /**
463
- * Determines the ordering of intervals in the internal interval list.
464
- *
465
- * This controls only the ordering of intervals relative to each other (by comparing
466
- * their head edges using `sortComparator`). It is intentionally decoupled from:
467
- * - the ordering of itemIds inside an interval
468
- * - the meaning of the head edge (controlled by `intervalItemIdsAreHeadFirst`)
427
+ * Order of intervals relative to each other, comparing head edges under `itemOrderComparator`.
428
+ * Independent of the `itemIds` order and of `intervalItemIdsAreHeadFirst`.
469
429
  */
470
430
  protected get intervalSortDirection(): 'asc' | 'desc';
471
431
  /**
472
- * @param options - what the **integrator** passed. Stage 3, so it outranks the declarative tree.
473
- * @param builtInDefaults - what the SDK supplies on this instance's behalf — a subclass's defaults, or
474
- * an owner's for the object it builds. Stage 1, so a `client.config.set()` overrides it. Keeping the
475
- * two apart is what lets the documented layer order apply here at all: they arrive through the same
476
- * object otherwise, and a paginator built with no configuration already carries four of them.
432
+ * @param options - What the integrator passed. Outranks the declarative `client.config` tree.
433
+ * @param builtInDefaults - What the SDK supplies on the instance's behalf (a subclass's or an
434
+ * owner's defaults). A `client.config.set()` overrides these.
477
435
  */
478
436
  protected constructor({ declarativeConfig, initialCursor, initialOffset, itemIndex, createItemIndex, ...options }?: PaginatorOptions<T, Q>, builtInDefaults?: Partial<BasePaginatorConfig<T, Q>>);
479
437
  get lastQueryError(): Error | undefined;
480
438
  get hasMoreTail(): boolean;
481
439
  get hasMoreHead(): boolean;
440
+ get hasResults(): boolean;
441
+ get isLoading(): boolean;
482
442
  /**
483
- * @deprecated Use `hasMoreTail` instead.
443
+ * True once a query has run or a non-empty interval was loaded without one (`setItems`, or a
444
+ * subclass calling `recordLoadedIntervalQueryShape`). Cleared by `resetState`.
484
445
  */
485
- get hasNext(): boolean;
446
+ get isInitialized(): boolean;
486
447
  /**
487
- * @deprecated Use `hasMoreHead` instead.
448
+ * True once a page was loaded: by a query, or by `setItems`, including an empty page (e.g. a
449
+ * catch-all list seeded so it never runs its own query). Items that live events ingested into a
450
+ * never-queried list are not a loaded page, although they make `items` defined: a UI deciding
451
+ * whether to run the first query reads this, not `items === undefined`. Unlike `isInitialized`,
452
+ * an empty `setItems` page counts, so connection recovery (which re-runs initialized lists'
453
+ * queries) still skips such a list. Cleared by `resetState`.
488
454
  */
489
- get hasPrev(): boolean;
490
- get hasResults(): boolean;
491
- get isLoading(): boolean;
492
- /** Signals that the paginator has not performed any query so far */
493
- get isInitialized(): boolean;
455
+ get hasLoadedPage(): boolean;
494
456
  get isOfflineSupportEnabled(): boolean;
495
457
  get isCursorPagination(): boolean;
496
458
  get initialState(): PaginatorState<T>;
497
459
  get items(): T[] | undefined;
498
- /**
499
- * The newest loaded window of items, independent of which window is currently *active*
500
- * (`items` follows the active interval, which may point at a jumped-to / searched window). This is
501
- * the head-most loaded interval under the paginator's ordering (anchored or the live-head logical
502
- * interval).
503
- *
504
- * NOTE: this deliberately uses the head-*most loaded* interval rather than requiring the
505
- * `isHead` flag — the query/hydration seed does not reliably mark a freshly loaded latest page
506
- * as `isHead`, so an isHead-only check would miss channel-list channels entirely. The trade-off
507
- * is that after jumping to an older window with the latest window not loaded, this reports that
508
- * older window as "latest" (best effort). Use for "latest"-derived reads: last message, unread
509
- * counting, delivery candidates, channel-list previews.
510
- */
511
- get headItems(): T[];
512
- /**
513
- * The item on the head edge of the head pagination interval (of {@link BasePaginator.headItems}).
514
- * `undefined` when nothing is loaded.
515
- */
516
- get headmostItem(): T | undefined;
517
460
  get cursor(): PaginatorCursor | undefined;
518
461
  get offset(): number | undefined;
519
- /**
520
- * The current resolved configuration.
521
- *
522
- * `Readonly` on purpose: the value is the store's live object, so assigning to a field of it would
523
- * mutate state without notifying anyone. That used to be the only way to change these values, so the
524
- * type is what turns those call sites into compile errors rather than silent non-reactive writes —
525
- * use {@link updateConfig}.
526
- */
527
462
  get config(): Readonly<BasePaginatorConfig<T, Q>>;
528
463
  /**
529
- * Merges a partial configuration into the resolved config and notifies subscribers, unless every
530
- * field in the patch already holds an equal value.
464
+ * Merges a partial configuration into the resolved config. The next `initializeConfig` discards
465
+ * it.
466
+ *
467
+ * @param config - The fields to merge.
531
468
  */
532
469
  updateConfig(config: Partial<BasePaginatorConfig<T, Q>>): void;
533
470
  get pageSize(): number;
534
471
  set pageSize(size: number);
535
472
  set initialCursor(cursor: PaginatorCursor);
536
473
  set initialOffset(offset: number);
537
- /** Single point of truth: always use the effective comparator */
474
+ /** The boost-aware comparator to use for ordering items. */
538
475
  get effectiveComparator(): (a: T, b: T) => number;
539
476
  protected get itemOrderComparator(): (a: T, b: T) => number;
540
477
  get intervalComparator(): (a: AnyInterval, b: AnyInterval) => number;
@@ -542,154 +479,233 @@ export declare abstract class BasePaginator<T, Q> {
542
479
  protected get itemIntervals(): AnyInterval[];
543
480
  protected get liveHeadLogical(): LogicalInterval | undefined;
544
481
  protected get liveTailLogical(): LogicalInterval | undefined;
545
- /**
546
- * The current contents of the live logical-head interval (items ingested out of pagination order).
547
- * Reads the same value published to {@link BasePaginator.intervalViews}.`logicalHead`.
548
- */
482
+ /** `intervalViews.logicalHead`: out-of-order items above the loaded interval. */
549
483
  get logicalHeadItems(): T[];
484
+ /** `intervalViews.logicalTail`: out-of-order items below the loaded interval. */
485
+ get logicalTailItems(): T[];
550
486
  /**
551
- * The current contents of the live logical-tail interval (out-of-order items below the loaded
552
- * window). Reads the same value published to {@link BasePaginator.intervalViews}.`logicalTail`.
487
+ * The anchored head interval: the loaded interval that reaches the head of the dataset (`isHead`).
488
+ * `undefined` while that interval is not loaded, for example when only an interval reached by a
489
+ * jump is.
553
490
  */
554
- get logicalTailItems(): T[];
491
+ protected get anchoredHeadInterval(): Interval | undefined;
555
492
  /**
556
- * The current contents of the anchored head interval (the loaded page bounded at the dataset head,
557
- * `isHead`). Reads the same value published to {@link BasePaginator.intervalViews}.`anchoredHead`.
493
+ * The items of the anchored head interval; empty while it is not loaded (an interval reached by a
494
+ * jump never counts). Reactive counterpart: `intervalViews.anchoredHead`.
558
495
  */
559
496
  get anchoredHeadItems(): T[];
560
497
  /**
561
- * Commit an interval into storage. Single choke point for adding/updating an interval, so it also
562
- * republishes the matching {@link intervalViews} field when the committed interval is a tracked one
563
- * (logical head / logical tail / anchored head). Use this instead of writing `_itemIntervals`
564
- * directly — bulk re-sorting (which does not change any interval's membership) goes through
565
- * {@link setIntervals}.
498
+ * The item at the head edge of the anchored head interval (see {@link anchoredHeadItems}).
499
+ * `undefined` while that interval is not loaded, including once an interval is known to lack items
500
+ * toward the head (see {@link unmarkHead}). A loaded interval always holds an item, so this also
501
+ * tells whether it is loaded.
502
+ */
503
+ get anchoredHeadItem(): T | undefined;
504
+ /**
505
+ * Commits an interval to storage and republishes its {@link intervalViews} field when tracked.
506
+ * Use it instead of writing `_itemIntervals` (bulk re-sorting goes through {@link setIntervals}).
566
507
  */
567
508
  protected commitInterval(interval: AnyInterval): void;
568
- /** Drop an interval from storage, republishing the matching {@link intervalViews} field if tracked. */
509
+ /** Drops an interval from storage, republishing its {@link intervalViews} field if tracked. */
569
510
  protected dropInterval(id: string): void;
570
511
  /**
571
- * Republish the {@link intervalViews} field backed by the given interval — called from
572
- * {@link commitInterval} / {@link dropInterval} (i.e. when that interval ingests or removes an item).
573
- * A write to an untracked interval touches nothing here. (The anchored head is also published
574
- * directly via {@link publishAsAnchoredHead} from the reconciliation points that flip `isHead` —
575
- * see {@link postQueryReconcile}.)
512
+ * Republishes the {@link intervalViews} field backed by the interval (untracked ones change
513
+ * nothing). Placing a page also publishes the anchored head when `isHead` flips (see
514
+ * {@link publishAsAnchoredHead}).
576
515
  */
577
516
  private publishIntervalViewFor;
578
- /**
579
- * Publish `interval` as the anchored head — the loaded page bounded at the dataset head (`isHead`),
580
- * or `undefined` to clear it (the head page was removed or a page stopped being the head). Callers
581
- * pass the interval they already have, so this does not re-scan storage for the head. Its content
582
- * changes via ingest/remove (routed through {@link commitInterval}/{@link dropInterval}) and its
583
- * identity changes when a page's `isHead` flag flips during query reconciliation — both call here.
584
- */
517
+ /** Publishes `interval` as the anchored head, or `undefined` to clear it. */
585
518
  protected publishAsAnchoredHead(interval: AnyInterval | undefined): void;
586
519
  /**
587
- * Keep `anchoredHead` in sync after a page's `isHead` flag was (re)computed during query
588
- * reconciliation, given its value `wasHead` beforehand. Acts only on an actual transition:
589
- * - became the head page → publish it as the anchored head;
590
- * - stopped being the head page → clear the anchored head;
591
- * - unchanged → nothing (a content change, if any, was already published when the interval was
592
- * committed — see {@link commitInterval}).
520
+ * Keeps `anchoredHead` in sync after `isHead` was recomputed while a page was placed (`wasHead`
521
+ * is the previous value): publishes the page on becoming the head, clears it on losing that.
593
522
  */
594
523
  protected syncAnchoredHeadAfterHeadFlip(interval: Interval, wasHead: boolean): void;
524
+ /**
525
+ * Clears the head mark of `interval`: it no longer reaches the head of the dataset, which holds
526
+ * more items toward the head. It stops being the anchored head ({@link anchoredHeadItem} is then
527
+ * `undefined`) and can load toward the head, which the paginator state reflects when it is the
528
+ * active interval.
529
+ */
530
+ protected unmarkHead(interval: Interval): void;
531
+ /** {@link unmarkHead} without touching the anchored head view. */
532
+ private clearHeadMark;
533
+ /**
534
+ * Makes `interval`, marked as the head and proven to reach it, the only head: two separate
535
+ * intervals cannot both reach it. Other heads lose the mark and can load toward the head, up to
536
+ * `interval`, except one reaching further headward, which contradicts the proof: it keeps the
537
+ * mark and is published as the anchored head (see {@link anchoredHeadInterval}).
538
+ */
539
+ protected makeOnlyHead(interval: Interval): void;
540
+ /** The ids of the anchored intervals marked as reaching the head of the dataset. */
541
+ private getHeadIntervalIds;
542
+ /**
543
+ * Whether `interval` reaches the head because a headward page joined it to the head interval:
544
+ * it is, or merged, one of `headIntervalIds` (the intervals marked as the head before the page
545
+ * was placed). Only where cursors are derived from the interval (`config.deriveCursor`): a
546
+ * cursor a response returned stays as sent.
547
+ */
548
+ private inheritsHeadMark;
549
+ /** Whether `a`'s head edge (see {@link getServerKnownEdges}) is further headward than `b`'s. */
550
+ private reachesFurtherHeadwardThan;
595
551
  private intervalItemsOrEmpty;
596
552
  /**
597
- * Empty every {@link intervalViews} field. Used by reset paths that clear intervals in bulk (via
598
- * {@link setIntervals}), which bypasses the per-interval {@link commitInterval}/{@link dropInterval}
599
- * publishing. No-ops when the views are already empty so a reset does not emit needlessly.
553
+ * Drops every loaded interval and item without publishing `state`, so the next ingest starts from
554
+ * empty storage while `state.items` keeps showing the previous interval until the caller
555
+ * publishes.
600
556
  */
557
+ protected clearItemStorage(): void;
558
+ /** Empties every {@link intervalViews} field, bypassing `commitInterval`/`dropInterval`. */
601
559
  protected clearIntervalViews(): void;
602
- abstract query(params: PaginationQueryParams<Q>): Promise<PaginationQueryReturnValue<T>>;
603
- abstract filterQueryResults(items: T[]): T[];
604
560
  /**
605
- * Subclasses must return the query shape.
561
+ * The fetching step of the query pipeline (see {@link executeQuery}): requests the page that
562
+ * `params.queryShape` describes (`executeQuery` always prepares it, and a retry sends it again)
563
+ * and returns the response. What the response carries besides the page is applied in the last
564
+ * step ({@link applyQueryResponseRest}).
565
+ */
566
+ protected abstract fetchQueryResponse(params: PaginationQueryParams<Q>): Promise<R>;
567
+ /**
568
+ * The extracting step of the query pipeline (see {@link executeQuery}): the page in a response,
569
+ * its items and cursors. A paginator whose response is the page returns it as it is.
570
+ */
571
+ protected abstract extractQueryPage(response: R, params: PaginationQueryParams<Q>): PaginationQueryReturnValue<T>;
572
+ /**
573
+ * The last step of the query pipeline (see {@link executeQuery}): applies what a response holds
574
+ * besides its page, once the page is placed with `placeParams`. Runs once for every response that
575
+ * arrived, also when extracting or placing its page failed. Does nothing by default.
606
576
  */
607
- protected getNextQueryShape(_params?: Pick<PaginationQueryParams<Q>, 'direction'>): Q;
577
+ protected applyQueryResponseRest(_response: R, _placeParams: QueryPagePlacement<Q>): void;
608
578
  /**
609
- * Filters an item is matched against locally (`matchesFilter`) — NOT the filters sent to the server.
610
- * A paginator whose backend query is filtered has to build the request filters separately (see
611
- * `ChannelPaginator.buildQueryFilters`), because the two can differ: the backend may resolve a
612
- * server-side stored filter of its own, and some paginators filter locally without sending anything.
579
+ * Filters a fetched page's items before the page is placed, synchronously, as placing runs in a
580
+ * single tick. Keeps every item by default; a paginator that drops some overrides it.
581
+ */
582
+ filterQueryResults(items: T[]): T[];
583
+ /** Subclasses must override it and return the query shape. */
584
+ protected getNextQueryShape(_params?: Pick<PaginationQueryParams<Q>, 'direction'> & {
585
+ pageSize?: number;
586
+ }): Q;
587
+ /**
588
+ * Filters that `matchesFilter` applies locally, not the ones sent to the server; a subclass whose
589
+ * backend query is filtered builds those separately. `null`: no filters.
613
590
  */
614
591
  protected buildMatchFilters(): object | null;
615
592
  matchesFilter(item: T): boolean;
616
593
  setFilterResolvers(resolvers: FieldToDataResolver<T>[]): void;
594
+ /**
595
+ * Adds rules ahead of the existing ones. The first rule that matches a field resolves it, so an
596
+ * added rule takes precedence over a built-in one, including a catch-all.
597
+ */
617
598
  addFilterResolvers(resolvers: FieldToDataResolver<T>[]): void;
618
599
  getItemId(item: T): string;
619
600
  getItem(id: string | undefined): T | undefined;
620
601
  /**
621
- * Whether this paginator's live `state.items` publishes are currently throttled — `stateThrottleMs`
622
- * is set, throttling is not globally disabled (tests), and item order is not locked (a locked-order
623
- * list must emit the caller-computed, order-preserved array, not a re-projection). When false, every
624
- * live mutation publishes immediately, exactly as before this feature.
602
+ * Whether live `state.items` publishes are throttled: `stateThrottleMs` is set, throttling is not
603
+ * disabled (tests) and item order is not locked (its emit is not a re-projection).
625
604
  */
626
605
  protected get isStateThrottled(): boolean;
627
- /** True while a coalescing {@link batch} scope is suspending this paginator's own window publishes. */
628
- protected get isWindowPublishSuspended(): boolean;
629
- /** Re-project the active window from its (live, source-of-truth) interval. `undefined` when inactive. */
630
- private projectActiveWindow;
606
+ protected get isActiveIntervalPublishSuspended(): boolean;
607
+ /** Re-projects the items of the active interval; `undefined` when none is active. */
608
+ private projectActiveInterval;
609
+ /**
610
+ * Publishes the active interval to `state`, re-projected at call time. Clears the shown interval
611
+ * when the active interval is gone.
612
+ */
613
+ private flushActiveIntervalPublish;
631
614
  /**
632
- * Publish the active window to `state`, re-projecting it fresh from the active interval at call time
633
- * (the throttle boundary / flush). Because the intervals are mutated synchronously by every live op,
634
- * this always reflects the latest settled state, so intermediate values within a window coalesce
635
- * away. Clears the visible window when the active interval is gone (e.g. the last item was removed).
615
+ * Publishes the active interval's items with `state` and any pending prune changes, at once.
616
+ * Inside a coalescing {@link batch}, call it after the batch's last interval change: the batch
617
+ * then publishes nothing more.
636
618
  */
637
- private flushWindowPublish;
619
+ protected publishActiveInterval(state?: Partial<PaginatorState<T>>): void;
638
620
  /**
639
- * Schedule a throttled active-window publish (leading + trailing). Called from live mutations
640
- * (ingest / content-change / remove) INSTEAD of an inline `state.partialNext({ items })` when
641
- * {@link isStateThrottled}. Safe to call many times within one op — they coalesce to a single emit.
621
+ * Schedules a throttled (leading and trailing) active-interval publish. Live mutations call it
622
+ * instead of publishing inline when {@link isStateThrottled}. Repeated calls coalesce.
642
623
  */
643
- protected scheduleWindowPublish(): void;
624
+ protected scheduleActiveIntervalPublish(): void;
644
625
  /**
645
- * Flush any pending throttled window + interval-view publishes immediately. No-op when nothing
646
- * is pending or throttling is off.
626
+ * Runs `fn` with active-interval publishes suspended and emits once on exit (a replace is
627
+ * remove-then-insert, which would emit twice), unless the interval was published after its last
628
+ * change. Only the outermost scope emits. `exit: 'auto'` rides the throttle when there is one,
629
+ * `'sync'` always flushes ({@link batch}). Skipped for `lockItemOrder` lists, whose emit
630
+ * republishes the last array and must not be re-derived from the interval.
647
631
  */
632
+ protected withSingleActiveIntervalPublish(fn: () => void, { exit }?: {
633
+ exit?: 'auto' | 'sync';
634
+ }): void;
635
+ /** Immediately flushes the pending throttled active-interval and interval-view publishes. */
648
636
  protected flushPendingPublishes(): void;
649
637
  /**
650
- * {@link _viewPublishThrottle} boundary: apply every interval-view change buffered since the last
651
- * flush, then clear the buffer. Independent of the `state.items` window publish, so a view update
652
- * lands within one throttle interval even when the active window stays quiet (e.g. a reaction on a
653
- * head message while a non-head window is active). No-op when nothing was buffered.
638
+ * Whether pruning is on hold, e.g. while the user reads near the tail edge, where a prune drops
639
+ * items. False: the configured cap always applies.
654
640
  */
655
- private flushIntervalViewPublish;
641
+ protected get isPruningSuspended(): boolean;
642
+ /**
643
+ * Whether the server knows `item`, so its ID is safe as a cursor. Prunes drop and anchor on such
644
+ * items only. Subclasses holding locally-created items narrow it.
645
+ */
646
+ protected isPaginationAnchorable(item: T | undefined): boolean;
647
+ /**
648
+ * The interval cap, or `undefined` when unbounded. Clamped up to `pageSize`: a smaller cap would
649
+ * prune each tailward page as it lands and `onEndReached` would refetch it in a loop.
650
+ */
651
+ protected get effectiveMaxLoadedItems(): number | undefined;
656
652
  /**
657
- * Refresh any tracked {@link intervalViews} field (logical head, logical tail, anchored head) that
658
- * holds one of `changedIds`. A sibling holder writing new content through the shared item store
659
- * swaps the item object those views reference, but only this paginator's own ingest/remove
660
- * ({@link commitInterval}/{@link dropInterval}) republish them — so a reaction/edit made elsewhere
661
- * would otherwise leave stale references in `anchoredHead`/`logicalHead`/`logicalTail` even though
662
- * the active window (`state.items`, see {@link reconcileChangedIds}) was refreshed.
653
+ * Drops the oldest items from `interval` until at most `maxLoadedItems` remain, releasing them
654
+ * from the item index. Returns whether anything was pruned.
663
655
  *
664
- * Called immediately for un-throttled paginators, or from {@link flushIntervalViewPublish} at the
665
- * view-publish throttle boundary when throttled — see {@link reconcileChangedIds}. Handled
666
- * independently of `state.items`. When the anchored head is also the active interval its content is
667
- * projected here as well as into `state.items`; deduping that double projection is a separate,
668
- * deferred perf follow-up.
656
+ * Runs from `ingestItem` on the uncommitted interval copy, so the following `commitInterval` and
657
+ * publish carry it (see {@link _prunedIntervalId}). No-op unless a cap is set, pruning is not
658
+ * suspended ({@link isPruningSuspended}) and the interval is the anchored, active head interval
659
+ * and over the cap. Assumes cursor pagination (`removeItem` is bypassed, so
660
+ * {@link shrinkOffsetAfterRemoval} never runs). Items the server does not know
661
+ * ({@link isPaginationAnchorable}) are skipped, so the interval may sit a few items above the cap.
662
+ */
663
+ protected pruneTailToLimit(interval: AnyInterval): boolean;
664
+ /**
665
+ * The interval's outermost items the server knows about (see {@link isPaginationAnchorable}), at
666
+ * its head and tail; `undefined` where it holds none. Items the server never saw do not count:
667
+ * they cannot continue its pagination as a cursor, nor be reached by a page the server returns.
668
+ */
669
+ protected getServerKnownEdges(interval: AnyInterval): {
670
+ head: T | undefined;
671
+ tail: T | undefined;
672
+ };
673
+ /** Keeps the `items` that are members of `interval`, in order. */
674
+ private retainIntervalMembers;
675
+ /**
676
+ * Returns the `state` pagination fields a prune moved, derived from the committed active interval
677
+ * at call time, and clears the pending prune. Publishes of the active interval spread it in. Only
678
+ * changed fields are returned, so an unchanged `cursor` keeps its identity. Left alone: another
679
+ * interval than the pruned one, `cursor.headward` (a `deriveCursor` verdict survives), and a null
680
+ * tail edge (every item is locally created: `null` would read as exhausted, so the cursor stays).
681
+ */
682
+ private consumePendingPrunePaginationState;
683
+ /** {@link _viewPublishThrottle} boundary: applies the buffered interval-view changes. */
684
+ private flushIntervalViewPublish;
685
+ /**
686
+ * Refreshes the tracked {@link intervalViews} fields holding one of `changedIds`. A sibling
687
+ * holder writing through the shared item store swaps the item objects the views reference, and
688
+ * only this paginator's own ingest/remove republishes them. Immediate unless throttled, then from
689
+ * {@link flushIntervalViewPublish}.
669
690
  */
670
691
  private refreshIntervalViewsForChangedIds;
671
692
  private intervalHoldsAnyChangedId;
672
693
  /**
673
- * Reconcile the projected window + interval views against a set of changed ids: another holder
674
- * swapped the shared item object those views reference. Refreshes any tracked interval view that
675
- * holds a changed id and re-projects (or slot-swaps) the active window — coalesced through the
676
- * publish throttles when throttling is on.
694
+ * Reconciles the active interval and interval views after another holder swapped the shared item
695
+ * objects they reference: refreshes views holding a changed ID and re-projects (or slot-swaps) the
696
+ * active interval, coalesced through the publish throttles when throttling is on.
677
697
  */
678
698
  protected reconcileChangedIds(changedIds: ReadonlySet<string>): void;
679
699
  protected clearExpiredBoosts(now?: number): void;
680
- /**
681
- * Applied by the effectiveComparator to take into consideration item boosts when sorting items.
682
- *
683
- * @param a - The first item to compare.
684
- * @param b - The second item to compare.
685
- */
700
+ /** Boosted items first (higher `seq` first), then `itemOrderComparator`. */
686
701
  protected boostComparator: (a: T, b: T) => number;
687
702
  /**
688
- * Increases the item's importance when sorting.
689
- * Boost affects position inside an item interval (if used), but should not redefine interval boundaries.
703
+ * Raises the item's priority in `effectiveComparator`. Affects position inside an interval, not
704
+ * interval boundaries.
690
705
  *
691
- * @param itemId - Id of the item to boost.
692
- * @param opts - Boost options: `ttlMs` / `until` control expiry and `seq` orders concurrent boosts.
706
+ * @param itemId - ID of the item to boost.
707
+ * @param opts - Boost options: `until` (or `ttlMs` from now) sets the expiry and `seq` orders
708
+ * concurrent boosts. Expiry defaults to 15s from now; `seq` defaults to 0.
693
709
  */
694
710
  boost(itemId: string, opts?: {
695
711
  ttlMs?: number;
@@ -705,29 +721,38 @@ export declare abstract class BasePaginator<T, Q> {
705
721
  generateIntervalId(_page: (T | string)[]): string;
706
722
  intervalToItems(interval: Interval | LogicalInterval): T[];
707
723
  makeInterval({ page, isHead, isTail }: MakeIntervalParams<T>): Interval;
708
- protected getCursorFromInterval(interval: Interval): PaginatorCursor;
709
- isActiveInterval(interval: AnyInterval): boolean;
710
724
  /**
711
- * Whether the currently active (viewed) interval is the anchored head. Used to decide if it is
712
- * safe to re-seed an already-loaded paginator with a fresh newest page: only when at the head
713
- * (the newest page overlaps it, so the re-seed reconciles + re-derives cursors in place). When the
714
- * caller has jumped to an older window (active interval is NOT the head), a first-page re-seed
715
- * would force-merge the newest page into that window across the gap - so the re-seed is skipped.
725
+ * The cursor continuing `interval` where it has more items (by default, per its own flags), at
726
+ * its outermost items the server knows about (see {@link getServerKnownEdges}).
716
727
  */
728
+ protected getCursorFromInterval(interval: Interval, { hasMoreHead, hasMoreTail }?: PaginationFlags): PaginatorCursor;
729
+ isActiveInterval(interval: AnyInterval): boolean;
730
+ /** Whether the active (shown) interval is the loaded one reaching the head of the dataset. */
717
731
  get isActiveIntervalAtHead(): boolean;
732
+ /**
733
+ * Claims the active interval for a call that decides it, and returns the claim; a query claims
734
+ * it as `claimsActiveInterval` says (see {@link decidesActiveInterval}). The latest claim wins: a
735
+ * page arriving after a later claim is only stored.
736
+ */
737
+ protected claimActiveInterval(): number;
738
+ /** Whether no claim on the active interval followed `claim` (see {@link claimActiveInterval}). */
739
+ protected isLatestActiveIntervalClaim(claim: number): boolean;
718
740
  setActiveInterval(interval: AnyInterval | undefined, opts?: {
719
741
  updateState?: boolean;
720
742
  }): void;
721
743
  protected getIntervalSortBounds(interval: Interval | LogicalInterval): IntervalSortBounds<T> | null;
722
744
  /**
723
- * Returns pagination head/tail edges of an interval.
724
- *
725
- * IMPORTANT:
726
- * - Edges are derived from the *sort bounds* of the interval (min/max under `sortComparator`).
727
- * - Which bound is treated as the pagination "head" is controlled by `intervalItemIdsAreHeadFirst`.
728
- * - This is a semantic notion of head/tail (where new items are expected to appear),
729
- * not necessarily "min/max under sortComparator".
730
- * New items are always expected to appear at the head of the interval.
745
+ * The items at the head and tail edges of a page given in item order (`sortComparator` order), as
746
+ * {@link getIntervalPaginationEdges} gives them for an interval. Both `undefined` for an empty page.
747
+ */
748
+ protected getPagePaginationEdges(page: T[]): {
749
+ head: T | undefined;
750
+ tail: T | undefined;
751
+ };
752
+ /**
753
+ * Pagination head/tail edges of an interval, taken from its sort bounds.
754
+ * `intervalItemIdsAreHeadFirst` decides which bound is the head: where new items appear, not
755
+ * necessarily the min under `itemOrderComparator`.
731
756
  */
732
757
  protected getIntervalPaginationEdges(interval: Interval | LogicalInterval): IntervalPaginationEdges<T> | null;
733
758
  protected compareIntervalHeadEdges(a: T, b: T): number;
@@ -737,105 +762,79 @@ export declare abstract class BasePaginator<T, Q> {
737
762
  protected getTailIntervalFromSortedIntervals(intervals: AnyInterval[]): AnyInterval | undefined;
738
763
  protected sortIntervals<I extends AnyInterval>(intervals: I[]): I[];
739
764
  protected setIntervals(intervals: AnyInterval[]): void;
765
+ /**
766
+ * The span pages and items are matched against: from the interval's outermost items the server
767
+ * knows about (see {@link isPaginationAnchorable}), or its sort bounds when it holds none. An
768
+ * item the server never saw does not stretch it, as its sort key may come from the client.
769
+ */
770
+ protected getIntervalSpan(interval: AnyInterval): IntervalSortBounds<T> | null;
771
+ /** The head and tail edges of the interval's span (see {@link getIntervalSpan}). */
772
+ private getIntervalSpanEdges;
740
773
  protected intervalsStrictlyOverlap(a: AnyInterval, b: AnyInterval): boolean;
741
774
  /**
742
- * Returns true if intervals A and B should be merged.
743
- *
744
- * 1) Strict overlap (range overlap in `sortComparator` order):
745
- * A.min ≤ B.max AND B.min ≤ A.max
746
- *
747
- * 2) Forced merge (policy: 'auto' only):
748
- * If one interval is marked as `isHead`/`isTail`, treat the other as mergeable
749
- * when it extends beyond that interval's pagination head/tail edge
750
- * (computed via `getIntervalPaginationEdges` + headward/tailward helpers).
751
- *
752
- * In 'strict-overlap-only' policy, only (1) applies.
775
+ * Whether intervals A and B should be merged: they strictly overlap in `itemOrderComparator` order
776
+ * (`A.min <= B.max && B.min <= A.max`) or, under policy 'auto' only, one is marked
777
+ * `isHead`/`isTail` and the other extends beyond its pagination head/tail edge.
753
778
  */
754
779
  protected intervalsOverlap(a: AnyInterval, b: AnyInterval, policy?: IntervalMergePolicy): boolean;
755
780
  /**
756
- * Whether an item belongs to an anchored interval.
781
+ * Whether `item` belongs in `interval`: within its span (see {@link getIntervalSpan}), or beyond
782
+ * the edge of a head or tail interval. An item the server never saw stays in the interval holding
783
+ * it, so updating it does not move it.
757
784
  */
758
785
  protected belongsToInterval(item: T, interval: AnyInterval): boolean;
759
786
  protected mergeTwoAnchoredIntervals(preceding: Interval, following: Interval): Interval;
760
- /**
761
- * Merges anchored intervals. Returns null if there are no intervals to merge.
762
- */
787
+ /** Merges anchored intervals; `null` when there are none. */
763
788
  protected mergeAnchoredIntervals(intervals: Interval[], baseInterval?: Interval): Interval | null;
764
789
  protected locateIntervalIndex(interval: Interval): number;
765
- /**
766
- * Locate item inside a specific interval using the same logic as locateByItem,
767
- * but scoped to interval items.
768
- */
769
- protected locateByItemInInterval({ item, interval, }: {
790
+ protected locateByItemInInterval({ item, interval, plateauScan, }: {
770
791
  item: T;
771
792
  interval: Interval | LogicalInterval;
793
+ /** Walk the interval for an item the binary search missed. Off when it cannot be there. */
794
+ plateauScan?: boolean;
772
795
  }): ItemLocation | null;
773
796
  protected locateIntervalForItem(item: T): AnyInterval | undefined;
774
- /**
775
- * The interval whose `itemIds` lists this id, regardless of where the item now sorts.
776
- */
797
+ /** The interval whose `itemIds` lists this ID, regardless of where the item sorts. */
777
798
  protected findIntervalHoldingItem(item: T): AnyInterval | undefined;
778
799
  protected locateByItemInIntervals(item: T): ItemCoordinates['interval'] | undefined;
779
- /**
780
- * Locates the current position of the item and the index at which the item should be inserted
781
- * according to effectiveComparator.
782
- *
783
- * @param item - The item to locate within the current state.
784
- */
800
+ /** Position of the item in `state.items` and its insertion index under `effectiveComparator`. */
785
801
  protected locateItemInState(item: T): ItemLocation | null;
786
802
  locateByItem: (item: T) => ItemCoordinates;
787
803
  protected removeItemIdFromInterval({ interval, ...itemLocation }: ItemIntervalCoordinates): ItemIntervalCoordinates;
788
- /**
789
- * Inserts an item ID into the interval in the correct sorted position.
790
- * Returns unchanged interval if the correct insertion position could not be determined.
791
- */
804
+ /** Inserts the item ID at its sorted position; no-op when none can be determined. */
792
805
  protected insertItemIdIntoInterval<I extends Interval | LogicalInterval>(interval: I, item: T): I;
793
806
  /**
794
- * Re-evaluates what the logical (live head / tail) intervals still hold against a freshly ingested
795
- * page, returning the resulting anchored interval. Live updates park items there before any page
796
- * exists — a channel archived while the archived list is untouched lands in the live head — and
797
- * once a page covers such an item, leaving it gives the same id two homes, which is what renders
798
- * as a duplicated row. The merge in `ingestPage` only folds logical intervals in when its
799
- * `isHead`/overlap heuristics fire; this pass is unconditional and idempotent.
807
+ * Re-evaluates what the logical (live head/tail) intervals hold against a freshly ingested page
808
+ * and returns the resulting anchored interval. Live updates park items there before any page
809
+ * exists; once a page covers one, leaving it gives the same ID two homes (a duplicated row).
810
+ * Unlike the `ingestPage` merge, whose heuristics fire only sometimes, this pass is unconditional
811
+ * and idempotent.
800
812
  */
801
813
  protected reconcileLogicalIntervalsAgainst(anchored: Interval): Interval;
802
814
  /**
803
- * Moves items the loaded window proves are parked on the wrong side: an item sitting in the live
804
- * head that actually sorts past the tail edge of everything loaded belongs to the live tail (the
805
- * unloaded region on that side), and vice versa. Leaving it claims the wrong end of the list —
806
- * the archived channel would render above a page it sorts below.
807
- *
808
- * Compared against the outermost anchored interval, not the page just ingested: an item that
809
- * lands between two loaded pages is not "beyond" either side, it is a gap item, and those stay
810
- * where they are (`ingestPage` turns them into their own island once the merge reaches the edge).
815
+ * Moves items the loaded interval proves are parked on the wrong side: an item in the live head
816
+ * that sorts past the tail edge of everything loaded belongs to the live tail, and vice versa.
817
+ * Compared against the outermost anchored interval, not the page just ingested: an item between
818
+ * two loaded pages is a gap item and stays.
811
819
  */
812
820
  protected moveMisfiledItemsToOppositeSide(logical: LogicalInterval, ingested: Interval): void;
813
- /**
814
- * Splits a logical interval by checking each item individually.
815
- * Items overlapping anchoredInterval are merged into it.
816
- * Others stay in a retained logical interval.
817
- */
821
+ /** Merges the logical interval's items that belong to `anchored` into it; the rest stay. */
818
822
  protected mergeItemsFromLogicalInterval(logical: LogicalInterval, anchored: Interval): {
819
823
  mergedAnchored: Interval;
820
824
  remainingLogical: LogicalInterval | null;
821
825
  };
822
826
  /**
823
- * Merges all intervals (anchored + logical head/tail).
824
- * Returns:
825
- * - merged anchored interval (or null if none merged)
826
- * - possibly reduced logical head / tail intervals
827
+ * Merges the anchored intervals and folds in the logical head/tail items that belong to the
828
+ * result. Returns the merged interval (`null` if none) and the possibly reduced logical
829
+ * intervals.
827
830
  */
828
831
  protected mergeIntervals(intervals: AnyInterval[], baseInterval?: Interval): MergeIntervalsResult;
829
- /**
830
- * Ingests the whole page into intervals and returns the resulting anchored interval.
831
- */
832
+ /** Ingests the page into intervals; returns the resulting anchored interval (`null` if empty). */
832
833
  ingestPage({ page, policy, isHead, isTail, targetIntervalId, setActive, }: {
833
834
  page: T[];
834
835
  /**
835
- * Describes the policy for merging intervals.
836
- * - 'auto' (default): Merge intervals if they overlap.
837
- * - 'strict-overlap-only': Merge intervals only if they strictly overlap. Useful for jumping to a specific message.
838
- * - This is useful for jumping to a specific message.
836
+ * 'auto' merges overlapping intervals. 'strict-overlap-only' merges only strictly overlapping
837
+ * ones, e.g. when jumping to a specific item. Defaults to 'auto'.
839
838
  */
840
839
  policy?: IntervalMergePolicy;
841
840
  isHead?: boolean;
@@ -844,30 +843,18 @@ export declare abstract class BasePaginator<T, Q> {
844
843
  setActive?: boolean;
845
844
  }): Interval | null;
846
845
  /**
847
- * Ingests a single item on live update:
848
- * - update the ItemIndex
849
- * - find an anchored interval whose sort bounds contain the item
850
- * - insert the item into that interval using locate+plateau logic
851
- * - if this is the active interval, re-emit state.items from interval
846
+ * Ingests a single live-updated item: updates the item index, inserts the item into the anchored
847
+ * interval whose sort bounds contain it, and re-emits `state.items` when that interval is active.
852
848
  */
853
849
  ingestItem(ingestedItem: T): boolean;
850
+ private applyItemIngestion;
854
851
  /**
855
- * Run `fn` as one batched mutation over this paginator's items, collapsing the redundant emits a
856
- * naive per-item loop would produce:
857
- *
858
- * - **Shared-store fan-out** (always, via the `_itemIndex.batch` wrapper): per-item store
859
- * notifications fold into a single flush, so sibling holders of the same ids (e.g. a thread /
860
- * pinned paginator sharing the entity) re-project once, not once per item. Inert for single-home
861
- * paginators (channels, reminders, user groups) whose index is over a private store with no
862
- * sibling subscribers — there it is a plain passthrough.
863
- * - **This paginator's own active window** (`coalesce: true`): every `ingestItem` / `removeItem`
864
- * inside `fn` records that the window changed instead of publishing it, then `batch` emits the
865
- * settled window exactly once on exit via {@link flushWindowPublish}. This is deterministic and
866
- * independent of state throttling — unlike leaving it off, where an un-throttled paginator emits
867
- * once per item and a throttled one merely coalesces within its 500ms window. Use it for one-shot
868
- * operations (reconciliation, reload re-ingest) that must settle in a single update. Omit it in WS
869
- * event handlers, where per-event publishes should ride the throttle so successive events coalesce
870
- * across its trailing edge rather than each forcing a synchronous emit.
852
+ * Runs `fn` as one batched mutation: per-item store notifications fold into one flush, so sibling
853
+ * holders of the same IDs re-project once. With `coalesce: true` the active interval also emits
854
+ * exactly once on exit ({@link flushActiveIntervalPublish}), independent of throttling: for
855
+ * one-shot operations. Omit it in WS event handlers so events ride the throttle. If `fn`
856
+ * publishes the interval after its last change (see {@link publishActiveInterval}), `batch`
857
+ * publishes nothing.
871
858
  */
872
859
  batch(fn: () => void, { coalesce }?: {
873
860
  coalesce?: boolean;
@@ -875,17 +862,13 @@ export declare abstract class BasePaginator<T, Q> {
875
862
  protected removeItemAtCoordinates(coords: ItemCoordinates): ItemCoordinates;
876
863
  /**
877
864
  * Keeps `offset` addressing the same position in the *server's* result set after an item left the
878
- * loaded window.
865
+ * loaded interval.
879
866
  */
880
867
  protected shrinkOffsetAfterRemoval(coordinates?: ItemCoordinates): void;
881
868
  /**
882
- * Meaning of location values
883
- * - currentIndex === -1 could not be found
884
- * - insertionIndex === -1 insertion index was no intended to be determined
885
- *
886
- * If we are removing the last item from the currently active interval, we do not search for a new active interval.
887
- * If the number of items approach 0 in an active interval, we expect from the UI to load new pages to populate
888
- * the active interval.
869
+ * In the returned coordinates `currentIndex === -1` means not found and `insertionIndex === -1`
870
+ * that none was determined. Removing the last item of the active interval does not activate
871
+ * another one: the UI is expected to load pages to repopulate it.
889
872
  */
890
873
  removeItem({ id, item: inputItem }: {
891
874
  id?: string;
@@ -893,59 +876,35 @@ export declare abstract class BasePaginator<T, Q> {
893
876
  }): ItemCoordinates;
894
877
  /** Sets the items in the state, ingesting them so the active interval is updated. */
895
878
  setItems({ valueOrFactory, cursor, isFirstPage, isLastPage, }: SetPaginatorItemsParams<T>): void;
896
- setDebounceOptions: ({ debounceMs }: PaginatorDebounceOptions) => void;
897
879
  /**
898
- * Rebuilds the state-publish throttles for a new interval, or drops them when the interval is unset.
899
- *
900
- * This exists because `stateThrottleMs` is read *once*: the throttles capture the interval in their
901
- * closures, so assigning `config.stateThrottleMs` afterwards does nothing at all — an unthrottled
902
- * paginator never gains a throttle, and a throttled one keeps its original interval. Anything
903
- * changing the value at runtime (declarative configuration registered after construction, or
904
- * `client.config.reset()`) has to come through here.
905
- *
906
- * Pending publishes are flushed first, so a swap cannot swallow a trailing-edge emit that was
907
- * already scheduled.
880
+ * Records the query shape of the loaded interval so the next pagination continues it. Data that
881
+ * arrives without the paginator's own query (`setItems`, a page from a query it did not run, a
882
+ * subclass reconciling a loaded interval) would otherwise make the next query a first page that
883
+ * publishes `items: undefined` first, and an empty response then loses the interval. Needs items:
884
+ * an empty interval has no shape to continue from.
908
885
  */
886
+ protected recordLoadedIntervalQueryShape(): void;
887
+ setDebounceOptions: ({ debounceMs }: PaginatorDebounceOptions) => void;
888
+ /** Changes `stateThrottleMs` at runtime. The config controller rebuilds the throttles. */
909
889
  setStateThrottleOptions: ({ stateThrottleMs }: {
910
890
  stateThrottleMs?: number;
911
891
  }) => void;
912
- /** Rebuilds the state-publish throttles for a new interval, or drops them when it is unset. */
892
+ /**
893
+ * Rebuilds the state-publish throttles for a new interval, or drops them when it is unset.
894
+ * Pending publishes are flushed first so a swap cannot swallow a scheduled trailing-edge emit.
895
+ */
913
896
  private rebuildStatePublishThrottles;
914
897
  /**
915
- * Re-derives this paginator's configuration from its real inputs: package defaults, the options it
916
- * was constructed with, and the declarative slice passed in.
917
- *
918
- * Called by the constructor and by `client.config.reset()` (through the owning `Channel` / `Thread`),
919
- * so the two share one code path and cannot drift. Both read-once fields are routed through their
920
- * rebuild setters, because assigning them would be silently discarded.
921
- *
922
- * Structural wiring is untouched here because it never reaches `config` in the first place:
923
- * `itemIndex` and `createItemIndex` are destructured out of the constructor's options and resolved
924
- * once into {@link _itemIndex}, so there is nothing in the derived config for a re-derivation to drop.
925
- *
926
- * Subclass behaviour overrides are folded in through {@link getBehaviourOverrides} rather than written
927
- * afterwards, so one re-derivation is one `configState` publish carrying a complete config. It used to
928
- * be a second write from an `initializeConfig` override, and the claim that both writes carried a
929
- * complete config was wrong: the base derivation knows nothing of the overlay, so it published the
930
- * config with `doRequest`, `deriveCursor` and `itemOrderComparator` **stripped**, and the subclass then
931
- * put them back. A `PinnedMessagePaginator` re-derivation emitted three notifications, of which the
932
- * first had no request function at all — a subscriber that paginated during that synchronous window
933
- * would have found none.
898
+ * Rebuilds the configuration from defaults, options and the declarative slice, dropping earlier
899
+ * `updateConfig` changes.
934
900
  *
935
- * Applied last, so the overlay still wins over constructor options exactly as the second write did.
901
+ * @param declarativeConfig - The declarative slice. Leave it out to rebuild without one.
936
902
  */
937
903
  initializeConfig(declarativeConfig?: DeclarativePaginatorConfig): void;
938
904
  /**
939
- * Behaviour a subclass installs that no set of options can express — a comparator or `deriveCursor`
940
- * closed over `this`, a `doRequest` bound to a particular endpoint. Empty on the base paginator.
941
- *
942
- * Folded into the single derivation in {@link initializeConfig}, which is why an override must return
943
- * **stable references**: rebuilding the closures on each call makes every derived config differ from
944
- * the last, defeating the guard above and republishing on every unrelated re-derivation. Memoize them
945
- * — their inputs are fixed at construction.
946
- *
947
- * Called only after construction. The base constructor builds `configState` directly rather than
948
- * through `initializeConfig`, so an override is never invoked before its own fields are initialized.
905
+ * Behaviour a subclass installs that options cannot express (a comparator, `deriveCursor` or
906
+ * `doRequest` closed over `this`). Applied last in `initializeConfig`. Must return stable
907
+ * references (memoize them), or every derivation republishes. Called only after construction.
949
908
  */
950
909
  protected getBehaviourOverrides(): Partial<BasePaginatorConfig<T, Q>>;
951
910
  protected shouldResetStateBeforeQuery(prevQueryShape: unknown | undefined, nextQueryShape: unknown | undefined): boolean;
@@ -957,59 +916,154 @@ export declare abstract class BasePaginator<T, Q> {
957
916
  } & Pick<PaginationQueryParams<Q>, "reset">) => boolean;
958
917
  protected getStateBeforeFirstQuery(): PaginatorState<T>;
959
918
  isJumpQueryShape(_queryShape: Q): boolean;
919
+ /**
920
+ * Whether a first page queried with this shape is the dataset's head page. True unless the shape
921
+ * starts the page elsewhere, such as at a cursor.
922
+ */
923
+ protected isHeadPageQueryShape(_queryShape: Q | undefined): boolean;
924
+ /**
925
+ * Whether a fetched page reaches the head of the dataset, whatever query fetched it — for example a
926
+ * page around an item that turns out to include the headmost one. Consulted when the query result
927
+ * does not say (a `null` {@link PaginationQueryReturnValue.headward} does), with the page sorted in
928
+ * item order, before it is ingested.
929
+ *
930
+ * - `true`: the page reaches the head; the interval it lands in is marked as the head.
931
+ * - `false`: the page does not reach the head.
932
+ * - `undefined` (the default): not known.
933
+ *
934
+ * Only `true` acts. On `false` or `undefined` the query shape and the cursor derivation decide, so a
935
+ * interval they mark as the head stays marked — for example a newest page that a live item joins.
936
+ */
937
+ protected pageReachesHead(_page: T[], _queryShape: Q | undefined): boolean | undefined;
938
+ /** The page size a query's results are measured against when deriving the head/tail flags. */
939
+ protected getRequestedPageSize(_queryShape: Q | undefined): number;
960
940
  protected getStateAfterQuery(stateUpdate: Partial<PaginatorState<T>>, _isFirstPage: boolean): PaginatorState<T>;
961
941
  preloadFirstPageFromOfflineDb: (_params: PaginationQueryParams<Q>) => Promise<T[] | undefined> | T[] | undefined;
962
942
  populateOfflineDbAfterQuery: (_params: {
963
943
  items: T[] | undefined;
964
944
  queryShape: Q | undefined;
965
945
  }) => Promise<T[] | undefined> | T[] | undefined;
966
- protected runQueryRetryable(params?: PaginationQueryParams<Q>): Promise<PaginationQueryReturnValue<T> | null>;
967
946
  /**
968
- * Falsy return value means query was not successful.
947
+ * {@link fetchQueryResponse} with the paginator's retries. Once every attempt failed, the last
948
+ * error is recorded as `lastQueryError` (unless offline support is on and items are loaded), and
949
+ * thrown with `throwErrors` set, after ending the query; otherwise it returns `null`, for the
950
+ * caller to end the query.
951
+ */
952
+ protected fetchQueryResponseWithRetries(params?: PaginationQueryParams<Q>): Promise<R | null>;
953
+ /**
954
+ * Runs one query through the query pipeline, step by step:
955
+ *
956
+ * 1. {@link prepareQuery}: the query shape, read from the paginator state, and the loading flag.
957
+ * A first page of a paginator not initialized yet shows what the offline database holds,
958
+ * before the request is sent.
959
+ * 2. {@link fetchQueryResponse}, retried as configured: the response.
960
+ * 3. {@link extractQueryPage}: the page in the response.
961
+ * 4. {@link placeQueryPage}: the page placed (shown unless only stored) and the query ended;
962
+ * when fetching, extracting or placing failed, only the query ended.
963
+ * 5. {@link applyQueryResponseRest}: the response's data besides its page, once that is placed.
964
+ *
965
+ * A failed fetch skips the steps after it; any other failed step skips none. Either is recorded
966
+ * as `lastQueryError` (a failed fetch not while offline support is on and items are loaded), and
967
+ * rejects the call only with `throwErrors` set.
968
+ *
969
+ * Resolves to `undefined` when the query cannot run now (see {@link canExecuteQuery}), and to
970
+ * what the placing step returned otherwise, whose `targetInterval` is `null` when no page was
971
+ * placed, with `isSuperseded`.
969
972
  *
970
973
  * @param params - Query parameters.
974
+ * @param params.claimsActiveInterval - Whether the query claims the active interval.
971
975
  * @param params.direction - Direction to paginate in (headward or tailward).
972
- * @param params.keepPreviousItems - Keep already-loaded items instead of clearing them on a first-page query.
976
+ * @param params.keepPreviousItems - Keep already-loaded items instead of clearing them on a
977
+ * first-page query.
973
978
  * @param params.queryShape - Explicit query shape overriding the one derived from current state.
974
- * @param params.reset - Whether to reset the loaded state before querying.
975
- * @param params.retryCount - Number of remaining retry attempts on failure.
976
- * @param params.silent - Suppress loading/state updates for this query.
977
- * @param params.updateState - Whether to write the query results back to state.
979
+ * Its page starts a separate interval (see `QueryPagePlacement.startsSeparateInterval`).
980
+ * @param params.requestOptions - Request options outside the query shape.
981
+ * @param params.reset - 'yes' forces a first page, 'no' continues, else the query shape decides.
982
+ * @param params.retryCount - Number of retries after a failure.
983
+ * @param params.silent - Skip the `isLoading: true` publish of a non-first-page or
984
+ * `keepPreviousItems` query.
985
+ * @param params.updateState - Whether the page's interval becomes the active one.
986
+ */
987
+ executeQuery(params?: PaginationQueryParams<Q>): Promise<ExecuteQueryReturnValue<T> | void>;
988
+ /** The steps after {@link prepareQuery} of the query pipeline (see {@link executeQuery}). */
989
+ private runPreparedQuery;
990
+ /**
991
+ * Ends a query whose step after the fetch failed: records the error as `lastQueryError` and
992
+ * throws it with `throwErrors` set (see {@link executeQuery}). Otherwise returns what the query
993
+ * placed with the error in its state, so a caller committing that state keeps the error.
994
+ */
995
+ private reportQueryError;
996
+ /**
997
+ * Whether a query claims the active interval by default (see
998
+ * `PaginationQueryParams.claimsActiveInterval`, which overrides it):
999
+ * - a reload (`reset: 'yes'`);
1000
+ * - a query at a shape the caller gave, unless `updateState` is `false`.
1001
+ */
1002
+ private decidesActiveInterval;
1003
+ /**
1004
+ * The preparing step of the query pipeline (see {@link executeQuery}): resets the state when
1005
+ * asked, builds the query shape from the paginator state and publishes the loading flag. A first
1006
+ * page of a paginator not initialized yet also starts loading what the offline database holds,
1007
+ * returned as `offlinePreloadPromise`. `undefined` when the query cannot run now (see
1008
+ * {@link canExecuteQuery}).
1009
+ */
1010
+ private prepareQuery;
1011
+ /**
1012
+ * The placing step of the query pipeline (see {@link executeQuery}): places the page (see
1013
+ * {@link placePage}), shown unless only stored (see {@link isPageOnlyStored}), and ends the
1014
+ * query. Without a page (`results: null`), it only ends the query.
1015
+ */
1016
+ placeQueryPage(params: PlaceQueryPageParams<T, Q>): ExecuteQueryReturnValue<T>;
1017
+ /**
1018
+ * Whether the page is only stored, leaving the active interval as it is, rather than shown:
1019
+ * - the interval it continues is no longer active (see {@link continuedIntervalIsInactive});
1020
+ * - a later claim on the active interval was made (see {@link claimIsSuperseded}).
1021
+ */
1022
+ private isPageOnlyStored;
1023
+ /**
1024
+ * Whether the interval the page continues stopped being active while the request ran, leaving
1025
+ * the page with no known place relative to the active interval.
1026
+ */
1027
+ private continuedIntervalIsInactive;
1028
+ /** Whether a claim on the active interval followed the query's own (`activeIntervalClaim`). */
1029
+ private claimIsSuperseded;
1030
+ /**
1031
+ * Places a page in the paginator's intervals — in the interval it continues, or in an interval of
1032
+ * its own merged with the intervals it overlaps — and derives the cursors and the more-pages
1033
+ * flags. With `updateState` (the default), its interval becomes the shown one and the state is
1034
+ * published. Without it, the page is only stored, and published only if it landed in the active
1035
+ * interval, so the shown items never go stale. A page proven to reach the head of the dataset
1036
+ * makes its interval the only head (see {@link makeOnlyHead}). Where cursors are derived from the
1037
+ * interval (`config.deriveCursor`), an interval a headward page joins to the head interval
1038
+ * reaches the head, whatever the page says (see {@link inheritsHeadMark}).
1039
+ *
1040
+ * `endsQuery` says the page comes from the paginator's own query, which placing it ends: the
1041
+ * loading flag goes off, the last query error is cleared, and a first page goes to the offline
1042
+ * database. A page from a query the paginator did not run is placed without any of that, as one
1043
+ * of the paginator's own queries may still be running.
1044
+ */
1045
+ protected placePage({ startsSeparateInterval, direction, isFirstPage, keepPreviousItems, queryShape, requestedPageSize, results, updateState, }: QueryPagePlacement<Q> & {
1046
+ results: PaginationQueryReturnValue<T>;
1047
+ }, { endsQuery }: {
1048
+ endsQuery: boolean;
1049
+ }): ExecuteQueryReturnValue<T>;
1050
+ /**
1051
+ * Publishes what placing an only-stored page changed (see {@link placePage}): the active interval
1052
+ * if the page landed in it, and the end of the query with `endsQuery`.
978
1053
  */
979
- executeQuery({ direction, keepPreviousItems, queryShape: forcedQueryShape, reset, retryCount, silent, updateState, }?: PaginationQueryParams<Q>): Promise<ExecuteQueryReturnValue<T> | void>;
980
- postQueryReconcile({ direction, isFirstPage, keepPreviousItems, queryShape, requestedPageSize, results, updateState, }: PostQueryReconcileParams<T, Q>): ExecuteQueryReturnValue<T>;
1054
+ private publishStoredPage;
981
1055
  cancelScheduledQuery(): void;
982
1056
  resetState(): void;
983
1057
  /**
984
- * Releases this paginator's hold on its item content. With a shared, refcounted item index this
985
- * unlinks every member id from the backing store, so the store no longer strong-references this
986
- * paginator through its subscriber registry — otherwise a discarded owner stays pinned, keeps
987
- * receiving change notifications, and its items never garbage-collect. Call on teardown of the
988
- * owner: a discard, not a reset (the owner is not reused; a re-appearing id gets a fresh instance;
989
- * leftover interval/state caches die with the paginator when it is dropped). Also cancels any
990
- * pending throttled window/view publish, so nothing emits after teardown.
1058
+ * Releases this paginator's hold on its item content (unlinks every member ID from the shared
1059
+ * store, which otherwise pins a discarded owner) and cancels pending throttled publishes. A
1060
+ * teardown, not a reset: the owner is not reused.
991
1061
  */
992
1062
  dispose(): void;
993
1063
  toTail: (params?: Omit<PaginationQueryParams<Q>, "direction" | "queryShape">) => Promise<void | ExecuteQueryReturnValue<T>>;
994
1064
  toHead: (params?: Omit<PaginationQueryParams<Q>, "direction" | "queryShape">) => Promise<void | ExecuteQueryReturnValue<T>>;
995
- /**
996
- * @deprecated Use `toTail` instead.
997
- */
998
- next: (params?: Omit<PaginationQueryParams<Q>, "direction" | "queryShape">) => Promise<void | ExecuteQueryReturnValue<T>>;
999
- /**
1000
- * @deprecated Use `toHead` instead.
1001
- */
1002
- prev: (params?: Omit<PaginationQueryParams<Q>, "direction" | "queryShape">) => Promise<void | ExecuteQueryReturnValue<T>>;
1003
1065
  toTailDebounced: (params?: Omit<PaginationQueryParams<Q>, "direction" | "queryShape">) => void;
1004
1066
  toHeadDebounced: (params?: Omit<PaginationQueryParams<Q>, "direction" | "queryShape">) => void;
1005
- /**
1006
- * @deprecated Use `toTailDebounced` instead.
1007
- */
1008
- nextDebounced: (params?: Omit<PaginationQueryParams<Q>, "direction" | "queryShape">) => void;
1009
- /**
1010
- * @deprecated Use `toHeadDebounced` instead.
1011
- */
1012
- prevDebounced: (params?: Omit<PaginationQueryParams<Q>, "direction" | "queryShape">) => void;
1013
1067
  reload: () => Promise<void>;
1014
1068
  }
1015
1069
  export {};