Skip to content

rosetta ​

@c9up/rosetta: internationalization: translation catalogs with ICU messages, locale negotiation and fallbacks, Intl number, date and list formatting, request locale detection and typed translation keys. Guide: I18n.

Installation ​

bash
pnpm add @c9up/rosetta

ream configure @c9up/rosetta registers the provider, writes config/i18n.ts and app/middleware/detect_user_locale_middleware.ts, registers that middleware on the router and adds resources/lang/**/*.{json,yaml,yml} to the files the build copies. The template globals need @c9up/inker.

Entry points ​

ImportContents
@c9up/rosettaRosetta, RosettaLocale, defineConfig, formatters, loaders, the formatter and loader classes, catalog tools and types. In a browser build, FileSystemLoader throws when built
@c9up/rosetta/typesSame as @c9up/rosetta
@c9up/rosetta/providerRosettaProvider (default export)
@c9up/rosetta/i18n_providerSame as @c9up/rosetta/provider; the path ream configure registers
@c9up/rosetta/services/mainThe application's Rosetta (default export)
@c9up/rosetta/middlewareDetectUserLocaleMiddleware (default export)
@c9up/rosetta/factoriesI18nManagerFactory, for tests
@c9up/rosetta/plugins/inkerinkerPluginI18n, the template globals
@c9up/rosetta/replregisterReplBindings
@c9up/rosetta/configureconfigure(), run by ream configure @c9up/rosetta

Exports ​

@c9up/rosetta ​

ExportKindDescription
RosettaclassThe manager: catalogs, locales, fallbacks, formatting
I18nManagerclassAnother name for Rosetta
RosettaLocaleclassA locale-scoped instance, as ctx.i18n holds it
I18nclassAnother name for RosettaLocale
I18nMessagesProviderclassValidation messages read from the catalog, for @c9up/rune
defineConfigfunctionTypes config/i18n.ts; defaultLocale defaults to 'en', formatter is required
formattersconstformatters.icu(), the ICU formatter factory
loadersconstloaders.fs({ location | rootDir }), the file system loader factory
IcuFormatterclassICU MessageFormat formatter, the default
FormatterclassIntl formatting for one locale; base of RosettaLocale
FileSystemLoaderclassnew FileSystemLoader(options: FileSystemLoaderOptions), reads json, yaml and yml catalogs
FsLoaderclassAnother name for FileSystemLoader
extractMessageParamsfunctionextractMessageParams(message: string): MessageParam[], the variables of an ICU message
checkCatalogsfunctioncheckCatalogs(translations: Translations, opts?: CheckCatalogsOptions): CatalogFinding[], compares every locale to a reference
verifyCatalogsfunctionverifyCatalogs(translations, opts?: CheckCatalogsOptions & { mode?: 'throw' | 'warn' }): CatalogFinding[]; mode defaults to 'warn'
runCatalogCheckfunctionrunCatalogCheck(translations, opts?): number, prints the report and returns an exit code (0 or 1)
formatCatalogFindingsfunctionformatCatalogFindings(findings: CatalogFinding[]): string
suggestKeyfunctionsuggestKey(name: string, candidates: string[]): string | undefined, the closest key
generateCatalogTypesfunctiongenerateCatalogTypes(translations: Translations, opts?: GenerateCatalogTypesOptions): string, the TranslationKeys augmentation for a catalog
configurefunctionSame as @c9up/rosetta/configure
registerReplBindingsfunctionSame as @c9up/rosetta/repl
stubsRootconstDirectory of the package's stubs (not in the browser build)
errorsnamespaceThe package's errors, one class per code, see Errors (in the browser build too)

Types:

