@kizunajs/i18n 0.1.0 → 0.2.0

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/generate.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { a as shownLocaleOf, i as problemsOf, n as sourceOf, o as toCatalog, r as formatProblems, t as loadMessages } from "./load-CE9FYddD.mjs";
1
+ import { a as shownLocaleOf, i as problemsOf, n as sourceOf, o as toCatalog, r as formatProblems, t as loadMessages } from "./load-CMmjOpu-.mjs";
2
2
  //#region src/config.ts
3
3
  /**
4
4
  * Declares where the messages are, and what `kizuna-i18n generate` writes from them.
@@ -61,29 +61,33 @@ function defineTarget(definition) {
61
61
  * messages it reads.
62
62
  */
63
63
  const runtimeSource = String.raw`/**
64
- * A message with params. Text values give a string. A rich value, like a React element, gives the
65
- * message as parts, which React renders directly.
64
+ * A message with params. A React element as a param returns parts in place of a string.
66
65
  */
67
66
  export type Message<Params> = {
68
67
  (params: Params): string;
69
- <Rich>(params: { [Name in keyof Params]: Params[Name] | Rich }): Array<string | Rich>;
68
+ <Rich extends object>(params: { [Name in keyof Params]: Params[Name] | Rich }): Array<string | Rich>;
70
69
  };
71
70
 
72
71
  /**
73
- * A message with tags. Each tag takes a renderer, which gets the text inside the tag and returns
74
- * what the tag becomes, like a link.
72
+ * A message with tags. Pass a function for each tag.
75
73
  */
76
- export type TaggedMessage<Params, Tags extends string> = <Result>(
77
- params: { [Name in keyof Params]: Params[Name] | Result } & {
78
- [Tag in Tags]: (text: string | Array<string | Result>) => Result;
79
- }
80
- ) => Array<string | Result>;
74
+ export type TaggedMessage<Params, Tags extends string> = {
75
+ <Result>(
76
+ params: Params & {
77
+ [Tag in Tags]: (text: string | Array<string | Result>) => Result;
78
+ }
79
+ ): Array<string | Result>;
80
+ <Result, Rich extends object>(
81
+ params: { [Name in keyof Params]: Params[Name] | Rich } & {
82
+ [Tag in Tags]: (text: string | Array<string | Rich | Result>) => Result;
83
+ }
84
+ ): Array<string | Rich | Result>;
85
+ };
81
86
 
82
87
  const cache = new Map<Locale, Translations>();
83
88
 
84
89
  /**
85
- * Returns the translations of a language. A language the app does not have gives the base
86
- * language.
90
+ * Returns the translations of a language.
87
91
  *
88
92
  * @example
89
93
  * const t = getTranslations('nb');
@@ -104,8 +108,8 @@ const sameLanguages: Record<string, string[]> = {
104
108
  };
105
109
 
106
110
  /**
107
- * Returns the language the app has that best matches the user's preferred languages, or the base
108
- * language. Takes an Accept-Language header or a list like navigator.languages.
111
+ * Returns the language that best matches an Accept-Language header or a list like
112
+ * navigator.languages, or the base language.
109
113
  *
110
114
  * @example
111
115
  * matchLocale(['nb-NO', 'en-US']);
@@ -149,8 +153,7 @@ const TAG_PAIR = '<(\\w+)>([\\s\\S]*?)<\\/\\1>';
149
153
  const PARAM = '\\{\\s*([A-Za-z_$][\\w$]*)\\s*\\}';
150
154
 
151
155
  /**
152
- * The marks React puts on its elements, so a part that is an element gets a key without importing
153
- * React.
156
+ * Marks React puts on its elements, so parts get keys without importing React.
154
157
  */
155
158
  const reactElements = new Set<symbol>([Symbol.for('react.element'), Symbol.for('react.transitional.element')]);
156
159
 
@@ -160,7 +163,9 @@ function text(template: string): any {
160
163
 
161
164
  function render(template: string, values: Record<string, unknown>): string | unknown[] {
162
165
  const hasTag = new RegExp(TAG_PAIR).test(template);
163
- const hasRichValue = Object.values(values).some((value) => typeof value !== 'string' && typeof value !== 'function');
166
+ const hasRichValue = Object.values(values).some(
167
+ (value) => typeof value !== 'string' && typeof value !== 'number' && typeof value !== 'function'
168
+ );
164
169
  if (!hasTag && !hasRichValue) {
165
170
  return template.replace(new RegExp(PARAM, 'g'), (_, name: string) => String(values[name] ?? ''));
166
171
  }
@@ -198,8 +203,8 @@ function pushValues(parts: unknown[], stretch: string, values: Record<string, un
198
203
  while ((match = param.exec(stretch))) {
199
204
  pushText(parts, stretch.slice(lastIndex, match.index));
200
205
  const value = values[match[1] ?? ''] ?? '';
201
- if (typeof value === 'string') {
202
- pushText(parts, value);
206
+ if (typeof value === 'string' || typeof value === 'number') {
207
+ pushText(parts, String(value));
203
208
  } else {
204
209
  parts.push(value);
205
210
  }
@@ -248,27 +253,33 @@ function filledOf(segments, values) {
248
253
  return segments.map((segment) => {
249
254
  if (segment.type === "text") return segment.text;
250
255
  if (segment.type === "param") return values[segment.name] ?? "";
251
- return filledOf(segment.children, values);
256
+ return `<${segment.name}>${filledOf(segment.children, values)}</${segment.name}>`;
252
257
  }).join("");
253
258
  }
254
- function exampleOf(message, base) {
259
+ function textsOf(message, catalog, values) {
260
+ return catalog.locales.map((locale) => {
261
+ const text = message.translations[locale.name];
262
+ if (text === void 0) return `// ${locale.name}: shows ${shownLocaleOf(catalog, message.translations, locale.name)}`;
263
+ return `// ${locale.name}: ${stringOf(filledOf(text.segments, values))}`;
264
+ });
265
+ }
266
+ function exampleOf(message, catalog) {
255
267
  const access = `t.${message.path.map(keyOf).join(".")}`;
256
- const baseText = message.translations[base];
257
- if (message.params.length === 0 && message.tags.length === 0) return [`${access}; // ${stringOf(baseText?.source ?? "")}`];
258
- const values = Object.fromEntries(message.params.map((name) => [name, message.examples?.[name] ?? "…"]));
259
- const lines = [
268
+ const values = Object.fromEntries(message.params.map((param) => [param.name, param.example === void 0 ? "…" : String(param.example)]));
269
+ if (message.params.length === 0 && message.tags.length === 0) return [`${access};`, ...textsOf(message, catalog, values)];
270
+ return [
260
271
  `${access}({`,
261
- ...message.params.map((name) => ` ${keyOf(name)}: ${stringOf(values[name])},`),
262
- ...message.tags.map((tag) => ` ${keyOf(tag)}: (text) => text,`)
272
+ ...message.params.map((param) => ` ${keyOf(param.name)}: ${typeof param.example === "number" ? String(param.example) : stringOf(values[param.name])},`),
273
+ ...message.tags.map((tag) => ` ${keyOf(tag)}: (text) => text,`),
274
+ "});",
275
+ ...textsOf(message, catalog, values)
263
276
  ];
264
- const result = message.tags.length === 0 ? ` // ${stringOf(filledOf(baseText?.segments ?? [], values))}` : "";
265
- return [...lines, `});${result}`];
266
277
  }
267
- function docOf(message, base, indent) {
278
+ function docOf(message, catalog, indent) {
268
279
  const paragraphs = [];
269
280
  if (message.description !== void 0) paragraphs.push(commentOf(message.description).split("\n"));
270
281
  if (message.maxLength !== void 0) paragraphs.push([`@maxLength ${message.maxLength}`]);
271
- paragraphs.push(["@example", ...exampleOf(message, base).map(commentOf)]);
282
+ paragraphs.push(["@example", ...exampleOf(message, catalog).map(commentOf)]);
272
283
  const body = paragraphs.flatMap((lines, index) => [...index === 0 ? [] : [""], ...lines]);
273
284
  return [
274
285
  `${indent}/**`,
@@ -278,7 +289,7 @@ function docOf(message, base, indent) {
278
289
  }
279
290
  function typeOf(message) {
280
291
  if (message.params.length === 0 && message.tags.length === 0) return ["string"];
281
- const params = message.params.map((name) => ` ${keyOf(name)}: string;`);
292
+ const params = message.params.map((param) => ` ${keyOf(param.name)}: ${param.type};`);
282
293
  if (message.tags.length === 0) return [
283
294
  "Message<{",
284
295
  ...params,
@@ -291,48 +302,66 @@ function typeOf(message) {
291
302
  `}, ${tags}>`
292
303
  ];
293
304
  }
294
- const groupsOf = (catalog) => {
295
- const groups = /* @__PURE__ */ new Map();
305
+ function treeOf(catalog) {
306
+ const root = /* @__PURE__ */ new Map();
296
307
  for (const message of catalog.messages) {
297
- const name = message.path[0];
298
- groups.set(name, [...groups.get(name) ?? [], message]);
308
+ let branch = root;
309
+ for (const name of message.path.slice(0, -1)) {
310
+ let next = branch.get(name);
311
+ if (!(next instanceof Map)) {
312
+ next = /* @__PURE__ */ new Map();
313
+ branch.set(name, next);
314
+ }
315
+ branch = next;
316
+ }
317
+ branch.set(message.path[message.path.length - 1], message);
299
318
  }
300
- return groups;
301
- };
319
+ return root;
320
+ }
321
+ function typeLinesOf(branch, catalog, indent) {
322
+ return [...branch].flatMap(([name, node]) => {
323
+ if (node instanceof Map) return [
324
+ `${indent}${keyOf(name)}: {`,
325
+ ...typeLinesOf(node, catalog, `${indent} `),
326
+ `${indent}};`
327
+ ];
328
+ const [first = "string", ...rest] = typeOf(node);
329
+ return [
330
+ ...docOf(node, catalog, indent),
331
+ `${indent}${keyOf(name)}: ${first}${rest.length === 0 ? ";" : ""}`,
332
+ ...rest.map((line, index) => `${indent}${line}${index === rest.length - 1 ? ";" : ""}`)
333
+ ];
334
+ });
335
+ }
336
+ function valueLinesOf(branch, catalog, locale, indent) {
337
+ return [...branch].flatMap(([name, node]) => {
338
+ if (node instanceof Map) return [
339
+ `${indent}${keyOf(name)}: {`,
340
+ ...valueLinesOf(node, catalog, locale, `${indent} `),
341
+ `${indent}},`
342
+ ];
343
+ const shown = shownLocaleOf(catalog, node.translations, locale);
344
+ const source = node.translations[shown]?.source ?? "";
345
+ const value = node.params.length === 0 && node.tags.length === 0 ? stringOf(source) : `text(${stringOf(source)})`;
346
+ return [`${indent}${keyOf(name)}: ${value},`];
347
+ });
348
+ }
302
349
  function translationsTypeOf(catalog) {
303
- const lines = [
350
+ return [
304
351
  "/**",
305
352
  " * The translations of one language, as `getTranslations` returns them.",
306
353
  " */",
307
- "export type Translations = {"
354
+ "export type Translations = {",
355
+ ...typeLinesOf(treeOf(catalog), catalog, " "),
356
+ "};"
308
357
  ];
309
- for (const [group, messages] of groupsOf(catalog)) {
310
- lines.push(` ${keyOf(group)}: {`);
311
- for (const message of messages) {
312
- const [first = "string", ...rest] = typeOf(message);
313
- lines.push(...docOf(message, catalog.base, " "));
314
- lines.push(` ${keyOf(message.path[1])}: ${first}${rest.length === 0 ? ";" : ""}`);
315
- rest.forEach((line, index) => lines.push(` ${line}${index === rest.length - 1 ? ";" : ""}`));
316
- }
317
- lines.push(" };");
318
- }
319
- lines.push("};");
320
- return lines;
321
358
  }
322
359
  function translationsOfLocale(catalog, locale) {
323
- const lines = [` ${keyOf(locale)}: () => ({`];
324
- for (const [group, messages] of groupsOf(catalog)) {
325
- lines.push(` ${keyOf(group)}: {`);
326
- for (const message of messages) {
327
- const shown = shownLocaleOf(catalog, message.translations, locale);
328
- const source = message.translations[shown]?.source ?? "";
329
- const value = message.params.length === 0 && message.tags.length === 0 ? stringOf(source) : `text(${stringOf(source)})`;
330
- lines.push(` ${keyOf(message.path[1])}: ${value},`);
331
- }
332
- lines.push(" },");
333
- }
334
- lines.push(" }),");
335
- return lines;
360
+ return [
361
+ ` ${keyOf(locale)}: () => ({`,
362
+ ...valueLinesOf(treeOf(catalog), catalog, locale, " "),
363
+ " }),"
364
+ ];
336
365
  }
337
366
  function render(catalog) {
338
367
  const names = catalog.locales.map((locale) => locale.name);
package/dist/index.cjs CHANGED
@@ -1,26 +1,33 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_source = require("./source-CDwD6Wcn.cjs");
2
+ const require_source = require("./source-B3RV-rox.cjs");
3
3
  //#region src/define-i18n.ts
4
- function buildMessage(definition) {
4
+ function buildParam(definition) {
5
5
  return {
6
- [require_source.messageSource]: definition,
7
- maxLength: (limit) => buildMessage({
6
+ [require_source.paramSource]: definition,
7
+ example: (value) => buildParam({
8
8
  ...definition,
9
- maxLength: limit
10
- }),
11
- describe: (description) => buildMessage({
12
- ...definition,
13
- description
14
- }),
15
- example: (values) => buildMessage({
16
- ...definition,
17
- examples: {
18
- ...definition.examples,
19
- ...values
20
- }
9
+ example: value
21
10
  })
22
11
  };
23
12
  }
13
+ function buildMessage(declaration, translations) {
14
+ const definition = {
15
+ translations: { ...translations },
16
+ params: Object.fromEntries(Object.entries(declaration.params ?? {}).map(([name, param]) => [name, param[require_source.paramSource]])),
17
+ ...declaration.description === void 0 ? {} : { description: declaration.description },
18
+ ...declaration.maxLength === void 0 ? {} : { maxLength: declaration.maxLength }
19
+ };
20
+ return { [require_source.messageSource]: definition };
21
+ }
22
+ function messagesOf(tree, path) {
23
+ return Object.entries(tree).flatMap(([name, value]) => {
24
+ const definition = value[require_source.messageSource];
25
+ return definition === void 0 ? messagesOf(value, [...path, name]) : [{
26
+ path: [...path, name],
27
+ definition
28
+ }];
29
+ });
30
+ }
24
31
  function checkFallbacks(locales, base) {
25
32
  const names = locales.map((locale) => locale.name);
26
33
  if (!names.includes(base)) throw new Error(`The base language '${base}' is not one of the languages.`);
@@ -57,12 +64,14 @@ function defineI18n(config) {
57
64
  });
58
65
  checkFallbacks(locales, base);
59
66
  return {
60
- message: (texts) => buildMessage({ translations: { ...texts } }),
67
+ message: (declaration = {}) => ({ translations: (texts) => buildMessage(declaration, texts) }),
68
+ string: () => buildParam({ type: "string" }),
69
+ number: () => buildParam({ type: "number" }),
61
70
  messages: (messages) => {
62
71
  const group = {
63
72
  base,
64
73
  locales,
65
- messages: Object.fromEntries(Object.entries(messages).map(([key, message]) => [key, message[require_source.messageSource]]))
74
+ messages: messagesOf(messages, [])
66
75
  };
67
76
  return { [require_source.messagesSource]: group };
68
77
  }
package/dist/index.d.cts CHANGED
@@ -1,4 +1,4 @@
1
- import { i as messagesSource, r as messageSource } from "./source-CAF21cuM.cjs";
1
+ import { a as messagesSource, i as messageSource, o as paramSource } from "./source-C6_RixNW.cjs";
2
2
 
3
3
  //#region src/types.d.ts
4
4
  /**
@@ -24,67 +24,101 @@ type TagsIn<Text> = Text extends `${string}<${infer Tag}>${infer Inner}</${infer
24
24
  type RequiredLocalesOf<Locales> = { [Locale in keyof Locales]-?: Locales[Locale] extends {
25
25
  fallback: string;
26
26
  } ? never : Locale }[keyof Locales] & string;
27
- type CheckText<Locale extends string, Text, Params extends string, Tags extends string> = Text extends string ? string extends Text ? Text : [Exclude<ParamsIn<Text>, Params>] extends [never] ? CheckLeftOut<Locale, Text, Params, Tags> : [Exclude<Params, ParamsIn<Text>>] extends [never] ? `${Locale} uses {${Exclude<ParamsIn<Text>, Params>}}, which the message does not have` : `${Locale} uses {${Exclude<ParamsIn<Text>, Params>}}, the message has {${Params}}` : string;
28
- type CheckLeftOut<Locale extends string, Text, Params extends string, Tags extends string> = [Exclude<Params, ParamsIn<Text>>] extends [never] ? [Exclude<TagsIn<Text>, Tags>] extends [never] ? [Exclude<Tags, TagsIn<Text>>] extends [never] ? Text : `${Locale} leaves out <${Exclude<Tags, TagsIn<Text>>}>` : `${Locale} uses <${Exclude<TagsIn<Text>, Tags>}>, which the message does not have` : `${Locale} leaves out {${Exclude<Params, ParamsIn<Text>>}}`;
27
+ type CheckText<Locale extends string, Text, Params extends string, Tags extends string, Limit extends number> = Text extends string ? string extends Text ? Text : [Exclude<ParamsIn<Text>, Params>] extends [never] ? CheckLeftOut<Locale, Text, Params, Tags, Limit> : [Exclude<Params, ParamsIn<Text>>] extends [never] ? `${Locale} uses {${Exclude<ParamsIn<Text>, Params>}}, which the message does not have` : `${Locale} uses {${Exclude<ParamsIn<Text>, Params>}}, the message has {${Params}}` : string;
28
+ type CheckLeftOut<Locale extends string, Text extends string, Params extends string, Tags extends string, Limit extends number> = [Exclude<Params, ParamsIn<Text>>] extends [never] ? [Exclude<TagsIn<Text>, Tags>] extends [never] ? [Exclude<Tags, TagsIn<Text>>] extends [never] ? CheckLength<Locale, Text, Limit> : `${Locale} leaves out <${Exclude<Tags, TagsIn<Text>>}>` : `${Locale} uses <${Exclude<TagsIn<Text>, Tags>}>, which the message does not have` : `${Locale} leaves out {${Exclude<Params, ParamsIn<Text>>}}`;
29
+ type LengthOf<Text extends string, Count extends unknown[] = []> = Text extends `${string}${infer Rest}` ? LengthOf<Rest, [...Count, unknown]> : Count['length'];
30
+ type IsLonger<Text extends string, Limit extends number, Count extends unknown[] = []> = Count['length'] extends Limit ? Text extends '' ? false : true : Text extends `${string}${infer Rest}` ? IsLonger<Rest, Limit, [...Count, unknown]> : false;
31
+ type CheckLength<Locale extends string, Text extends string, Limit extends number> = [Limit] extends [never] ? Text : number extends Limit ? Text : [ParamsIn<Text>] extends [never] ? IsLonger<Text, Limit> extends true ? `${Locale} is ${LengthOf<Text>} characters, the limit is ${Limit}` : Text : Text;
29
32
  type BaseTextOf<Texts, Base extends string> = Base extends keyof Texts ? Texts[Base] : never;
33
+ type ParamsOf<Declaration> = Declaration extends {
34
+ params: infer Params;
35
+ } ? keyof Params & string : never;
36
+ type LimitOf<Declaration> = Declaration extends {
37
+ maxLength: infer Limit extends number;
38
+ } ? Limit : never;
30
39
  /**
31
- * Checks every language of a message against the base language's params and tags. A wrong text
32
- * becomes the sentence that says what is wrong, so the compiler shows it on that text.
40
+ * Checks every language of a message against its declared params, the base language's tags and
41
+ * its length limit. A wrong text becomes the sentence that says what is wrong, so the compiler
42
+ * shows it on that text.
33
43
  */
34
- type CheckTexts<Texts, Locales, Base extends string> = { [Locale in keyof Texts]: Locale extends keyof Locales ? CheckText<Locale & string, Texts[Locale], ParamsIn<BaseTextOf<Texts, Base>>, TagsIn<BaseTextOf<Texts, Base>>> : `${Locale & string} is not one of the languages` } & { [Locale in RequiredLocalesOf<Locales>]: string };
35
- type LengthOf<Text extends string, Count extends unknown[] = []> = Text extends `${string}${infer Rest}` ? LengthOf<Rest, [...Count, unknown]> : Count['length'];
36
- type IsLonger<Text extends string, Limit extends number, Count extends unknown[] = []> = Count['length'] extends Limit ? Text extends '' ? false : true : Text extends `${string}${infer Rest}` ? IsLonger<Rest, Limit, [...Count, unknown]> : false;
37
- type TooLong<Texts, Limit extends number> = { [Locale in keyof Texts]: Texts[Locale] extends string ? [ParamsIn<Texts[Locale]>] extends [never] ? IsLonger<Texts[Locale], Limit> extends true ? `${Locale & string} is ${LengthOf<Texts[Locale]>} characters, the limit is ${Limit}` : never : never : never }[keyof Texts];
44
+ type CheckTexts<Texts, Locales, Base extends string, Params extends string, Limit extends number> = { [Locale in keyof Texts]: Locale extends keyof Locales ? CheckText<Locale & string, Texts[Locale], Params, TagsIn<BaseTextOf<Texts, Base>>, Limit> : `${Locale & string} is not one of the languages` } & { [Locale in RequiredLocalesOf<Locales>]: string };
38
45
  /**
39
- * Checks that every text without params fits the limit. `kizuna-i18n check` checks a text with
40
- * params, with its example values filled in.
46
+ * A text param made by `i18n.string`.
41
47
  */
42
- type CheckLimit<Texts, Limit extends number> = [TooLong<Texts, Limit>] extends [never] ? Limit : TooLong<Texts, Limit>;
48
+ type StringParam = {
49
+ /**
50
+ * Gives a sample value. The generated JSDoc shows it, and `kizuna-i18n check` fills it in to
51
+ * check the length.
52
+ *
53
+ * @example
54
+ * i18n.string().example('Ada');
55
+ */
56
+ example: (value: string) => StringParam;
57
+ readonly [paramSource]: unknown;
58
+ };
43
59
  /**
44
- * A message made by `i18n.message`.
60
+ * A number param made by `i18n.number`.
45
61
  */
46
- type Message<Texts = Record<string, string>, Base extends string = string> = {
62
+ type NumberParam = {
47
63
  /**
48
- * Sets the most characters the message may have, in every language.
64
+ * Gives a sample value. The generated JSDoc shows it, and `kizuna-i18n check` fills it in to
65
+ * check the length.
49
66
  *
50
67
  * @example
51
- * i18n
52
- * .message({
53
- * en: 'Your cart',
54
- * nb: 'Handlekurven din',
55
- * })
56
- * .maxLength(16);
68
+ * i18n.number().example(3);
57
69
  */
58
- maxLength: <const Limit extends number>(limit: CheckLimit<Texts, Limit>) => Message<Texts, Base>;
70
+ example: (value: number) => NumberParam;
71
+ readonly [paramSource]: unknown;
72
+ };
73
+ /**
74
+ * What a message is: what it is for, its length limit and its params.
75
+ */
76
+ type MessageDeclaration = {
59
77
  /**
60
78
  * Tells whoever translates the message what it is for.
79
+ */
80
+ description?: string;
81
+ /**
82
+ * The most characters the message may have, in every language.
83
+ */
84
+ maxLength?: number;
85
+ /**
86
+ * The params every language uses, like `{firstName}`.
61
87
  *
62
88
  * @example
63
- * i18n
64
- * .message({
65
- * en: 'Save',
66
- * nb: 'Lagre',
67
- * })
68
- * .describe('Button that saves the order as a draft');
89
+ * params: {
90
+ * firstName: i18n.string().example('Ada'),
91
+ * },
69
92
  */
70
- describe: (description: string) => Message<Texts, Base>;
93
+ params?: Record<string, StringParam | NumberParam>;
94
+ };
95
+ /**
96
+ * A message that is declared and waits for its texts.
97
+ */
98
+ type DeclaredMessage<Declaration, Locales, Base extends string> = {
71
99
  /**
72
- * Gives sample values for the params. The generated JSDoc shows them, and the length check fills
73
- * them in.
100
+ * Gives the message one text per language.
74
101
  *
75
102
  * @example
76
- * i18n
77
- * .message({
78
- * en: 'Welcome back, {firstName}',
79
- * nb: 'Velkommen tilbake, {firstName}',
80
- * })
81
- * .example({
82
- * firstName: 'Ada',
83
- * });
103
+ * i18n.message().translations({
104
+ * en: 'Your cart',
105
+ * nb: 'Handlekurven din',
106
+ * });
84
107
  */
85
- example: (values: { [Param in ParamsIn<BaseTextOf<Texts, Base>>]?: string }) => Message<Texts, Base>;
108
+ translations: <const Texts extends Record<string, string>>(texts: CheckTexts<Texts, Locales, Base, ParamsOf<Declaration>, LimitOf<Declaration>>) => Message;
109
+ };
110
+ /**
111
+ * A message made by `i18n.message`.
112
+ */
113
+ type Message = {
86
114
  readonly [messageSource]: unknown;
87
115
  };
116
+ /**
117
+ * Messages by name. A plain object inside is a nested group, like `t.checkout.form.email`.
118
+ */
119
+ type MessageTree = {
120
+ [name: string]: Message | MessageTree;
121
+ };
88
122
  /**
89
123
  * A group of messages made by `i18n.messages`. `kizuna-i18n generate` reads every group the
90
124
  * translations folder exports, named by its export.
@@ -97,25 +131,55 @@ type Messages = {
97
131
  */
98
132
  type I18n<Locales extends Record<string, LocaleOptions>, Base extends keyof Locales & string> = {
99
133
  /**
100
- * Declares a message, with one text per language.
134
+ * Declares a message. `.translations` then gives it one text per language.
101
135
  *
102
136
  * @example
103
- * i18n.message({
104
- * en: 'Your cart',
105
- * nb: 'Handlekurven din',
106
- * });
137
+ * i18n
138
+ * .message({
139
+ * description: 'Shown above the cart to a customer who is logged in',
140
+ * params: {
141
+ * firstName: i18n.string().example('Ada'),
142
+ * },
143
+ * })
144
+ * .translations({
145
+ * en: 'Welcome back, {firstName}',
146
+ * nb: 'Velkommen tilbake, {firstName}',
147
+ * });
107
148
  */
108
- message: <const Texts extends Record<string, string>>(texts: CheckTexts<Texts, Locales, Base>) => Message<Texts, Base>;
149
+ message: <const Declaration extends MessageDeclaration = {}>(declaration?: Declaration) => DeclaredMessage<Declaration, Locales, Base>;
109
150
  /**
110
- * Groups messages. Each key names a message, like `t.cart.title`.
151
+ * Declares a text param.
152
+ *
153
+ * @example
154
+ * i18n.string().example('Ada');
155
+ */
156
+ string: () => StringParam;
157
+ /**
158
+ * Declares a number param.
159
+ *
160
+ * @example
161
+ * i18n.number().example(3);
162
+ */
163
+ number: () => NumberParam;
164
+ /**
165
+ * Groups messages. Each key names a message, like `t.cart.title`, and a plain object nests a
166
+ * group, like `t.cart.summary.total`.
111
167
  *
112
168
  * @example
113
169
  * export const cart = i18n.messages({
114
- * title,
115
- * greeting,
170
+ * title: i18n.message().translations({
171
+ * en: 'Your cart',
172
+ * nb: 'Handlekurven din',
173
+ * }),
174
+ * summary: {
175
+ * total: i18n.message().translations({
176
+ * en: 'Total',
177
+ * nb: 'Totalt',
178
+ * }),
179
+ * },
116
180
  * });
117
181
  */
118
- messages: (messages: Record<string, Message<any, any>>) => Messages;
182
+ messages: (messages: MessageTree) => Messages;
119
183
  };
120
184
  //#endregion
121
185
  //#region src/define-i18n.d.ts
@@ -134,7 +198,7 @@ type I18n<Locales extends Record<string, LocaleOptions>, Base extends keyof Loca
134
198
  */
135
199
  declare function defineI18n<const Locales extends Record<string, LocaleOptions>, const Base extends keyof Locales & string>(config: {
136
200
  /**
137
- * The base language. Every other language is checked against its params and tags.
201
+ * The base language. Every other language is checked against its tags.
138
202
  */
139
203
  base: Base;
140
204
  /**