@softistx/alxia-i18n 0.0.0-stage → 0.7.1

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/docs/guide.md ADDED
@@ -0,0 +1,924 @@
1
+ # Guide
2
+
3
+ This page covers `createI18n()`: the catalogues and the fallback, the
4
+ `@softistx/alxia-language` options it passes through, what the routes behind it
5
+ read, how messages are formatted and keys typed, where its own `t()` knows
6
+ the request's language and where it does not, and how `@softistx/i18n`'s
7
+ `translate` follows it.
8
+
9
+ ```ts
10
+ import { alxia } from '@softistx/alxia';
11
+ import { createI18n } from '@softistx/alxia-i18n';
12
+
13
+ const en = { home: { title: 'Welcome', greeting: 'Hello {name}' } };
14
+ const fr = { home: { title: 'Bienvenue', greeting: 'Bonjour {name}' } };
15
+
16
+ const i18n = createI18n({ resources: { en, fr }, fallback: 'en' });
17
+
18
+ const app = alxia()
19
+ .use(i18n)
20
+ .get('/', ({ t, reply }) => reply(200, { title: t('home.title'), greeting: t('home.greeting', { name: 'Ada' }) }));
21
+
22
+ app.listen(3000);
23
+ ```
24
+
25
+ A browser set to French gets `{"title":"Bienvenue","greeting":"Bonjour Ada"}`,
26
+ `/?lang=en` gets English whatever the browser says, and a client that names
27
+ no language the catalogues have gets the fallback's, English.
28
+ `t('home.titel')` does not compile.
29
+
30
+ ## The signature
31
+
32
+ ```ts
33
+ function createI18n<
34
+ const C extends Catalogues,
35
+ const Fallback extends keyof C & string,
36
+ Ctx extends object = BaseContext,
37
+ >(
38
+ options: I18nOptions<C, Fallback, Ctx>,
39
+ ): Middleware<RequiresOf<Ctx, 'resolve'>, Promise<Next<LanguageContext<keyof C & string> & I18nContext<KeyOf<C[Fallback]>>>>> & {
40
+ t: Translate<KeyOf<C[Fallback]>>;
41
+ language: () => keyof C & string;
42
+ supported: (keyof C & string)[];
43
+ fallBackTo: (language: string) => void;
44
+ chain: () => string[];
45
+ setResources: (resources: Catalogues) => void;
46
+ };
47
+
48
+ // With an explicit Key: the keys are named, the catalogues may come later.
49
+ function createI18n<Key extends string = never, Language extends string = string, Ctx extends object = BaseContext>(
50
+ options: RuntimeI18nOptions<Language, Ctx>, // without a Key, the options are refused with a message
51
+ ): I18nMiddleware<Language, Key, RequiresOf<Ctx, 'resolve'>>;
52
+
53
+ interface I18nOptions<C extends Catalogues, Fallback extends keyof C & string, Ctx extends object = BaseContext>
54
+ extends Omit<LanguageOptions<keyof C & string, Ctx>, 'supported' | 'fallback'> {
55
+ readonly resources: C;
56
+ readonly fallback: Fallback;
57
+ readonly fallbacks?: (language: keyof C & string) => readonly string[];
58
+ }
59
+
60
+ interface RuntimeI18nOptions<Language extends string = string, Ctx extends object = BaseContext>
61
+ extends Omit<LanguageOptions<Language, Ctx>, 'supported' | 'fallback'> {
62
+ readonly languages?: readonly Language[];
63
+ readonly resources?: Catalogues;
64
+ readonly fallback: Language;
65
+ readonly fallbacks?: (language: Language) => readonly string[];
66
+ }
67
+
68
+ type Catalogues = Readonly<Record<string, Readonly<Record<string, unknown>>>>;
69
+ type KeyOf<Catalogue> = …; // every key, dotted: 'home.title', nine levels deep
70
+ type Translate<Key extends string> = (key: Key, context?: TranslationContext) => string;
71
+ interface I18nContext<Key extends string> {
72
+ readonly t: Translate<Key>;
73
+ }
74
+ ```
75
+
76
+ `C` and `Fallback` are inferred from `resources` and `fallback`, and `Ctx`
77
+ from the type `resolve`'s parameter is annotated with: `RequiresOf<Ctx, 'resolve'>`,
78
+ `@softistx/alxia`'s, is what that annotation adds to `BaseContext`, and `Empty`
79
+ when `resolve` is absent or not annotated. See
80
+ [Reading the app's context](#reading-the-apps-context).
81
+
82
+ `createI18n()` returns two things in one value:
83
+
84
+ - **a middleware**: pass it to `app.use`. It runs on every request the app
85
+ takes, and applies to what is declared **after** it, in the same app or
86
+ [group](https://github.com/softistx/alxia/blob/develop/packages/core/docs/guide/groups-and-plugins.md):
87
+ the middlewares and the routes. It adds `t`, `language` and `languageSource`
88
+ to their context;
89
+ - **`t()`, `language()` and `supported`**, to call where no context is at
90
+ hand: a service, a model, a job. See [Outside a route](#outside-a-route).
91
+ **`fallBackTo()`, `chain()` and `setResources()`** are covered by
92
+ [The fallback chain](#the-fallback-chain) and
93
+ [Catalogues loaded at runtime](#catalogues-loaded-at-runtime).
94
+
95
+ It also registers the request's language with `@softistx/i18n` — one source,
96
+ however many times `createI18n()` is called, so building an app per test
97
+ does not grow `@softistx/i18n`'s list; see [`@softistx/i18n`'s own `translate`](#softistxi18ns-own-translate).
98
+
99
+ ## Options
100
+
101
+ | Option | Type | Default | Effect |
102
+ | --- | --- | --- | --- |
103
+ | `resources` | `Catalogues` | required (optional with an explicit `Key`) | one catalogue per language; its keys are the languages the app supports |
104
+ | `fallback` | one of `resources`' keys | required | the language when no source names a supported one, and the catalogue whose keys type `t` |
105
+ | `fallbacks` | `(language) => readonly string[]` | none | the languages `t()` tries after the request's own and before `fallback`; see [The fallback chain](#the-fallback-chain) |
106
+ | `languages` | `readonly string[]` | `resources`' keys, else `[fallback]` | with an explicit `Key` only: the languages supported until `setResources()` gives catalogues |
107
+ | `order` | `readonly LanguageSource[]` | `['query', 'cookie', 'header']` | the sources read, in this order |
108
+ | `query` | `string` | `'lang'` | the query parameter: `?lang=fr` |
109
+ | `cookie` | `string` | `'language'` | the cookie read, and written by `persist` |
110
+ | `pathIndex` | `number` | `0` | the path segment the `path` source reads |
111
+ | `persist` | `boolean \| { maxAge?, secure? }` | `false` | a language the query named is kept in the cookie |
112
+ | `contentLanguage` | `boolean` | `true` | `Content-Language` on every response the middleware runs for |
113
+ | `resolve` | `(ctx: BaseContext & Ctx) => string \| undefined` | none | decides after every source, before `fallback`; annotate `ctx` to read what an earlier middleware adds |
114
+
115
+ Every option but `resources`, `fallback`, `fallbacks` and `languages` is `@softistx/alxia-language`'s, passed
116
+ through as it is; its [guide](https://github.com/softistx/alxia/blob/develop/packages/language/docs/guide.md)
117
+ details each one, how `Accept-Language` is negotiated, and the `Vary` the
118
+ middleware adds. `supported` is not an option here: it is `resources`' keys.
119
+
120
+ ### `resources`
121
+
122
+ One catalogue per language, nested as deep as you like. A leaf is an
123
+ [ICU message](#messages); a key is its dotted path, `cart.items`:
124
+
125
+ ```ts
126
+ import { createI18n } from '@softistx/alxia-i18n';
127
+
128
+ const en = {
129
+ cart: {
130
+ items: '{count, plural, =0 {No items} one {One item} other {# items}}',
131
+ total: 'Total: {amount, number, ::currency/EUR}',
132
+ },
133
+ };
134
+ const fr = {
135
+ cart: {
136
+ items: '{count, plural, =0 {Aucun article} one {Un article} other {# articles}}',
137
+ total: 'Total : {amount, number, ::currency/EUR}',
138
+ },
139
+ };
140
+
141
+ export const i18n = createI18n({ resources: { en, fr }, fallback: 'en' });
142
+ ```
143
+
144
+ Catalogues kept in JSON files work as they are, typed keys included, with
145
+ `resolveJsonModule` in your `tsconfig.json`:
146
+
147
+ ```ts
148
+ import { createI18n } from '@softistx/alxia-i18n';
149
+ import en from './locales/en.json';
150
+ import fr from './locales/fr.json';
151
+
152
+ export const i18n = createI18n({ resources: { en, fr }, fallback: 'en' });
153
+ ```
154
+
155
+ `@softistx/i18n` ships catalogues of its own, in English and French: error
156
+ messages (`errors.not-found`, `errors.unauthenticated`, …), validation
157
+ messages, and `zod.*`. Spread its `resources` into yours to translate them
158
+ with the same `t`:
159
+
160
+ ```ts
161
+ import { createI18n } from '@softistx/alxia-i18n';
162
+ import { resources as shared } from '@softistx/i18n';
163
+
164
+ const en = { ...shared.en, home: { title: 'Welcome' } };
165
+ const fr = { ...shared.fr, home: { title: 'Bienvenue' } };
166
+
167
+ export const i18n = createI18n({ resources: { en, fr }, fallback: 'en' });
168
+
169
+ i18n.t('errors.not-found'); // 'Could not find the requested resource.'
170
+ ```
171
+
172
+ ### `fallback`
173
+
174
+ The language of every request that names none the catalogues have, of
175
+ `i18n.t()` outside a request — and the catalogue that types the keys. It
176
+ must be one of `resources`' keys; anything else is a compile error:
177
+
178
+ ```text
179
+ error TS2769: No overload matches this call.
180
+ Overload 1 of 2, '(options: I18nOptions<…>): I18nMiddleware<…>', gave the following error.
181
+ Type '"de"' is not assignable to type '"en" | "fr"'.
182
+ ```
183
+
184
+ and, when a cast hides it from the compiler, an error when `createI18n()`
185
+ is called:
186
+
187
+ ```text
188
+ TypeError: createI18n(): there is no catalogue for the fallback "de"
189
+ ```
190
+
191
+ ### The language options
192
+
193
+ To read the language from the path rather than the query:
194
+
195
+ ```ts
196
+ import { alxia } from '@softistx/alxia';
197
+ import { createI18n } from '@softistx/alxia-i18n';
198
+
199
+ const i18n = createI18n({
200
+ resources: { en: { home: { title: 'Welcome' } }, fr: { home: { title: 'Bienvenue' } } },
201
+ fallback: 'en',
202
+ order: ['path', 'header'],
203
+ });
204
+
205
+ export const app = alxia()
206
+ .use(i18n)
207
+ .get('/:lang/home', ({ t, reply }) => reply(200, t('home.title'))); // /fr/home → 'Bienvenue'
208
+ ```
209
+
210
+ The middleware reads the segment; it does not route on it, so the routes
211
+ declare it.
212
+
213
+ ### Reading the app's context
214
+
215
+ To speak the language a signed-in user saved, annotate `resolve`'s
216
+ parameter with what an earlier middleware added. `createI18n()` infers it from
217
+ the annotation — the languages and the keys are still inferred from
218
+ `resources` and `fallback` — and the middleware then requires it: an app that
219
+ does not give `user` before it cannot use it.
220
+
221
+ ```ts
222
+ import { alxia, type BaseContext } from '@softistx/alxia';
223
+ import { createI18n } from '@softistx/alxia-i18n';
224
+
225
+ interface User {
226
+ readonly language: string | null;
227
+ }
228
+
229
+ const i18n = createI18n({
230
+ resources: { en, fr },
231
+ fallback: 'en',
232
+ order: ['query'], // the query decides first, then the user's saved language
233
+ resolve: ({ user }: BaseContext & { user: User | null }) => user?.language ?? undefined,
234
+ });
235
+
236
+ export const app = alxia()
237
+ .plugin(auth) // an app: derives user: User | null
238
+ .use(i18n)
239
+ .get('/', ({ t, reply }) => reply(200, t('home.title')));
240
+
241
+ alxia().use(i18n);
242
+ // error TS2345: … `user` is missing from the context: add a middleware that gives it before this one
243
+ ```
244
+
245
+ This is `@softistx/alxia-language`'s check, carried through; its
246
+ [guide](https://github.com/softistx/alxia/blob/develop/packages/language/docs/guide.md#reading-the-apps-context)
247
+ details it. A `resolve` left unannotated reads `BaseContext` only, and the
248
+ middleware requires nothing. Annotated `any`, it is refused on every
249
+ app:
250
+ [`the plugin's resolve reads its context as any: annotate what it reads, or leave it unannotated`](troubleshooting.md#the-plugins-resolve-reads-its-context-as-any-annotate-what-it-reads-or-leave-it-unannotated).
251
+
252
+ ## What the routes read
253
+
254
+ | Property | Type | Is |
255
+ | --- | --- | --- |
256
+ | `t` | `Translate<KeyOf<C[Fallback]>>` | translates into the request's language |
257
+ | `language` | `keyof C & string` | the request's language: `'en' \| 'fr'` |
258
+ | `languageSource` | `LanguageSource \| 'resolve' \| 'fallback'` | what decided it, from `@softistx/alxia-language` |
259
+
260
+ ```ts
261
+ import { alxia } from '@softistx/alxia';
262
+ import { createI18n } from '@softistx/alxia-i18n';
263
+
264
+ const i18n = createI18n({
265
+ resources: { en: { home: { title: 'Welcome' } }, fr: { home: { title: 'Bienvenue' } } },
266
+ fallback: 'en',
267
+ });
268
+
269
+ export const app = alxia()
270
+ .use(i18n)
271
+ .get('/', ({ t, language, languageSource, reply }) =>
272
+ reply(200, { title: t('home.title'), language, languageSource }),
273
+ );
274
+ // GET /?lang=fr → {"title":"Bienvenue","language":"fr","languageSource":"query"}
275
+ ```
276
+
277
+ They are in the context of every route, and of every `derive`, declared
278
+ after `.use(i18n)`. A standalone middleware (`defineMiddleware`) does not
279
+ know the app it is used on: it calls `i18n.t()`, which follows the request
280
+ ([Outside a route](#outside-a-route)). A route declared before `.use(i18n)`
281
+ reads none of them:
282
+
283
+ ```text
284
+ error TS2339: Property 't' does not exist on type 'Context<Empty, "/", Empty>'.
285
+ ```
286
+
287
+ ## Messages
288
+
289
+ Messages are ICU, formatted by `@softistx/i18n` with `intl-messageformat` in
290
+ the request's language. The second argument of `t` holds the values:
291
+
292
+ ```ts
293
+ import { createI18n } from '@softistx/alxia-i18n';
294
+
295
+ const en = {
296
+ greeting: 'Hello {name}',
297
+ items: '{count, plural, =0 {No items} one {One item} other {# items}}',
298
+ role: '{role, select, admin {an administrator} other {a member}}',
299
+ total: 'Total: {amount, number, ::currency/EUR}',
300
+ };
301
+ const i18n = createI18n({ resources: { en }, fallback: 'en' });
302
+
303
+ i18n.t('greeting', { name: 'Ada' }); // 'Hello Ada'
304
+ i18n.t('items', { count: 3 }); // '3 items'
305
+ i18n.t('role', { role: 'admin' }); // 'an administrator'
306
+ i18n.t('total', { amount: 12.5 }); // 'Total: €12.50'
307
+ ```
308
+
309
+ What `t` answers when it cannot do better — it never throws:
310
+
311
+ | Case | Answer |
312
+ | --- | --- |
313
+ | the key is in the request's catalogue | the message, formatted |
314
+ | the request's catalogue lacks the key | **the key itself**, `'home.title'` — not the fallback's message |
315
+ | a value the message names is missing, or the message is not valid ICU | the message unformatted, `'Hello {name}'`, and the error logged with `console.error` |
316
+
317
+ The values are not typed by the message: `t('greeting')` compiles, and
318
+ answers `'Hello {name}'` with this line in the log:
319
+
320
+ ```text
321
+ The intl string context variable "name" was not provided to the string "Hello {name}"
322
+ ```
323
+
324
+ A language whose catalogue is partial shows keys, not the fallback's
325
+ messages. Fill it from the fallback before passing it — a nested merge, as
326
+ a spread only replaces whole branches:
327
+
328
+ ```ts
329
+ import { createI18n } from '@softistx/alxia-i18n';
330
+
331
+ type Tree = { readonly [key: string]: unknown };
332
+
333
+ const fill = (from: Tree, into: Tree): Tree =>
334
+ Object.fromEntries(
335
+ Object.entries(from).map(([key, value]) => {
336
+ const own = into[key];
337
+ return [
338
+ key,
339
+ typeof value === 'object' && value !== null && typeof own === 'object' && own !== null
340
+ ? fill(value as Tree, own as Tree)
341
+ : (own ?? value),
342
+ ];
343
+ }),
344
+ );
345
+
346
+ const en = { home: { title: 'Welcome', subtitle: 'Good to see you' } };
347
+ const de = { home: { title: 'Willkommen' } }; // no subtitle yet
348
+
349
+ export const i18n = createI18n({ resources: { en, de: fill(en, de) }, fallback: 'en' });
350
+ // in German: t('home.subtitle') → 'Good to see you', not 'home.subtitle'
351
+ ```
352
+
353
+ ## Typed keys
354
+
355
+ `t` takes the dotted keys of the **fallback's** catalogue, and nothing
356
+ else:
357
+
358
+ ```ts
359
+ import { createI18n } from '@softistx/alxia-i18n';
360
+
361
+ const en = { cart: { items: '{count, plural, one {One item} other {# items}}' } };
362
+ const fr = { cart: { items: '{count, plural, one {Un article} other {# articles}}', extra: 'Rien' } };
363
+
364
+ const i18n = createI18n({ resources: { en, fr }, fallback: 'en' });
365
+
366
+ i18n.t('cart.items', { count: 2 });
367
+ // @ts-expect-error: a typo
368
+ i18n.t('cart.itmes');
369
+ // @ts-expect-error: only in French
370
+ i18n.t('cart.extra');
371
+ ```
372
+
373
+ ```text
374
+ error TS2345: Argument of type '"cart.itmes"' is not assignable to parameter of type '"cart.items"'.
375
+ ```
376
+
377
+ The keys are read from the catalogue's type. A catalogue typed
378
+ `Record<string, …>` — built at runtime, or annotated so — has no keys to
379
+ read, and `t` then takes any string. Declare catalogues as literals, import
380
+ them from JSON, or name the keys yourself:
381
+ [Catalogues loaded at runtime](#catalogues-loaded-at-runtime).
382
+
383
+ To type a function that receives `t`, or a key it is given, name the types
384
+ from the catalogue:
385
+
386
+ ```ts
387
+ import { createI18n, type KeyOf, type Translate } from '@softistx/alxia-i18n';
388
+
389
+ const en = { cart: { items: '{count, plural, one {One item} other {# items}}' } };
390
+ export const i18n = createI18n({ resources: { en }, fallback: 'en' });
391
+
392
+ type Key = KeyOf<typeof en>; // 'cart.items'
393
+
394
+ export const describeCart = (t: Translate<Key>, count: number) => t('cart.items', { count });
395
+ ```
396
+
397
+ `KeyOf` gives the keys of `@softistx/i18n`'s `Path`, nine levels deep; a section
398
+ nested deeper gives `section.${string}`, any key under it. The bound is what
399
+ lets a function generic over its catalogues hand them to `createI18n`:
400
+
401
+ ```ts
402
+ import { alxia } from '@softistx/alxia';
403
+ import { type Catalogues, createI18n } from '@softistx/alxia-i18n';
404
+
405
+ export function translatedWith<const C extends Catalogues, const Fallback extends keyof C & string>(
406
+ resources: C,
407
+ fallback: Fallback,
408
+ ) {
409
+ return alxia()
410
+ .use(createI18n({ resources, fallback }))
411
+ .get('/', ({ language, reply }) => reply(200, language));
412
+ }
413
+ ```
414
+
415
+ ## The fallback chain
416
+
417
+ By default a key the request's catalogue lacks answers **itself**. Give
418
+ `t()` a chain of languages to try instead, with the `fallbacks` option and
419
+ `fallBackTo()`:
420
+
421
+ ```ts
422
+ import { alxia } from '@softistx/alxia';
423
+ import { createI18n } from '@softistx/alxia-i18n';
424
+
425
+ const en = { home: { title: 'Welcome', soon: 'Coming soon' } };
426
+ const fr = { home: { title: 'Bienvenue' } };
427
+ const pt = { home: { title: 'Bem-vindo' } };
428
+ const ptBR = {};
429
+
430
+ export const i18n = createI18n({
431
+ resources: { en, fr, pt, 'pt-BR': ptBR },
432
+ fallback: 'en',
433
+ fallbacks: (language) => (language === 'pt-BR' ? ['pt'] : []),
434
+ });
435
+
436
+ const app = alxia()
437
+ .use(i18n)
438
+ // the app knows more once the school is read: add its language for this request
439
+ .derive(({ request }) => {
440
+ i18n.fallBackTo(request.headers.get('x-tenant-language') ?? 'fr');
441
+ return {};
442
+ })
443
+ .get('/', ({ t, reply }) =>
444
+ reply(200, { title: t('home.title'), soon: t('home.soon'), chain: i18n.chain() }),
445
+ );
446
+
447
+ // GET /?lang=pt-BR with x-tenant-language: fr
448
+ // → { "title": "Bienvenue", "soon": "Coming soon", "chain": ["pt-BR", "fr", "pt", "en"] }
449
+ ```
450
+
451
+ `t(key)` tries, in this order and each language once:
452
+
453
+ 1. the request's language;
454
+ 2. the steps `fallBackTo()` added to this request, in the order added;
455
+ 3. `fallbacks(language)`;
456
+ 4. `fallback`.
457
+
458
+ It answers the key itself only when all of them miss. A step can be a
459
+ language with no catalogue (the school's, say): it simply misses, and still
460
+ appears in `chain()`.
461
+
462
+ - **`fallBackTo(language)`** is kept in the request's frame, so concurrent
463
+ requests never see each other's steps. It does nothing outside a request.
464
+ Call it as soon as the app knows — in a `derive` or the GraphQL `context` option — and
465
+ before the `t()` calls it should affect.
466
+ - **`chain()`** returns that list for the request running (`[fallback]` plus
467
+ `fallbacks(fallback)` outside one), for data the app labels itself: pick
468
+ the first language of the chain a stored label has.
469
+ - **`@softistx/i18n`'s own fallback is never part of it.** `@softistx/i18n` 3 looks a
470
+ missing key up in its global fallback language (`getFallbackLanguage()`);
471
+ `t()` finds the language that holds the key itself, in the chain's order,
472
+ and hands it over, so that fallback is neither tried first nor tried at all:
473
+ a key that every language of the chain lacks answers itself.
474
+ - **Without `fallbacks` and without a `fallBackTo` call**, `t()` reads the
475
+ request's language alone, as it always did; `chain()` still lists the
476
+ language then `fallback`. `fallback` joins `t()`'s lookup as soon as the
477
+ `fallbacks` option is given (even returning `[]`), or from the first
478
+ `fallBackTo()` call of a request.
479
+
480
+ ## Catalogues loaded at runtime
481
+
482
+ Catalogues read from a database or a file are typed `Record<string, …>`, so
483
+ `t` would take any string. Name the keys with a type argument instead, and
484
+ give the catalogues when you have them:
485
+
486
+ ```ts
487
+ import { alxia } from '@softistx/alxia';
488
+ import { createI18n } from '@softistx/alxia-i18n';
489
+
490
+ type Key = 'home.title' | 'cart.items';
491
+
492
+ export const i18n = createI18n<Key>({ fallback: 'en' });
493
+
494
+ // at start-up, or whenever the catalogues change: all at once
495
+ export function load(rows: Record<string, Record<string, unknown>>) {
496
+ i18n.setResources(rows);
497
+ }
498
+
499
+ load({
500
+ en: { home: { title: 'Welcome' }, cart: { items: '{count} items' } },
501
+ fr: { home: { title: 'Bienvenue' }, cart: { items: '{count} articles' } },
502
+ });
503
+
504
+ i18n.supported; // ['en', 'fr']
505
+
506
+ alxia()
507
+ .use(i18n)
508
+ .get('/', ({ t, reply }) => reply(200, t('cart.items', { count: 2 })));
509
+ // t('cart.itmes') does not compile: not a Key
510
+ ```
511
+
512
+ - **`Key`** replaces the keys inferred from a literal catalogue. A literal
513
+ `resources` with no type argument still infers them, as before. Name the
514
+ languages too with a second type argument,
515
+ `createI18n<Key, 'en' | 'fr'>(…)`; the third, `Ctx`, is `resolve`'s
516
+ context (inference does not reach it once a type argument is given).
517
+ - **`languages`** seeds `supported` until the first `setResources()`; it
518
+ defaults to `resources`' keys, else `[fallback]`.
519
+ - **`setResources(resources)`** replaces the catalogues atomically. The
520
+ languages supported become its keys: `supported` is updated **in place**
521
+ (the same array) and `@softistx/alxia-language` reads it for the next request. It
522
+ throws a `TypeError`, changing nothing, when `resources` has no catalogue
523
+ for `fallback` (so does `createI18n()` given such `resources`). On a literal
524
+ catalogue its parameter is typed by the known languages, so `language`
525
+ keeps its type.
526
+ - **Only the language-to-catalogue map is copied** (shallow), when given to
527
+ `createI18n()` or `setResources()`: adding, replacing or removing a language
528
+ in the object you passed changes nothing. Mutating a message inside a
529
+ catalogue in place reaches the requests running; give new objects instead.
530
+ - **A request keeps the snapshot it started with**: one in flight when
531
+ `setResources()` runs translates, `t` and `i18n.t()` alike, with the
532
+ catalogues it began with; the next request gets the new ones. Outside a
533
+ request, `i18n.t()` reads the current ones.
534
+
535
+ ## Messages from a database
536
+
537
+ An app that keeps its messages in a collection (one row per key and
538
+ language, `{ key, language, text }`) writes the same few helpers each time.
539
+ They are here, over plain rows and a two-method store, so no database client
540
+ is a dependency.
541
+
542
+ ### Declare the codes
543
+
544
+ ```ts
545
+ import { defineCodes } from '@softistx/alxia-i18n';
546
+
547
+ export const authCodes = defineCodes('auth', ['forbidden', 'expired']);
548
+ type AuthCode = (typeof authCodes)[number]; // 'auth.errors.forbidden' | 'auth.errors.expired'
549
+ ```
550
+
551
+ Write the area and the slugs as literals so that the union type is exact.
552
+
553
+ ### Build a catalogue, with a stable version
554
+
555
+ ```ts
556
+ import { catalogueOf, catalogueVersion, resolveCatalogue } from '@softistx/alxia-i18n';
557
+
558
+ const rows = [
559
+ { key: 'auth.errors.forbidden', language: 'en', text: 'Forbidden' },
560
+ { key: 'auth.errors.forbidden', language: 'fr', text: 'Interdit' },
561
+ { key: 'auth.errors.expired', language: 'en', text: 'Expired' },
562
+ ];
563
+
564
+ catalogueOf(rows, 'fr'); // { auth: { errors: { forbidden: 'Interdit' } } }
565
+
566
+ const { chain, version, messages } = resolveCatalogue(rows, ['fr', 'en']);
567
+ messages(['auth.errors.expired']); // [{ code: 'auth.errors.expired', message: 'Expired' }]
568
+ catalogueVersion(chain) === version; // true
569
+ ```
570
+
571
+ - The chain is `[own, fallback]`; a code comes from the first language that has it.
572
+ - `version` is the first 32 hex characters of the SHA-256 of the chain's JSON
573
+ with every object's keys sorted. The order of the rows, or of the keys in a
574
+ tree, never changes it; any text does. Hand it to clients as a cache key.
575
+ - `catalogueOf` throws on a key that is both a message and a branch
576
+ (`auth` and `auth.errors.x`), on an empty segment (`a..b`, `''`) and on
577
+ `__proto__`, `constructor`, `prototype`.
578
+ - A collection that keeps one row per code with its languages in a map
579
+ (`{ _id, texts: { en, fr } }`) is flattened to rows first:
580
+
581
+ ```ts
582
+ const flat = rows.flatMap((r) =>
583
+ Object.entries(r.texts).map(([language, text]) => ({ key: r._id, language, text })),
584
+ );
585
+ ```
586
+ - The tree is the form `createI18n({ resources })` and `setResources()` take.
587
+
588
+ ### Read one message, or a list of them
589
+
590
+ ```ts
591
+ import { catalogueOf, has, messageAt, messagesOf, stableJson } from '@softistx/alxia-i18n';
592
+
593
+ const fr = catalogueOf(rows, 'fr');
594
+ const en = catalogueOf(rows, 'en');
595
+
596
+ messageAt(fr, 'auth.errors.forbidden'); // 'Interdit' (undefined when absent)
597
+ has(fr, 'auth.errors.expired'); // false
598
+ messagesOf([fr, en], ['auth.errors.expired', 'auth.errors.nope']);
599
+ // [{ code: 'auth.errors.expired', message: 'Expired' }]: each from the first tree that has it, a code none has is left out
600
+ stableJson({ b: 1, a: 2 }); // '{"a":2,"b":1}': the string `version` hashes
601
+ ```
602
+
603
+ `messageAt` and `has` try a flat key (`'auth.errors.x': …`) before the
604
+ dotted path.
605
+
606
+ ### Check the coverage at load time
607
+
608
+ ```ts
609
+ import { assertCoverage, catalogueOf, defineCodes } from '@softistx/alxia-i18n';
610
+
611
+ const codes = defineCodes('auth', ['forbidden', 'expired']);
612
+ const rows = [{ key: 'auth.errors.forbidden', language: 'en', text: 'Forbidden' }];
613
+
614
+ const missing = assertCoverage(codes, catalogueOf(rows, 'en'), { onMissing: 'report' });
615
+ // ['auth.errors.expired']; without onMissing: 'report' it throws, naming them
616
+ ```
617
+
618
+ `assertCoverage(codes, tree, { language?, onMissing? })` throws by default,
619
+ naming the codes and `language`; `onMissing: 'report'` returns the missing
620
+ codes instead. Run it after loading the rows: a declared code with no text in the fallback
621
+ language is otherwise left out of the catalogue without a sound.
622
+
623
+ To check every language, not only the fallback, loop over them with
624
+ `uncovered`:
625
+
626
+ ```ts
627
+ import { catalogueOf, uncovered } from '@softistx/alxia-i18n';
628
+
629
+ for (const language of ['en', 'fr']) {
630
+ const missing = uncovered(codes, catalogueOf(rows, language));
631
+ if (missing.length > 0) console.warn(language, 'lacks', missing);
632
+ }
633
+ ```
634
+
635
+ ### Seed a migration
636
+
637
+ ```ts
638
+ import { removeTexts, restoreTexts, seedsOf, upsertTexts, type TextStore } from '@softistx/alxia-i18n';
639
+
640
+ const store: TextStore = {
641
+ async upsert(rows) {
642
+ // e.g. bulkWrite of updateOne({ key, language }, { $set: { text } }, { upsert: true })
643
+ console.log('upsert', rows.length);
644
+ },
645
+ async remove(keys) {
646
+ // e.g. deleteMany({ key: { $in: keys } })
647
+ console.log('remove', keys.length);
648
+ },
649
+ };
650
+
651
+ const texts = { 'auth.errors.expired': { en: 'Expired', fr: 'Expiré' } };
652
+ seedsOf(texts); // [{ key, language: 'en', text }, { key, language: 'fr', text }]
653
+ await upsertTexts(store, texts);
654
+ await removeTexts(store, texts); // or removeTexts(store, ['auth.errors.expired'])
655
+ await restoreTexts(store, texts);
656
+ ```
657
+
658
+ Texts go code first, `{ code: { en, fr } }`, and a code is dotted. `seedsOf`
659
+ throws on a language-first map (`{ en: { 'a.b': '…' } }`, which the `Texts`
660
+ type also refuses) and on a code that lacks a language another code has, so no
661
+ migration ships a half-translated code. The helpers write nothing when there
662
+ is nothing to write.
663
+
664
+ ### `removeTexts` or `restoreTexts`
665
+
666
+ | the migration | `up` | `down` |
667
+ | --- | --- | --- |
668
+ | created codes | `upsertTexts(store, texts)` | `removeTexts(store, texts)`: the codes did not exist before |
669
+ | reworded existing codes | `upsertTexts(store, next)` | `restoreTexts(store, previous)`: the old wording comes back |
670
+
671
+ `removeTexts` on a rewording deletes messages that existed before the
672
+ migration; the rollback then leaves the codes with no text at all.
673
+
674
+ `down` cannot remove a language row that a rewording added: `restoreTexts`
675
+ only writes the previous wording back, so a language the old texts did not
676
+ have stays. Delete that row in the `down` by hand, or ship the new language
677
+ as its own migration of created codes.
678
+
679
+ ## Outside a route
680
+
681
+ `i18n.t()` translates in the language of the request it runs in, and
682
+ `i18n.language()` says which; outside a request, both are the fallback's.
683
+ Nothing is passed down: the request's language follows every `await` and
684
+ every function the route calls, an event stream's generator included.
685
+
686
+ ```ts
687
+ import { alxia } from '@softistx/alxia';
688
+ import { createI18n } from '@softistx/alxia-i18n';
689
+
690
+ const i18n = createI18n({
691
+ resources: {
692
+ en: { cart: { items: '{count, plural, one {One item} other {# items}}' } },
693
+ fr: { cart: { items: '{count, plural, one {Un article} other {# articles}}' } },
694
+ },
695
+ fallback: 'en',
696
+ });
697
+
698
+ // a service, deep down: no language passed
699
+ async function describeCart(count: number) {
700
+ await Bun.sleep(1);
701
+ return i18n.t('cart.items', { count });
702
+ }
703
+
704
+ export const app = alxia()
705
+ .use(i18n)
706
+ .get('/cart', async ({ reply }) => reply(200, await describeCart(3))); // ?lang=fr → '3 articles'
707
+
708
+ i18n.language(); // 'en': no request here
709
+ ```
710
+
711
+ The middleware reads the request's language, then runs the rest of the
712
+ chain inside it: everything after it knows the language, through every
713
+ `await`, and so does the answer to an error, since `i18n` settles `next()`.
714
+ Before it, `i18n.t()` and `i18n.language()` answer in the fallback:
715
+
716
+ | Where | `i18n.t()` answers in |
717
+ | --- | --- |
718
+ | a middleware, `derive` or route declared after `.use(i18n)`, before and after its `next()`, and what they call | the request's language |
719
+ | a middleware after it that catches an error | the request's language |
720
+ | a middleware after it, on a `404` or a `405` no route matched | the request's language |
721
+ | a middleware declared before `.use(i18n)`, in and out | the fallback: the language is not read yet |
722
+ | a route declared before `.use(i18n)` | the fallback: the middleware does not run for it |
723
+ | code outside any request: start-up, a timer, a queue consumer | the fallback: pass the language, see below |
724
+
725
+ An error-handling middleware translates an error's message with `i18n.t()`.
726
+ Declare it after `.use(i18n)` (and after the observers, `logger()` and
727
+ `telemetry()`):
728
+
729
+ ```ts
730
+ import { alxia, defineMiddleware, HttpError } from '@softistx/alxia';
731
+ import { createI18n } from '@softistx/alxia-i18n';
732
+ import { resources as shared } from '@softistx/i18n';
733
+
734
+ const i18n = createI18n({ resources: { en: shared.en, fr: shared.fr }, fallback: 'en' });
735
+
736
+ export const app = alxia()
737
+ .use(i18n)
738
+ .use(
739
+ defineMiddleware(async ({ reply }, next) => {
740
+ try {
741
+ return await next();
742
+ } catch (error) {
743
+ if (error instanceof HttpError && error.status === 404)
744
+ return reply(404, { error: i18n.t('errors.not-found') });
745
+ throw error;
746
+ }
747
+ }),
748
+ )
749
+ .get('/users/:id', () => {
750
+ throw new HttpError(404, {});
751
+ });
752
+ // GET /users/1?lang=fr → 404 {"error":"Impossible de trouver la ressource demandée."}
753
+ ```
754
+
755
+ Outside any request, a job that knows its user's language uses
756
+ `@softistx/i18n`'s `createTranslator` on the same catalogues, with that
757
+ language:
758
+
759
+ ```ts
760
+ import { createI18n, type KeyOf } from '@softistx/alxia-i18n';
761
+ import { createTranslator } from '@softistx/i18n';
762
+
763
+ const en = { mail: { subject: 'Your order {id}' } };
764
+ const fr = { mail: { subject: 'Votre commande {id}' } };
765
+ const resources = { en, fr };
766
+
767
+ export const i18n = createI18n({ resources, fallback: 'en' });
768
+
769
+ const translator = createTranslator<KeyOf<typeof en>>(resources);
770
+ translator('mail.subject', { id: 42 }, 'fr'); // 'Votre commande 42'
771
+ ```
772
+
773
+ `createTranslator`'s third argument is any language string (`@softistx/i18n` 3's
774
+ `Language` is `string`). Unlike `t()`, that translator looks a missing key, or a
775
+ language with no catalogue, up in `@softistx/i18n`'s own fallback language
776
+ (`getFallbackLanguage()`, `'en'` unless `setFallbackLanguage()` changed it)
777
+ before answering the key.
778
+
779
+ ## `@softistx/i18n`'s own `translate`
780
+
781
+ `createI18n()` registers the request's language as a language source of
782
+ `@softistx/i18n`. Its `getLanguage()` and `translate` — and every package that
783
+ translates through them — answer in the alxia request's language, for a language `@softistx/i18n` has a
784
+ catalogue for:
785
+
786
+ ```ts
787
+ import { alxia } from '@softistx/alxia';
788
+ import { createI18n } from '@softistx/alxia-i18n';
789
+ import { getLanguage, translate, resources as shared } from '@softistx/i18n';
790
+
791
+ const i18n = createI18n({ resources: { en: shared.en, fr: shared.fr }, fallback: 'en' });
792
+
793
+ export const app = alxia()
794
+ .use(i18n)
795
+ .get('/', ({ reply }) => reply(200, { language: getLanguage(), message: translate('errors.not-found') }));
796
+ // GET /?lang=fr → {"language":"fr","message":"Impossible de trouver la ressource demandée."}
797
+ ```
798
+
799
+ Its limits are `@softistx/i18n`'s:
800
+
801
+ - **It speaks the languages it has a catalogue for.** `en` and `fr`, and any
802
+ you give it with `registerCatalogue('de', catalogue)`. A request in `de`
803
+ with no registered catalogue is not one of them, and `getLanguage()` answers
804
+ as if no source had: its fallback language.
805
+ - **Its fallback is `'en'`, not yours**, until `setFallbackLanguage()` says
806
+ otherwise (it throws a `RangeError` for a language with no catalogue).
807
+ Outside a request, or before the language is read, `getLanguage()` answers
808
+ that language even when your `fallback` is `'fr'`. Its `translate` also
809
+ looks a key the language lacks up there; `i18n.t()` does not, it follows
810
+ [your chain](#the-fallback-chain) and answers the key.
811
+ - **It hears one middleware.** With two `createI18n()` on one app, it follows
812
+ the language the first one read — its fallback included, when the
813
+ request named a language only the second supports.
814
+
815
+ ## Caching
816
+
817
+ A response in the request's language varies by what decided it. The
818
+ middleware says so in `Vary` — `Accept-Language, Cookie` with the default `order` —
819
+ and a cache in front of it needs the same headers:
820
+
821
+ ```ts
822
+ import { alxia } from '@softistx/alxia';
823
+ import { cache } from '@softistx/alxia-cache';
824
+ import { createI18n } from '@softistx/alxia-i18n';
825
+
826
+ const i18n = createI18n({
827
+ resources: { en: { home: { title: 'Welcome' } }, fr: { home: { title: 'Bienvenue' } } },
828
+ fallback: 'en',
829
+ });
830
+
831
+ export const app = alxia()
832
+ .use(i18n)
833
+ .use(cache({ ttl: 60, vary: ['accept-language', 'cookie'] }))
834
+ .get('/', ({ t, reply }) => reply(200, t('home.title')));
835
+ ```
836
+
837
+ ## Testing
838
+
839
+ `app.request()` takes the header a browser sends, or the query:
840
+
841
+ ```ts
842
+ import { expect, test } from 'bun:test';
843
+ import { alxia } from '@softistx/alxia';
844
+ import { createI18n } from '@softistx/alxia-i18n';
845
+
846
+ const i18n = createI18n({
847
+ resources: { en: { home: { title: 'Welcome' } }, fr: { home: { title: 'Bienvenue' } } },
848
+ fallback: 'en',
849
+ });
850
+ const app = alxia()
851
+ .use(i18n)
852
+ .get('/', ({ t, reply }) => reply(200, t('home.title')));
853
+
854
+ test("answers in the browser's language", async () => {
855
+ const response = await app.request('/', { headers: { 'accept-language': 'fr-FR,fr;q=0.9' } });
856
+ expect(await response.text()).toBe('Bienvenue');
857
+ expect(response.headers.get('content-language')).toBe('fr');
858
+ });
859
+
860
+ test('answers in the fallback when nothing names a language', async () => {
861
+ expect(await (await app.request('/')).text()).toBe('Welcome');
862
+ });
863
+ ```
864
+
865
+ ## A realistic setup
866
+
867
+ Catalogues in JSON, `@softistx/i18n`'s shared messages spread in, a service
868
+ that translates without being passed a language, errors rendered in the
869
+ request's language, and a language switcher that sticks:
870
+
871
+ ```ts
872
+ // src/i18n.ts
873
+ import { createI18n } from '@softistx/alxia-i18n';
874
+ import { resources as shared } from '@softistx/i18n';
875
+ import ownEn from './locales/en.json';
876
+ import ownFr from './locales/fr.json';
877
+
878
+ export const i18n = createI18n({
879
+ resources: { en: { ...shared.en, ...ownEn }, fr: { ...shared.fr, ...ownFr } },
880
+ fallback: 'en',
881
+ persist: { secure: Bun.env.NODE_ENV !== 'development' }, // read at runtime: bun build inlines process.env
882
+ });
883
+ ```
884
+
885
+ ```ts
886
+ // src/app.ts
887
+ import { alxia, defineMiddleware, HttpError } from '@softistx/alxia';
888
+ import { i18n } from './i18n';
889
+
890
+ const carts = new Map<string, string[]>([['c1', ['book', 'pen']]]);
891
+
892
+ // a service: no language passed
893
+ const describeCart = (items: readonly string[]) => i18n.t('cart.items', { count: items.length });
894
+
895
+ export const app = alxia()
896
+ .use(i18n)
897
+ .use(
898
+ defineMiddleware(async ({ reply }, next) => {
899
+ try {
900
+ return await next();
901
+ } catch (error) {
902
+ if (error instanceof HttpError && error.status === 404)
903
+ return reply(404, { error: i18n.t('errors.not-found') });
904
+ throw error;
905
+ }
906
+ }),
907
+ )
908
+ .get('/carts/:id', ({ params, reply }) => {
909
+ const items = carts.get(params.id);
910
+ if (items === undefined) throw new HttpError(404, {});
911
+ return reply(200, { items, summary: describeCart(items) });
912
+ });
913
+
914
+ app.listen(3000);
915
+ ```
916
+
917
+ With `locales/en.json` holding
918
+ `{ "cart": { "items": "{count, plural, =0 {No items} one {One item} other {# items}}" } }`,
919
+ `/carts/c1?lang=fr` answers `{"items":["book","pen"],"summary":"2 articles"}`
920
+ and sets the `language` cookie, so `/carts/c2` — without the query —
921
+ answers `404 {"error":"Impossible de trouver la ressource demandée."}`.
922
+
923
+ When something does not answer in the language you expected, see
924
+ [Troubleshooting](troubleshooting.md).