API
The functions and types @k8ordo/i18n exports, all from one entry point that Server Components and Client Components both import.
On this page
defineLocales
Import from @k8ordo/i18n
Defines the app’s locale set. Everything that needs the list of locales reads it from this value.
defineLocales(
definitions: Record<string, LocaleDefinition>,
options?: LocalesOptions<D>,
): Locales<L, D>Parameters
definitionsRecord<string, LocaleDefinition>- An object keyed by locale tag. Each value holds that locale’s
timeZoneanddir. Tags are BCP 47, and the order written is the order ofall. optionsLocalesOptions<D>- The option that picks the default locale. See
LocalesOptions.
Returns
Locales<L, D> — The set: the list of locales and the functions and schema built from it.
Caveats
- A definition with no locale throws a
TypeError,defineLocales: no locale is defined, where it is called. Adefaultoutside the list and a tag that is not BCP 47 also throw aTypeError. So do a missingtimeZone, atimeZonethe runtime does not know, and adirother thanltrorrtl. Each has its own message. - The set is registered on
globalThis, andmessagereads the default locale from there. The set defined last wins, so call it once per app. - The keys are inferred as literal types. No
as constis needed.
src/i18n.tsexport const locales = defineLocales(
{
ja: { timeZone: 'Asia/Tokyo', dir: 'ltr' },
en: { timeZone: 'America/New_York', dir: 'ltr' },
},
{ default: 'en' },
);Locales
Import from @k8ordo/i18n
The type of the set defineLocales returns. L is the union of its tags, and D is the default locale’s tag.
type Locales<L extends string, D extends L> =
IntlFormats & {
all: readonly L[];
definitions: Readonly<Record<L, LocaleDefinition>>;
default: D;
is: (value: unknown) => value is L;
negotiate: (requested: Iterable<string>) => L;
negotiateRequest: (
request: Request,
options?: NegotiateRequestOptions,
) => L;
localize: (pathname: string, locale: L) => string;
delocalize: (pathname: string) => Delocalized<L>;
paramsSchema: LocaleParamsSchema<L>;
getLocale: () => L;
run: <T>(locale: L, fn: () => T) => T;
};Fields
allreadonly L[]- The tags, in the order written.
definitionsReadonly<Record<L, LocaleDefinition>>- Each locale’s
{ timeZone, dir }: the object passed todefineLocales. defaultD- The default locale. It is used when nothing names a locale, and when negotiation matches none.
is(value: unknown) => value is L- A type guard for membership in the list. It is case-sensitive:
is('EN')isfalse. negotiate(requested) => L- Picks one locale of the set from a list of preferred tags. Each tag is tried as an exact match, then by language. When nothing matches, the default is returned.
negotiateRequest(request, options?) => L- Picks a locale for a
Request. The cookie named byoptions.cookieis read first, thenAccept-Language. localize(pathname, locale) => string- Puts a locale segment in front of a pathname.
'/ui'becomes'/en/ui', and'/'becomes'/en'. delocalize(pathname) => Delocalized<L>- Takes the leading locale segment off and returns a
Delocalized. paramsSchemaLocaleParamsSchema<L>- A Standard Schema that validates
{ locale }. On the server, an accepted locale is set for the rest of the async context that called it. getLocale() => L- The current locale: in the browser, the first segment of the URL; on the server, the locale
paramsSchemaaccepted orrunwas given. When neither names one, the default. run(locale, fn) => T- Runs
fnwithlocaleas the current locale and returns whatfnreturns. The async workfnstarts is covered too. Server only. dateTimeFormat …IntlFormats- The members that return
Intlobjects for the current locale. SeeIntlFormatsbelow.
Caveats
- No member uses
this, so any of them can be taken out of the set, as inexport const { getLocale } = locales. - Called in a browser,
runthrowslocales.run: in the browser the URL is the locale — navigate instead. - On a server runtime that cannot reach
AsyncLocalStorage(throughprocess.getBuiltinModule),runthrows, and so doesparamsSchemawhen it accepts a locale. The message includesthis runtime has no AsyncLocalStorage to scope a locale to.
IntlFormats
Import from @k8ordo/i18n
The members of the set that return Intl objects for the current locale. What comes back is the Intl object itself, so format, select and the rest are called directly.
type IntlFormats = {
dateTimeFormat: (
options?: LocaleDateTimeFormatOptions,
) => Intl.DateTimeFormat;
numberFormat: (
options?: Intl.NumberFormatOptions,
) => Intl.NumberFormat;
relativeTimeFormat: (
options?: Intl.RelativeTimeFormatOptions,
) => Intl.RelativeTimeFormat;
pluralRules: (
options?: Intl.PluralRulesOptions,
) => Intl.PluralRules;
listFormat: (options?: Intl.ListFormatOptions) => Intl.ListFormat;
};Fields
dateTimeFormat(options?) => Intl.DateTimeFormatIntl.DateTimeFormatin the current locale and that locale’stimeZone.numberFormat(options?) => Intl.NumberFormatIntl.NumberFormatin the current locale.relativeTimeFormat(options?) => Intl.RelativeTimeFormatIntl.RelativeTimeFormatin the current locale.pluralRules(options?) => Intl.PluralRulesIntl.PluralRulesin the current locale.listFormat(options?) => Intl.ListFormatIntl.ListFormatin the current locale.
Caveats
- One object is made per locale and options, and returned again after that. Options are compared by their JSON.
- None of them is a hook. Each can be called in a Server Component, in a Client Component, and inside a message’s function.
message
Import from @k8ordo/i18n
Declares one message with its text in every locale. The function it returns gives the text in the locale where it is called.
function message(variants: Variants<string>): Message;
function message<A extends readonly unknown[]>(
variants: Variants<(...args: A) => string>,
): Message<A>;Parameters
variantsVariants<string> | Variants<(...args: A) => string>- The text per locale: a string in every locale, or a function of the same arguments in every locale.
Returns
Message<A> — A function that takes the arguments and returns the text in the current locale.
Caveats
- Once
Registercarries the locale type, a declaration missing a locale is a type error. A missing locale the types did not catch throws aTypeErrorsuch asmessage: no text for "en" in ["ja"]where the message is read. - When nothing names a locale, it returns the default locale’s text. In an environment where no set has been defined yet, it returns the first text written instead.
- The argument types are inferred from the locale whose function you annotate. With no annotation anywhere they are
unknown. Annotate at least one, or pass them as a type argument:message<[name: string]>({ … }). - The declaration has no side effect, so a bundler drops a message nothing calls.
src/messages/nav.tsexport const home = message({ ja: 'ホーム', en: 'Home' });
export const greeting = message({
ja: (name: string) => `こんにちは、${name}さん`,
en: (name) => `Hello, ${name}`,
});Message
Import from @k8ordo/i18n
The type of the function message returns. A component that takes a message as a prop takes this type.
type Message<A extends readonly unknown[] = []> = (
...args: A
) => string;Caveats
- It is a function, so it cannot be passed as a prop from a Server Component to a Client Component. Call it in the Server Component and pass the string.
parseAcceptLanguage
Import from @k8ordo/i18n
Turns an Accept-Language header into a list of tags for negotiate.
parseAcceptLanguage(header: string | null): string[]Parameters
headerstring | null- The header’s value.
request.headers.get('accept-language')can be passed as it is.
Returns
string[] — The tags, highest weight first. An empty array for a missing or blank header.
Caveats
- Tags of equal weight keep the header’s order. Tags weighted 0 or less, and
*, are dropped. - The tags themselves are not checked.
negotiateskips a tag that is not BCP 47.
parseAcceptLanguage('en-US;q=0.8, ja, en;q=0.9');
// ['ja', 'en', 'en-US']currentLocale
Import from @k8ordo/i18n
Returns the current locale from the set defineLocales defined. It is for a library that cannot import the app’s set.
currentLocale(): RegisteredLocale | nullReturns
RegisteredLocale | null — The locale named, or else the set’s default. null in an environment where no set has been defined.
Caveats
@k8ordo/uipicks the locale of its built-in text with this.- App code uses
locales.getLocale(), which is typed by the set.
Register
Import from @k8ordo/i18n
The declaration that tells the package the app’s locale type. Write it once per app by hand; in an @k8ordo/framework app it is generated from the locales that src/i18n.ts exports.
declare module '@k8ordo/i18n' {
interface Register {
locale: LocaleOf<typeof locales>;
}
}Caveats
- It exists to be merged, so it is an
interface, not atype. - Until
Registercarries the locale type,RegisteredLocaleisstring, and a missing locale is not a type error.
RegisteredLocale
Import from @k8ordo/i18n
The union of the locales in Register.
type RegisteredLocale = Register extends {
locale: infer L extends string;
}
? L
: string;Variants
Import from @k8ordo/i18n
An object with one value per locale in Register. It is also what message takes.
type Variants<V> = Readonly<Record<RegisteredLocale, V>>;Caveats
- It fits more than messages: any value every locale must have, such as the names a language switcher lists.
LocaleOf
Import from @k8ordo/i18n
The union of a set’s tags. It is also what Register’s locale is set to.
type LocaleOf<Ls> =
Ls extends Locales<infer L, infer _D> ? L : never;LocaleDefinition
Import from @k8ordo/i18n
What the app states for each locale. Neither value is derived from the runtime.
type LocaleDefinition = {
timeZone: string;
dir: 'ltr' | 'rtl';
};Fields
timeZonestring- The IANA time zone the locale’s dates are shown in. The server and every browser use the same one, so a date reads the same on both.
dir'ltr' | 'rtl'- The direction the locale’s text runs in, for
<html dir>.
LocalesOptions
Import from @k8ordo/i18n
The type of defineLocales’ second argument.
type LocalesOptions<D extends string> = { default?: D };Fields
defaultD- The default locale. It must be one of the list. Without it, the first locale written.
NegotiateRequestOptions
Import from @k8ordo/i18n
The type of negotiateRequest’s second argument.
type NegotiateRequestOptions = { cookie?: string };Fields
cookiestring- The name of the cookie holding the visitor’s choice. Without it, only
Accept-Languageis read.
Delocalized
Import from @k8ordo/i18n
The type of what delocalize returns.
type Delocalized<L extends string> = {
locale: L | null;
pathname: string;
};Fields
localeL | null- The locale the first segment names, or
nullwhen it names none. pathnamestring- The pathname with the segment taken off.
/when there was nothing else.
LocaleParamsSchema
Import from @k8ordo/i18n
The type of paramsSchema. The package declares the Standard Schema shape itself, so no schema library is needed.
type LocaleParamsSchema<L extends string> = {
'~standard': {
version: 1;
vendor: '@k8ordo/i18n';
validate: (value: unknown) =>
| { value: { locale: L } }
| { issues: { message: string; path: ['locale'] }[] };
};
};Caveats
- Validation is synchronous. A locale outside the list gets an issue at
path: ['locale']. - The accepted value is
{ locale }alone; other keys are left out.
LocaleDateTimeFormatOptions
Import from @k8ordo/i18n
The options of dateTimeFormat: Intl.DateTimeFormatOptions without timeZone.
type LocaleDateTimeFormatOptions = Intl.DateTimeFormatOptions & {
timeZone?: never;
};Caveats
- A
timeZoneforced through withasis overridden by the locale’s.