@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/dist/index.js ADDED
@@ -0,0 +1,266 @@
1
+ // src/catalogue.ts
2
+ import { createHash } from "node:crypto";
3
+
4
+ // src/lookup.ts
5
+ function messageAt(catalogue, key) {
6
+ if (catalogue === undefined)
7
+ return;
8
+ if (Object.hasOwn(catalogue, key)) {
9
+ const flat = catalogue[key];
10
+ return typeof flat === "string" ? flat : undefined;
11
+ }
12
+ let at = catalogue;
13
+ for (const part of key.split(".")) {
14
+ if (typeof at !== "object" || at === null)
15
+ return;
16
+ if (!Object.hasOwn(at, part))
17
+ return;
18
+ at = at[part];
19
+ }
20
+ return typeof at === "string" ? at : undefined;
21
+ }
22
+ function has(catalogue, key) {
23
+ return messageAt(catalogue, key) !== undefined;
24
+ }
25
+ function holder(resources, chain, key) {
26
+ return chain.find((language) => has(Object.hasOwn(resources, language) ? resources[language] : undefined, key));
27
+ }
28
+ function unique(...steps) {
29
+ return [...new Set(steps)];
30
+ }
31
+
32
+ // src/catalogue.ts
33
+ var unsafe = new Set(["__proto__", "constructor", "prototype"]);
34
+ var clash = (key) => new TypeError(`translations: "${key}" is both a message and a branch`);
35
+ function catalogueOf(rows, language) {
36
+ const root = Object.create(null);
37
+ for (const row of rows) {
38
+ if (row.language !== language)
39
+ continue;
40
+ const path = row.key.split(".");
41
+ if (path.some((step) => step === ""))
42
+ throw new TypeError(`translations: "${row.key}" has an empty segment (a key is dotted names, like "area.errors.slug")`);
43
+ if (path.some((step) => unsafe.has(step)))
44
+ throw new TypeError(`translations: "${row.key}" names a prototype member (__proto__, constructor or prototype)`);
45
+ const leaf = path.pop();
46
+ let branch = root;
47
+ for (const step of path) {
48
+ const next = branch[step] ?? Object.create(null);
49
+ if (typeof next === "string")
50
+ throw clash(row.key);
51
+ branch[step] = next;
52
+ branch = next;
53
+ }
54
+ if (branch[leaf] !== undefined)
55
+ throw clash(row.key);
56
+ branch[leaf] = row.text;
57
+ }
58
+ return root;
59
+ }
60
+ function messagesOf(chain, codes) {
61
+ const messages = [];
62
+ for (const code of codes) {
63
+ for (const tree of chain) {
64
+ const message = messageAt(tree, code);
65
+ if (message === undefined)
66
+ continue;
67
+ messages.push({ code, message });
68
+ break;
69
+ }
70
+ }
71
+ return messages;
72
+ }
73
+ function stableJson(value) {
74
+ if (typeof value !== "object" || value === null)
75
+ return JSON.stringify(value) ?? "null";
76
+ if (Array.isArray(value))
77
+ return `[${value.map(stableJson).join(",")}]`;
78
+ const entries = Object.entries(value).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([key, item]) => `${JSON.stringify(key)}:${stableJson(item)}`);
79
+ return `{${entries.join(",")}}`;
80
+ }
81
+ function catalogueVersion(chain) {
82
+ return createHash("sha256").update(stableJson(chain)).digest("hex").slice(0, 32);
83
+ }
84
+ function resolveCatalogue(rows, languages) {
85
+ const chain = languages.map((language) => catalogueOf(rows, language));
86
+ return {
87
+ language: languages[0],
88
+ chain,
89
+ version: catalogueVersion(chain),
90
+ messages: (codes) => messagesOf(chain, codes)
91
+ };
92
+ }
93
+ // src/codes.ts
94
+ function defineCodes(area, slugs) {
95
+ return slugs.map((slug) => `${area}.errors.${slug}`);
96
+ }
97
+ // src/coverage.ts
98
+ function uncovered(codes, catalogue) {
99
+ return codes.filter((code) => !has(catalogue, code));
100
+ }
101
+ function assertCoverage(codes, fallback, options = {}) {
102
+ const missing = uncovered(codes, fallback);
103
+ if (missing.length > 0 && options.onMissing !== "report") {
104
+ const where = options.language === undefined ? "" : ` in "${options.language}"`;
105
+ throw new TypeError(`translations: ${missing.length} declared code(s) have no text${where}: ${missing.join(", ")}`);
106
+ }
107
+ return missing;
108
+ }
109
+ // src/i18n.ts
110
+ import { AsyncLocalStorage } from "node:async_hooks";
111
+ import {
112
+ defineMiddleware,
113
+ markFactory,
114
+ settle
115
+ } from "@softistx/alxia";
116
+ import { language } from "@softistx/alxia-language";
117
+ import { registerLanguageSource } from "@softistx/i18n";
118
+
119
+ // src/chain.ts
120
+ import { createTranslator } from "@softistx/i18n";
121
+ var unanswered = createTranslator({});
122
+ var snapshotOf = (resources) => ({
123
+ resources,
124
+ translator: createTranslator(resources)
125
+ });
126
+ function chainOf({ fallback, fallbacks }, frame) {
127
+ const language = frame?.language ?? fallback;
128
+ return unique(language, ...frame?.steps ?? [], ...fallbacks?.(language) ?? [], fallback);
129
+ }
130
+ function translateFor(steps, of, live) {
131
+ return (key, context) => {
132
+ const frame = of();
133
+ const { resources, translator } = frame?.snapshot ?? live();
134
+ const language = frame?.language ?? steps.fallback;
135
+ const chained = steps.fallbacks !== undefined || (frame?.steps.length ?? 0) > 0;
136
+ const found = holder(resources, chained ? chainOf(steps, frame) : [language], key);
137
+ return found === undefined ? unanswered(key, context, language) : translator(key, context, found);
138
+ };
139
+ }
140
+
141
+ // src/i18n.ts
142
+ var requests = new AsyncLocalStorage;
143
+ function hearing(url, work) {
144
+ return requests.getStore()?.url === url ? work() : requests.run({ url }, work);
145
+ }
146
+ var requestLanguage = () => requests.getStore()?.language;
147
+ function perRequest({ current, detected, steps, live }) {
148
+ return defineMiddleware()(function i18n(ctx, next) {
149
+ const own = { snapshot: live(), steps: [] };
150
+ const bound = translateFor(steps, () => own, live);
151
+ const found = (heard) => {
152
+ own.language = heard.language;
153
+ const store = requests.getStore();
154
+ if (store !== undefined)
155
+ store.language ??= heard.language;
156
+ return settle(ctx, next({ ...heard, t: bound }));
157
+ };
158
+ const detecting = Object.assign(found, {
159
+ behind: next.behind
160
+ });
161
+ return current.run(own, () => hearing(ctx.url, () => detected(ctx, detecting)));
162
+ });
163
+ }
164
+ function createI18n(options) {
165
+ const {
166
+ resources: initial = {},
167
+ languages,
168
+ fallback,
169
+ fallbacks,
170
+ resolve,
171
+ ...detect
172
+ } = options;
173
+ if (options.resources !== undefined && !Object.hasOwn(options.resources, fallback)) {
174
+ throw new TypeError(`createI18n(): there is no catalogue for the fallback "${fallback}"`);
175
+ }
176
+ const supported = [...languages ?? Object.keys(initial)];
177
+ if (languages === undefined && !supported.includes(fallback)) {
178
+ supported.push(fallback);
179
+ }
180
+ let live = snapshotOf({ ...initial });
181
+ const steps = { fallback, fallbacks };
182
+ const current = new AsyncLocalStorage;
183
+ const spoken = () => current.getStore()?.language ?? fallback;
184
+ registerLanguageSource(requestLanguage);
185
+ const detected = language({
186
+ ...detect,
187
+ supported,
188
+ fallback,
189
+ ...resolve === undefined ? {} : { resolve }
190
+ });
191
+ const middleware = perRequest({
192
+ current,
193
+ detected,
194
+ steps,
195
+ live: () => live
196
+ });
197
+ return Object.assign(middleware, {
198
+ t: translateFor(steps, () => current.getStore(), () => live),
199
+ language: spoken,
200
+ supported,
201
+ chain: () => chainOf(steps, current.getStore()),
202
+ fallBackTo(language) {
203
+ current.getStore()?.steps.push(language);
204
+ },
205
+ setResources(resources) {
206
+ if (!Object.hasOwn(resources, fallback)) {
207
+ throw new TypeError(`setResources(): there is no catalogue for the fallback "${fallback}"`);
208
+ }
209
+ live = snapshotOf({ ...resources });
210
+ supported.splice(0, supported.length, ...Object.keys(resources));
211
+ }
212
+ });
213
+ }
214
+ markFactory(createI18n);
215
+ // src/seeds.ts
216
+ function seedsOf(texts) {
217
+ for (const [code, byLanguage] of Object.entries(texts)) {
218
+ if (!code.includes("."))
219
+ throw new TypeError(`translation "${code}" is not a code: codes are dotted ("area.errors.slug"); texts go code first, { code: { en, fr } }, not language first`);
220
+ for (const language of Object.keys(byLanguage))
221
+ if (language.includes("."))
222
+ throw new TypeError(`translation "${code}" has a language "${language}" that looks like a code: texts go code first, { code: { en, fr } }`);
223
+ }
224
+ const languages = [
225
+ ...new Set(Object.values(texts).flatMap((byLanguage) => Object.keys(byLanguage)))
226
+ ];
227
+ return Object.keys(texts).sort().flatMap((key) => languages.map((language) => {
228
+ const text = texts[key]?.[language];
229
+ if (text === undefined)
230
+ throw new TypeError(`translation "${key}" has no ${language} text`);
231
+ return { key, language, text };
232
+ }));
233
+ }
234
+ async function upsertTexts(store, texts) {
235
+ const rows = seedsOf(texts);
236
+ if (rows.length > 0)
237
+ await store.upsert(rows);
238
+ }
239
+ async function removeTexts(store, codes) {
240
+ const keys = Array.isArray(codes) ? codes : Object.keys(codes);
241
+ if (keys.length > 0)
242
+ await store.remove([...new Set(keys)]);
243
+ }
244
+ async function restoreTexts(store, previous) {
245
+ await upsertTexts(store, previous);
246
+ }
247
+ export {
248
+ assertCoverage,
249
+ catalogueOf,
250
+ catalogueVersion,
251
+ createI18n,
252
+ defineCodes,
253
+ has,
254
+ messageAt,
255
+ messagesOf,
256
+ removeTexts,
257
+ resolveCatalogue,
258
+ restoreTexts,
259
+ seedsOf,
260
+ stableJson,
261
+ uncovered,
262
+ upsertTexts
263
+ };
264
+
265
+ //# debugId=44F35C4E639F24CF64756E2164756E21
266
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,16 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/catalogue.ts", "../src/lookup.ts", "../src/codes.ts", "../src/coverage.ts", "../src/i18n.ts", "../src/chain.ts", "../src/seeds.ts"],
4
+ "sourcesContent": [
5
+ "import { createHash } from 'node:crypto';\nimport { messageAt } from './lookup';\n\n/** A row of a translations collection. */\nexport interface TextRow {\n\tkey: string;\n\tlanguage: string;\n\ttext: string;\n}\n\n/** A catalogue as `createI18n` reads it: dotted keys as a nested tree. */\nexport type Tree = { [key: string]: string | Tree };\n\nexport interface MessageView {\n\tcode: string;\n\tmessage: string;\n}\n\nconst unsafe = new Set(['__proto__', 'constructor', 'prototype']);\n\nconst clash = (key: string) =>\n\tnew TypeError(`translations: \"${key}\" is both a message and a branch`);\n\n/**\n * The message tree of one language: the rows that have a text in it\n * (`auth.errors.forbidden` is `{ auth: { errors: { forbidden } } }`). A key\n * that is both a message and the start of another key, that has an empty\n * segment (`a..b`, ``) or that names a prototype member throws: the tree\n * cannot hold it.\n */\nexport function catalogueOf(rows: readonly TextRow[], language: string): Tree {\n\tconst root: Tree = Object.create(null) as Tree;\n\tfor (const row of rows) {\n\t\tif (row.language !== language) continue;\n\t\tconst path = row.key.split('.');\n\t\tif (path.some((step) => step === ''))\n\t\t\tthrow new TypeError(\n\t\t\t\t`translations: \"${row.key}\" has an empty segment (a key is dotted names, like \"area.errors.slug\")`,\n\t\t\t);\n\t\tif (path.some((step) => unsafe.has(step)))\n\t\t\tthrow new TypeError(\n\t\t\t\t`translations: \"${row.key}\" names a prototype member (__proto__, constructor or prototype)`,\n\t\t\t);\n\t\tconst leaf = path.pop() as string;\n\t\tlet branch = root;\n\t\tfor (const step of path) {\n\t\t\tconst next = branch[step] ?? (Object.create(null) as Tree);\n\t\t\tif (typeof next === 'string') throw clash(row.key);\n\t\t\tbranch[step] = next;\n\t\t\tbranch = next;\n\t\t}\n\t\tif (branch[leaf] !== undefined) throw clash(row.key);\n\t\tbranch[leaf] = row.text;\n\t}\n\treturn root;\n}\n\n/** Every code's message, each from the first tree of `chain` that has it; a code none has is left out. */\nexport function messagesOf(\n\tchain: readonly Tree[],\n\tcodes: readonly string[],\n): MessageView[] {\n\tconst messages: MessageView[] = [];\n\tfor (const code of codes) {\n\t\tfor (const tree of chain) {\n\t\t\tconst message = messageAt(tree, code);\n\t\t\tif (message === undefined) continue;\n\t\t\tmessages.push({ code, message });\n\t\t\tbreak;\n\t\t}\n\t}\n\treturn messages;\n}\n\n/** JSON with the keys of every object sorted: the same tree is the same string whatever the order it was built in. */\nexport function stableJson(value: unknown): string {\n\tif (typeof value !== 'object' || value === null)\n\t\treturn JSON.stringify(value) ?? 'null';\n\tif (Array.isArray(value)) return `[${value.map(stableJson).join(',')}]`;\n\tconst entries = Object.entries(value as Record<string, unknown>)\n\t\t.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n\t\t.map(([key, item]) => `${JSON.stringify(key)}:${stableJson(item)}`);\n\treturn `{${entries.join(',')}}`;\n}\n\n/**\n * The version of what a language serves: 32 hex characters of the SHA-256 of\n * its chain's key-sorted JSON. It changes with any text and is the same\n * after a restart and on every instance.\n */\nexport function catalogueVersion(chain: readonly Tree[]): string {\n\treturn createHash('sha256')\n\t\t.update(stableJson(chain))\n\t\t.digest('hex')\n\t\t.slice(0, 32);\n}\n\nexport interface ResolvedCatalogue {\n\t/** The first language of the chain. */\n\tlanguage: string;\n\t/** One tree per language of the chain, own language first. */\n\tchain: Tree[];\n\tversion: string;\n\t/** The messages of `codes`, each from the first language that has it. */\n\tmessages(codes: readonly string[]): MessageView[];\n}\n\n/** Resolves `rows` for a language chain (`[own, fallback]`): its trees, its version and its messages. */\nexport function resolveCatalogue(\n\trows: readonly TextRow[],\n\tlanguages: readonly [string, ...string[]],\n): ResolvedCatalogue {\n\tconst chain = languages.map((language) => catalogueOf(rows, language));\n\treturn {\n\t\tlanguage: languages[0],\n\t\tchain,\n\t\tversion: catalogueVersion(chain),\n\t\tmessages: (codes) => messagesOf(chain, codes),\n\t};\n}\n",
6
+ "import type { Catalogues } from './types';\n\n/**\n * The message at the dotted `key` of `catalogue`, or `undefined`: the lookup\n * `@softistx/i18n`'s translator makes, a string — a number or a section of\n * messages is not one, and `@softistx/i18n` 3 would answer it from its own\n * fallback language — so that a language which lacks a key can be told from one whose\n * message happens to be the key itself. A key is a dotted path, or a flat\n * key of the catalogue (tried first, as in lodash's `get`); bracket paths\n * (`a[0]`) are not supported.\n */\nexport function messageAt(\n\tcatalogue: Readonly<Record<string, unknown>> | undefined,\n\tkey: string,\n): string | undefined {\n\tif (catalogue === undefined) return undefined;\n\tif (Object.hasOwn(catalogue, key)) {\n\t\tconst flat = catalogue[key];\n\t\treturn typeof flat === 'string' ? flat : undefined;\n\t}\n\tlet at: unknown = catalogue;\n\tfor (const part of key.split('.')) {\n\t\tif (typeof at !== 'object' || at === null) return undefined;\n\t\tif (!Object.hasOwn(at, part)) return undefined;\n\t\tat = (at as Record<string, unknown>)[part];\n\t}\n\treturn typeof at === 'string' ? at : undefined;\n}\n\n/** Whether `catalogue` has a message at the dotted `key` (see `messageAt`). */\nexport function has(\n\tcatalogue: Readonly<Record<string, unknown>> | undefined,\n\tkey: string,\n): boolean {\n\treturn messageAt(catalogue, key) !== undefined;\n}\n\n/** The first language of `chain` whose catalogue has `key`. */\nexport function holder(\n\tresources: Catalogues,\n\tchain: readonly string[],\n\tkey: string,\n): string | undefined {\n\treturn chain.find((language) =>\n\t\thas(\n\t\t\tObject.hasOwn(resources, language) ? resources[language] : undefined,\n\t\t\tkey,\n\t\t),\n\t);\n}\n\n/** `steps` in order, each once. */\nexport function unique(...steps: readonly string[]): string[] {\n\treturn [...new Set(steps)];\n}\n",
7
+ "/** An error code, `<area>.errors.<slug>`. */\nexport type Code<\n\tArea extends string,\n\tSlug extends string,\n> = `${Area}.errors.${Slug}`;\n\n/**\n * An area's error codes as `<area>.errors.<slug>` literals, with their union\n * type. Write the area and the slugs as literals, so that a tool reading\n * the calls can find them: `defineCodes('nodes', ['not-found'])`.\n */\nexport function defineCodes<\n\tconst Area extends string,\n\tconst Slugs extends readonly string[],\n>(area: Area, slugs: Slugs): readonly Code<Area, Slugs[number]>[] {\n\treturn slugs.map((slug) => `${area}.errors.${slug}` as const);\n}\n",
8
+ "import type { Tree } from './catalogue';\nimport { has } from './lookup';\n\nexport interface CoverageOptions {\n\t/** Named in the error, e.g. the fallback language. */\n\tlanguage?: string;\n\t/** `'throw'` (default) refuses; `'report'` returns the missing codes. */\n\tonMissing?: 'throw' | 'report';\n}\n\n/** The declared `codes` that have no message in `catalogue`, in order. */\nexport function uncovered(codes: readonly string[], catalogue: Tree): string[] {\n\treturn codes.filter((code) => !has(catalogue, code));\n}\n\n/**\n * The load-time coverage check: every declared code needs a text in the\n * fallback language's catalogue, or `catalogueOf`-built catalogues would\n * silently leave it out. Throws naming the missing codes, or with\n * `onMissing: 'report'` returns them. Returns `[]` when all are covered.\n */\nexport function assertCoverage(\n\tcodes: readonly string[],\n\tfallback: Tree,\n\toptions: CoverageOptions = {},\n): string[] {\n\tconst missing = uncovered(codes, fallback);\n\tif (missing.length > 0 && options.onMissing !== 'report') {\n\t\tconst where =\n\t\t\toptions.language === undefined ? '' : ` in \"${options.language}\"`;\n\t\tthrow new TypeError(\n\t\t\t`translations: ${missing.length} declared code(s) have no text${where}: ${missing.join(', ')}`,\n\t\t);\n\t}\n\treturn missing;\n}\n",
9
+ "import { AsyncLocalStorage } from 'node:async_hooks';\nimport {\n\ttype BaseContext,\n\tdefineMiddleware,\n\tmarkFactory,\n\ttype Next,\n\ttype NextFunction,\n\ttype RequiresOf,\n\tsettle,\n} from '@softistx/alxia';\nimport { type LanguageContext, language } from '@softistx/alxia-language';\nimport { registerLanguageSource } from '@softistx/i18n';\nimport {\n\tchainOf,\n\ttype Frame,\n\ttype Snapshot,\n\ttype Steps,\n\tsnapshotOf,\n\ttranslateFor,\n} from './chain';\nimport type {\n\tCatalogues,\n\tI18nContext,\n\tI18nMiddleware,\n\tI18nOptions,\n\tKeyOf,\n\tRuntimeI18nOptions,\n} from './types';\n\n/**\n * The request's language as `@softistx/i18n` hears it: the first an i18n\n * middleware read, when an app uses several. Opened for each request —\n * one made from inside another included — by the first that runs on it.\n */\nconst requests = new AsyncLocalStorage<{ url: URL; language?: string }>();\n\n/** Runs `work` with the request `url`'s store open: the one in force, or a fresh one. */\nfunction hearing<T>(url: URL, work: () => T): T {\n\treturn requests.getStore()?.url === url\n\t\t? work()\n\t\t: requests.run({ url }, work);\n}\n\n/** `@softistx/i18n`'s source: one function, so registering it again keeps one. */\nconst requestLanguage = () => requests.getStore()?.language;\n\n/** What the middleware of one `createI18n()` works with. */\ninterface Parts {\n\treadonly current: AsyncLocalStorage<Frame>;\n\treadonly detected: ReturnType<typeof language<string>>;\n\treadonly steps: Steps;\n\treadonly live: () => Snapshot;\n}\n\ntype Added = LanguageContext<string> & I18nContext<string>;\n\n/** The middleware: opens a request's frame around everything after it. */\nfunction perRequest({ current, detected, steps, live }: Parts) {\n\treturn defineMiddleware<object>()(function i18n(ctx, next): Promise<\n\t\tNext<Added>\n\t> {\n\t\tconst own: Frame = { snapshot: live(), steps: [] };\n\t\tconst bound = translateFor(steps, () => own, live);\n\t\tconst found = (heard: LanguageContext<string>) => {\n\t\t\town.language = heard.language;\n\t\t\tconst store = requests.getStore();\n\t\t\tif (store !== undefined) store.language ??= heard.language;\n\t\t\treturn settle(ctx, next({ ...heard, t: bound }));\n\t\t};\n\t\t// `language()`'s middleware, run inline: its `next` is this one's.\n\t\tconst detecting = Object.assign(found, {\n\t\t\tbehind: next.behind,\n\t\t}) as unknown as NextFunction;\n\t\treturn current.run(own, () =>\n\t\t\thearing(ctx.url, () => detected(ctx as never, detecting)),\n\t\t) as Promise<Next<Added>>;\n\t});\n}\n\n/**\n * Translations, as a middleware, on [`@softistx/i18n`](https://www.npmjs.com/package/@softistx/i18n):\n * `@softistx/alxia-language` reads the request's language among the catalogues', and\n * the routes declared after it read `language` and `t`, bound to it. Keys\n * are typed by the fallback's catalogue; messages are ICU — plurals,\n * selects, numbers — and a key missing in every language of the chain\n * answers itself.\n *\n * Its own `t()` translates anywhere a request runs after it — a service,\n * the answer to an error, a try/catch middleware's included — in that\n * request's language, and in the fallback outside.\n *\n * ```ts\n * const i18n = createI18n({ resources: { en, fr }, fallback: 'en' });\n * app.use(i18n).get('/', ({ t, reply }) => reply(200, t('home.title')));\n * ```\n *\n * Catalogues that load at runtime take their keys as a type argument:\n * `createI18n<Key>({ fallback: 'en' })`, then `i18n.setResources(loaded)`.\n *\n * It registers the request's language as one of `@softistx/i18n`'s language\n * sources, so its own `getLanguage()` and `translate` — and every nxgt\n * package that translates through them — speak it too.\n */\nexport function createI18n<\n\tconst C extends Catalogues,\n\tconst Fallback extends keyof C & string,\n\tCtx extends object = BaseContext,\n>(\n\toptions: I18nOptions<C, Fallback, Ctx>,\n): I18nMiddleware<\n\tkeyof C & string,\n\tKeyOf<C[Fallback]>,\n\tRequiresOf<Ctx, 'resolve'>\n>;\nexport function createI18n<\n\tKey extends string = never,\n\tLanguage extends string = string,\n\tCtx extends object = BaseContext,\n>(\n\toptions: [Key] extends [never]\n\t\t? 'name the keys with createI18n<Key>(…), or give resources whose fallback is one of their languages'\n\t\t: RuntimeI18nOptions<Language, Ctx>,\n): I18nMiddleware<Language, Key, RequiresOf<Ctx, 'resolve'>>;\nexport function createI18n(\n\toptions: RuntimeI18nOptions<string, object>,\n): I18nMiddleware<string, string, any> {\n\tconst {\n\t\tresources: initial = {},\n\t\tlanguages,\n\t\tfallback,\n\t\tfallbacks,\n\t\tresolve,\n\t\t...detect\n\t} = options;\n\tif (\n\t\toptions.resources !== undefined &&\n\t\t!Object.hasOwn(options.resources, fallback)\n\t) {\n\t\tthrow new TypeError(\n\t\t\t`createI18n(): there is no catalogue for the fallback \"${fallback}\"`,\n\t\t);\n\t}\n\tconst supported = [...(languages ?? Object.keys(initial))];\n\tif (languages === undefined && !supported.includes(fallback)) {\n\t\tsupported.push(fallback);\n\t}\n\tlet live: Snapshot = snapshotOf({ ...initial });\n\tconst steps = { fallback, fallbacks };\n\t/**\n\t * This middleware's frame for the request running, opened fresh for each\n\t * request — one made from inside another included — around everything\n\t * after it, the answer to an error included: `settle` answers it inside.\n\t */\n\tconst current = new AsyncLocalStorage<Frame>();\n\tconst spoken = (): string => current.getStore()?.language ?? fallback;\n\n\t// nxgt's own getLanguage() and translate speak the request's language too.\n\tregisterLanguageSource(requestLanguage);\n\n\t// The plugin requires what `resolve` reads, and `app.plugin` checks the app gives\n\t// it; the `language()` inside is then handed `resolve` as reading only\n\t// `BaseContext`, since a context that is a type parameter defers the check.\n\tconst detected = language<string>({\n\t\t...detect,\n\t\tsupported,\n\t\tfallback,\n\t\t...(resolve === undefined\n\t\t\t? {}\n\t\t\t: { resolve: resolve as (ctx: BaseContext) => string | undefined }),\n\t});\n\tconst middleware = perRequest({\n\t\tcurrent,\n\t\tdetected,\n\t\tsteps,\n\t\tlive: () => live,\n\t});\n\n\treturn Object.assign(middleware, {\n\t\tt: translateFor(\n\t\t\tsteps,\n\t\t\t() => current.getStore(),\n\t\t\t() => live,\n\t\t),\n\t\tlanguage: spoken,\n\t\tsupported,\n\t\tchain: () => chainOf(steps, current.getStore()),\n\t\tfallBackTo(language: string) {\n\t\t\tcurrent.getStore()?.steps.push(language);\n\t\t},\n\t\tsetResources(resources: Catalogues) {\n\t\t\tif (!Object.hasOwn(resources, fallback)) {\n\t\t\t\tthrow new TypeError(\n\t\t\t\t\t`setResources(): there is no catalogue for the fallback \"${fallback}\"`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tlive = snapshotOf({ ...resources });\n\t\t\tsupported.splice(0, supported.length, ...Object.keys(resources));\n\t\t},\n\t}) as unknown as I18nMiddleware<string, string, any>;\n}\n\nmarkFactory(createI18n);\n",
10
+ "import { createTranslator, type TranslationContext } from '@softistx/i18n';\nimport { holder, unique } from './lookup';\nimport type { Catalogues, Translate } from './types';\n\n/** What a request keeps from the catalogues it started with. */\nexport interface Snapshot {\n\treadonly resources: Catalogues;\n\treadonly translator: (\n\t\tkey: string,\n\t\tcontext?: TranslationContext,\n\t\tlanguage?: string,\n\t) => string;\n}\n\n/** One request's frame, opened around everything after the middleware. */\nexport interface Frame {\n\treadonly snapshot: Snapshot;\n\t/** `fallBackTo`'s steps, in order. */\n\treadonly steps: string[];\n\tlanguage?: string;\n}\n\n/**\n * A translator over no catalogue: it answers the key, formatted as ICU as\n * `@softistx/i18n` does. `@softistx/i18n` 3 looks a missing key up in its own global\n * fallback language (`getFallbackLanguage()`, `'en'` unless set), which is not\n * this package's `fallback`; a key no language of the chain holds therefore\n * never reaches the catalogues' translator.\n */\nconst unanswered = createTranslator<string>({});\n\n/** The catalogues, ready to translate. */\nexport const snapshotOf = (resources: Catalogues): Snapshot => ({\n\tresources,\n\ttranslator: createTranslator<string>(resources as Record<string, unknown>),\n});\n\n/** What decides a chain: the `fallback` and the `fallbacks` option. */\nexport interface Steps {\n\treadonly fallback: string;\n\treadonly fallbacks?: ((language: string) => readonly string[]) | undefined;\n}\n\n/** The chain of a request (none: outside one): its language, its steps, `fallbacks`, `fallback`. */\nexport function chainOf(\n\t{ fallback, fallbacks }: Steps,\n\tframe: Frame | undefined,\n): string[] {\n\tconst language = frame?.language ?? fallback;\n\treturn unique(\n\t\tlanguage,\n\t\t...(frame?.steps ?? []),\n\t\t...(fallbacks?.(language) ?? []),\n\t\tfallback,\n\t);\n}\n\n/**\n * `t` for the frame `of` answers (none: outside a request, the `live`\n * catalogues): its snapshot's catalogues, its chain. The language that holds\n * the key is found here, in the chain's order, and handed to `@softistx/i18n`,\n * whose own fallback lookup therefore never runs. Until the chain is used —\n * no `fallbacks`, no step — only the request's language is tried, and a key it\n * lacks answers itself.\n */\nexport function translateFor(\n\tsteps: Steps,\n\tof: () => Frame | undefined,\n\tlive: () => Snapshot,\n): Translate<string> {\n\treturn (key, context?: TranslationContext) => {\n\t\tconst frame = of();\n\t\tconst { resources, translator } = frame?.snapshot ?? live();\n\t\tconst language = frame?.language ?? steps.fallback;\n\t\tconst chained =\n\t\t\tsteps.fallbacks !== undefined || (frame?.steps.length ?? 0) > 0;\n\t\tconst found = holder(\n\t\t\tresources,\n\t\t\tchained ? chainOf(steps, frame) : [language],\n\t\t\tkey,\n\t\t);\n\t\treturn found === undefined\n\t\t\t? unanswered(key, context, language)\n\t\t\t: translator(key, context, found);\n\t};\n}\n",
11
+ "import type { TextRow } from './catalogue';\n\nexport type { TextRow };\n\n/**\n * The texts of a migration, code first: `{ 'auth.errors.expired': { en, fr } }`.\n * A code is dotted, so a language-first literal (`{ en: { … } }`) does not\n * type-check.\n */\nexport type Texts = Readonly<\n\tRecord<`${string}.${string}`, Readonly<Record<string, string>>>\n>;\n\n/**\n * What the seed helpers need of the database: two writes. An app implements\n * it over its driver (a `bulkWrite` of upserts, a `deleteMany`), so the\n * package depends on no client. `upsert` adds a row or changes the text a\n * key has in a language; `remove` deletes every row of the keys.\n */\nexport interface TextStore {\n\tupsert(rows: readonly TextRow[]): Promise<void>;\n\tremove(keys: readonly string[]): Promise<void>;\n}\n\n/** A `{ code: { en, fr } }` map as rows, sorted by code. A code that lacks a language another has throws, so no migration ships a half-translated code, and so does a language-first map. */\nexport function seedsOf(texts: Texts): TextRow[] {\n\tfor (const [code, byLanguage] of Object.entries(texts)) {\n\t\tif (!code.includes('.'))\n\t\t\tthrow new TypeError(\n\t\t\t\t`translation \"${code}\" is not a code: codes are dotted (\"area.errors.slug\"); texts go code first, { code: { en, fr } }, not language first`,\n\t\t\t);\n\t\tfor (const language of Object.keys(byLanguage))\n\t\t\tif (language.includes('.'))\n\t\t\t\tthrow new TypeError(\n\t\t\t\t\t`translation \"${code}\" has a language \"${language}\" that looks like a code: texts go code first, { code: { en, fr } }`,\n\t\t\t\t);\n\t}\n\tconst languages = [\n\t\t...new Set(\n\t\t\tObject.values(texts).flatMap((byLanguage) => Object.keys(byLanguage)),\n\t\t),\n\t];\n\treturn Object.keys(texts)\n\t\t.sort()\n\t\t.flatMap((key) =>\n\t\t\tlanguages.map((language) => {\n\t\t\t\tconst text = (\n\t\t\t\t\ttexts as Readonly<Record<string, Record<string, string>>>\n\t\t\t\t)[key]?.[language];\n\t\t\t\tif (text === undefined)\n\t\t\t\t\tthrow new TypeError(`translation \"${key}\" has no ${language} text`);\n\t\t\t\treturn { key, language, text };\n\t\t\t}),\n\t\t);\n}\n\n/** For a migration's `up`: adds the texts, or changes the text a code has in a language. Never deletes. */\nexport async function upsertTexts(\n\tstore: TextStore,\n\ttexts: Texts,\n): Promise<void> {\n\tconst rows = seedsOf(texts);\n\tif (rows.length > 0) await store.upsert(rows);\n}\n\n/**\n * For the `down` of a migration that CREATED its codes: deletes them in every\n * language. Takes the migration's texts or just the codes. Wrong for a\n * rewording, which would delete codes that existed before: use `restoreTexts`.\n */\nexport async function removeTexts(\n\tstore: TextStore,\n\tcodes: Texts | readonly string[],\n): Promise<void> {\n\tconst keys = Array.isArray(codes)\n\t\t? (codes as readonly string[])\n\t\t: Object.keys(codes);\n\tif (keys.length > 0) await store.remove([...new Set(keys)]);\n}\n\n/**\n * For the `down` of a migration that REWORDED existing codes: writes the\n * previous wording back, so a rollback restores the old texts instead of\n * deleting the codes.\n */\nexport async function restoreTexts(\n\tstore: TextStore,\n\tprevious: Texts,\n): Promise<void> {\n\tawait upsertTexts(store, previous);\n}\n"
12
+ ],
13
+ "mappings": ";AAAA;;;ACWO,SAAS,SAAS,CACxB,WACA,KACqB;AAAA,EACrB,IAAI,cAAc;AAAA,IAAW;AAAA,EAC7B,IAAI,OAAO,OAAO,WAAW,GAAG,GAAG;AAAA,IAClC,MAAM,OAAO,UAAU;AAAA,IACvB,OAAO,OAAO,SAAS,WAAW,OAAO;AAAA,EAC1C;AAAA,EACA,IAAI,KAAc;AAAA,EAClB,WAAW,QAAQ,IAAI,MAAM,GAAG,GAAG;AAAA,IAClC,IAAI,OAAO,OAAO,YAAY,OAAO;AAAA,MAAM;AAAA,IAC3C,IAAI,CAAC,OAAO,OAAO,IAAI,IAAI;AAAA,MAAG;AAAA,IAC9B,KAAM,GAA+B;AAAA,EACtC;AAAA,EACA,OAAO,OAAO,OAAO,WAAW,KAAK;AAAA;AAI/B,SAAS,GAAG,CAClB,WACA,KACU;AAAA,EACV,OAAO,UAAU,WAAW,GAAG,MAAM;AAAA;AAI/B,SAAS,MAAM,CACrB,WACA,OACA,KACqB;AAAA,EACrB,OAAO,MAAM,KAAK,CAAC,aAClB,IACC,OAAO,OAAO,WAAW,QAAQ,IAAI,UAAU,YAAY,WAC3D,GACD,CACD;AAAA;AAIM,SAAS,MAAM,IAAI,OAAoC;AAAA,EAC7D,OAAO,CAAC,GAAG,IAAI,IAAI,KAAK,CAAC;AAAA;;;ADnC1B,IAAM,SAAS,IAAI,IAAI,CAAC,aAAa,eAAe,WAAW,CAAC;AAEhE,IAAM,QAAQ,CAAC,QACd,IAAI,UAAU,kBAAkB,qCAAqC;AAS/D,SAAS,WAAW,CAAC,MAA0B,UAAwB;AAAA,EAC7E,MAAM,OAAa,OAAO,OAAO,IAAI;AAAA,EACrC,WAAW,OAAO,M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AAI,CAAC,aAAa;AAAA,IAC3B,MAAM,OACL,MACC,OAAO;AAAA,IACT,IAAI,SAAS;AAAA,MACZ,MAAM,IAAI,UAAU,gBAAgB,eAAe,eAAe;AAAA,IACnE,OAAO,EAAE,KAAK,UAAU,KAAK;AAAA,GAC7B,CACF;AAAA;AAIK,eAAe,WAAW,CAChC,OACA,OACgB;AAAA,EAChB,MAAM,OAAO,QAAQ,KAAK;AAAA,EAC1B,IAAI,KAAK,SAAS;AAAA,IAAG,MAAM,MAAM,OAAO,IAAI;AAAA;AAQtC,eAAe,WAAW,CAChC,OACA,OACgB;AAAA,EAChB,MAAM,OAAO,MAAM,QAAQ,KAAK,IAC5B,QACD,OAAO,KAAK,KAAK;AAAA,EACpB,IAAI,KAAK,SAAS;AAAA,IAAG,MAAM,MAAM,OAAO,CAAC,GAAG,IAAI,IAAI,IAAI,CAAC,CAAC;AAAA;AAQpD,eAAe,YAAY,CACjC,OACA,UACgB;AAAA,EAChB,MAAM,YAAY,OAAO,QAAQ;AAAA;",
14
+ "debugId": "44F35C4E639F24CF64756E2164756E21",
15
+ "names": []
16
+ }
@@ -0,0 +1,18 @@
1
+ import type { Catalogues } from './types';
2
+ /**
3
+ * The message at the dotted `key` of `catalogue`, or `undefined`: the lookup
4
+ * `@softistx/i18n`'s translator makes, a string — a number or a section of
5
+ * messages is not one, and `@softistx/i18n` 3 would answer it from its own
6
+ * fallback language — so that a language which lacks a key can be told from one whose
7
+ * message happens to be the key itself. A key is a dotted path, or a flat
8
+ * key of the catalogue (tried first, as in lodash's `get`); bracket paths
9
+ * (`a[0]`) are not supported.
10
+ */
11
+ export declare function messageAt(catalogue: Readonly<Record<string, unknown>> | undefined, key: string): string | undefined;
12
+ /** Whether `catalogue` has a message at the dotted `key` (see `messageAt`). */
13
+ export declare function has(catalogue: Readonly<Record<string, unknown>> | undefined, key: string): boolean;
14
+ /** The first language of `chain` whose catalogue has `key`. */
15
+ export declare function holder(resources: Catalogues, chain: readonly string[], key: string): string | undefined;
16
+ /** `steps` in order, each once. */
17
+ export declare function unique(...steps: readonly string[]): string[];
18
+ //# sourceMappingURL=lookup.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"lookup.d.ts","sourceRoot":"","sources":["../src/lookup.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AAE1C;;;;;;;;GAQG;AACH,wBAAgB,SAAS,CACxB,SAAS,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,GAAG,SAAS,EACxD,GAAG,EAAE,MAAM,GACT,MAAM,GAAG,SAAS,CAapB;AAED,+EAA+E;AAC/E,wBAAgB,GAAG,CAClB,SAAS,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,GAAG,SAAS,EACxD,GAAG,EAAE,MAAM,GACT,OAAO,CAET;AAED,+DAA+D;AAC/D,wBAAgB,MAAM,CACrB,SAAS,EAAE,UAAU,EACrB,KAAK,EAAE,SAAS,MAAM,EAAE,EACxB,GAAG,EAAE,MAAM,GACT,MAAM,GAAG,SAAS,CAOpB;AAED,mCAAmC;AACnC,wBAAgB,MAAM,CAAC,GAAG,KAAK,EAAE,SAAS,MAAM,EAAE,GAAG,MAAM,EAAE,CAE5D"}
@@ -0,0 +1,35 @@
1
+ import type { TextRow } from './catalogue';
2
+ export type { TextRow };
3
+ /**
4
+ * The texts of a migration, code first: `{ 'auth.errors.expired': { en, fr } }`.
5
+ * A code is dotted, so a language-first literal (`{ en: { … } }`) does not
6
+ * type-check.
7
+ */
8
+ export type Texts = Readonly<Record<`${string}.${string}`, Readonly<Record<string, string>>>>;
9
+ /**
10
+ * What the seed helpers need of the database: two writes. An app implements
11
+ * it over its driver (a `bulkWrite` of upserts, a `deleteMany`), so the
12
+ * package depends on no client. `upsert` adds a row or changes the text a
13
+ * key has in a language; `remove` deletes every row of the keys.
14
+ */
15
+ export interface TextStore {
16
+ upsert(rows: readonly TextRow[]): Promise<void>;
17
+ remove(keys: readonly string[]): Promise<void>;
18
+ }
19
+ /** A `{ code: { en, fr } }` map as rows, sorted by code. A code that lacks a language another has throws, so no migration ships a half-translated code, and so does a language-first map. */
20
+ export declare function seedsOf(texts: Texts): TextRow[];
21
+ /** For a migration's `up`: adds the texts, or changes the text a code has in a language. Never deletes. */
22
+ export declare function upsertTexts(store: TextStore, texts: Texts): Promise<void>;
23
+ /**
24
+ * For the `down` of a migration that CREATED its codes: deletes them in every
25
+ * language. Takes the migration's texts or just the codes. Wrong for a
26
+ * rewording, which would delete codes that existed before: use `restoreTexts`.
27
+ */
28
+ export declare function removeTexts(store: TextStore, codes: Texts | readonly string[]): Promise<void>;
29
+ /**
30
+ * For the `down` of a migration that REWORDED existing codes: writes the
31
+ * previous wording back, so a rollback restores the old texts instead of
32
+ * deleting the codes.
33
+ */
34
+ export declare function restoreTexts(store: TextStore, previous: Texts): Promise<void>;
35
+ //# sourceMappingURL=seeds.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"seeds.d.ts","sourceRoot":"","sources":["../src/seeds.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AAE3C,YAAY,EAAE,OAAO,EAAE,CAAC;AAExB;;;;GAIG;AACH,MAAM,MAAM,KAAK,GAAG,QAAQ,CAC3B,MAAM,CAAC,GAAG,MAAM,IAAI,MAAM,EAAE,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC,CAC/D,CAAC;AAEF;;;;;GAKG;AACH,MAAM,WAAW,SAAS;IACzB,MAAM,CAAC,IAAI,EAAE,SAAS,OAAO,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAChD,MAAM,CAAC,IAAI,EAAE,SAAS,MAAM,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CAC/C;AAED,6LAA6L;AAC7L,wBAAgB,OAAO,CAAC,KAAK,EAAE,KAAK,GAAG,OAAO,EAAE,CA6B/C;AAED,2GAA2G;AAC3G,wBAAsB,WAAW,CAChC,KAAK,EAAE,SAAS,EAChB,KAAK,EAAE,KAAK,GACV,OAAO,CAAC,IAAI,CAAC,CAGf;AAED;;;;GAIG;AACH,wBAAsB,WAAW,CAChC,KAAK,EAAE,SAAS,EAChB,KAAK,EAAE,KAAK,GAAG,SAAS,MAAM,EAAE,GAC9B,OAAO,CAAC,IAAI,CAAC,CAKf;AAED;;;;GAIG;AACH,wBAAsB,YAAY,CACjC,KAAK,EAAE,SAAS,EAChB,QAAQ,EAAE,KAAK,GACb,OAAO,CAAC,IAAI,CAAC,CAEf"}
@@ -0,0 +1,106 @@
1
+ import type { BaseContext, Empty, Middleware, Next } from '@softistx/alxia';
2
+ import type { LanguageContext, LanguageOptions } from '@softistx/alxia-language';
3
+ import type { TranslationContext } from '@softistx/i18n';
4
+ /** Catalogues by language: `{ en: { greeting: 'Hello {name}' }, fr: … }`. */
5
+ export type Catalogues = Readonly<Record<string, Readonly<Record<string, unknown>>>>;
6
+ /**
7
+ * Every key of a catalogue, dotted: `users.greeting`. The keys of
8
+ * `@softistx/i18n`'s `Path`, nine levels deep: a section nested deeper gives
9
+ * `${section}.${string}`, any key under it.
10
+ *
11
+ * `Path` recurses without a bound. A catalogue that is a type parameter —
12
+ * a function generic over the catalogues it hands to `createI18n` — leaves
13
+ * it deferred, and some checks then unfold it forever (TS2589, "Type
14
+ * instantiation is excessively deep and possibly infinite"). The depth
15
+ * stops them.
16
+ */
17
+ export type KeyOf<Catalogue> = KeysOf<Catalogue, 8> & string;
18
+ /** One level shallower: `Shallower[8]` is `7`, and `Shallower[0]` is `never`. */
19
+ type Shallower = [never, 0, 1, 2, 3, 4, 5, 6, 7];
20
+ /**
21
+ * The dotted keys of `T`, `Depth` more levels down at most. `Path`'s own
22
+ * test, `Record<string, any>`, kept so that the keys stay `Path`'s.
23
+ */
24
+ type KeysOf<T, Depth extends number, K extends keyof T = keyof T> = K extends string ? T[K] extends Record<string, any> ? [Shallower[Depth]] extends [never] ? `${K}.${string}` : `${K}.${KeysOf<T[K], Shallower[Depth]>}` : K : never;
25
+ /** A translation of a key, in a language, formatted with ICU's `context`. */
26
+ export type Translate<Key extends string> = (key: Key, context?: TranslationContext) => string;
27
+ /** What both forms of `createI18n()` take beside their catalogues. */
28
+ interface CommonOptions<Language extends string, Ctx extends object> extends Omit<LanguageOptions<Language, Ctx>, 'supported' | 'fallback'> {
29
+ /**
30
+ * The languages to try after the request's own, before `fallback`:
31
+ * `(language) => ['fr']`, or the closest ones, `pt-BR` then `pt`. A key
32
+ * missing in a catalogue is looked up in each, in order; it answers
33
+ * itself only when every one misses. Default: none.
34
+ */
35
+ readonly fallbacks?: (language: Language) => readonly string[];
36
+ }
37
+ /**
38
+ * `Ctx` is the type `resolve`'s parameter is annotated with —
39
+ * `BaseContext & { user: User }`, or `{ user: User }` alone — and
40
+ * `BaseContext` when it is not: what the plugin then requires of the app.
41
+ */
42
+ export interface I18nOptions<C extends Catalogues, Fallback extends keyof C & string, Ctx extends object = BaseContext> extends CommonOptions<keyof C & string, Ctx> {
43
+ /**
44
+ * The catalogues, one per language: their keys are the languages
45
+ * supported. Spread `@softistx/i18n`'s `resources` into them for its shared
46
+ * keys — `errors.not-found`, `zod.*`.
47
+ */
48
+ readonly resources: C;
49
+ /** The language spoken when the request names none, and whose keys type `t`. */
50
+ readonly fallback: Fallback;
51
+ }
52
+ /**
53
+ * The options of `createI18n<Key>()`: the keys are the explicit `Key`, the
54
+ * catalogues may come later, from `setResources()`.
55
+ */
56
+ export interface RuntimeI18nOptions<Language extends string = string, Ctx extends object = BaseContext> extends CommonOptions<Language, Ctx> {
57
+ /**
58
+ * The languages supported until `setResources()` gives catalogues; then
59
+ * the catalogues' own. Default: those of `resources`, else `[fallback]`.
60
+ */
61
+ readonly languages?: readonly Language[];
62
+ /** The catalogues, when known now; else give them to `setResources()`. */
63
+ readonly resources?: Catalogues;
64
+ /** The language spoken when the request names none. */
65
+ readonly fallback: Language;
66
+ }
67
+ /** What the routes behind the plugin read. */
68
+ export interface I18nContext<Key extends string> {
69
+ /** Translates into the request's language. */
70
+ readonly t: Translate<Key>;
71
+ }
72
+ /**
73
+ * What `createI18n()` makes: a middleware that gives `language`, one of
74
+ * `Language`, and `t`, typed by `Key`, and requires `Requires` of the app —
75
+ * what `resolve` reads — with a `t` and a `language` of its own for the
76
+ * request running.
77
+ */
78
+ export type I18nMiddleware<Language extends string, Key extends string, Requires extends object = Empty> = Middleware<Requires, Promise<Next<LanguageContext<Language> & I18nContext<Key>>>> & {
79
+ /** Translates into the current request's language, or the fallback outside one. */
80
+ t: Translate<Key>;
81
+ /** The current request's language, or the fallback outside one. */
82
+ language: () => Language;
83
+ /** The languages of the catalogues: the same array, updated in place by `setResources()`. */
84
+ supported: Language[];
85
+ /**
86
+ * Adds a step to the current request's chain, after its language and
87
+ * before `fallbacks`: the school's language, once the app knows it. A
88
+ * no-op outside a request.
89
+ */
90
+ fallBackTo: (language: string) => void;
91
+ /**
92
+ * The languages `t()` tries, in order and each once: the request's, the
93
+ * `fallBackTo` steps, `fallbacks(language)`, then `fallback`. For data
94
+ * the app labels itself. Until `fallbacks` is given or `fallBackTo` is
95
+ * called, `t()` reads the request's language alone; the list is the same.
96
+ */
97
+ chain: () => string[];
98
+ /**
99
+ * Swaps the catalogues, all at once, and `supported` follows. A request
100
+ * running keeps the ones it started with. Throws, changing nothing, when
101
+ * there is none for the fallback.
102
+ */
103
+ setResources: (resources: Readonly<Record<Language, Readonly<Record<string, unknown>>>>) => void;
104
+ };
105
+ export {};
106
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,KAAK,EAAE,UAAU,EAAE,IAAI,EAAE,MAAM,iBAAiB,CAAC;AAC5E,OAAO,KAAK,EAC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AC,QAAQ,CAAC,GAAG,WAAW,CAAC,GAAG,CAAC,CAAC,CAAC,CAC3D,GAAG;IACH,mFAAmF;IACnF,CAAC,EAAE,SAAS,CAAC,GAAG,CAAC,CAAC;IAClB,mEAAmE;IACnE,QAAQ,EAAE,MAAM,QAAQ,CAAC;IACzB,6FAA6F;IAC7F,SAAS,EAAE,QAAQ,EAAE,CAAC;IACtB;;;;OAIG;IACH,UAAU,EAAE,CAAC,QAAQ,EAAE,MAAM,KAAK,IAAI,CAAC;IACvC;;;;;OAKG;IACH,KAAK,EAAE,MAAM,MAAM,EAAE,CAAC;IACtB;;;;OAIG;IACH,YAAY,EAAE,CACb,SAAS,EAAE,QAAQ,CAAC,MAAM,CAAC,QAAQ,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC,KACpE,IAAI,CAAC;CACV,CAAC"}
package/docs/README.md ADDED
@@ -0,0 +1,13 @@
1
+ # @softistx/alxia-i18n documentation
2
+
3
+ The [package README](../README.md) is the short version. This folder is
4
+ the long one: the catalogues and every option, what the routes behind the
5
+ middleware read, how messages are formatted and keys typed, where the
6
+ request's language reaches and where it does not, and what to do when a
7
+ response shows a key or the wrong language.
8
+
9
+ | Page | Read it when |
10
+ | --- | --- |
11
+ | [Guide](guide.md) | writing the catalogues, choosing where the language is read from, falling back to other languages key by key, loading catalogues at runtime, reading a user's saved language from an earlier middleware, typing a function that translates, keeping messages in a database (`defineCodes`, catalogue version, seeds, coverage check), translating in a service or an error-handling middleware, caching the responses, or testing them |
12
+ | [Troubleshooting](troubleshooting.md) | `createI18n()` threw at start-up, `tsc` refused a key, an option or `use(i18n)`, a function generic over its catalogues hit TS2589, the log shows an ICU error, `fallBackTo()` or `setResources()` seems to do nothing, a response shows a key or the wrong language, or a database-backed catalogue refuses a key, a seed or a declared code with no text |
13
+ | [Roadmap](roadmap.md) | wondering what is coming, and what is not planned |