locale-keysmith 0.3.2 → 0.4.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/README.md CHANGED
@@ -11,7 +11,7 @@ source language, and checks which keys your code still uses. It can then sort th
11
11
  delete unused keys, and fill in missing translations with Google Translate.
12
12
 
13
13
  - **Audit:** one `health` command reports missing, extra, unused, duplicate and empty keys,
14
- type mismatches and unsorted files.
14
+ type mismatches, broken placeholders, missing files and unsorted files.
15
15
  - **Clean up:** `sort` and `remove-unused` rewrite files while keeping their indentation, line
16
16
  endings and YAML comments.
17
17
  - **Translate:** fill missing keys via Google Translate, with `{{placeholders}}`, ICU messages
@@ -59,16 +59,17 @@ a config file (see [Configuration](#configuration)).
59
59
  The examples use `npx locale-keysmith <command>`; with pnpm or yarn, `pnpm exec` or `yarn`
60
60
  work the same way.
61
61
 
62
- | Command | What it does |
63
- | -------------------------- | ------------------------------------------------------------------------ |
64
- | `init` | Write a starter `locale-keysmith.config.json` for this project. |
65
- | `scan` | List the locale files that were found, with their inferred locale. |
66
- | `health` | Run every check below plus extra keys, empty values and type mismatches. |
67
- | `missing` | List keys present in the source locale but missing from the others. |
68
- | `unused` | List source-locale keys that no source file references. |
69
- | `sort` | Sort every locale file's keys alphabetically (nested too). |
70
- | `remove-unused` | Delete unused keys from every locale file. |
71
- | `translate --to <locales>` | Fill missing keys in target locales via Google Translate. |
62
+ | Command | What it does |
63
+ | --------------- | -------------------------------------------------------------------------------------- |
64
+ | `init` | Write a starter `locale-keysmith.config.json` for this project. |
65
+ | `scan` | List the locale files that were found, with their inferred locale. |
66
+ | `health` | Run every check below plus extra keys, empty values, type mismatches and placeholders. |
67
+ | `missing` | List keys present in the source locale but missing from the others. |
68
+ | `unused` | List source-locale keys that no source file references. |
69
+ | `why <key>` | Show where and how a key is used. |
70
+ | `sort` | Sort every locale file's keys alphabetically (nested too). |
71
+ | `remove-unused` | Delete unused keys from every locale file. |
72
+ | `translate` | Fill missing keys in target locales via Google Translate. |
72
73
 
73
74
  ### `init`
74
75
 
@@ -125,15 +126,21 @@ unused draft.placeholder
125
126
  7 issues found.
126
127
  ```
127
128
 
128
- | Issue | Meaning |
129
- | --------------- | ----------------------------------------------------------------------------- |
130
- | `unsorted` | The file's keys are not in alphabetical order (fix with `sort --write`). |
131
- | `duplicate` | The file defines a key twice, e.g. `"nav.home"` and `"nav": { "home" }`. |
132
- | `missing` | A key from the source locale is absent in this locale. |
133
- | `extra` | This locale has a key the source locale does not (often a leftover). |
134
- | `empty` | The value is an empty or whitespace-only string, or `null`. |
135
- | `type-mismatch` | The key holds a different kind of value than in the source (text vs. object). |
136
- | `unused` | No source file references the key. |
129
+ | Issue | Meaning |
130
+ | --------------- | ---------------------------------------------------------------------------------------------------------------------------- |
131
+ | `unsorted` | The file's keys are not in alphabetical order (fix with `sort --write`). |
132
+ | `duplicate` | A key is written twice: `"nav.home"` and `"nav": { "home" }`, or twice in one object. |
133
+ | `missing-file` | A locale listed in `locales` has no file for this set of translations. |
134
+ | `missing` | A key from the source locale is absent in this locale. |
135
+ | `extra` | This locale has a key the source locale does not (often a leftover). |
136
+ | `empty` | The value is an empty or whitespace-only string, or `null`. |
137
+ | `type-mismatch` | The key holds a different kind of value than in the source (text vs. object, text vs. number), however either file nests it. |
138
+ | `placeholder` | The translation lost, misspelled or added a placeholder such as `{{name}}`, `{count}`, `<0>` or `$t(key)`. |
139
+ | `unused` | No source file references the key. |
140
+
141
+ Placeholders are compared regardless of order and spacing. The text inside an ICU message is
142
+ not compared, since it is translated, and `{{count}}` may differ between plural forms ("One
143
+ item" / "{{count}} items").
137
144
 
138
145
  It exits with a non-zero status when any issue is found, so it can gate CI. When everything
139
146
  is fine it prints `All locale files are healthy.` and exits `0`. Keys matching `ignoreKeys`
@@ -147,6 +154,11 @@ npx locale-keysmith missing
147
154
 
148
155
  Lists, per non-source locale, the keys that exist in the source locale but are absent.
149
156
 
157
+ With `locales` in the config, it also lists translation files that do not exist at all, such
158
+ as a `de/checkout.json` that was never created or was deleted, including a source file such as
159
+ `en/account.json` whose translations still exist. Without it, only files that exist are
160
+ compared, and a set of translations with no source file is skipped with a warning.
161
+
150
162
  Plural keys follow each language's plural rules, as i18next does: English `item_one` /
151
163
  `item_other` means Polish needs `item_one`, `item_few`, `item_many` and `item_other`, while
152
164
  Japanese only needs `item_other`. Neither is reported as missing or extra for doing so, and
@@ -161,6 +173,27 @@ npx locale-keysmith unused
161
173
  Lists source-locale keys that are never referenced in your source files. See
162
174
  [Key usage detection](#key-usage-detection) for exactly what counts as "referenced".
163
175
 
176
+ ### `why`
177
+
178
+ ```bash
179
+ npx locale-keysmith why cart.item_one
180
+ npx locale-keysmith why account:title # only the account namespace
181
+ ```
182
+
183
+ Shows what keeps a key alive, so you can check what `unused` and `remove-unused` will do:
184
+
185
+ ```text
186
+ cart.item_one (src/locales/en.json)
187
+ a plural or context form of "cart.item":
188
+ src/components/Cart.tsx:12
189
+ read as part of "cart":
190
+ src/pages/Checkout.tsx:40
191
+ ```
192
+
193
+ Each reason lists the source lines, or the translations that nest the key with `$t()`. A
194
+ key nothing uses is reported as `not used` and the command exits 1. `--json` prints the same
195
+ as data.
196
+
164
197
  ### `sort`
165
198
 
166
199
  ```bash
@@ -180,7 +213,11 @@ npx locale-keysmith remove-unused --write # delete unused keys and re-sort
180
213
  ```
181
214
 
182
215
  Removes unused keys from **every** locale file (not just the source), then re-sorts them.
183
- It lists every key it removes; without `--write` it only lists the keys that would be removed.
216
+ When a whole plural family is unused, the forms only other languages have (Polish
217
+ `item_few`, `item_many`) are removed with it.
218
+ It lists every key it removes and how many keys each file loses; without `--write` it lists
219
+ exactly what `--write` would do, and nothing is written until every change is worked out.
220
+ `--dry-run` and `--write` cannot be combined.
184
221
 
185
222
  > **Warning:** `--write` deletes translations. Commit your work first and read the list it prints: a key
186
223
  > that your code builds entirely at runtime cannot be detected (see
@@ -196,11 +233,12 @@ npx locale-keysmith translate --from en --to de,fr --write
196
233
 
197
234
  Translates the source locale's missing keys into each target locale using the Google
198
235
  Translate API. A target locale that has no file yet is created next to the source file. Keys
199
- matching `ignoreKeys` are not translated.
236
+ matching `ignoreKeys` are not translated, including plural forms such as `*_few`. Without
237
+ `--to`, it translates into every locale listed in `locales` in the config.
200
238
 
201
239
  | Option | Default | Description |
202
240
  | ----------------- | ----------------------- | ----------------------------------------------- |
203
- | `--to <locales>` | — | Comma-separated target locales (required). |
241
+ | `--to <locales>` | `locales` (config) | Comma-separated target locales. |
204
242
  | `--from <locale>` | `sourceLocale` (config) | Source locale to translate from. |
205
243
  | `--write` | off | Write results to disk (otherwise preview only). |
206
244
 
@@ -213,6 +251,11 @@ never in the URL.
213
251
  with a warning rather than written broken. (The text inside an ICU message is kept as is.)
214
252
  - **Progress is saved.** If a request fails midway, the keys translated so far are written
215
253
  before the error is reported, so rerunning only translates what is left.
254
+ - **Existing translations are never replaced.** A key is written with the same layout as in
255
+ the source (a dotted `"cart.title"` key stays dotted). When the target already holds
256
+ something else in its place, such as text where the source has nested keys, the key is
257
+ skipped with a warning. If a target file exists but is not among the scanned locale
258
+ files, or cannot be written, the command stops before sending anything.
216
259
  - Keys are sent in batches of up to 100 strings per request.
217
260
 
218
261
  #### Getting an API key
@@ -256,8 +299,8 @@ Exit codes:
256
299
  | Code | Meaning |
257
300
  | ---- | --------------------------------------------------------------------------------- |
258
301
  | `0` | Nothing to report. |
259
- | `1` | `missing`, `unused` or `health` found something. |
260
- | `2` | The command itself failed (invalid config, unreadable locale file, API error...). |
302
+ | `1` | `missing`, `unused` or `health` found something, or `why` found no use. |
303
+ | `2` | The command itself failed (invalid option or config, unreadable file, API error). |
261
304
 
262
305
  `scan`, `missing`, `unused` and `health` accept `--json` and print a machine-readable
263
306
  result on stdout (warnings go to stderr, so stdout always parses):
@@ -278,7 +321,8 @@ npx locale-keysmith health --json
278
321
 
279
322
  Configuration is **optional**. With no config file, locale-keysmith scans **only the `src`
280
323
  folder** — it looks there for locale files (`.json`, `.yml`, `.yaml`) and for source usage,
281
- and any writes are confined to it.
324
+ and only rewrites the locale files it finds there (a linked one may point elsewhere in the
325
+ project).
282
326
 
283
327
  Create `locale-keysmith.config.json` in your project root to customise behaviour.
284
328
 
@@ -301,25 +345,35 @@ set either explicitly, which overrides the derived globs:
301
345
  "roots": ["src"],
302
346
  "translationFiles": ["src/locales/*.{json,yml,yaml}", "public/locales/**/*.{json,yml,yaml}"],
303
347
  "src": ["src/**/*.{ts,tsx,js,jsx,vue}"],
304
- "ignoreKeys": ["debug.*"]
348
+ "ignoreKeys": ["debug.*"],
349
+ "locales": ["en", "de", "fr"]
305
350
  }
306
351
  ```
307
352
 
308
353
  ### Fields and defaults
309
354
 
310
- | Field | Default | Purpose |
311
- | ------------------ | --------------------------------------------------------- | ----------------------------------------------------- |
312
- | `sourceLocale` | `"en"` | Locale treated as the source of truth. |
313
- | `roots` | `["src"]` | Folders to scan for locale files and source usage. |
314
- | `translationFiles` | `<root>/**/*.{json,yml,yaml}` per root | Globs for locale files (overrides the derived globs). |
315
- | `src` | `<root>/**/*.{ts,tsx,js,jsx,mjs,cjs,vue,svelte}` per root | Globs for source files (overrides the derived globs). |
316
- | `ignoreKeys` | `[]` | Key patterns excluded from audits (`*` wildcard). |
355
+ | Field | Default | Purpose |
356
+ | ------------------ | --------------------------------------------------------- | ------------------------------------------------------- |
357
+ | `sourceLocale` | `"en"` | Locale treated as the source of truth. |
358
+ | `roots` | `["src"]` | Folders to scan for locale files and source usage. |
359
+ | `translationFiles` | `<root>/**/*.{json,yml,yaml}` per root | Globs for locale files (overrides the derived globs). |
360
+ | `src` | `<root>/**/*.{ts,tsx,js,jsx,mjs,cjs,vue,svelte}` per root | Globs for source files (overrides the derived globs). |
361
+ | `ignoreKeys` | `[]` | Key patterns excluded from audits (`*` wildcard). |
362
+ | `locales` | `[]` | Locales every set of translations must have a file for. |
317
363
 
318
364
  The config is checked before any command runs. Wrong types (`"roots": "src"` instead of
319
365
  `["src"]`), a `sourceLocale` that is not a locale code, and unknown fields (with a "did you
320
366
  mean" hint for typos) are all reported together.
321
367
 
322
- `node_modules`, `dist`, and `.next` are always ignored.
368
+ `node_modules`, `dist`, and `.next` are always ignored. A linked locale file is used only
369
+ when it points inside the project, linked folders are not entered, and no command writes
370
+ outside the project directory.
371
+
372
+ Writes replace a file in one step and keep its permissions. A file that changed on disk
373
+ since the command read it is left alone and the command fails, so rerun it. A file that repeats
374
+ a key in one object is never rewritten, since only the last value would survive; `health`
375
+ reports it as `duplicate` so you can merge the values by hand. `sort` and `remove-unused`
376
+ check every file before writing the first one.
323
377
 
324
378
  ### How locale files are recognised
325
379
 
@@ -349,6 +403,8 @@ referenced indirectly. All of these are detected:
349
403
  t("app.title"); // direct call (also i18n.t / $t / translate)
350
404
  <Trans i18nKey="banner.welcome" />; // JSX i18nKey prop
351
405
  t(online ? "status.online" : "status.offline"); // ternary branches
406
+ t(["error.specific", "error.generic"]); // fallback keys
407
+ t(($) => $.menu.title); // selector function
352
408
 
353
409
  const priorityKey = { low: "priority.low", high: "priority.high" };
354
410
  t(priorityKey[level]); // value from a lookup object
@@ -364,12 +420,21 @@ runtime:
364
420
  ```ts
365
421
  t("cart.item", { count }); // cart.item_one, cart.item_other, cart.item_zero, ... are used
366
422
  t("friend.greeting", { context }); // friend.greeting_male, friend.greeting_female, ... are used
367
- t("common:common.title"); // namespaced: common.title is used
423
+ t("common:common.title"); // namespaced: common.title in the common namespace is used
424
+ t("menu", { returnObjects: true }); // every key under menu is used
425
+ t("steps.0"); // the steps array is used
368
426
 
369
427
  const { t } = useTranslation("translation", { keyPrefix: "settings" });
370
428
  t("title"); // keyPrefix: settings.title is used (also getFixedT(lng, ns, "settings"))
371
429
  ```
372
430
 
431
+ Translations can use other keys through i18next nesting, as in `"title": "$t(brand) app"`.
432
+ A key referenced that way from any locale file is used too.
433
+
434
+ A namespaced reference only counts for its own namespace: with `public/locales/en/account.json`
435
+ and `public/locales/en/home.json`, `t("account:title")` keeps `title` in `account.json` but
436
+ not in `home.json`. A reference without a namespace counts for every namespace.
437
+
373
438
  In a file that sets a `keyPrefix`, every key is counted both with and without the prefix,
374
439
  since another `t` in the same file may not use it. A `keyPrefix` built at runtime cannot be
375
440
  resolved, so keep its keys out of `remove-unused` with `ignoreKeys`.
@@ -385,6 +450,9 @@ t("errors." + code); // every key under errors. is used
385
450
  A key computed entirely at runtime (`t(keyFromServer)`) leaves no trace in the source, so it
386
451
  is reported as unused. Add such keys to `ignoreKeys`.
387
452
 
453
+ If the `src` globs match no file at all, every key would look unused. `unused` and
454
+ `health` then print a warning, and `remove-unused` stops without removing anything.
455
+
388
456
  ## Contributing
389
457
 
390
458
  Bug reports and pull requests are welcome. See [CONTRIBUTING.md](CONTRIBUTING.md) for the
package/dist/checks.d.ts CHANGED
@@ -1,30 +1,105 @@
1
- import type { LocaleFile, LocaleObject } from "./types.js";
1
+ import type { LocaleFile, LocaleLintConfig, LocaleObject, LocaleValue } from "./types.js";
2
+ import type { KeyUsage } from "./usage.js";
3
+ type Leaves = Array<[string, LocaleValue]>;
2
4
  export interface TypeMismatch {
3
5
  key: string;
4
6
  /** Value kind in the source file: string, number, boolean, null, array or object. */
5
7
  source: string;
6
8
  target: string;
7
9
  }
10
+ export type HealthIssueType = "unsorted" | "duplicate" | "missing-file" | "missing" | "extra" | "empty" | "type-mismatch" | "placeholder" | "unused";
11
+ export interface HealthIssue {
12
+ type: HealthIssueType;
13
+ file: LocaleFile;
14
+ key?: string;
15
+ /** For type mismatches: what the key holds in the source and in this file. */
16
+ kinds?: {
17
+ source: string;
18
+ target: string;
19
+ };
20
+ /** For placeholder issues: placeholders of the source text this file lacks, and extra ones. */
21
+ placeholders?: {
22
+ missing: string[];
23
+ unexpected: string[];
24
+ };
25
+ }
26
+ export interface PlaceholderMismatch {
27
+ key: string;
28
+ missing: string[];
29
+ unexpected: string[];
30
+ }
31
+ /** Every issue `health` reports for groups of a source file and its translations. */
32
+ export declare function healthIssues(groups: Array<{
33
+ source: LocaleFile;
34
+ targets: LocaleFile[];
35
+ }>, config: Pick<LocaleLintConfig, "sourceLocale" | "ignoreKeys" | "locales">, usage: KeyUsage, orphans?: Array<{
36
+ targets: LocaleFile[];
37
+ }>): HealthIssue[];
38
+ /**
39
+ * The files a group lacks for the required `locales`, as empty locale files at the path each
40
+ * would have (`locales/de/checkout.json` next to `locales/en/checkout.json`).
41
+ */
42
+ export declare function absentLocaleFiles({ source, targets }: {
43
+ source?: LocaleFile;
44
+ targets: LocaleFile[];
45
+ }, locales: string[]): LocaleFile[];
46
+ /**
47
+ * Every file the required `locales` call for that does not exist. A set of translations
48
+ * without its source file (`orphans`) is missing that file too; without `locales` nothing is
49
+ * required.
50
+ */
51
+ export declare function missingLocaleFiles(groups: Array<{
52
+ source: LocaleFile;
53
+ targets: LocaleFile[];
54
+ }>, orphans: Array<{
55
+ targets: LocaleFile[];
56
+ }>, { sourceLocale, locales }: Pick<LocaleLintConfig, "sourceLocale" | "locales">): LocaleFile[];
57
+ /** Source keys no code or translation reads, judged within the file's own namespace. */
58
+ export declare function unusedKeys(source: LocaleFile, ignoreKeys: string[], usage: KeyUsage): string[];
8
59
  /**
9
60
  * The keys a target locale should contain: the source keys, with plural forms adjusted to
10
61
  * the target language. English `item_one`/`item_other` becomes `item_one`/`item_few`/
11
62
  * `item_many`/`item_other` for Polish and just `item_other` for Japanese.
12
63
  */
13
64
  export declare function expectedKeys(sourceKeys: string[], targetLocale: string): string[];
14
- export declare function missingKeys(sourceKeys: string[], target: LocaleFile): string[];
65
+ /**
66
+ * `keys` plus every plural form of the plural families among them that are complete: every
67
+ * form of the family in `allKeys` is in `keys`. Removing English `item_one`/`item_other`
68
+ * also removes Polish `item_few` and `item_many`, but not while `item_one` is still kept.
69
+ */
70
+ export declare function withPluralForms(keys: string[], allKeys?: string[]): string[];
71
+ /**
72
+ * What `remove-unused` deletes for one source file and its translations: the unused keys, plus
73
+ * the other plural forms of families unused as a whole. A form that is still read is kept.
74
+ */
75
+ export declare function removableKeys(source: LocaleFile, ignoreKeys: string[], usage: KeyUsage): string[];
76
+ /** Expected keys the target lacks. Ignore patterns apply to the target's own plural forms too. */
77
+ export declare function missingKeys(sourceKeys: string[], target: LocaleFile, ignoreKeys?: string[]): string[];
15
78
  /** Keys in the target that the source does not have (allowing for the target's plural forms). */
16
79
  export declare function extraKeys(sourceKeys: string[], target: LocaleFile): string[];
17
80
  /**
18
81
  * Keys written more than once in a file. `{ "a.b": "x", "a": { "b": "y" } }` defines `a.b`
19
- * twice, and i18next only ever reads one of the two values.
82
+ * twice, and i18next only ever reads one of the two values. A key repeated in one JSON object
83
+ * never reaches `data` (the parser keeps the last), so it comes from `duplicateMembers`.
20
84
  */
21
- export declare function duplicateKeys(file: LocaleFile): string[];
85
+ export declare function duplicateKeys(file: LocaleFile, leaves?: Leaves): string[];
22
86
  /** Keys whose value is an empty or whitespace-only string, or null. */
23
- export declare function emptyValueKeys(file: LocaleFile): string[];
24
- /** Keys that hold a different kind of value in the target than in the source. */
25
- export declare function typeMismatches(source: LocaleObject, target: LocaleObject, prefix?: string): TypeMismatch[];
87
+ export declare function emptyValueKeys(file: LocaleFile, leaves?: Leaves): string[];
88
+ /**
89
+ * Keys that hold a different kind of value in the target than in the source. Keys are compared
90
+ * as i18next reads them, so `{ "a.b": "x" }` and `{ "a": { "b": 1 } }` are the same key.
91
+ */
92
+ export declare function typeMismatches(source: LocaleObject, target: LocaleObject, sourceLeaves?: Leaves): TypeMismatch[];
93
+ /**
94
+ * Translations whose placeholders differ from the source text's: `{{name}}` dropped or
95
+ * misspelled, a `<0>` tag lost, a `$t()` added. A plural form is compared with the same form
96
+ * in the source, or with `_other` when the source language lacks it; `{{count}}` may come and
97
+ * go between plural forms ("One item" / "{{count}} items").
98
+ */
99
+ export declare function placeholderMismatches(source: LocaleObject, target: LocaleObject, targetLeaves?: Leaves): PlaceholderMismatch[];
26
100
  /**
27
101
  * For a plural form the source language does not have (Polish `_few` from English), the
28
102
  * source text to translate from: the `_other` form, which i18next treats as the general one.
29
103
  */
30
104
  export declare function pluralFallbackKey(key: string): string | undefined;
105
+ export {};