ExportKindDescription
RosettaOptionsinterfaceOptions of new Rosetta() (see Configuration)
I18nManagerConfiginterfaceRosettaOptions with defaultLocale, formatter: FormatterFactory and loaders: LoaderFactory[] required
BaseI18nConfiginterface{ defaultLocale, supportedLocales?, fallbackLocales?, fallback? }
RosettaProviderConfiginterfaceRosettaOptions & { rootDir?: string }
TranslationKeysinterfaceEmpty; augment it (see generateCatalogTypes) and t() checks keys and variables
TranslationKeytypeEvery string until TranslationKeys is augmented, then its keys
ParamsFortypeParamsFor<K>, the variables a key needs
TranslationParamstypeRecord<string, unknown>
TranslateOptionsinterface{ locale?, defaultValue?, fallbackLocale? }
MessageTree, MessageTreeList, MessageCatalog, TranslationstypeNested catalog, list in a catalog, flat catalog (Record<string, string>), catalogs by locale
LoadertypeRosettaLoader | TranslationsLoaderContract
RosettaLoaderinterface{ load(locale: string): Promise<MessageTree | MessageCatalog | null | undefined> }
TranslationsLoaderContractinterface{ load(): Promise<Record<string, MessageTree | MessageCatalog>>; loadAll?() }
LoaderFactorytype(config: RosettaOptions) => Loader
FormatterFactorytype(config: RosettaOptions) => TranslationsFormatterContract
TranslationsFormatterContractinterface{ readonly name: string; format(message: string, locale: string, data?): string }
MissingTranslationHandlertype(payload: MissingTranslationEventPayload) => void
MissingTranslationEventPayloadinterface{ locale: string; identifier: string; hasFallback: boolean }
MissingTranslationEmitterinterface{ emit(event: 'i18n:missing:translation', payload): unknown }
I18nEventsinterface{ 'i18n:missing:translation': MissingTranslationEventPayload }
LocaleResolverInputinterface{ header?: string | null; accepted?: string[] }
NumberFormatDatainterface{ decimal, group, minus, plusSign }
CurrencyFormatOptionstypeIntl.NumberFormatOptions without style, unit, unitDisplay, with currency: string required
DateTimeValuetypeDate | number | string | { toJSDate(): Date } | { toMillis(): number }
NumberFormatOptions, TimeFormatOptionstypeOptions of IcuFormatter.addFormatFor
MessageParaminterface{ name, kind: MessageParamKind, options? }
MessageParamKindtype'text' | 'number' | 'date' | 'time' | 'plural' | 'selectordinal' | 'select'
ValidationFieldContextinterface{ name: string | number; wildCardPath: string }
CatalogFindinginterface{ locale, key, kind, detail, suggestion? }
CatalogFindingKindtype'missing-in-locale' | 'orphan-key' | 'param-mismatch' | 'invalid-message'
CheckCatalogsOptionsinterface{ referenceLocale? }
GenerateCatalogTypesOptionsinterface{ referenceLocale?, moduleName? }; moduleName defaults to '@c9up/rosetta'
FileSystemLoaderOptions, FsLoaderOptionsinterface{ rootDir?: string; location?: string | URL }
ResolvableConfiginterface{ resolver(app): Promise<T> }
DefinedI18nConfigtypeWhat defineConfig returns
I18nHttpContext, RequestValidatorLikeinterfaceSame as @c9up/rosetta/middleware
I18nReplContext, I18nReplLikeinterfaceSame as @c9up/rosetta/repl

Rosetta ​

new Rosetta(options?: RosettaOptions), or new Rosetta(emitter: MissingTranslationEmitter, config: I18nManagerConfig).

