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
package/dist/esm/i18n.mjs DELETED
@@ -1,1098 +0,0 @@
1
- // src/i18n/dayjs.ts
2
- import Dayjs from "dayjs";
3
- import calendar from "dayjs/plugin/calendar.js";
4
- import duration from "dayjs/plugin/duration.js";
5
- import localeData from "dayjs/plugin/localeData.js";
6
- import localizedFormat from "dayjs/plugin/localizedFormat.js";
7
- import relativeTime from "dayjs/plugin/relativeTime.js";
8
- import timezone from "dayjs/plugin/timezone.js";
9
- import updateLocale from "dayjs/plugin/updateLocale.js";
10
- import utc from "dayjs/plugin/utc.js";
11
- var ownDayjs = () => Dayjs;
12
- var EN_LOCALE_FALLBACK = {
13
- /**
14
- * `formats` and `relativeTime` are empty on purpose, and are not removable: `Dayjs.locale()` takes an
15
- * `ILocale`, which declares both as required, so omitting them is a type error. Empty means "inherit
16
- * dayjs's own defaults", which is the intent.
17
- */
18
- formats: {},
19
- relativeTime: {},
20
- months: [
21
- "January",
22
- "February",
23
- "March",
24
- "April",
25
- "May",
26
- "June",
27
- "July",
28
- "August",
29
- "September",
30
- "October",
31
- "November",
32
- "December"
33
- ],
34
- weekdays: [
35
- "Sunday",
36
- "Monday",
37
- "Tuesday",
38
- "Wednesday",
39
- "Thursday",
40
- "Friday",
41
- "Saturday"
42
- ]
43
- };
44
- var REQUIRED_PLUGINS = [
45
- updateLocale,
46
- utc,
47
- timezone,
48
- localizedFormat,
49
- calendar,
50
- localeData,
51
- relativeTime,
52
- duration
53
- ];
54
- var extendedModules = /* @__PURE__ */ new WeakSet();
55
- var ensureDayjsPlugins = (module = Dayjs) => {
56
- if (extendedModules.has(module)) return;
57
- if (typeof module.extend !== "function") return;
58
- for (const plugin of REQUIRED_PLUGINS) module.extend(plugin);
59
- extendedModules.add(module);
60
- };
61
- var defaultDateTimeParser = (input) => {
62
- ensureDayjsPlugins();
63
- return Dayjs(input);
64
- };
65
- var getDefaultDateTimeParserModule = () => {
66
- ensureDayjsPlugins();
67
- return Dayjs;
68
- };
69
- var addOrUpdateDayjsLocale = (language, config, module = ownDayjs()) => {
70
- ensureDayjsPlugins(module);
71
- if (dayjsLocaleExists(language, module)) {
72
- module.updateLocale?.(language, { ...config });
73
- return;
74
- }
75
- module.locale?.({ name: language, ...EN_LOCALE_FALLBACK, ...config }, void 0, true);
76
- };
77
- var dayjsLocaleExists = (language, module = ownDayjs()) => Object.keys(module.Ls ?? {}).includes(language);
78
- var isDayjsLike = (parser) => typeof parser === "function" && typeof parser.extend === "function";
79
- var supportsTimezone = (parser) => typeof parser === "function" && typeof parser.tz === "function";
80
- var isDate = (value) => value instanceof Date;
81
- var isNumberOrString = (value) => typeof value === "number" || typeof value === "string";
82
- var isDayOrMoment = (value) => typeof value === "object" && value !== null && !(value instanceof Date) && typeof value.format === "function";
83
-
84
- // src/i18n/translator.ts
85
- var asDynamicKey = (key) => key;
86
- var INTERPOLATION_PATTERN = /\{\{\s*([\w.]+)\s*\}\}/g;
87
- var interpolate = (copy, values) => copy.replace(
88
- INTERPOLATION_PATTERN,
89
- (whole, name) => values[name] === void 0 ? whole : String(values[name])
90
- );
91
- var createDefaultTranslatorFunction = () => ((key, defaultValueOrOptions, maybeOptions) => {
92
- if (typeof defaultValueOrOptions === "string") {
93
- return maybeOptions ? interpolate(defaultValueOrOptions, maybeOptions) : defaultValueOrOptions;
94
- }
95
- const options = defaultValueOrOptions ?? maybeOptions;
96
- if (!options) return key;
97
- const resolved = (options.count === 1 ? options.defaultValue_one : options.defaultValue_other) ?? options.defaultValue;
98
- return typeof resolved === "string" ? interpolate(resolved, options) : key;
99
- });
100
- var guardMissingKeyHandler = (handler) => (key, defaultValue) => typeof defaultValue === "string" ? defaultValue : handler(key, defaultValue);
101
-
102
- // src/i18n/formatters.ts
103
- var RELATIVE_TIME_CATALOG = {
104
- "relativeTime.daysAgo_one": "{{ count }}d ago",
105
- "relativeTime.daysAgo_other": "{{ count }}d ago",
106
- "relativeTime.today": "Today",
107
- "relativeTime.weeksAgo_one": "{{ count }}w ago",
108
- "relativeTime.weeksAgo_other": "{{ count }}w ago",
109
- "relativeTime.yesterday": "Yesterday"
110
- };
111
- var DEFAULT_RELATIVE_COMPACT_MAX_DAYS = 6;
112
- var DEFAULT_RELATIVE_COMPACT_MAX_WEEKS = 3;
113
- var isUnparseableDateString = (value) => Number.isNaN(Date.parse(value));
114
- var asWeekRounding = (value) => value === "ceil" || value === true ? "ceil" : "floor";
115
- var asNumber = (value, fallback) => {
116
- const parsed = typeof value === "number" ? value : Number.parseInt(String(value ?? ""), 10);
117
- return Number.isFinite(parsed) ? parsed : fallback;
118
- };
119
- var parseCalendarFormats = (value, logger) => {
120
- if (!value) return void 0;
121
- if (typeof value !== "string") return value;
122
- try {
123
- return JSON.parse(value);
124
- } catch (error) {
125
- logger(
126
- `Streami18n: calendarFormats is not valid JSON, ignoring it: ${value} (${error instanceof Error ? error.message : String(error)})`
127
- );
128
- return void 0;
129
- }
130
- };
131
- var relativeCompactDateString = ({
132
- maxDays,
133
- maxWeeks,
134
- tDateTimeParser,
135
- timestamp,
136
- translate,
137
- weekRounding
138
- }) => {
139
- const parsed = tDateTimeParser(timestamp);
140
- if (!isDayOrMoment(parsed)) return null;
141
- const now = tDateTimeParser(/* @__PURE__ */ new Date());
142
- if (!isDayOrMoment(now)) return null;
143
- const daysAgo = now.startOf("day").diff(parsed.startOf("day"), "day");
144
- if (daysAgo < 0) return parsed.format("DD/MM/YY");
145
- if (daysAgo === 0)
146
- return translate("relativeTime.today", RELATIVE_TIME_CATALOG["relativeTime.today"]);
147
- if (daysAgo === 1)
148
- return translate(
149
- "relativeTime.yesterday",
150
- RELATIVE_TIME_CATALOG["relativeTime.yesterday"]
151
- );
152
- if (daysAgo <= maxDays) {
153
- return translate("relativeTime.daysAgo", {
154
- count: daysAgo,
155
- defaultValue_one: RELATIVE_TIME_CATALOG["relativeTime.daysAgo_one"],
156
- defaultValue_other: RELATIVE_TIME_CATALOG["relativeTime.daysAgo_other"]
157
- });
158
- }
159
- const weeksAgo = weekRounding === "ceil" ? Math.ceil(daysAgo / 7) : Math.floor(daysAgo / 7);
160
- const withinWindow = weekRounding === "ceil" ? daysAgo <= maxWeeks * 7 : weeksAgo <= maxWeeks;
161
- if (maxWeeks > 0 && daysAgo >= 7 && withinWindow) {
162
- return translate("relativeTime.weeksAgo", {
163
- count: weeksAgo,
164
- defaultValue_one: RELATIVE_TIME_CATALOG["relativeTime.weeksAgo_one"],
165
- defaultValue_other: RELATIVE_TIME_CATALOG["relativeTime.weeksAgo_other"]
166
- });
167
- }
168
- return parsed.format("DD/MM/YY");
169
- };
170
- var timestampFormatter = ({ logger, tDateTimeParser, translate }) => (value, _lng, options) => {
171
- const {
172
- calendar: calendar2,
173
- calendarFormats,
174
- format,
175
- relativeCompact,
176
- relativeCompactMaxDays,
177
- relativeCompactMaxWeeks,
178
- relativeCompactWeekRounding
179
- } = options;
180
- if (value === null || value === void 0) return "";
181
- if (typeof value === "string" && isUnparseableDateString(value)) return "";
182
- if (relativeCompact) {
183
- const relative = relativeCompactDateString({
184
- maxDays: asNumber(relativeCompactMaxDays, DEFAULT_RELATIVE_COMPACT_MAX_DAYS),
185
- maxWeeks: asNumber(relativeCompactMaxWeeks, DEFAULT_RELATIVE_COMPACT_MAX_WEEKS),
186
- tDateTimeParser,
187
- timestamp: value,
188
- translate,
189
- weekRounding: asWeekRounding(relativeCompactWeekRounding)
190
- });
191
- if (relative !== null) return relative;
192
- }
193
- const parsed = tDateTimeParser(value);
194
- if (isDayOrMoment(parsed)) {
195
- if (calendar2 && typeof parsed.calendar === "function") {
196
- return parsed.calendar(void 0, parseCalendarFormats(calendarFormats, logger));
197
- }
198
- return parsed.format(format);
199
- }
200
- if (isDate(parsed)) return parsed.toDateString();
201
- if (isNumberOrString(parsed)) return String(parsed);
202
- return "";
203
- };
204
- var durationFormatter = ({ dateTimeParser }) => (value, _lng, options) => {
205
- const { format, withSuffix } = options;
206
- if (typeof dateTimeParser.duration !== "function") return String(value);
207
- const duration2 = dateTimeParser.duration(value);
208
- if (format && typeof duration2.format === "function") return duration2.format(format);
209
- return duration2.humanize(Boolean(withSuffix));
210
- };
211
- var fromNowFormatter = ({ tDateTimeParser }) => (value, _lng, options) => {
212
- if (value === null || value === void 0) return "";
213
- const parsed = tDateTimeParser(value);
214
- if (!isDayOrMoment(parsed) || typeof parsed.fromNow !== "function") return "";
215
- return parsed.fromNow(
216
- Boolean(options.withoutSuffix)
217
- );
218
- };
219
- var predefinedFormatters = {
220
- durationFormatter,
221
- fromNowFormatter,
222
- timestampFormatter
223
- };
224
- var getDateString = ({
225
- calendar: calendar2,
226
- calendarFormats,
227
- format,
228
- formatDate,
229
- messageCreatedAt,
230
- relativeCompact,
231
- relativeCompactMaxDays,
232
- relativeCompactMaxWeeks,
233
- relativeCompactWeekRounding,
234
- t,
235
- tDateTimeParser,
236
- timestampTranslationKey
237
- }) => {
238
- if (!messageCreatedAt || typeof messageCreatedAt === "string" && isUnparseableDateString(messageCreatedAt)) {
239
- return null;
240
- }
241
- if (formatDate) return formatDate(new Date(messageCreatedAt));
242
- if (relativeCompact && t && tDateTimeParser) {
243
- const relative = relativeCompactDateString({
244
- maxDays: asNumber(relativeCompactMaxDays, DEFAULT_RELATIVE_COMPACT_MAX_DAYS),
245
- maxWeeks: asNumber(relativeCompactMaxWeeks, DEFAULT_RELATIVE_COMPACT_MAX_WEEKS),
246
- tDateTimeParser,
247
- timestamp: messageCreatedAt,
248
- translate: t,
249
- weekRounding: asWeekRounding(relativeCompactWeekRounding)
250
- });
251
- if (relative) return relative;
252
- }
253
- if (t && timestampTranslationKey) {
254
- const overrides = {};
255
- const supplied = {
256
- calendar: calendar2,
257
- calendarFormats,
258
- format,
259
- relativeCompact,
260
- relativeCompactMaxDays,
261
- relativeCompactMaxWeeks,
262
- relativeCompactWeekRounding
263
- };
264
- for (const [key, value] of Object.entries(supplied)) {
265
- if (value !== void 0) overrides[key] = value;
266
- }
267
- const translated = t(asDynamicKey(timestampTranslationKey), {
268
- ...overrides,
269
- // A `Date`, not the raw value. Integrators override a `timestamp.*` key with their own
270
- // formatter, and those read `options.timestamp` expecting a Date — passing the string through
271
- // breaks them with `timestamp.toISOString is not a function`.
272
- timestamp: new Date(messageCreatedAt)
273
- });
274
- if (translated !== timestampTranslationKey) return translated;
275
- }
276
- if (!tDateTimeParser) return null;
277
- const parsed = tDateTimeParser(messageCreatedAt);
278
- if (isDayOrMoment(parsed)) {
279
- if (calendar2 && typeof parsed.calendar === "function") {
280
- return parsed.calendar(
281
- void 0,
282
- typeof calendarFormats === "string" ? void 0 : calendarFormats
283
- );
284
- }
285
- return parsed.format(format);
286
- }
287
- if (isDate(parsed)) return parsed.toDateString();
288
- if (isNumberOrString(parsed)) return parsed;
289
- return null;
290
- };
291
- var getDateStringForA11y = ({
292
- messageCreatedAt,
293
- t,
294
- tDateTimeParser,
295
- timestampTranslationKey
296
- }) => getDateString({
297
- calendar: false,
298
- format: "LLLL",
299
- messageCreatedAt,
300
- t,
301
- tDateTimeParser,
302
- timestampTranslationKey
303
- });
304
- var A11Y_CALENDAR_FORMATS = {
305
- en: {
306
- lastDay: "[Yesterday]",
307
- lastWeek: "dddd",
308
- nextDay: "[Tomorrow]",
309
- nextWeek: "dddd [at] LT",
310
- sameDay: "[Today]",
311
- sameElse: "L"
312
- }
313
- };
314
- var getCalendarDateStringForA11y = ({
315
- calendarFormatOverrides,
316
- calendarFormats = A11Y_CALENDAR_FORMATS,
317
- messageCreatedAt,
318
- tDateTimeParser,
319
- userLanguage
320
- }) => {
321
- if (!messageCreatedAt || typeof messageCreatedAt === "string" && isUnparseableDateString(messageCreatedAt) || !tDateTimeParser) {
322
- return void 0;
323
- }
324
- const parsed = tDateTimeParser(messageCreatedAt);
325
- if (!isDayOrMoment(parsed) || !parsed.calendar) return void 0;
326
- const localeFormats = userLanguage && calendarFormats[userLanguage] || calendarFormats.en;
327
- return parsed.calendar(void 0, {
328
- ...localeFormats,
329
- sameElse: "LL",
330
- ...calendarFormatOverrides
331
- });
332
- };
333
-
334
- // src/i18n/languageNames.ts
335
- var LANGUAGE_NAMES = {
336
- af: "Afrikaans",
337
- am: "Amharic",
338
- ar: "Arabic",
339
- az: "Azerbaijani",
340
- bg: "Bulgarian",
341
- bn: "Bengali",
342
- bs: "Bosnian",
343
- cs: "Czech",
344
- da: "Danish",
345
- de: "German",
346
- el: "Greek",
347
- en: "English",
348
- es: "Spanish",
349
- "es-MX": "Spanish (Mexico)",
350
- et: "Estonian",
351
- fa: "Persian",
352
- "fa-AF": "Dari",
353
- fi: "Finnish",
354
- fr: "French",
355
- "fr-CA": "French (Canada)",
356
- ha: "Hausa",
357
- he: "Hebrew",
358
- hi: "Hindi",
359
- hr: "Croatian",
360
- ht: "Haitian Creole",
361
- hu: "Hungarian",
362
- id: "Indonesian",
363
- it: "Italian",
364
- ja: "Japanese",
365
- ka: "Georgian",
366
- ko: "Korean",
367
- lt: "Lithuanian",
368
- lv: "Latvian",
369
- ms: "Malay",
370
- nl: "Dutch",
371
- no: "Norwegian",
372
- pl: "Polish",
373
- ps: "Pashto",
374
- pt: "Portuguese",
375
- ro: "Romanian",
376
- ru: "Russian",
377
- sk: "Slovak",
378
- sl: "Slovenian",
379
- so: "Somali",
380
- sq: "Albanian",
381
- sr: "Serbian",
382
- sv: "Swedish",
383
- sw: "Swahili",
384
- ta: "Tamil",
385
- th: "Thai",
386
- tl: "Tagalog",
387
- tr: "Turkish",
388
- uk: "Ukrainian",
389
- ur: "Urdu",
390
- vi: "Vietnamese",
391
- zh: "Chinese (Simplified)",
392
- "zh-TW": "Chinese (Traditional)"
393
- };
394
- var languageNameDefaults = Object.fromEntries(
395
- Object.entries(LANGUAGE_NAMES).map(([code, name]) => [`language.${code}`, name])
396
- );
397
-
398
- // src/i18n/Streami18n.ts
399
- import i18next from "i18next";
400
-
401
- // src/store.ts
402
- var isPatch = (value) => typeof value === "function";
403
- var noop = () => {
404
- };
405
- var StateStore = class {
406
- constructor(value) {
407
- this.value = value;
408
- this.handlers = /* @__PURE__ */ new Set();
409
- this.preprocessors = /* @__PURE__ */ new Set();
410
- this.partialNext = (partial) => this.next((current) => ({ ...current, ...partial }));
411
- this.subscribeWithSelector = (selector, handler) => {
412
- let previouslySelectedValues;
413
- const wrappedHandler = (nextValue) => {
414
- const newlySelectedValues = selector(nextValue);
415
- let hasUpdatedValues = typeof previouslySelectedValues === "undefined";
416
- for (const key in previouslySelectedValues) {
417
- if (previouslySelectedValues[key] === newlySelectedValues[key]) continue;
418
- hasUpdatedValues = true;
419
- break;
420
- }
421
- if (!hasUpdatedValues) return;
422
- const previouslySelectedValuesCopy = previouslySelectedValues;
423
- previouslySelectedValues = newlySelectedValues;
424
- handler(newlySelectedValues, previouslySelectedValuesCopy);
425
- };
426
- return this.subscribe(wrappedHandler);
427
- };
428
- }
429
- /**
430
- * Allows merging two stores only if their keys differ otherwise there's no way to ensure the data type stability.
431
- *
432
- * @experimental
433
- * This method is experimental and may change in future versions.
434
- */
435
- merge(stateStore) {
436
- return new MergedStateStore({
437
- original: this,
438
- merged: stateStore
439
- });
440
- }
441
- next(newValueOrPatch) {
442
- const newValue = isPatch(newValueOrPatch) ? newValueOrPatch(this.value) : newValueOrPatch;
443
- if (newValue === this.value) return;
444
- this.preprocessors.forEach((preprocessor) => preprocessor(newValue, this.value));
445
- const oldValue = this.value;
446
- this.value = newValue;
447
- this.handlers.forEach((handler) => handler(this.value, oldValue));
448
- }
449
- getLatestValue() {
450
- return this.value;
451
- }
452
- subscribe(handler) {
453
- handler(this.value, void 0);
454
- this.handlers.add(handler);
455
- return () => {
456
- this.handlers.delete(handler);
457
- };
458
- }
459
- /**
460
- * Registers a preprocessor function that will be called before the state is updated.
461
- *
462
- * Preprocessors are invoked with the new and previous values whenever `next` or `partialNext` methods
463
- * are called, allowing you to mutate or react to the new value before it is set. Preprocessors run in the
464
- * order they were registered.
465
- *
466
- * @example
467
- * ```ts
468
- * const store = new StateStore<{ count: number; isMaxValue: bool; }>({ count: 0, isMaxValue: false });
469
- *
470
- * store.addPreprocessor((nextValue, prevValue) => {
471
- * if (nextValue.count > 10) {
472
- * nextValue.count = 10; // Clamp the value to a maximum of 10
473
- * }
474
- *
475
- * if (nextValue.count === 10) {
476
- * nextValue.isMaxValue = true; // Set isMaxValue to true if count is 10
477
- * } else {
478
- * nextValue.isMaxValue = false; // Reset isMaxValue otherwise
479
- * }
480
- * });
481
- *
482
- * store.partialNext({ count: 15 });
483
- *
484
- * store.getLatestValue(); // { count: 10, isMaxValue: true }
485
- *
486
- * store.partialNext({ count: 5 });
487
- *
488
- * store.getLatestValue(); // { count: 5, isMaxValue: false }
489
- * ```
490
- *
491
- * @param preprocessor - The function to be called with the next and previous values before the state is updated.
492
- * @returns A `RemovePreprocessor` function that removes the preprocessor when called.
493
- */
494
- addPreprocessor(preprocessor) {
495
- this.preprocessors.add(preprocessor);
496
- return () => {
497
- this.preprocessors.delete(preprocessor);
498
- };
499
- }
500
- };
501
- var MergedStateStore = class _MergedStateStore extends StateStore {
502
- constructor({ original, merged }) {
503
- const originalValue = original.getLatestValue();
504
- const mergedValue = merged.getLatestValue();
505
- super({
506
- ...originalValue,
507
- ...mergedValue
508
- });
509
- // override original methods and "disable" them
510
- this.next = () => {
511
- console.warn(
512
- `${_MergedStateStore.name}.next is disabled, call original.next or merged.next instead`
513
- );
514
- };
515
- this.partialNext = () => {
516
- console.warn(
517
- `${_MergedStateStore.name}.partialNext is disabled, call original.partialNext or merged.partialNext instead`
518
- );
519
- };
520
- this.cachedOriginalValue = originalValue;
521
- this.cachedMergedValue = mergedValue;
522
- this.original = original;
523
- this.merged = merged;
524
- }
525
- /**
526
- * Subscribes to changes in the merged state store.
527
- *
528
- * This method extends the base subscribe functionality to handle the merged nature of this store:
529
- * 1. The first subscriber triggers registration of helper subscribers that listen to both source stores
530
- * 2. Changes from either source store are propagated to this merged store
531
- * 3. Source store values are cached to prevent unnecessary updates
532
- *
533
- * When the first subscriber is added, the method sets up listeners on both original and merged stores.
534
- * These listeners update the combined store value whenever either source store changes.
535
- * All subscriptions (helpers and the actual handler) are tracked so they can be properly cleaned up.
536
- *
537
- * @param handler - The callback function that will be executed when the state changes
538
- * @returns An unsubscribe function that, when called, removes the subscription and any helper subscriptions
539
- */
540
- subscribe(handler) {
541
- const unsubscribeFunctions = [];
542
- if (!this.handlers.size) {
543
- const base = (nextValue) => {
544
- super.next((currentValue) => ({
545
- ...currentValue,
546
- ...nextValue
547
- }));
548
- };
549
- unsubscribeFunctions.push(
550
- this.original.subscribe((nextValue) => {
551
- if (nextValue === this.cachedOriginalValue) return;
552
- this.cachedOriginalValue = nextValue;
553
- base(nextValue);
554
- }),
555
- this.merged.subscribe((nextValue) => {
556
- if (nextValue === this.cachedMergedValue) return;
557
- this.cachedMergedValue = nextValue;
558
- base(nextValue);
559
- })
560
- );
561
- }
562
- unsubscribeFunctions.push(super.subscribe(handler));
563
- return () => {
564
- unsubscribeFunctions.forEach((unsubscribe) => unsubscribe());
565
- };
566
- }
567
- /**
568
- * Retrieves the latest combined state from both original and merged stores.
569
- *
570
- * This method extends the base getLatestValue functionality to ensure the merged store
571
- * remains in sync with its source stores even when there are no active subscribers.
572
- *
573
- * When there are no handlers registered, the method:
574
- * 1. Fetches the latest values from both source stores
575
- * 2. Compares them with the cached values to detect changes
576
- * 3. If changes are detected, updates the internal value and caches
577
- * the new source values to maintain consistency
578
- *
579
- * This approach ensures that calling getLatestValue() always returns the most
580
- * up-to-date combined state, even if the merged store hasn't been actively
581
- * receiving updates through subscriptions.
582
- *
583
- * @returns The latest combined state from both original and merged stores
584
- */
585
- getLatestValue() {
586
- if (!this.handlers.size) {
587
- const originalValue = this.original.getLatestValue();
588
- const mergedValue = this.merged.getLatestValue();
589
- if (originalValue !== this.cachedOriginalValue || mergedValue !== this.cachedMergedValue) {
590
- this.value = {
591
- ...originalValue,
592
- ...mergedValue
593
- };
594
- this.cachedMergedValue = mergedValue;
595
- this.cachedOriginalValue = originalValue;
596
- }
597
- }
598
- return super.getLatestValue();
599
- }
600
- addPreprocessor() {
601
- console.warn(
602
- `${_MergedStateStore.name}.addPreprocessor is disabled, call original.addPreprocessor or merged.addPreprocessor instead`
603
- );
604
- return noop;
605
- }
606
- };
607
-
608
- // src/i18n/TranslationBuilder.ts
609
- var TranslationTopic = class {
610
- constructor(options) {
611
- this.options = options;
612
- this.translators = /* @__PURE__ */ new Map();
613
- this.setTranslator = (name, translator) => {
614
- this.translators.set(name, translator);
615
- };
616
- this.removeTranslator = (name) => {
617
- this.translators.delete(name);
618
- };
619
- this.i18next = options.i18next;
620
- if (options.translators) {
621
- Object.entries(options.translators).forEach(([name, translator]) => {
622
- this.setTranslator(name, translator);
623
- });
624
- }
625
- }
626
- };
627
- var forwardTranslation = ({ value }) => value;
628
- var TranslationBuilder = class {
629
- constructor(i18next2) {
630
- this.i18next = i18next2;
631
- this.topics = /* @__PURE__ */ new Map();
632
- /**
633
- * Translators registered before their topic exists.
634
- *
635
- * Topics are only created during `Streami18n.init()`, but an integrator registers translators against
636
- * the constructed instance — so registrations that arrive first are buffered and flushed when the
637
- * topic appears, rather than silently dropped.
638
- */
639
- this.translatorRegistrationsBuffer = {};
640
- this.registerTopic = (name, Topic) => {
641
- let topic = this.topics.get(name);
642
- if (!topic) {
643
- topic = new Topic({ i18next: this.i18next });
644
- this.topics.set(name, topic);
645
- this.i18next.use({
646
- name,
647
- process: (value, key, options) => {
648
- const registered = this.topics.get(name);
649
- if (!registered) return value;
650
- return registered.translate(value, key, options);
651
- },
652
- type: "postProcessor"
653
- });
654
- }
655
- const buffered = this.translatorRegistrationsBuffer[name];
656
- if (buffered) {
657
- Object.entries(buffered).forEach(([translatorName, translator]) => {
658
- topic.setTranslator(translatorName, translator);
659
- });
660
- delete this.translatorRegistrationsBuffer[name];
661
- }
662
- return topic;
663
- };
664
- this.disableTopic = (topicName) => {
665
- const topic = this.topics.get(topicName);
666
- if (!topic) return;
667
- this.i18next.use({
668
- name: topicName,
669
- process: forwardTranslation,
670
- type: "postProcessor"
671
- });
672
- this.topics.delete(topicName);
673
- };
674
- this.getTopic = (topicName) => this.topics.get(topicName);
675
- }
676
- registerTranslators(topicName, translators) {
677
- var _a;
678
- const topic = this.getTopic(topicName);
679
- if (!topic) {
680
- (_a = this.translatorRegistrationsBuffer)[topicName] ?? (_a[topicName] = {});
681
- Object.entries(translators).forEach(([translatorName, translator]) => {
682
- this.translatorRegistrationsBuffer[topicName][translatorName] = translator;
683
- });
684
- return;
685
- }
686
- Object.entries(translators).forEach(([name, translator]) => {
687
- topic.setTranslator(name, translator);
688
- });
689
- }
690
- removeTranslators(topicName, translators) {
691
- if (this.translatorRegistrationsBuffer[topicName]) {
692
- translators.forEach((translatorName) => {
693
- delete this.translatorRegistrationsBuffer[topicName][translatorName];
694
- });
695
- }
696
- const topic = this.getTopic(topicName);
697
- if (!topic) return;
698
- translators.forEach((name) => {
699
- topic.removeTranslator(name);
700
- });
701
- }
702
- };
703
-
704
- // src/i18n/TranslationStore.ts
705
- var DEFAULT_LANGUAGE = "en";
706
- var TranslationStore = class {
707
- constructor(runtimeDefaults = {}) {
708
- this.dictionaries = /* @__PURE__ */ new Map();
709
- this.registered = /* @__PURE__ */ new Set([DEFAULT_LANGUAGE]);
710
- this.runtimeDefaults = runtimeDefaults;
711
- }
712
- /**
713
- * Languages an integrator actually supplied a dictionary for.
714
- *
715
- * Deliberately narrower than {@link TranslationStore.languages}, which also counts every language
716
- * created just to carry the bundled defaults. Without the distinction there would be no way to warn
717
- * that the active language has no translations — every language would look registered.
718
- */
719
- get registeredLanguages() {
720
- return this.registered;
721
- }
722
- /** Every language with a dictionary, including those carrying only the bundled defaults. */
723
- get languages() {
724
- return [...this.dictionaries.keys()];
725
- }
726
- /** `language -> dictionary`, for a caller that has to hand them all over at once. */
727
- entries() {
728
- return [...this.dictionaries];
729
- }
730
- isRegistered(language) {
731
- return this.registered.has(language);
732
- }
733
- /**
734
- * Guarantees `language` has a dictionary, and returns it.
735
- *
736
- * Called for a language nobody registered, so that it still formats dates and renders the SDK's copy
737
- * in English rather than raw dotted keys.
738
- */
739
- ensure(language) {
740
- return this.merge(language);
741
- }
742
- /**
743
- * Layers a dictionary over what `language` already has, and marks it registered.
744
- *
745
- * **Merged, not replaced.** Repeated calls for one language accumulate, and — the reason this class
746
- * exists — the bundled defaults survive a partial dictionary. A bundled key has no inline
747
- * `defaultValue` at its call site and `fallbackLng` is false, so a language that loses them renders
748
- * raw dotted keys and unformatted ISO timestamps. That is guarantee G1 of the i18n suite.
749
- */
750
- register(language, dictionary) {
751
- const merged = this.merge(language, dictionary);
752
- this.registered.add(language);
753
- return merged;
754
- }
755
- /**
756
- * Bundled defaults first, then whatever the language already had, then the incoming dictionary — so
757
- * an integrator can override a bundled key, and a later registration wins over an earlier one.
758
- */
759
- merge(language, dictionary) {
760
- const merged = {
761
- ...this.runtimeDefaults,
762
- ...this.dictionaries.get(language),
763
- ...dictionary
764
- };
765
- this.dictionaries.set(language, merged);
766
- return merged;
767
- }
768
- };
769
-
770
- // src/i18n/Streami18n.ts
771
- var DEFAULT_NAMESPACE = "translation";
772
- var Streami18n = class {
773
- constructor(options = {}) {
774
- this.i18nInstance = i18next.createInstance();
775
- /** Applied when the language becomes active, not on registration: `Dayjs.locale()` is global. */
776
- this.dayjsLocales = {};
777
- /** Set by {@link overrideTFunction}, so `init()` does not clobber a swapped-in implementation. */
778
- this.tOverridden = false;
779
- /**
780
- * Re-run on every language change, not just at `init()`: factories destructure the language out of
781
- * their context, so one built once keeps formatting in the initial language forever. `formatter.add`
782
- * replaces by name, which is what makes re-registering sufficient.
783
- */
784
- this.registerFormatters = () => {
785
- const context = this.createFormatterContext();
786
- Object.entries(this.formatters).forEach(([name, factory]) => {
787
- if (!factory) return;
788
- const formatter = factory(context);
789
- this.i18nInstance.services.formatter?.add(
790
- name,
791
- formatter
792
- );
793
- });
794
- };
795
- /**
796
- * Accessors rather than snapshots, for a formatter that holds the context and reads per call; one
797
- * that destructures is covered by {@link registerFormatters} re-running instead.
798
- *
799
- * The nested arrows are load-bearing: a getter in an object literal binds `this` to the literal.
800
- */
801
- this.createFormatterContext = () => {
802
- const readLanguage = () => this.currentLanguage;
803
- const readDateTimeParser = () => this.tDateTimeParser;
804
- return {
805
- get currentLanguage() {
806
- return readLanguage();
807
- },
808
- dateTimeParser: this.DateTimeParser,
809
- logger: this.logger,
810
- get tDateTimeParser() {
811
- return readDateTimeParser();
812
- },
813
- timezone: this.timezone,
814
- translate: this.translate
815
- };
816
- };
817
- /** The store's flat dictionaries in i18next's nested `resources` shape. */
818
- this.i18nextResources = () => Object.fromEntries(
819
- this.translations.entries().map(([language, dictionary]) => [language, { [DEFAULT_NAMESPACE]: dictionary }])
820
- );
821
- /** The only route for a language added after `init()`. */
822
- this.ensureLanguage = (language) => {
823
- this.addResources(language, this.translations.ensure(language));
824
- };
825
- this.addResources = (language, dictionary) => {
826
- if (!this.initialized) return;
827
- this.i18nInstance.addResources(language, DEFAULT_NAMESPACE, dictionary);
828
- };
829
- /**
830
- * Warns rather than falling back to `en`: the language renders English copy from the inline defaults
831
- * while keeping its own date formats, and resetting it would discard the integrator's choice.
832
- */
833
- this.validateCurrentLanguage = () => {
834
- const language = this.currentLanguageValue;
835
- if (this.translations.isRegistered(language)) return;
836
- this.logger(
837
- `Streami18n: no translation dictionary is registered for '${language}', so the SDK's copy renders in English. Call registerTranslation('${language}', {...}) to translate it. Registered: ${[...this.translations.registeredLanguages].join(", ")}`
838
- );
839
- };
840
- /**
841
- * Checked against the module that actually formats the dates.
842
- *
843
- * A supplied dayjs copy has its own locale registry, so consulting ours would answer for the wrong
844
- * one. True for a non-dayjs parser, whose registry we cannot inspect.
845
- */
846
- this.localeExists = (language) => {
847
- if (!isDayjsLike(this.DateTimeParser)) return true;
848
- return dayjsLocaleExists(language, this.DateTimeParser);
849
- };
850
- /**
851
- * For formatters, which resolve keys handed to them at runtime -- including their own
852
- * `relativeTime.*` copy, which no catalog declares.
853
- */
854
- this.translate = (key, defaultValueOrOptions, options) => this.t(
855
- asDynamicKey(key),
856
- defaultValueOrOptions,
857
- options
858
- );
859
- /**
860
- * Hermes ships a partial ICU: `Intl.PluralRules` silently falls back to root rules (`other` only) for
861
- * locales it lacks, so a dictionary's `_few` / `_many` never render and nothing errors.
862
- *
863
- * Called from `init()` because i18next caches a resolver per language there — the last moment
864
- * `intl-pluralrules` could still have been loaded in time.
865
- */
866
- this.assertPluralRulesCoverage = (language) => {
867
- try {
868
- const resolved = new Intl.PluralRules(language).resolvedOptions().locale;
869
- if (resolved.split("-")[0] === language.split("-")[0]) return;
870
- this.logger(
871
- `Streami18n: Intl.PluralRules has no data for '${language}' (it resolved to '${resolved}'), so every count selects the '_other' form. On React Native, import 'intl-pluralrules' before anything else in your entry file.`
872
- );
873
- } catch {
874
- this.logger(
875
- `Streami18n: Intl.PluralRules is unavailable, so plural selection will not work. On React Native, import 'intl-pluralrules' before anything else in your entry file.`
876
- );
877
- }
878
- };
879
- this.logger = options.logger ?? ((message) => console.warn(message));
880
- this.translations = new TranslationStore(options.runtimeDefaults);
881
- this.disableDateTimeTranslations = options.disableDateTimeTranslations ?? false;
882
- this.timezone = options.timezone;
883
- this.formatters = { ...predefinedFormatters, ...options.formatters };
884
- this.translationBuilder = new TranslationBuilder(this.i18nInstance);
885
- this.translationBuilderTopics = options.translationBuilderTopics ?? {};
886
- const language = options.language ?? DEFAULT_LANGUAGE;
887
- if (options.DateTimeParser) {
888
- this.DateTimeParser = options.DateTimeParser;
889
- if (isDayjsLike(this.DateTimeParser)) ensureDayjsPlugins(this.DateTimeParser);
890
- } else {
891
- this.DateTimeParser = getDefaultDateTimeParserModule();
892
- }
893
- const tDateTimeParser = (timestamp) => {
894
- const locale = this.disableDateTimeTranslations || !this.localeExists(this.currentLanguageValue) ? DEFAULT_LANGUAGE : this.currentLanguageValue;
895
- const parsed = this.DateTimeParser(timestamp);
896
- const withZone = this.timezone && supportsTimezone(this.DateTimeParser) ? parsed.tz(this.timezone) : parsed;
897
- return withZone.locale(
898
- locale
899
- );
900
- };
901
- this.state = new StateStore({
902
- initialized: false,
903
- language,
904
- t: createDefaultTranslatorFunction(),
905
- tDateTimeParser
906
- });
907
- this.translations.ensure(DEFAULT_LANGUAGE);
908
- this.translations.ensure(language);
909
- if (options.translationsForLanguage) {
910
- this.translations.register(
911
- language,
912
- options.translationsForLanguage
913
- );
914
- }
915
- const missingKeyHandler = options.parseMissingKeyHandler ?? options.i18nextConfigOverrides?.parseMissingKeyHandler;
916
- this.i18nextConfig = {
917
- debug: options.debug ?? false,
918
- fallbackLng: false,
919
- interpolation: { escapeValue: false, formatSeparator: "|" },
920
- // Must stay false: keys are flat strings containing dots, and some copy contains `...`.
921
- keySeparator: false,
922
- lng: language,
923
- nsSeparator: false,
924
- // i18next only runs post-processors it was told about at init time.
925
- ...Object.keys(this.translationBuilderTopics).length > 0 ? { postProcess: Object.keys(this.translationBuilderTopics) } : {},
926
- ...options.i18nextConfigOverrides,
927
- // Guarded even when integrator-supplied: an unguarded handler silently blanks every prose key.
928
- parseMissingKeyHandler: missingKeyHandler ? guardMissingKeyHandler(missingKeyHandler) : (key, defaultValue) => {
929
- if (typeof defaultValue === "string") return defaultValue;
930
- this.logger(`Streami18n: missing translation for key: ${key}`);
931
- return key;
932
- }
933
- };
934
- if (options.dayjsLocaleConfigForLanguage) {
935
- this.addOrUpdateLocale(language, options.dayjsLocaleConfigForLanguage);
936
- } else if (!this.localeExists(language)) {
937
- this.logger(
938
- `Streami18n: no dayjs locale is registered for '${language}', so dates render with the English locale. Import it with "import 'dayjs/locale/${language}';" in your app, or pass a config via registerTranslation('${language}', translation, dayjsLocaleConfig).`
939
- );
940
- }
941
- }
942
- get t() {
943
- return this.state.getLatestValue().t;
944
- }
945
- get tDateTimeParser() {
946
- return this.state.getLatestValue().tDateTimeParser;
947
- }
948
- get currentLanguage() {
949
- return this.state.getLatestValue().language;
950
- }
951
- get initialized() {
952
- return this.state.getLatestValue().initialized;
953
- }
954
- /** Read inside the constructor, before `state` getters are safe to rely on externally. */
955
- get currentLanguageValue() {
956
- return this.state?.getLatestValue().language ?? DEFAULT_LANGUAGE;
957
- }
958
- /**
959
- * Initializes i18next. Memoized, so concurrent callers share one initialization.
960
- *
961
- * **Rejects on failure**, so handle it. The instance stays usable either way: `initialized` stays
962
- * false, keeping {@link Streami18n.registerTranslation} and {@link Streami18n.setLanguage} off a
963
- * dead i18next instance, and `t` keeps returning each call site's inline English.
964
- */
965
- init() {
966
- if (this.initPromise) return this.initPromise;
967
- const pending = this.runInit();
968
- this.initPromise = pending;
969
- pending.catch(() => {
970
- if (this.initPromise === pending) this.initPromise = void 0;
971
- });
972
- return pending;
973
- }
974
- async runInit() {
975
- this.validateCurrentLanguage();
976
- this.assertPluralRulesCoverage(this.currentLanguage);
977
- const dayjsLocale = this.dayjsLocales[this.currentLanguage];
978
- if (dayjsLocale) this.addOrUpdateLocale(this.currentLanguage, dayjsLocale);
979
- const t = await this.i18nInstance.init({
980
- ...this.i18nextConfig,
981
- lng: this.currentLanguage,
982
- resources: this.i18nextResources()
983
- });
984
- this.registerFormatters();
985
- Object.entries(this.translationBuilderTopics).forEach(([topic, Topic]) => {
986
- this.translationBuilder.registerTopic(topic, Topic);
987
- });
988
- this.state.partialNext({
989
- initialized: true,
990
- ...this.tOverridden ? {} : { t }
991
- });
992
- return this.state.getLatestValue();
993
- }
994
- registerTranslation(language, translation, dayjsLocaleConfig) {
995
- if (!translation) {
996
- this.logger(
997
- "Streami18n: registerTranslation called without a translation dictionary"
998
- );
999
- return;
1000
- }
1001
- const merged = this.translations.register(
1002
- language,
1003
- translation
1004
- );
1005
- if (dayjsLocaleConfig) {
1006
- this.dayjsLocales[language] = { ...dayjsLocaleConfig };
1007
- } else if (!this.localeExists(language)) {
1008
- this.logger(
1009
- `Streami18n: no dayjs locale is registered for '${language}'. Import it with "import 'dayjs/locale/${language}';" in your app, or pass a config as the third argument to registerTranslation.`
1010
- );
1011
- }
1012
- this.addResources(language, merged);
1013
- }
1014
- /**
1015
- * Returns nothing: the new `t` is published to {@link Streami18n.state}. Handing one back would offer
1016
- * a value that goes stale on the next language change.
1017
- */
1018
- async setLanguage(language) {
1019
- const previousLanguage = this.state.getLatestValue().language;
1020
- this.state.partialNext({ language });
1021
- this.ensureLanguage(language);
1022
- if (!this.initialized) return;
1023
- this.validateCurrentLanguage();
1024
- this.assertPluralRulesCoverage(language);
1025
- try {
1026
- const t = await this.i18nInstance.changeLanguage(language);
1027
- const dayjsLocale = this.dayjsLocales[language];
1028
- if (dayjsLocale) this.addOrUpdateLocale(language, dayjsLocale);
1029
- this.registerFormatters();
1030
- if (!this.tOverridden) {
1031
- this.state.partialNext({ t });
1032
- }
1033
- } catch (error) {
1034
- this.state.partialNext({ language: previousLanguage });
1035
- this.logger(`Streami18n: failed to set language: ${describeError(error)}`);
1036
- }
1037
- }
1038
- /**
1039
- * Swaps in a different translation implementation, for an app that already has an i18n layer. Safe
1040
- * before `init()`, which will not overwrite it.
1041
- */
1042
- overrideTFunction(t) {
1043
- this.tOverridden = true;
1044
- this.state.partialNext({ t });
1045
- }
1046
- /**
1047
- * Languages an integrator supplied a dictionary for. Read-only because adding to it would claim a
1048
- * language is registered with no dictionary behind it; use `registerTranslation`.
1049
- */
1050
- get registeredLanguages() {
1051
- return this.translations.registeredLanguages;
1052
- }
1053
- /**
1054
- * Registers a locale on the module that formats the dates, not on ours.
1055
- *
1056
- * Only dayjs has a registry we can write to. For a Moment the config cannot be applied at all, so it
1057
- * is reported -- previously it was written to core's own dayjs, where nothing would ever read it.
1058
- */
1059
- addOrUpdateLocale(language, config) {
1060
- if (!isDayjsLike(this.DateTimeParser)) {
1061
- this.logger(
1062
- `Streami18n: a dayjs locale config was supplied for '${language}', but DateTimeParser is not dayjs, so it cannot be applied. Configure the locale on your own date library instead.`
1063
- );
1064
- return;
1065
- }
1066
- addOrUpdateDayjsLocale(language, config, this.DateTimeParser);
1067
- }
1068
- };
1069
- var describeError = (error) => error instanceof Error ? error.message : String(error);
1070
- export {
1071
- A11Y_CALENDAR_FORMATS,
1072
- DEFAULT_LANGUAGE,
1073
- LANGUAGE_NAMES,
1074
- RELATIVE_TIME_CATALOG,
1075
- Streami18n,
1076
- TranslationBuilder,
1077
- TranslationStore,
1078
- TranslationTopic,
1079
- addOrUpdateDayjsLocale,
1080
- asDynamicKey,
1081
- createDefaultTranslatorFunction,
1082
- dayjsLocaleExists,
1083
- defaultDateTimeParser,
1084
- ensureDayjsPlugins,
1085
- getCalendarDateStringForA11y,
1086
- getDateString,
1087
- getDateStringForA11y,
1088
- getDefaultDateTimeParserModule,
1089
- guardMissingKeyHandler,
1090
- isDate,
1091
- isDayOrMoment,
1092
- isDayjsLike,
1093
- isNumberOrString,
1094
- languageNameDefaults,
1095
- predefinedFormatters,
1096
- supportsTimezone
1097
- };
1098
- //# sourceMappingURL=i18n.mjs.map