@k8ordo/i18n

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.

ts
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 timeZone and dir. Tags are BCP 47, and the order written is the order of all.
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. A default outside the list and a tag that is not BCP 47 also throw a TypeError. So do a missing timeZone, a timeZone the runtime does not know, and a dir other than ltr or rtl. Each has its own message.
  • The set is registered on globalThis, and message reads 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 const is needed.
src/i18n.ts
export 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.

ts
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 to defineLocales.
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') is false.
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 by options.cookie is read first, then Accept-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 paramsSchema accepted or run was given. When neither names one, the default.
run(locale, fn) => T
Runs fn with locale as the current locale and returns what fn returns. The async work fn starts is covered too. Server only.
dateTimeFormat …IntlFormats
The members that return Intl objects for the current locale. See IntlFormats below.

Caveats

  • No member uses this, so any of them can be taken out of the set, as in export const { getLocale } = locales.
  • Called in a browser, run throws locales.run: in the browser the URL is the locale — navigate instead.
  • On a server runtime that cannot reach AsyncLocalStorage (through process.getBuiltinModule), run throws, and so does paramsSchema when it accepts a locale. The message includes this 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.

ts
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.DateTimeFormat
Intl.DateTimeFormat in the current locale and that locale’s timeZone.
numberFormat(options?) => Intl.NumberFormat
Intl.NumberFormat in the current locale.
relativeTimeFormat(options?) => Intl.RelativeTimeFormat
Intl.RelativeTimeFormat in the current locale.
pluralRules(options?) => Intl.PluralRules
Intl.PluralRules in the current locale.
listFormat(options?) => Intl.ListFormat
Intl.ListFormat in 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.

ts
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 Register carries the locale type, a declaration missing a locale is a type error. A missing locale the types did not catch throws a TypeError such as message: 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.ts
export 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.

ts
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.

ts
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. negotiate skips a tag that is not BCP 47.
ts
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.

ts
currentLocale(): RegisteredLocale | null

Returns

RegisteredLocale | null — The locale named, or else the set’s default. null in an environment where no set has been defined.

Caveats

  • @k8ordo/ui picks 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.

ts
declare module '@k8ordo/i18n' {
  interface Register {
    locale: LocaleOf<typeof locales>;
  }
}

Caveats

  • It exists to be merged, so it is an interface, not a type.
  • Until Register carries the locale type, RegisteredLocale is string, and a missing locale is not a type error.

RegisteredLocale

Import from @k8ordo/i18n

The union of the locales in Register.

ts
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.

ts
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.

ts
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.

ts
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.

ts
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.

ts
type NegotiateRequestOptions = { cookie?: string };

Fields

cookiestring
The name of the cookie holding the visitor’s choice. Without it, only Accept-Language is read.

Delocalized

Import from @k8ordo/i18n

The type of what delocalize returns.

ts
type Delocalized<L extends string> = {
  locale: L | null;
  pathname: string;
};

Fields

localeL | null
The locale the first segment names, or null when 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.

ts
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.

ts
type LocaleDateTimeFormatOptions = Intl.DateTimeFormatOptions & {
  timeZone?: never;
};

Caveats

  • A timeZone forced through with as is overridden by the locale’s.
k8ordo

React libraries that use Baseline features without holding back.