MemberSignatureDescription
bootboot(): Promise<void>Load every loader's catalogs
localelocale(locale?: string): RosettaLocaleAn instance for locale (the default locale without one)
tt(key: string, params?: TranslationParams, options?: TranslateOptions): stringTranslate in the current locale; a key missing everywhere gives fallback(key, locale), else translation missing: <locale>, <key>
hashas(key: string, locale?: string): booleanWhether the key resolves in the locale or its fallbacks
formatRawMessageformatRawMessage(message: string, locale?: string, data?: TranslationParams): stringFormat an ICU message not in a catalog
loadMessagesloadMessages(locale: string, messages: MessageTree | MessageCatalog): thisAdd a catalog in code; kept over the loaders on reload
loadLocaleloadLocale(locale: string): Promise<this>Load one locale through the loaders
loadTranslationsloadTranslations(): Promise<void>Load the catalogs once
reloadTranslationsreloadTranslations(): Promise<void>Read the loaders again
getTranslationsgetTranslations(): Record<string, MessageCatalog>Every flattened catalog
getTranslationsForgetTranslationsFor(locale: string): MessageCatalogOne locale's catalog
hasCachedTranslationsreadonly hasCachedTranslations: booleanWhether the catalogs were loaded
setLocale / getLocalesetLocale(locale: string): this / getLocale(): stringThe current locale
runWithLocalerunWithLocale<T>(locale: string, callback: () => T): TRun callback with locale as the current locale
defaultLocalereadonly defaultLocale: stringThe default locale
setDefaultLocale / getDefaultLocalesetDefaultLocale(locale: string): this / getDefaultLocale(): string
supportedLocalessupportedLocales(): string[]The configured locales, or those inferred from the default, the fallbacks and the loaded catalogs
setSupportedLocales / getSupportedLocalessetSupportedLocales(locales: string[]): this / getSupportedLocales(): string[] | undefinedThe configured list only
resolveLocaleresolveLocale(input: string | LocaleResolverInput): stringNegotiate a supported locale from an Accept-Language header or a list; always answers one
getSupportedLocaleForgetSupportedLocaleFor(userLanguage: string | string[]): string | nullThe best supported locale, or null
getFallbackLocaleForgetFallbackLocaleFor(locale: string): stringA locale's fallback
setFallbackLocale / getFallbackLocalesetFallbackLocale(locale: string): this / getFallbackLocale(): stringThe global fallback locale
setFallbackLocales / getFallbackLocalessetFallbackLocales(locales: Record<string, string>): this / getFallbackLocales(): Record<string, string>Fallback per locale
setFallbacksetFallback(fallback: ((identifier: string, locale: string) => string) | undefined): thisWhat t() returns for a key missing everywhere
getFallbackMessagegetFallbackMessage(identifier: string, locale: string): string | undefined
onMissingTranslationonMissingTranslation(handler: MissingTranslationHandler): () => voidAdd a handler; returns the remover
setOnMissingTranslationsetOnMissingTranslation(handler: MissingTranslationHandler | undefined): thisReplace the handlers
getFormattergetFormatter(): TranslationsFormatterContractThe message formatter
formatNumberformatNumber(value: string | number | bigint, options?: Intl.NumberFormatOptions): stringIn the current locale
formatCurrencyformatCurrency(value: string | number | bigint, options: CurrencyFormatOptions, locale?: string): stringAlso formatCurrency(value, currency, options?, locale?)
formatDate / formatTimeformatDate(value: DateTimeValue, options?: Intl.DateTimeFormatOptions): string
formatRelativeTimeformatRelativeTime(value: DateTimeValue, unit: Intl.RelativeTimeFormatUnit | 'auto', options?): string
formatPluralformatPlural(value: number | string, options?: Intl.PluralRulesOptions): stringThe plural category
formatListformatList(list: Iterable<string>, options?: Intl.ListFormatOptions): string
formatDisplayNamesformatDisplayNames(code: string, options: Intl.DisplayNamesOptions): string | undefined
getNumberFormatDatagetNumberFormatData(locale?: string): NumberFormatDataSeparators of a locale, through its fallbacks
formatNumberStringformatNumberString(value: string, options?: Intl.NumberFormatOptions): stringFormat a decimal string without going through a float
configreadonly config: RosettaOptionsThe options it was built with

RosettaLocale ​

manager.locale(locale) builds it. It has the Formatter methods (formatNumber, formatCurrency, formatDate, formatTime, formatRelativeTime, formatPlural, formatList, formatDisplayNames) in its locale, and:

MemberSignatureDescription
tt<K extends TranslationKey>(key: K, ...rest: TranslateArgs<K>): stringTranslate; rest is the variables, then a fallback message or { defaultValue }. A declared key requires its variables
formatMessageformatMessage<K extends TranslationKey>(identifier: K, ...rest: TranslateArgs<K>): stringSame as t
formatRawMessageformatRawMessage(message: string, data?: TranslationParams): string
hashas(key: string): boolean
hasMessage / hasFallbackMessagehasMessage(identifier: string): booleanIn this locale, or in its fallback
resolveIdentifierresolveIdentifier(identifier: string): { message: string; isFallback: boolean } | null
localereadonly locale: string
getLocalegetLocale(): string
switchLocaleswitchLocale(locale: string): voidChange this instance's locale
fallbackLocalefallbackLocale: string
localeTranslations / fallbackTranslationsreadonly localeTranslations: MessageCatalogCatalog of the locale and of its fallback
createMessagesProvidercreateMessagesProvider(prefix?: string): I18nMessagesProviderValidation messages under prefix (default 'validator.shared')
getNumberFormatDatagetNumberFormatData(): NumberFormatData
formatNumberStringformatNumberString(value: string, options?: Intl.NumberFormatOptions): string

