stream-chat 10.0.0-rc.8 → 10.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +7 -6
- package/dist/cjs/index.browser.js +22095 -22290
- package/dist/cjs/index.browser.js.map +4 -4
- package/dist/cjs/index.node.js +22143 -22298
- package/dist/cjs/index.node.js.map +4 -4
- package/dist/esm/index.mjs +22093 -22288
- package/dist/esm/index.mjs.map +4 -4
- package/dist/types/ChannelManager.d.ts +216 -135
- package/dist/types/CooldownTimer.d.ts +16 -27
- package/dist/types/EventHandlerPipeline.d.ts +18 -38
- package/dist/types/LiveLocationManager.d.ts +25 -47
- package/dist/types/api-client.d.ts +17 -5
- package/dist/types/channel.d.ts +435 -500
- package/dist/types/channel_state.d.ts +72 -112
- package/dist/types/client.d.ts +323 -440
- package/dist/types/client_state.d.ts +1 -3
- package/dist/types/configuration/ConfigController.d.ts +31 -125
- package/dist/types/configuration/InstanceConfigurationRegistry.d.ts +32 -124
- package/dist/types/configuration/keys.d.ts +5 -19
- package/dist/types/configuration/shape.d.ts +12 -29
- package/dist/types/configuration/types.d.ts +64 -79
- package/dist/types/configuration/utils/applyInstanceConfiguration.d.ts +14 -36
- package/dist/types/configuration/utils/copyConfigPatch.d.ts +8 -0
- package/dist/types/configuration/utils/declarativeSlices.d.ts +5 -16
- package/dist/types/configuration/utils/deepFreezeConfig.d.ts +3 -17
- package/dist/types/configuration/utils/serverAuthority.d.ts +9 -29
- package/dist/types/connection/ConnectionIdManager.d.ts +45 -0
- package/dist/types/connection/ConnectionRecoveryManager.d.ts +84 -0
- package/dist/types/connection/index.d.ts +4 -0
- package/dist/types/connection/networkConnection/NetworkConnectionObserver.d.ts +82 -0
- package/dist/types/connection/networkConnection/index.d.ts +3 -0
- package/dist/types/connection/networkConnection/reporters.d.ts +20 -0
- package/dist/types/connection/networkConnection/types.d.ts +40 -0
- package/dist/types/connection/wsConnection/StableWSConnection.d.ts +137 -0
- package/dist/types/connection/wsConnection/WSConnection.d.ts +105 -0
- package/dist/types/connection/wsConnection/WSConnectionFallback.d.ts +47 -0
- package/dist/types/connection/wsConnection/config.d.ts +31 -0
- package/dist/types/connection/wsConnection/index.d.ts +4 -0
- package/dist/types/connection/wsConnection/types.d.ts +46 -0
- package/dist/types/constants.d.ts +3 -1
- package/dist/types/custom_types.d.ts +0 -2
- package/dist/types/entityStore/EntityStore.d.ts +226 -65
- package/dist/types/entityStore/StoreBackedItemIndex.d.ts +19 -33
- package/dist/types/entityStore/index.d.ts +0 -1
- package/dist/types/errors.d.ts +16 -19
- package/dist/types/formatMessageMemo.d.ts +5 -0
- package/dist/types/gen/chat/ChannelApi.d.ts +5 -1
- package/dist/types/gen/chat/ChatApi.d.ts +149 -105
- package/dist/types/gen/models/index.d.ts +2540 -698
- package/dist/types/gen/models/timestamp-guard.d.ts +22 -0
- package/dist/types/gen/moderation/ModerationApi.d.ts +37 -14
- package/dist/types/index.d.ts +10 -5
- package/dist/types/{i18n/languageNames.d.ts → languageNames.d.ts} +9 -24
- package/dist/types/logger.d.ts +1 -3
- package/dist/types/messageComposer/CustomDataManager.d.ts +7 -1
- package/dist/types/messageComposer/LocationComposer.d.ts +8 -2
- package/dist/types/messageComposer/attachmentIdentity.d.ts +24 -0
- package/dist/types/messageComposer/attachmentManager.d.ts +52 -24
- package/dist/types/messageComposer/attachmentUtils.d.ts +23 -0
- package/dist/types/messageComposer/configuration/configuration.d.ts +2 -5
- package/dist/types/messageComposer/configuration/types.d.ts +38 -50
- package/dist/types/messageComposer/index.d.ts +1 -0
- package/dist/types/messageComposer/linkPreviewsManager.d.ts +12 -9
- package/dist/types/messageComposer/messageComposer.d.ts +60 -123
- package/dist/types/messageComposer/middleware/attachmentManager/postUpload/attachmentEnrichment.d.ts +10 -1
- package/dist/types/messageComposer/middleware/messageComposer/attachments.d.ts +4 -0
- package/dist/types/messageComposer/middleware/messageComposer/commandInjection.d.ts +5 -0
- package/dist/types/messageComposer/middleware/messageComposer/index.d.ts +2 -0
- package/dist/types/messageComposer/middleware/messageComposer/pollOnly.d.ts +6 -0
- package/dist/types/messageComposer/middleware/messageComposer/userDataInjection.d.ts +5 -0
- package/dist/types/messageComposer/middleware/pollComposer/types.d.ts +2 -4
- package/dist/types/messageComposer/middleware/pollComposer/validation.d.ts +7 -19
- package/dist/types/messageComposer/middleware/textComposer/commandUtils.d.ts +4 -0
- package/dist/types/messageComposer/middleware/textComposer/commands.d.ts +11 -2
- package/dist/types/messageComposer/middleware/textComposer/mentions.d.ts +20 -19
- package/dist/types/messageComposer/middleware/textComposer/textMiddlewareUtils.d.ts +9 -3
- package/dist/types/messageComposer/middleware/textComposer/types.d.ts +1 -6
- package/dist/types/messageComposer/pollComposer.d.ts +15 -5
- package/dist/types/messageComposer/textComposer.d.ts +14 -7
- package/dist/types/messageComposer/types.d.ts +27 -7
- package/dist/types/messageDelivery/MessageDeliveryReporter.d.ts +27 -80
- package/dist/types/messageDelivery/MessageReceiptsTracker.d.ts +43 -73
- package/dist/types/messageOperations/FailedSendCache.d.ts +29 -0
- package/dist/types/messageOperations/MessageOperationStatePolicy.d.ts +16 -22
- package/dist/types/messageOperations/MessageOperations.d.ts +63 -34
- package/dist/types/messageOperations/applyReactionLocally.d.ts +15 -0
- package/dist/types/messageOperations/createMessageOperations.d.ts +9 -0
- package/dist/types/messageOperations/index.d.ts +6 -4
- package/dist/types/messageOperations/reflectReactionEvent.d.ts +16 -0
- package/dist/types/messageOperations/sendOrdering.d.ts +14 -0
- package/dist/types/messageOperations/settlePendingAttachmentUploads.d.ts +20 -0
- package/dist/types/messageOperations/types.d.ts +43 -14
- package/dist/types/middleware.d.ts +10 -0
- package/dist/types/moderation.d.ts +21 -14
- package/dist/types/notifications/NotificationManager.d.ts +10 -23
- package/dist/types/notifications/types.d.ts +21 -57
- package/dist/types/offline-support/offline_support_api.d.ts +150 -528
- package/dist/types/offline-support/offline_sync_manager.d.ts +21 -42
- package/dist/types/offline-support/queueableOperations.d.ts +35 -37
- package/dist/types/offline-support/types.d.ts +40 -185
- package/dist/types/pagination/FilterBuilder.d.ts +1 -18
- package/dist/types/pagination/ItemIndex.d.ts +4 -12
- package/dist/types/pagination/cursorDerivation/aroundPaginationFlags.d.ts +13 -0
- package/dist/types/pagination/cursorDerivation/createdAtAroundPaginationFlags.d.ts +4 -5
- package/dist/types/pagination/cursorDerivation/linearPaginationFlags.d.ts +19 -5
- package/dist/types/pagination/index.d.ts +1 -0
- package/dist/types/pagination/paginators/BasePaginator.d.ts +604 -550
- package/dist/types/pagination/paginators/ChannelPaginator.d.ts +123 -106
- package/dist/types/pagination/paginators/MessageIntervalPaginator.d.ts +576 -327
- package/dist/types/pagination/paginators/MessagePaginator.d.ts +237 -131
- package/dist/types/pagination/paginators/PinnedMessagePaginator.d.ts +15 -26
- package/dist/types/pagination/paginators/ReminderPaginator.d.ts +4 -3
- package/dist/types/pagination/paginators/ThreadPaginator.d.ts +44 -0
- package/dist/types/pagination/paginators/UserGroupPaginator.d.ts +5 -8
- package/dist/types/pagination/paginators/index.d.ts +1 -0
- package/dist/types/pagination/sortCompiler.d.ts +11 -22
- package/dist/types/pagination/utility.normalization.d.ts +8 -13
- package/dist/types/pagination/utility.search.d.ts +3 -8
- package/dist/types/poll.d.ts +35 -8
- package/dist/types/poll_manager.d.ts +12 -2
- package/dist/types/poll_optimistic_votes.d.ts +57 -0
- package/dist/types/reminders/Reminder.d.ts +17 -7
- package/dist/types/reminders/ReminderManager.d.ts +13 -25
- package/dist/types/search/BaseSearchSource.d.ts +10 -8
- package/dist/types/search/ChannelSearchSource.d.ts +16 -0
- package/dist/types/search/MessageSearchSource.d.ts +17 -0
- package/dist/types/search/SearchController.d.ts +26 -28
- package/dist/types/search/types.d.ts +6 -10
- package/dist/types/signing.d.ts +12 -3
- package/dist/types/thread.d.ts +67 -129
- package/dist/types/thread_manager.d.ts +95 -66
- package/dist/types/token_manager.d.ts +8 -13
- package/dist/types/types.d.ts +81 -197
- package/dist/types/types.utility.d.ts +3 -3
- package/dist/types/upload-utils.d.ts +5 -10
- package/dist/types/uploadManager.d.ts +31 -11
- package/dist/types/utils/FixedSizeQueueCache.d.ts +8 -11
- package/dist/types/utils/WithSubscriptions.d.ts +6 -16
- package/dist/types/utils/abort.d.ts +17 -0
- package/dist/types/utils/concurrency.d.ts +12 -20
- package/dist/types/utils/mergeWith/mergeWith.d.ts +8 -11
- package/dist/types/utils/mergeWith/mergeWithCore.d.ts +5 -13
- package/dist/types/utils/mergeWith/mergeWithDiff.d.ts +22 -0
- package/dist/types/utils/objectPath.d.ts +6 -41
- package/dist/types/utils/retryable.d.ts +8 -12
- package/dist/types/utils/throttling/throttle.d.ts +8 -23
- package/dist/types/utils/time.d.ts +45 -0
- package/dist/types/utils.d.ts +74 -93
- package/package.json +14 -40
- package/src/ChannelManager.ts +494 -303
- package/src/CooldownTimer.ts +46 -59
- package/src/EventHandlerPipeline.ts +22 -45
- package/src/LiveLocationManager.ts +99 -91
- package/src/api-client.ts +113 -50
- package/src/campaign.ts +1 -1
- package/src/channel.ts +1098 -1351
- package/src/channel_batch_updater.ts +1 -1
- package/src/channel_state.ts +81 -174
- package/src/client.ts +755 -970
- package/src/client_state.ts +3 -8
- package/src/configuration/ConfigController.ts +42 -158
- package/src/configuration/InstanceConfigurationRegistry.ts +43 -172
- package/src/configuration/index.ts +1 -1
- package/src/configuration/keys.ts +13 -32
- package/src/configuration/shape.ts +169 -59
- package/src/configuration/types.ts +69 -92
- package/src/configuration/utils/applyInstanceConfiguration.ts +22 -54
- package/src/configuration/utils/copyConfigPatch.ts +11 -32
- package/src/configuration/utils/declarativeSlices.ts +9 -39
- package/src/configuration/utils/deepFreezeConfig.ts +3 -17
- package/src/configuration/utils/index.ts +2 -4
- package/src/configuration/utils/serverAuthority.ts +20 -68
- package/src/connection/ConnectionIdManager.ts +111 -0
- package/src/connection/ConnectionRecoveryManager.ts +257 -0
- package/src/connection/index.ts +4 -0
- package/src/connection/networkConnection/NetworkConnectionObserver.ts +204 -0
- package/src/connection/networkConnection/index.ts +3 -0
- package/src/connection/networkConnection/reporters.ts +58 -0
- package/src/connection/networkConnection/types.ts +45 -0
- package/src/{connection.ts → connection/wsConnection/StableWSConnection.ts} +230 -231
- package/src/connection/wsConnection/WSConnection.ts +270 -0
- package/src/connection/wsConnection/WSConnectionFallback.ts +250 -0
- package/src/connection/wsConnection/config.ts +73 -0
- package/src/connection/wsConnection/index.ts +4 -0
- package/src/connection/wsConnection/types.ts +48 -0
- package/src/constants.ts +7 -5
- package/src/custom_types.ts +0 -1
- package/src/entityStore/EntityStore.ts +415 -79
- package/src/entityStore/StoreBackedItemIndex.ts +37 -41
- package/src/entityStore/index.ts +0 -1
- package/src/errors.ts +39 -20
- package/src/formatMessageMemo.ts +17 -0
- package/src/gen/chat/ChannelApi.ts +122 -36
- package/src/gen/chat/ChatApi.ts +578 -1752
- package/src/gen/models/index.ts +2566 -3440
- package/src/gen/models/timestamp-guard.ts +27 -0
- package/src/gen/moderation/ModerationApi.ts +183 -406
- package/src/index.ts +32 -10
- package/src/languageNames.ts +88 -0
- package/src/logger.ts +1 -3
- package/src/messageComposer/CustomDataManager.ts +19 -6
- package/src/messageComposer/LocationComposer.ts +49 -9
- package/src/messageComposer/MessageComposerEffectHandlers.ts +1 -2
- package/src/messageComposer/attachmentIdentity.ts +54 -0
- package/src/messageComposer/attachmentManager.ts +170 -185
- package/src/messageComposer/attachmentUtils.ts +44 -0
- package/src/messageComposer/configuration/configuration.ts +15 -8
- package/src/messageComposer/configuration/types.ts +38 -50
- package/src/messageComposer/fileUtils.ts +1 -1
- package/src/messageComposer/index.ts +1 -0
- package/src/messageComposer/linkPreviewsManager.ts +18 -21
- package/src/messageComposer/messageComposer.ts +234 -179
- package/src/messageComposer/middleware/attachmentManager/postUpload/AttachmentPostUploadMiddlewareExecutor.ts +1 -1
- package/src/messageComposer/middleware/attachmentManager/postUpload/attachmentEnrichment.ts +46 -33
- package/src/messageComposer/middleware/attachmentManager/postUpload/uploadErrorHandler.ts +4 -1
- package/src/messageComposer/middleware/attachmentManager/preUpload/blockedUploadNotification.ts +1 -1
- package/src/messageComposer/middleware/messageComposer/MessageComposerMiddlewareExecutor.ts +6 -0
- package/src/messageComposer/middleware/messageComposer/attachments.ts +76 -5
- package/src/messageComposer/middleware/messageComposer/commandInjection.ts +10 -4
- package/src/messageComposer/middleware/messageComposer/customData.ts +17 -5
- package/src/messageComposer/middleware/messageComposer/index.ts +2 -0
- package/src/messageComposer/middleware/messageComposer/linkPreviews.ts +22 -12
- package/src/messageComposer/middleware/messageComposer/pollOnly.ts +9 -1
- package/src/messageComposer/middleware/messageComposer/sharedLocation.ts +7 -2
- package/src/messageComposer/middleware/messageComposer/textComposer.ts +1 -1
- package/src/messageComposer/middleware/messageComposer/userDataInjection.ts +12 -12
- package/src/messageComposer/middleware/pollComposer/state.ts +2 -2
- package/src/messageComposer/middleware/pollComposer/types.ts +2 -4
- package/src/messageComposer/middleware/pollComposer/validation.ts +8 -26
- package/src/messageComposer/middleware/textComposer/TextComposerMiddlewareExecutor.ts +8 -6
- package/src/messageComposer/middleware/textComposer/commandUtils.ts +10 -3
- package/src/messageComposer/middleware/textComposer/commands.ts +11 -16
- package/src/messageComposer/middleware/textComposer/mentions.ts +32 -70
- package/src/messageComposer/middleware/textComposer/textMiddlewareUtils.ts +10 -4
- package/src/messageComposer/middleware/textComposer/types.ts +1 -6
- package/src/messageComposer/pollComposer.ts +21 -9
- package/src/messageComposer/textComposer.ts +37 -57
- package/src/messageComposer/types.ts +39 -11
- package/src/messageDelivery/MessageDeliveryReporter.ts +86 -124
- package/src/messageDelivery/MessageReceiptsTracker.ts +122 -139
- package/src/messageOperations/FailedSendCache.ts +85 -0
- package/src/messageOperations/MessageOperationStatePolicy.ts +124 -116
- package/src/messageOperations/MessageOperations.ts +297 -175
- package/src/{entityStore → messageOperations}/applyReactionLocally.ts +13 -25
- package/src/messageOperations/createMessageOperations.ts +176 -0
- package/src/messageOperations/index.ts +6 -14
- package/src/messageOperations/reflectReactionEvent.ts +43 -0
- package/src/messageOperations/sendOrdering.ts +25 -0
- package/src/messageOperations/settlePendingAttachmentUploads.ts +98 -0
- package/src/messageOperations/types.ts +51 -13
- package/src/middleware.ts +13 -5
- package/src/moderation.ts +25 -21
- package/src/notifications/NotificationManager.ts +19 -28
- package/src/notifications/types.ts +21 -57
- package/src/offline-support/offline_support_api.ts +231 -681
- package/src/offline-support/offline_sync_manager.ts +51 -90
- package/src/offline-support/queueableOperations.ts +98 -73
- package/src/offline-support/types.ts +43 -185
- package/src/pagination/FilterBuilder.ts +1 -22
- package/src/pagination/ItemIndex.ts +4 -12
- package/src/pagination/cursorDerivation/aroundPaginationFlags.ts +29 -0
- package/src/pagination/cursorDerivation/createdAtAroundPaginationFlags.ts +17 -62
- package/src/pagination/cursorDerivation/idAroundPaginationFlags.ts +11 -39
- package/src/pagination/cursorDerivation/linearPaginationFlags.ts +53 -33
- package/src/pagination/filterCompiler.ts +11 -25
- package/src/pagination/index.ts +1 -0
- package/src/pagination/paginators/BasePaginator.ts +1415 -1041
- package/src/pagination/paginators/ChannelPaginator.ts +481 -219
- package/src/pagination/paginators/MessageIntervalPaginator.ts +1362 -775
- package/src/pagination/paginators/MessagePaginator.ts +521 -240
- package/src/pagination/paginators/PinnedMessagePaginator.ts +32 -40
- package/src/pagination/paginators/ReminderPaginator.ts +21 -16
- package/src/pagination/paginators/ThreadPaginator.ts +170 -0
- package/src/pagination/paginators/UserGroupPaginator.ts +18 -15
- package/src/pagination/paginators/index.ts +1 -0
- package/src/pagination/paginators/stateThrottling.ts +5 -10
- package/src/pagination/sortCompiler.ts +23 -50
- package/src/pagination/utility.normalization.ts +17 -24
- package/src/pagination/utility.search.ts +4 -11
- package/src/poll.ts +183 -102
- package/src/poll_manager.ts +24 -22
- package/src/poll_optimistic_votes.ts +335 -0
- package/src/reminders/Reminder.ts +33 -16
- package/src/reminders/ReminderManager.ts +23 -56
- package/src/reminders/ReminderTimer.ts +6 -6
- package/src/search/BaseSearchSource.ts +19 -25
- package/src/search/ChannelSearchSource.ts +43 -1
- package/src/search/MessageSearchSource.ts +77 -13
- package/src/search/SearchController.ts +39 -36
- package/src/search/types.ts +6 -10
- package/src/segment.ts +1 -1
- package/src/signing.ts +23 -3
- package/src/thread.ts +430 -712
- package/src/thread_manager.ts +300 -234
- package/src/token_manager.ts +12 -22
- package/src/types.ts +102 -214
- package/src/types.utility.ts +3 -3
- package/src/upload-utils.ts +5 -10
- package/src/uploadManager.ts +64 -18
- package/src/utils/FixedSizeQueueCache.ts +18 -21
- package/src/utils/WithSubscriptions.ts +6 -16
- package/src/utils/abort.ts +45 -0
- package/src/utils/concurrency.ts +16 -55
- package/src/utils/mergeWith/mergeWith.ts +10 -13
- package/src/utils/mergeWith/mergeWithCore.ts +24 -81
- package/src/utils/mergeWith/mergeWithDiff.ts +15 -33
- package/src/utils/objectPath.ts +6 -41
- package/src/utils/retryable.ts +10 -14
- package/src/utils/throttling/throttle.ts +9 -25
- package/src/utils/time.ts +64 -0
- package/src/utils.ts +227 -174
- package/codegen/i18n/callSites.ts +0 -126
- package/codegen/i18n/generate.ts +0 -226
- package/codegen/i18n/guards.ts +0 -178
- package/codegen/i18n/index.ts +0 -29
- package/codegen/i18n/stringMaps.ts +0 -91
- package/codegen/i18n/types.ts +0 -100
- package/dist/cjs/i18n.browser.js +0 -1131
- package/dist/cjs/i18n.browser.js.map +0 -7
- package/dist/cjs/i18n.node.js +0 -1160
- package/dist/cjs/i18n.node.js.map +0 -7
- package/dist/esm/i18n-codegen.mjs +0 -409
- package/dist/esm/i18n-codegen.mjs.map +0 -7
- package/dist/esm/i18n.mjs +0 -1098
- package/dist/esm/i18n.mjs.map +0 -7
- package/dist/types/ConnectionRecoveryManager.d.ts +0 -156
- package/dist/types/connection.d.ts +0 -139
- package/dist/types/entityStore/applyReactionLocally.d.ts +0 -26
- package/dist/types/gen/model-decoders/decoders.d.ts +0 -3
- package/dist/types/gen/model-decoders/event-decoder-mapping.d.ts +0 -6
- package/dist/types/i18n/Streami18n.d.ts +0 -168
- package/dist/types/i18n/TranslationBuilder.d.ts +0 -70
- package/dist/types/i18n/TranslationStore.d.ts +0 -57
- package/dist/types/i18n/dayjs.d.ts +0 -104
- package/dist/types/i18n/formatters.d.ts +0 -91
- package/dist/types/i18n/index.d.ts +0 -15
- package/dist/types/i18n/translator.d.ts +0 -29
- package/dist/types/i18n/types.d.ts +0 -262
- package/dist/types/i18n-codegen/callSites.d.ts +0 -10
- package/dist/types/i18n-codegen/generate.d.ts +0 -15
- package/dist/types/i18n-codegen/guards.d.ts +0 -61
- package/dist/types/i18n-codegen/index.d.ts +0 -29
- package/dist/types/i18n-codegen/stringMaps.d.ts +0 -14
- package/dist/types/i18n-codegen/types.d.ts +0 -94
- package/dist/types/insights.d.ts +0 -56
- package/dist/types/messageOperations/optimistic.d.ts +0 -118
- package/dist/types/messageOperations/persistence.d.ts +0 -21
- package/dist/types/pagination/utility.queryChannel.d.ts +0 -26
- package/dist/types/store.d.ts +0 -125
- package/src/ConnectionRecoveryManager.ts +0 -293
- package/src/gen/model-decoders/decoders.ts +0 -2710
- package/src/gen/model-decoders/event-decoder-mapping.ts +0 -198
- package/src/i18n/Streami18n.ts +0 -520
- package/src/i18n/TranslationBuilder.ts +0 -176
- package/src/i18n/TranslationStore.ts +0 -96
- package/src/i18n/dayjs.ts +0 -228
- package/src/i18n/formatters.ts +0 -461
- package/src/i18n/index.ts +0 -15
- package/src/i18n/languageNames.ts +0 -103
- package/src/i18n/translator.ts +0 -76
- package/src/i18n/types.ts +0 -375
- package/src/insights.ts +0 -82
- package/src/messageOperations/optimistic.ts +0 -249
- package/src/messageOperations/persistence.ts +0 -40
- package/src/pagination/utility.queryChannel.ts +0 -84
- package/src/store.ts +0 -304
package/src/i18n/Streami18n.ts
DELETED
|
@@ -1,520 +0,0 @@
|
|
|
1
|
-
import i18next from 'i18next';
|
|
2
|
-
import type { i18n as I18nInstance, InitOptions } from 'i18next';
|
|
3
|
-
|
|
4
|
-
import { StateStore } from '../store';
|
|
5
|
-
import {
|
|
6
|
-
addOrUpdateDayjsLocale,
|
|
7
|
-
dayjsLocaleExists,
|
|
8
|
-
ensureDayjsPlugins,
|
|
9
|
-
getDefaultDateTimeParserModule,
|
|
10
|
-
isDayjsLike,
|
|
11
|
-
supportsTimezone,
|
|
12
|
-
} from './dayjs';
|
|
13
|
-
import type { DayjsLocaleConfig } from './dayjs';
|
|
14
|
-
import { predefinedFormatters } from './formatters';
|
|
15
|
-
import { TranslationBuilder } from './TranslationBuilder';
|
|
16
|
-
import type { TranslationTopicConstructor } from './TranslationBuilder';
|
|
17
|
-
import { DEFAULT_LANGUAGE, TranslationStore } from './TranslationStore';
|
|
18
|
-
import {
|
|
19
|
-
asDynamicKey,
|
|
20
|
-
createDefaultTranslatorFunction,
|
|
21
|
-
guardMissingKeyHandler,
|
|
22
|
-
} from './translator';
|
|
23
|
-
import type {
|
|
24
|
-
AnyTranslationCatalog,
|
|
25
|
-
CustomFormatters,
|
|
26
|
-
DateTimeParserModule,
|
|
27
|
-
FormatterContext,
|
|
28
|
-
LooseTranslateFunction,
|
|
29
|
-
PredefinedFormatters,
|
|
30
|
-
StreamTFunctionFor,
|
|
31
|
-
TDateTimeParser,
|
|
32
|
-
TranslationDictionaryOf,
|
|
33
|
-
} from './types';
|
|
34
|
-
|
|
35
|
-
const DEFAULT_NAMESPACE = 'translation';
|
|
36
|
-
|
|
37
|
-
export type Streami18nOptions<C extends AnyTranslationCatalog = AnyTranslationCatalog> = {
|
|
38
|
-
/** A dayjs or moment module. Defaults to dayjs with the required plugins registered. */
|
|
39
|
-
DateTimeParser?: DateTimeParserModule;
|
|
40
|
-
dayjsLocaleConfigForLanguage?: DayjsLocaleConfig;
|
|
41
|
-
debug?: boolean;
|
|
42
|
-
/** Keep dates in English regardless of the active language. */
|
|
43
|
-
disableDateTimeTranslations?: boolean;
|
|
44
|
-
formatters?: Partial<PredefinedFormatters> & CustomFormatters;
|
|
45
|
-
/**
|
|
46
|
-
* Any i18next `InitOptions`. Applied over the SDK's defaults, so it can reach settings the SDK does
|
|
47
|
-
* not surface. `parseMissingKeyHandler` supplied here is guarded the same way as the top-level
|
|
48
|
-
* option.
|
|
49
|
-
*/
|
|
50
|
-
i18nextConfigOverrides?: Partial<InitOptions>;
|
|
51
|
-
language?: string;
|
|
52
|
-
logger?: (message?: string) => void;
|
|
53
|
-
/**
|
|
54
|
-
* Called only for keys that are genuinely missing — one with no inline default and no bundled
|
|
55
|
-
* value. See {@link guardMissingKeyHandler} for why it cannot be passed straight to i18next.
|
|
56
|
-
*/
|
|
57
|
-
parseMissingKeyHandler?: (key: string, defaultValue?: string) => string;
|
|
58
|
-
/**
|
|
59
|
-
* The SDK's bundled translation data: the keys that cannot carry an inline `defaultValue` at their
|
|
60
|
-
* call site.
|
|
61
|
-
*
|
|
62
|
-
* Injected rather than imported because the catalog belongs to the UI SDK, not to core. Layered
|
|
63
|
-
* under **every** language, which is what stops a partial dictionary from knocking out formatter
|
|
64
|
-
* keys.
|
|
65
|
-
*/
|
|
66
|
-
runtimeDefaults?: Record<string, string>;
|
|
67
|
-
/** A valid TZ identifier, e.g. `Europe/Prague`. */
|
|
68
|
-
timezone?: string;
|
|
69
|
-
/**
|
|
70
|
-
* Post-processor topics for copy that cannot be resolved from a key alone — see
|
|
71
|
-
* {@link TranslationBuilder}. The key here must match the post-processor name in the translation
|
|
72
|
-
* value, i.e. `{{ value, topicName }}`.
|
|
73
|
-
*/
|
|
74
|
-
translationBuilderTopics?: Record<string, TranslationTopicConstructor>;
|
|
75
|
-
translationsForLanguage?: TranslationDictionaryOf<C>;
|
|
76
|
-
};
|
|
77
|
-
|
|
78
|
-
export type Streami18nState<
|
|
79
|
-
C extends AnyTranslationCatalog = AnyTranslationCatalog,
|
|
80
|
-
Bundled extends string = never,
|
|
81
|
-
> = {
|
|
82
|
-
initialized: boolean;
|
|
83
|
-
language: string;
|
|
84
|
-
t: StreamTFunctionFor<C, Bundled>;
|
|
85
|
-
tDateTimeParser: TDateTimeParser;
|
|
86
|
-
};
|
|
87
|
-
|
|
88
|
-
/**
|
|
89
|
-
* Wrapper around [i18next](https://www.i18next.com/) for Stream's translations. A UI SDK passes an
|
|
90
|
-
* instance to its `<Chat>` component to control language and copy. Only English ships; every other
|
|
91
|
-
* language comes from the integrator, and a partial dictionary is safe.
|
|
92
|
-
*
|
|
93
|
-
* ```ts
|
|
94
|
-
* import 'dayjs/locale/de';
|
|
95
|
-
*
|
|
96
|
-
* const i18n = new Streami18n({ language: 'de' });
|
|
97
|
-
* i18n.registerTranslation('de', de, { calendar: { sameDay: '[heute um] LT', ... } });
|
|
98
|
-
* ```
|
|
99
|
-
*
|
|
100
|
-
* No dayjs locale file defines `calendar` — that field belongs to the calendar plugin — so a new
|
|
101
|
-
* language needs both the locale import and a `calendar` config, or relative dates render English
|
|
102
|
-
* scaffolding around translated day names.
|
|
103
|
-
*/
|
|
104
|
-
export class Streami18n<
|
|
105
|
-
C extends AnyTranslationCatalog = AnyTranslationCatalog,
|
|
106
|
-
Bundled extends string = never,
|
|
107
|
-
> {
|
|
108
|
-
readonly i18nInstance: I18nInstance = i18next.createInstance();
|
|
109
|
-
|
|
110
|
-
readonly state: StateStore<Streami18nState<C, Bundled>>;
|
|
111
|
-
|
|
112
|
-
readonly translationBuilder: TranslationBuilder;
|
|
113
|
-
|
|
114
|
-
readonly logger: (message?: string) => void;
|
|
115
|
-
readonly DateTimeParser: DateTimeParserModule;
|
|
116
|
-
readonly formatters: PredefinedFormatters & CustomFormatters;
|
|
117
|
-
readonly timezone?: string;
|
|
118
|
-
|
|
119
|
-
private readonly translations: TranslationStore;
|
|
120
|
-
|
|
121
|
-
/** Applied when the language becomes active, not on registration: `Dayjs.locale()` is global. */
|
|
122
|
-
private readonly dayjsLocales: Record<string, DayjsLocaleConfig> = {};
|
|
123
|
-
|
|
124
|
-
private readonly translationBuilderTopics: Record<string, TranslationTopicConstructor>;
|
|
125
|
-
private readonly disableDateTimeTranslations: boolean;
|
|
126
|
-
private readonly i18nextConfig: InitOptions;
|
|
127
|
-
private initPromise?: Promise<Streami18nState<C, Bundled>>;
|
|
128
|
-
/** Set by {@link overrideTFunction}, so `init()` does not clobber a swapped-in implementation. */
|
|
129
|
-
private tOverridden = false;
|
|
130
|
-
|
|
131
|
-
constructor(options: Streami18nOptions<C> = {}) {
|
|
132
|
-
this.logger = options.logger ?? ((message?: string) => console.warn(message));
|
|
133
|
-
this.translations = new TranslationStore(options.runtimeDefaults);
|
|
134
|
-
this.disableDateTimeTranslations = options.disableDateTimeTranslations ?? false;
|
|
135
|
-
this.timezone = options.timezone;
|
|
136
|
-
this.formatters = { ...predefinedFormatters, ...options.formatters };
|
|
137
|
-
this.translationBuilder = new TranslationBuilder(this.i18nInstance);
|
|
138
|
-
this.translationBuilderTopics = options.translationBuilderTopics ?? {};
|
|
139
|
-
|
|
140
|
-
const language = options.language ?? DEFAULT_LANGUAGE;
|
|
141
|
-
|
|
142
|
-
if (options.DateTimeParser) {
|
|
143
|
-
this.DateTimeParser = options.DateTimeParser;
|
|
144
|
-
// The supplied module, not ours -- it may be a second copy of dayjs, and extending ours would
|
|
145
|
-
// leave theirs plugin-less, rendering every `LT` / `LLLL` token literally.
|
|
146
|
-
if (isDayjsLike(this.DateTimeParser)) ensureDayjsPlugins(this.DateTimeParser);
|
|
147
|
-
} else {
|
|
148
|
-
this.DateTimeParser = getDefaultDateTimeParserModule();
|
|
149
|
-
}
|
|
150
|
-
|
|
151
|
-
const tDateTimeParser: TDateTimeParser = (timestamp) => {
|
|
152
|
-
const locale =
|
|
153
|
-
this.disableDateTimeTranslations || !this.localeExists(this.currentLanguageValue)
|
|
154
|
-
? DEFAULT_LANGUAGE
|
|
155
|
-
: this.currentLanguageValue;
|
|
156
|
-
|
|
157
|
-
const parsed = this.DateTimeParser(timestamp);
|
|
158
|
-
const withZone =
|
|
159
|
-
this.timezone && supportsTimezone(this.DateTimeParser)
|
|
160
|
-
? (parsed as unknown as { tz: (tz: string) => typeof parsed }).tz(this.timezone)
|
|
161
|
-
: parsed;
|
|
162
|
-
|
|
163
|
-
return (withZone as unknown as { locale: (l: string) => typeof parsed }).locale(
|
|
164
|
-
locale,
|
|
165
|
-
);
|
|
166
|
-
};
|
|
167
|
-
|
|
168
|
-
this.state = new StateStore<Streami18nState<C, Bundled>>({
|
|
169
|
-
initialized: false,
|
|
170
|
-
language,
|
|
171
|
-
t: createDefaultTranslatorFunction<C, Bundled>(),
|
|
172
|
-
tDateTimeParser,
|
|
173
|
-
});
|
|
174
|
-
|
|
175
|
-
// Both always exist, so an unregistered language still renders English copy rather than dotted keys.
|
|
176
|
-
this.translations.ensure(DEFAULT_LANGUAGE);
|
|
177
|
-
this.translations.ensure(language);
|
|
178
|
-
|
|
179
|
-
if (options.translationsForLanguage) {
|
|
180
|
-
this.translations.register(
|
|
181
|
-
language,
|
|
182
|
-
options.translationsForLanguage as Record<string, string>,
|
|
183
|
-
);
|
|
184
|
-
}
|
|
185
|
-
|
|
186
|
-
const missingKeyHandler =
|
|
187
|
-
options.parseMissingKeyHandler ??
|
|
188
|
-
options.i18nextConfigOverrides?.parseMissingKeyHandler;
|
|
189
|
-
|
|
190
|
-
this.i18nextConfig = {
|
|
191
|
-
debug: options.debug ?? false,
|
|
192
|
-
fallbackLng: false,
|
|
193
|
-
interpolation: { escapeValue: false, formatSeparator: '|' },
|
|
194
|
-
// Must stay false: keys are flat strings containing dots, and some copy contains `...`.
|
|
195
|
-
keySeparator: false,
|
|
196
|
-
lng: language,
|
|
197
|
-
nsSeparator: false,
|
|
198
|
-
// i18next only runs post-processors it was told about at init time.
|
|
199
|
-
...(Object.keys(this.translationBuilderTopics).length > 0
|
|
200
|
-
? { postProcess: Object.keys(this.translationBuilderTopics) }
|
|
201
|
-
: {}),
|
|
202
|
-
...options.i18nextConfigOverrides,
|
|
203
|
-
// Guarded even when integrator-supplied: an unguarded handler silently blanks every prose key.
|
|
204
|
-
parseMissingKeyHandler: missingKeyHandler
|
|
205
|
-
? guardMissingKeyHandler(missingKeyHandler)
|
|
206
|
-
: (key: string, defaultValue?: string) => {
|
|
207
|
-
if (typeof defaultValue === 'string') return defaultValue;
|
|
208
|
-
this.logger(`Streami18n: missing translation for key: ${key}`);
|
|
209
|
-
return key;
|
|
210
|
-
},
|
|
211
|
-
};
|
|
212
|
-
|
|
213
|
-
// No dictionary check here -- `registerTranslation()` legitimately runs after construction, so
|
|
214
|
-
// `init()` is the first moment the registered set is final.
|
|
215
|
-
if (options.dayjsLocaleConfigForLanguage) {
|
|
216
|
-
this.addOrUpdateLocale(language, options.dayjsLocaleConfigForLanguage);
|
|
217
|
-
} else if (!this.localeExists(language)) {
|
|
218
|
-
this.logger(
|
|
219
|
-
`Streami18n: no dayjs locale is registered for '${language}', so dates render with the ` +
|
|
220
|
-
`English locale. Import it with "import 'dayjs/locale/${language}';" in your app, or pass ` +
|
|
221
|
-
`a config via registerTranslation('${language}', translation, dayjsLocaleConfig).`,
|
|
222
|
-
);
|
|
223
|
-
}
|
|
224
|
-
}
|
|
225
|
-
|
|
226
|
-
get t(): StreamTFunctionFor<C, Bundled> {
|
|
227
|
-
return this.state.getLatestValue().t;
|
|
228
|
-
}
|
|
229
|
-
|
|
230
|
-
get tDateTimeParser(): TDateTimeParser {
|
|
231
|
-
return this.state.getLatestValue().tDateTimeParser;
|
|
232
|
-
}
|
|
233
|
-
|
|
234
|
-
get currentLanguage(): string {
|
|
235
|
-
return this.state.getLatestValue().language;
|
|
236
|
-
}
|
|
237
|
-
|
|
238
|
-
get initialized(): boolean {
|
|
239
|
-
return this.state.getLatestValue().initialized;
|
|
240
|
-
}
|
|
241
|
-
|
|
242
|
-
/** Read inside the constructor, before `state` getters are safe to rely on externally. */
|
|
243
|
-
private get currentLanguageValue(): string {
|
|
244
|
-
return this.state?.getLatestValue().language ?? DEFAULT_LANGUAGE;
|
|
245
|
-
}
|
|
246
|
-
|
|
247
|
-
/**
|
|
248
|
-
* Initializes i18next. Memoized, so concurrent callers share one initialization.
|
|
249
|
-
*
|
|
250
|
-
* **Rejects on failure**, so handle it. The instance stays usable either way: `initialized` stays
|
|
251
|
-
* false, keeping {@link Streami18n.registerTranslation} and {@link Streami18n.setLanguage} off a
|
|
252
|
-
* dead i18next instance, and `t` keeps returning each call site's inline English.
|
|
253
|
-
*/
|
|
254
|
-
init(): Promise<Streami18nState<C, Bundled>> {
|
|
255
|
-
if (this.initPromise) return this.initPromise;
|
|
256
|
-
|
|
257
|
-
const pending = this.runInit();
|
|
258
|
-
this.initPromise = pending;
|
|
259
|
-
|
|
260
|
-
// Clear the memo so a later call retries. Attached to a derived promise, so `pending` stays
|
|
261
|
-
// unhandled and still reaches the caller's `catch`.
|
|
262
|
-
pending.catch(() => {
|
|
263
|
-
if (this.initPromise === pending) this.initPromise = undefined;
|
|
264
|
-
});
|
|
265
|
-
|
|
266
|
-
return pending;
|
|
267
|
-
}
|
|
268
|
-
|
|
269
|
-
private async runInit(): Promise<Streami18nState<C, Bundled>> {
|
|
270
|
-
this.validateCurrentLanguage();
|
|
271
|
-
this.assertPluralRulesCoverage(this.currentLanguage);
|
|
272
|
-
|
|
273
|
-
const dayjsLocale = this.dayjsLocales[this.currentLanguage];
|
|
274
|
-
if (dayjsLocale) this.addOrUpdateLocale(this.currentLanguage, dayjsLocale);
|
|
275
|
-
|
|
276
|
-
const t = await this.i18nInstance.init({
|
|
277
|
-
...this.i18nextConfig,
|
|
278
|
-
lng: this.currentLanguage,
|
|
279
|
-
resources: this.i18nextResources(),
|
|
280
|
-
});
|
|
281
|
-
|
|
282
|
-
this.registerFormatters();
|
|
283
|
-
|
|
284
|
-
// After init, so post-processors attach to a live instance and buffered translators flush.
|
|
285
|
-
Object.entries(this.translationBuilderTopics).forEach(([topic, Topic]) => {
|
|
286
|
-
this.translationBuilder.registerTopic(topic, Topic);
|
|
287
|
-
});
|
|
288
|
-
|
|
289
|
-
this.state.partialNext({
|
|
290
|
-
initialized: true,
|
|
291
|
-
...(this.tOverridden ? {} : { t: t as unknown as StreamTFunctionFor<C, Bundled> }),
|
|
292
|
-
});
|
|
293
|
-
|
|
294
|
-
return this.state.getLatestValue();
|
|
295
|
-
}
|
|
296
|
-
|
|
297
|
-
/**
|
|
298
|
-
* Re-run on every language change, not just at `init()`: factories destructure the language out of
|
|
299
|
-
* their context, so one built once keeps formatting in the initial language forever. `formatter.add`
|
|
300
|
-
* replaces by name, which is what makes re-registering sufficient.
|
|
301
|
-
*/
|
|
302
|
-
private registerFormatters = () => {
|
|
303
|
-
const context = this.createFormatterContext();
|
|
304
|
-
|
|
305
|
-
Object.entries(this.formatters).forEach(([name, factory]) => {
|
|
306
|
-
if (!factory) return;
|
|
307
|
-
const formatter = factory(context);
|
|
308
|
-
// Widened here rather than in the public type: a custom formatter's value is `never` so any
|
|
309
|
-
// implementation is assignable (parameters are contravariant), while i18next's takes `any`.
|
|
310
|
-
this.i18nInstance.services.formatter?.add(
|
|
311
|
-
name,
|
|
312
|
-
formatter as (value: any, lng: string | undefined, options: any) => string,
|
|
313
|
-
);
|
|
314
|
-
});
|
|
315
|
-
};
|
|
316
|
-
|
|
317
|
-
/**
|
|
318
|
-
* Accessors rather than snapshots, for a formatter that holds the context and reads per call; one
|
|
319
|
-
* that destructures is covered by {@link registerFormatters} re-running instead.
|
|
320
|
-
*
|
|
321
|
-
* The nested arrows are load-bearing: a getter in an object literal binds `this` to the literal.
|
|
322
|
-
*/
|
|
323
|
-
private createFormatterContext = (): FormatterContext => {
|
|
324
|
-
const readLanguage = () => this.currentLanguage;
|
|
325
|
-
const readDateTimeParser = () => this.tDateTimeParser;
|
|
326
|
-
|
|
327
|
-
return {
|
|
328
|
-
get currentLanguage() {
|
|
329
|
-
return readLanguage();
|
|
330
|
-
},
|
|
331
|
-
dateTimeParser: this.DateTimeParser,
|
|
332
|
-
logger: this.logger,
|
|
333
|
-
get tDateTimeParser() {
|
|
334
|
-
return readDateTimeParser();
|
|
335
|
-
},
|
|
336
|
-
timezone: this.timezone,
|
|
337
|
-
translate: this.translate,
|
|
338
|
-
};
|
|
339
|
-
};
|
|
340
|
-
|
|
341
|
-
/** The store's flat dictionaries in i18next's nested `resources` shape. */
|
|
342
|
-
private i18nextResources = (): Record<string, Record<string, Record<string, string>>> =>
|
|
343
|
-
Object.fromEntries(
|
|
344
|
-
this.translations
|
|
345
|
-
.entries()
|
|
346
|
-
.map(([language, dictionary]) => [language, { [DEFAULT_NAMESPACE]: dictionary }]),
|
|
347
|
-
);
|
|
348
|
-
|
|
349
|
-
/** The only route for a language added after `init()`. */
|
|
350
|
-
private ensureLanguage = (language: string) => {
|
|
351
|
-
this.addResources(language, this.translations.ensure(language));
|
|
352
|
-
};
|
|
353
|
-
|
|
354
|
-
private addResources = (language: string, dictionary: Record<string, string>) => {
|
|
355
|
-
if (!this.initialized) return;
|
|
356
|
-
this.i18nInstance.addResources(language, DEFAULT_NAMESPACE, dictionary);
|
|
357
|
-
};
|
|
358
|
-
|
|
359
|
-
registerTranslation(
|
|
360
|
-
language: string,
|
|
361
|
-
translation: TranslationDictionaryOf<C>,
|
|
362
|
-
dayjsLocaleConfig?: DayjsLocaleConfig,
|
|
363
|
-
) {
|
|
364
|
-
if (!translation) {
|
|
365
|
-
this.logger(
|
|
366
|
-
'Streami18n: registerTranslation called without a translation dictionary',
|
|
367
|
-
);
|
|
368
|
-
return;
|
|
369
|
-
}
|
|
370
|
-
|
|
371
|
-
const merged = this.translations.register(
|
|
372
|
-
language,
|
|
373
|
-
translation as Record<string, string>,
|
|
374
|
-
);
|
|
375
|
-
|
|
376
|
-
if (dayjsLocaleConfig) {
|
|
377
|
-
this.dayjsLocales[language] = { ...dayjsLocaleConfig };
|
|
378
|
-
} else if (!this.localeExists(language)) {
|
|
379
|
-
this.logger(
|
|
380
|
-
`Streami18n: no dayjs locale is registered for '${language}'. Import it with ` +
|
|
381
|
-
`"import 'dayjs/locale/${language}';" in your app, or pass a config as the third ` +
|
|
382
|
-
`argument to registerTranslation.`,
|
|
383
|
-
);
|
|
384
|
-
}
|
|
385
|
-
|
|
386
|
-
// `merged`, not `translation`: for a post-init language this is the only write into i18next's
|
|
387
|
-
// store, so the partial would leave the bundled defaults absent there.
|
|
388
|
-
this.addResources(language, merged);
|
|
389
|
-
}
|
|
390
|
-
|
|
391
|
-
/**
|
|
392
|
-
* Returns nothing: the new `t` is published to {@link Streami18n.state}. Handing one back would offer
|
|
393
|
-
* a value that goes stale on the next language change.
|
|
394
|
-
*/
|
|
395
|
-
async setLanguage(language: string): Promise<void> {
|
|
396
|
-
const previousLanguage = this.state.getLatestValue().language;
|
|
397
|
-
|
|
398
|
-
// Published up front so the warnings below name the language being adopted, and rolled back in the
|
|
399
|
-
// `catch` -- otherwise the store advertises one i18next never switched to.
|
|
400
|
-
this.state.partialNext({ language });
|
|
401
|
-
this.ensureLanguage(language);
|
|
402
|
-
|
|
403
|
-
if (!this.initialized) return;
|
|
404
|
-
|
|
405
|
-
this.validateCurrentLanguage();
|
|
406
|
-
this.assertPluralRulesCoverage(language);
|
|
407
|
-
|
|
408
|
-
try {
|
|
409
|
-
const t = await this.i18nInstance.changeLanguage(language);
|
|
410
|
-
const dayjsLocale = this.dayjsLocales[language];
|
|
411
|
-
if (dayjsLocale) this.addOrUpdateLocale(language, dayjsLocale);
|
|
412
|
-
this.registerFormatters();
|
|
413
|
-
if (!this.tOverridden) {
|
|
414
|
-
this.state.partialNext({ t: t as unknown as StreamTFunctionFor<C, Bundled> });
|
|
415
|
-
}
|
|
416
|
-
} catch (error) {
|
|
417
|
-
this.state.partialNext({ language: previousLanguage });
|
|
418
|
-
this.logger(`Streami18n: failed to set language: ${describeError(error)}`);
|
|
419
|
-
}
|
|
420
|
-
}
|
|
421
|
-
|
|
422
|
-
/**
|
|
423
|
-
* Swaps in a different translation implementation, for an app that already has an i18n layer. Safe
|
|
424
|
-
* before `init()`, which will not overwrite it.
|
|
425
|
-
*/
|
|
426
|
-
overrideTFunction(t: StreamTFunctionFor<C, Bundled>) {
|
|
427
|
-
this.tOverridden = true;
|
|
428
|
-
this.state.partialNext({ t });
|
|
429
|
-
}
|
|
430
|
-
|
|
431
|
-
/**
|
|
432
|
-
* Languages an integrator supplied a dictionary for. Read-only because adding to it would claim a
|
|
433
|
-
* language is registered with no dictionary behind it; use `registerTranslation`.
|
|
434
|
-
*/
|
|
435
|
-
get registeredLanguages(): ReadonlySet<string> {
|
|
436
|
-
return this.translations.registeredLanguages;
|
|
437
|
-
}
|
|
438
|
-
|
|
439
|
-
/**
|
|
440
|
-
* Warns rather than falling back to `en`: the language renders English copy from the inline defaults
|
|
441
|
-
* while keeping its own date formats, and resetting it would discard the integrator's choice.
|
|
442
|
-
*/
|
|
443
|
-
private validateCurrentLanguage = () => {
|
|
444
|
-
const language = this.currentLanguageValue;
|
|
445
|
-
if (this.translations.isRegistered(language)) return;
|
|
446
|
-
|
|
447
|
-
this.logger(
|
|
448
|
-
`Streami18n: no translation dictionary is registered for '${language}', so the SDK's copy ` +
|
|
449
|
-
`renders in English. Call registerTranslation('${language}', {...}) to translate it. ` +
|
|
450
|
-
`Registered: ${[...this.translations.registeredLanguages].join(', ')}`,
|
|
451
|
-
);
|
|
452
|
-
};
|
|
453
|
-
|
|
454
|
-
/**
|
|
455
|
-
* Checked against the module that actually formats the dates.
|
|
456
|
-
*
|
|
457
|
-
* A supplied dayjs copy has its own locale registry, so consulting ours would answer for the wrong
|
|
458
|
-
* one. True for a non-dayjs parser, whose registry we cannot inspect.
|
|
459
|
-
*/
|
|
460
|
-
private localeExists = (language: string) => {
|
|
461
|
-
if (!isDayjsLike(this.DateTimeParser)) return true;
|
|
462
|
-
return dayjsLocaleExists(language, this.DateTimeParser);
|
|
463
|
-
};
|
|
464
|
-
|
|
465
|
-
/**
|
|
466
|
-
* Registers a locale on the module that formats the dates, not on ours.
|
|
467
|
-
*
|
|
468
|
-
* Only dayjs has a registry we can write to. For a Moment the config cannot be applied at all, so it
|
|
469
|
-
* is reported -- previously it was written to core's own dayjs, where nothing would ever read it.
|
|
470
|
-
*/
|
|
471
|
-
private addOrUpdateLocale(language: string, config: DayjsLocaleConfig) {
|
|
472
|
-
if (!isDayjsLike(this.DateTimeParser)) {
|
|
473
|
-
this.logger(
|
|
474
|
-
`Streami18n: a dayjs locale config was supplied for '${language}', but DateTimeParser is ` +
|
|
475
|
-
`not dayjs, so it cannot be applied. Configure the locale on your own date library instead.`,
|
|
476
|
-
);
|
|
477
|
-
return;
|
|
478
|
-
}
|
|
479
|
-
addOrUpdateDayjsLocale(language, config, this.DateTimeParser);
|
|
480
|
-
}
|
|
481
|
-
|
|
482
|
-
/**
|
|
483
|
-
* For formatters, which resolve keys handed to them at runtime -- including their own
|
|
484
|
-
* `relativeTime.*` copy, which no catalog declares.
|
|
485
|
-
*/
|
|
486
|
-
private translate: LooseTranslateFunction = (key, defaultValueOrOptions, options) =>
|
|
487
|
-
(this.t as LooseTranslateFunction)(
|
|
488
|
-
asDynamicKey(key),
|
|
489
|
-
defaultValueOrOptions,
|
|
490
|
-
options,
|
|
491
|
-
) as string;
|
|
492
|
-
|
|
493
|
-
/**
|
|
494
|
-
* Hermes ships a partial ICU: `Intl.PluralRules` silently falls back to root rules (`other` only) for
|
|
495
|
-
* locales it lacks, so a dictionary's `_few` / `_many` never render and nothing errors.
|
|
496
|
-
*
|
|
497
|
-
* Called from `init()` because i18next caches a resolver per language there — the last moment
|
|
498
|
-
* `intl-pluralrules` could still have been loaded in time.
|
|
499
|
-
*/
|
|
500
|
-
private assertPluralRulesCoverage = (language: string) => {
|
|
501
|
-
try {
|
|
502
|
-
const resolved = new Intl.PluralRules(language).resolvedOptions().locale;
|
|
503
|
-
if (resolved.split('-')[0] === language.split('-')[0]) return;
|
|
504
|
-
this.logger(
|
|
505
|
-
`Streami18n: Intl.PluralRules has no data for '${language}' (it resolved to ` +
|
|
506
|
-
`'${resolved}'), so every count selects the '_other' form. On React Native, import ` +
|
|
507
|
-
`'intl-pluralrules' before anything else in your entry file.`,
|
|
508
|
-
);
|
|
509
|
-
} catch {
|
|
510
|
-
this.logger(
|
|
511
|
-
`Streami18n: Intl.PluralRules is unavailable, so plural selection will not work. On React ` +
|
|
512
|
-
`Native, import 'intl-pluralrules' before anything else in your entry file.`,
|
|
513
|
-
);
|
|
514
|
-
}
|
|
515
|
-
};
|
|
516
|
-
}
|
|
517
|
-
|
|
518
|
-
/** `JSON.stringify(error)` renders an `Error` as `{}`. */
|
|
519
|
-
const describeError = (error: unknown) =>
|
|
520
|
-
error instanceof Error ? error.message : String(error);
|
|
@@ -1,176 +0,0 @@
|
|
|
1
|
-
import type { i18n as I18nInstance } from 'i18next';
|
|
2
|
-
|
|
3
|
-
/**
|
|
4
|
-
* An i18next instance, as accepted by {@link TranslationTopic} and exposed as
|
|
5
|
-
* `Streami18n.i18nInstance`.
|
|
6
|
-
*
|
|
7
|
-
* Re-exported because it is part of this module's public surface: a consumer implementing a topic, or
|
|
8
|
-
* mocking one in a test, has to be able to name the type. Without this they would reach past
|
|
9
|
-
* `stream-chat` into `i18next` directly and have to declare it themselves — the same mistake the
|
|
10
|
-
* `moment-timezone` type leak was.
|
|
11
|
-
*/
|
|
12
|
-
export type { I18nInstance };
|
|
13
|
-
|
|
14
|
-
import type { LooseTranslateFunction } from './types';
|
|
15
|
-
|
|
16
|
-
/**
|
|
17
|
-
* i18next post-processor plumbing, for copy that cannot be resolved from a key alone.
|
|
18
|
-
*
|
|
19
|
-
* The motivating case is a notification: what to render depends on a runtime object, not just the key,
|
|
20
|
-
* so `t('translationBuilderTopic.notification', { notification })` dispatches through a *topic* which
|
|
21
|
-
* picks a *translator* based on that object. This is only the mechanism — the topics and their
|
|
22
|
-
* translators are SDK-specific and stay in the UI SDKs, since they reference SDK key names.
|
|
23
|
-
*
|
|
24
|
-
* A UI SDK may not need this at all: dispatching on the object at the render site instead is perfectly
|
|
25
|
-
* valid, and the React Native SDK does exactly that. The plumbing lives here so either approach is
|
|
26
|
-
* available without a core change.
|
|
27
|
-
*/
|
|
28
|
-
type TopicName = string;
|
|
29
|
-
type TranslatorName = string;
|
|
30
|
-
|
|
31
|
-
/**
|
|
32
|
-
* Resolves one case within a topic. Returning `null` means "not mine" and lets the next candidate try.
|
|
33
|
-
*
|
|
34
|
-
* `t` is loose rather than catalog-typed: a translator is handed keys by the post-processor at runtime,
|
|
35
|
-
* so it cannot be checked against a specific catalog.
|
|
36
|
-
*/
|
|
37
|
-
export type Translator<O extends Record<string, unknown> = Record<string, unknown>> =
|
|
38
|
-
(params: {
|
|
39
|
-
key: string;
|
|
40
|
-
options: O;
|
|
41
|
-
t: LooseTranslateFunction;
|
|
42
|
-
value: string;
|
|
43
|
-
}) => string | null;
|
|
44
|
-
|
|
45
|
-
export type TranslationTopicOptions<
|
|
46
|
-
O extends Record<string, unknown> = Record<string, unknown>,
|
|
47
|
-
> = {
|
|
48
|
-
i18next: I18nInstance;
|
|
49
|
-
translators?: Record<string, Translator<O>>;
|
|
50
|
-
};
|
|
51
|
-
|
|
52
|
-
export abstract class TranslationTopic<
|
|
53
|
-
O extends Record<string, unknown> = Record<string, unknown>,
|
|
54
|
-
> {
|
|
55
|
-
protected translators: Map<string, Translator<O>> = new Map();
|
|
56
|
-
protected i18next: I18nInstance;
|
|
57
|
-
|
|
58
|
-
constructor(protected options: TranslationTopicOptions<O>) {
|
|
59
|
-
this.i18next = options.i18next;
|
|
60
|
-
if (options.translators) {
|
|
61
|
-
Object.entries(options.translators).forEach(([name, translator]) => {
|
|
62
|
-
this.setTranslator(name, translator);
|
|
63
|
-
});
|
|
64
|
-
}
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
abstract translate(value: string, key: string, options: O): string;
|
|
68
|
-
|
|
69
|
-
setTranslator = (name: string, translator: Translator<O>) => {
|
|
70
|
-
this.translators.set(name, translator);
|
|
71
|
-
};
|
|
72
|
-
|
|
73
|
-
removeTranslator = (name: string) => {
|
|
74
|
-
this.translators.delete(name);
|
|
75
|
-
};
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
export type TranslationTopicConstructor = new (
|
|
79
|
-
options: TranslationTopicOptions,
|
|
80
|
-
) => TranslationTopic;
|
|
81
|
-
|
|
82
|
-
const forwardTranslation: Translator = ({ value }) => value;
|
|
83
|
-
|
|
84
|
-
export class TranslationBuilder {
|
|
85
|
-
private topics = new Map<string, TranslationTopic>();
|
|
86
|
-
|
|
87
|
-
/**
|
|
88
|
-
* Translators registered before their topic exists.
|
|
89
|
-
*
|
|
90
|
-
* Topics are only created during `Streami18n.init()`, but an integrator registers translators against
|
|
91
|
-
* the constructed instance — so registrations that arrive first are buffered and flushed when the
|
|
92
|
-
* topic appears, rather than silently dropped.
|
|
93
|
-
*/
|
|
94
|
-
private translatorRegistrationsBuffer: Record<
|
|
95
|
-
TopicName,
|
|
96
|
-
Record<TranslatorName, Translator>
|
|
97
|
-
> = {};
|
|
98
|
-
|
|
99
|
-
constructor(private i18next: I18nInstance) {}
|
|
100
|
-
|
|
101
|
-
registerTopic = (name: TopicName, Topic: TranslationTopicConstructor) => {
|
|
102
|
-
let topic = this.topics.get(name);
|
|
103
|
-
|
|
104
|
-
if (!topic) {
|
|
105
|
-
topic = new Topic({ i18next: this.i18next });
|
|
106
|
-
this.topics.set(name, topic);
|
|
107
|
-
this.i18next.use({
|
|
108
|
-
name,
|
|
109
|
-
process: (value: string, key: string, options: Record<string, unknown>) => {
|
|
110
|
-
// Re-read from the map rather than closing over `topic`, so `disableTopic` takes effect.
|
|
111
|
-
const registered = this.topics.get(name);
|
|
112
|
-
if (!registered) return value;
|
|
113
|
-
return registered.translate(value, key, options);
|
|
114
|
-
},
|
|
115
|
-
type: 'postProcessor' as const,
|
|
116
|
-
});
|
|
117
|
-
}
|
|
118
|
-
|
|
119
|
-
const buffered = this.translatorRegistrationsBuffer[name];
|
|
120
|
-
if (buffered) {
|
|
121
|
-
Object.entries(buffered).forEach(([translatorName, translator]) => {
|
|
122
|
-
topic.setTranslator(translatorName, translator);
|
|
123
|
-
});
|
|
124
|
-
delete this.translatorRegistrationsBuffer[name];
|
|
125
|
-
}
|
|
126
|
-
|
|
127
|
-
return topic;
|
|
128
|
-
};
|
|
129
|
-
|
|
130
|
-
disableTopic = (topicName: TopicName) => {
|
|
131
|
-
const topic = this.topics.get(topicName);
|
|
132
|
-
if (!topic) return;
|
|
133
|
-
// i18next has no way to remove a post-processor, so it is replaced with a pass-through.
|
|
134
|
-
this.i18next.use({
|
|
135
|
-
name: topicName,
|
|
136
|
-
process: forwardTranslation,
|
|
137
|
-
type: 'postProcessor',
|
|
138
|
-
});
|
|
139
|
-
this.topics.delete(topicName);
|
|
140
|
-
};
|
|
141
|
-
|
|
142
|
-
getTopic = (topicName: TopicName) => this.topics.get(topicName);
|
|
143
|
-
|
|
144
|
-
registerTranslators(
|
|
145
|
-
topicName: TopicName,
|
|
146
|
-
translators: Record<TranslatorName, Translator>,
|
|
147
|
-
) {
|
|
148
|
-
const topic = this.getTopic(topicName);
|
|
149
|
-
|
|
150
|
-
if (!topic) {
|
|
151
|
-
this.translatorRegistrationsBuffer[topicName] ??= {};
|
|
152
|
-
Object.entries(translators).forEach(([translatorName, translator]) => {
|
|
153
|
-
this.translatorRegistrationsBuffer[topicName][translatorName] = translator;
|
|
154
|
-
});
|
|
155
|
-
return;
|
|
156
|
-
}
|
|
157
|
-
|
|
158
|
-
Object.entries(translators).forEach(([name, translator]) => {
|
|
159
|
-
topic.setTranslator(name, translator);
|
|
160
|
-
});
|
|
161
|
-
}
|
|
162
|
-
|
|
163
|
-
removeTranslators(topicName: TopicName, translators: TranslatorName[]) {
|
|
164
|
-
if (this.translatorRegistrationsBuffer[topicName]) {
|
|
165
|
-
translators.forEach((translatorName) => {
|
|
166
|
-
delete this.translatorRegistrationsBuffer[topicName][translatorName];
|
|
167
|
-
});
|
|
168
|
-
}
|
|
169
|
-
|
|
170
|
-
const topic = this.getTopic(topicName);
|
|
171
|
-
if (!topic) return;
|
|
172
|
-
translators.forEach((name) => {
|
|
173
|
-
topic.removeTranslator(name);
|
|
174
|
-
});
|
|
175
|
-
}
|
|
176
|
-
}
|