I18nMessagesProvider (new I18nMessagesProvider(prefix: string, i18n: RosettaLocale)) answers getMessage(defaultMessage, rule, field, meta?) from <prefix>.messages.<field>.<rule>, then <prefix>.messages.<rule>, else defaultMessage; translateField(name) reads <prefix>.fields.<name>.

IcuFormatter.addFormatFor(type: 'number' \| 'date' \| 'time', key: string, options) registers a named format usable in messages.

@c9up/rosetta/provider ​

ExportKindDescription
defaultproviderRosettaProvider: builds Rosetta from the i18n config, boots it, fills @c9up/rosetta/services/main, forwards missing translations to the emitter binding as i18n:missing:translation, installs the validator messages provider on requestValidator, the template globals when @c9up/inker is used and the i18n REPL binding
RosettaAppContextinterface{ container, config, usingInker? }
RosettaProviderConfiginterfaceRosettaOptions & { rootDir?: string }; rootDir appends a FileSystemLoader

@c9up/rosetta/services/main ​

ExportKindDescription
defaultconsti18n: Rosetta, the application's manager once RosettaProvider booted; a member read before throws
setI18nfunctionsetI18n(value: Rosetta): void, seat a manager built outside the provider
getI18nfunctiongetI18n(): Rosetta | undefined
clearI18nfunctionclearI18n(value?: Rosetta): void

@c9up/rosetta/middleware ​

ExportKindDescription
defaultclassDetectUserLocaleMiddleware
I18nHttpContextinterfaceWhat the middleware reads and sets on the context: request, i18n, locale, view, containerResolver
RequestValidatorLikeinterface{ messagesProvider?(context): I18nMessagesProvider | undefined }

new DetectUserLocaleMiddleware(manager?: Rosetta) (the application's Rosetta by default). handle(context, next) picks the request locale from request.language(), the Accept-Language header or request.languages(), else the default locale; sets ctx.i18n and ctx.locale, binds RosettaLocale on the request container, shares i18n with the view, and runs next with that locale current. Override getRequestLocale(context): string to choose otherwise. DetectUserLocaleMiddleware.messagesProvider(context) and registerMessagesProvider(validator) are static.

@c9up/rosetta/factories ​

ExportKindDescription
I18nManagerFactoryclassmerge(options: I18nManagerFactoryOptions): this, create(): Rosetta, createMiddleware(): DetectUserLocaleMiddleware; defaults to en, ICU, catalogs in ./resources/lang
I18nManagerFactoryOptionsinterface{ config?: Partial<I18nManagerConfig>; emitter?: MissingTranslationEmitter }

@c9up/rosetta/plugins/inker ​

ExportKindDescription
inkerPluginI18nfunctioninkerPluginI18n(manager: Rosetta): (engine) => void: publishes the globals i18n (in the request's locale), t, getDefaultLocale and getSupportedLocales

@c9up/rosetta/repl ​

ExportKindDescription
registerReplBindingsfunctionregisterReplBindings(repl: I18nReplLike, manager: Rosetta): void, binds i18n and adds a loadI18n method
I18nReplLikeinterface{ addBinding?, addMethod?, server?, notify? }
I18nReplContextinterface{ i18n?: Rosetta }

@c9up/rosetta/configure ​

ExportKindDescription
configurefunctionconfigure(codemods): Promise<void>: registers @c9up/rosetta/i18n_provider, adds the catalogs to the build, writes config/i18n.ts and the locale middleware, and registers it on the router

Configuration ​

config/i18n.ts, read under the i18n key. The provider refuses to build Rosetta without it.

ts
import { defineConfig, formatters, loaders } from '@c9up/rosetta'

export default defineConfig({
  defaultLocale: 'en',
  supportedLocales: ['en', 'fr'],
  formatter: formatters.icu(),
  loaders: [loaders.fs({ location: new URL('../resources/lang/', import.meta.url) })],
})
OptionTypeDefaultDescription
defaultLocalestring'en'Locale used when none is asked
supportedLocalesstring[]inferredLocales the application serves; without it, the default, the fallback keys and the loaded catalogs
fallbackLocalestringdefaultLocaleGlobal fallback
fallbackLocalesRecord<string, string>{}Fallback per locale ({ 'fr-CA': 'fr' })
messagesRecord<string, MessageTree | MessageCatalog>—Catalogs given in code
loadersArray<Loader | LoaderFactory>[]Where catalogs come from
formatterTranslationsFormatterContract | FormatterFactoryIcuFormatterMessage formatter; defineConfig requires it
onMissingTranslationMissingTranslationHandler—Called when a key does not resolve in the requested locale
fallback(identifier: string, locale: string) => string—What t() returns for a key missing everywhere
rootDirstring—Provider only: appends a FileSystemLoader on this directory

FileSystemLoader reads <locale>.json|yaml|yml and every file under <locale>/, whose keys are prefixed with the file's path (resources/lang/fr/messages.json gives messages.*).

Container bindings ​

TokenResolves to
Rosetta (class)The manager built from the i18n config
'rosetta.i18n'The same Rosetta
'i18n'The same Rosetta
'rosetta'The same Rosetta
RosettaLocale (class, request container)The request's ctx.i18n, bound by the middleware

'rosetta.i18n', 'i18n' and 'rosetta' are declared in ContainerBindings.

Errors ​

Every error Rosetta raises is a @c9up/flare Exception with a code, and each code is a class of the errors namespace: test error.code, or error instanceof errors.E_ROSETTA_INVALID_ICU_MESSAGE.

CodeRaised when
E_ROSETTA_NOT_BOOTEDThe services/main singleton was used before RosettaProvider booted, or before setI18n().
E_ROSETTA_CONFIG_MISSINGconfig/i18n exports no config built with defineConfig().
E_ROSETTA_INVALID_CONFIGThe i18n config has no formatter.
E_ROSETTA_INVALID_ARGUMENTA constructor or method got an argument of the wrong shape (an emitter, a manager, a locale, a FileSystemLoader without location or rootDir, an empty format key).
E_ROSETTA_UNSAFE_KEYA catalog key or an ICU custom format key is one that would reach the prototype (__proto__, constructor, prototype).
E_ROSETTA_DUPLICATE_KEYA catalog defines the same key twice: a YAML key, or a nested and a dotted key that flatten to one.
E_ROSETTA_INVALID_CATALOGA catalog file does not parse (unsupported YAML) or holds a value that is neither a mapping nor a scalar message.
E_ROSETTA_CATALOG_LIMIT_EXCEEDEDA catalog is too deep, has too many keys, or a catalog file is too large.
E_ROSETTA_UNSAFE_PATHA translation directory or file is a symbolic link, or resolves outside the loader's root.
E_ROSETTA_INVALID_PATHA translation path is not a directory, or not a file, where one is expected.
E_ROSETTA_UNSUPPORTED_RUNTIMEFileSystemLoader was used from the browser build, which has no filesystem.
E_ROSETTA_INVALID_ICU_MESSAGEAn ICU message does not parse, or uses a style, skeleton or option Rosetta or Intl does not support.
E_ROSETTA_ICU_LIMIT_EXCEEDEDAn ICU message is too long, too deeply nested, or has too many nodes.
E_ROSETTA_MISSING_VARIABLEAn ICU message uses a variable the call did not provide.
E_ROSETTA_INVALID_DATEAn ICU date or time value is not a Date, a timestamp, an ISO string or a Luxon-like DateTime, or names an impossible date.
E_ROSETTA_CATALOG_MISMATCHverifyCatalogs({ mode: 'throw' }) found catalogs that disagree; the message is the report.
E_ROSETTA_INTERNALAn internal invariant broke (an unknown ICU node, a parser state); report it as a bug.

Migration ​

  • A refusal is no longer a built-in TypeError, RangeError or SyntaxError (an invalid ICU message, a YAML catalog that does not parse, a limit exceeded, an argument of the wrong shape): error instanceof SyntaxError no longer matches. Test error.code (error.code === 'E_ROSETTA_INVALID_ICU_MESSAGE') or error instanceof errors.E_ROSETTA_INVALID_ICU_MESSAGE, errors coming from @c9up/rosetta.

See also ​