@rivinia/i18n 0.4.0 → 0.5.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/CHANGELOG.md +103 -0
- package/README.md +73 -7
- package/cli/rivinia-i18n-keys.mjs +267 -32
- package/fesm2022/rivinia-i18n-http-loader.impl-sLjTazQZ.mjs +20 -0
- package/fesm2022/rivinia-i18n-http-loader.impl-sLjTazQZ.mjs.map +1 -0
- package/fesm2022/rivinia-i18n-remote-loader.impl-DE90KQn_.mjs +19 -0
- package/fesm2022/rivinia-i18n-remote-loader.impl-DE90KQn_.mjs.map +1 -0
- package/fesm2022/rivinia-i18n.mjs +464 -187
- package/fesm2022/rivinia-i18n.mjs.map +1 -1
- package/package.json +22 -1
- package/types/rivinia-i18n.d.ts +130 -10
- package/fesm2022/rivinia-i18n-http-loader.impl--BRii7w1.mjs +0 -17
- package/fesm2022/rivinia-i18n-http-loader.impl--BRii7w1.mjs.map +0 -1
- package/fesm2022/rivinia-i18n-json-loader.impl-Bq-W-UW9.mjs +0 -18
- package/fesm2022/rivinia-i18n-json-loader.impl-Bq-W-UW9.mjs.map +0 -1
- package/fesm2022/rivinia-i18n-loader-url-B9SlR1XB.mjs +0 -11
- package/fesm2022/rivinia-i18n-loader-url-B9SlR1XB.mjs.map +0 -1
- package/fesm2022/rivinia-i18n-remote-loader.impl-CqKS6JWN.mjs +0 -16
- package/fesm2022/rivinia-i18n-remote-loader.impl-CqKS6JWN.mjs.map +0 -1
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
# @rivinia/i18n
|
|
2
|
+
|
|
3
|
+
Pre-1.0 policy: a minor bump may break, a patch is a bug fix.
|
|
4
|
+
|
|
5
|
+
## 0.5.0
|
|
6
|
+
|
|
7
|
+
The 0.4.0 code-review set. 0.4.1 was never published, so its fixes ship here;
|
|
8
|
+
RIV-18 (the internal split) moves to 0.6.0.
|
|
9
|
+
|
|
10
|
+
- **RIV-01 (fix):** compact ICU templates parse. `one{# item}` (no space
|
|
11
|
+
before `{`) was read as the selector `one{# item`, so translation-tool
|
|
12
|
+
output was returned raw. Plural, select, selectordinal and exact `=N` are
|
|
13
|
+
covered, including the Arabic six forms.
|
|
14
|
+
- **RIV-02 (fix):** an in-flight load shares the FETCH, not the decision to
|
|
15
|
+
apply it. A background fallback load joined by an explicit language switch
|
|
16
|
+
used to finish silently and never reach the UI; the dictionary is now
|
|
17
|
+
applied against the state at resolution time. `loadingState` follows a
|
|
18
|
+
counter of non-background loads, and `onLoadError` fires once per failed
|
|
19
|
+
fetch.
|
|
20
|
+
- **RIV-03 (packaging):** `@angular-devkit/schematics` is an OPTIONAL peer
|
|
21
|
+
(`peerDependenciesMeta`). `ng add` still requires it — the Angular CLI
|
|
22
|
+
provides it — but a plain install no longer warns.
|
|
23
|
+
- **RIV-04 (performance):** the default `jsonLoader` and its URL helper ship in
|
|
24
|
+
the main bundle. The app initializer used to fetch two extra chunks before
|
|
25
|
+
the first dictionary; `httpLoader`/`remoteLoader` stay lazy.
|
|
26
|
+
- **RIV-05 (fix):** `onMissingKey` runs from the deferred missing-key flush,
|
|
27
|
+
not inside `t()`'s computed. A handler that writes a signal no longer
|
|
28
|
+
throws NG0600; once-per-key dedupe and lookup order are unchanged.
|
|
29
|
+
- **RIV-06 (performance):** ICU templates compile once into a cached AST.
|
|
30
|
+
Rendering the same plural 100k times is ~13x faster; output is unchanged.
|
|
31
|
+
- **RIV-07 (feature):** loader failures throw `RiviniaLoadError`
|
|
32
|
+
(`url`, `status`, `language`) with the message
|
|
33
|
+
`[rivinia/i18n] Failed to load 'URL' (HTTP STATUS)`. HTTP/2 leaves
|
|
34
|
+
`statusText` empty, so the numeric status is always present.
|
|
35
|
+
- **RIV-08 (feature, behavior change):** ICU apostrophe quoting. `''` renders
|
|
36
|
+
one apostrophe (it previously rendered two), and `'{'`…`'}'` quotes literal
|
|
37
|
+
braces.
|
|
38
|
+
- **RIV-09 (DX):** missing message arguments are reported via `onMissingParam`
|
|
39
|
+
(once per key/param, from a microtask) with a dev-mode warning controlled by
|
|
40
|
+
`warnOnMissingParam`. Output keeps the placeholder.
|
|
41
|
+
- **RIV-10 (feature):** `date` arguments accept strict ISO-8601 strings.
|
|
42
|
+
Invalid strings still render raw.
|
|
43
|
+
- **RIV-11 (behavior change):** `<html lang>` now uses the language `locale`
|
|
44
|
+
when configured (`ar` + `ar-EG` → `lang="ar-EG"`); without a locale the id is
|
|
45
|
+
used, as before.
|
|
46
|
+
- **RIV-12 (feature):** dictionaries may keep dotted keys flat
|
|
47
|
+
(`{ "app.title": "…" }`). A flat key wins over a nested path on collision, and
|
|
48
|
+
the CLI warns.
|
|
49
|
+
- **RIV-13 (DX):** `toggle()` is documented as a two-language flip and warns in
|
|
50
|
+
dev mode when more than two languages are configured.
|
|
51
|
+
- **RIV-14 (packaging):** `repository`, `homepage`, `bugs`, `author`,
|
|
52
|
+
`engines` (Angular 22's supported Node range), `publishConfig.access`, and
|
|
53
|
+
this changelog are part of the published tarball.
|
|
54
|
+
- **RIV-15 (API):** every export is classified Stable/Experimental/Internal in
|
|
55
|
+
the README; internal helpers carry `@internal`; `languageChanged` is
|
|
56
|
+
deprecated in favour of `currentLanguage`.
|
|
57
|
+
- **RIV-16 (feature):** `rivinia-i18n-keys --parity --dir public/i18n --base en`
|
|
58
|
+
reports missing keys, extra keys and placeholder mismatches (including
|
|
59
|
+
arguments nested in plural/select branches), and exits 1 for CI.
|
|
60
|
+
- **RIV-17 (privacy):** the language is persisted only after an explicit
|
|
61
|
+
switch, never on first load; writes already reflected in storage are skipped.
|
|
62
|
+
`persist: false` disables persistence.
|
|
63
|
+
- **Fix:** switching to a cached language after a failed load left
|
|
64
|
+
`loadingState` at `'error'`; it now returns to `'idle'`.
|
|
65
|
+
|
|
66
|
+
## 0.4.0
|
|
67
|
+
|
|
68
|
+
The production-hardening release. Additive API; two behaviour changes.
|
|
69
|
+
|
|
70
|
+
- **SSR-safe loaders.** `LoaderContext` (`baseUrl`, `isServer`) built from
|
|
71
|
+
`REQUEST` + `<base href>` on the server and `document.baseURI` in the
|
|
72
|
+
browser. The built-in loaders absolutize only on the server, so a custom SSR
|
|
73
|
+
host must provide `REQUEST`.
|
|
74
|
+
- **`fallbackLanguage`.** Lookup is current → fallback → `defaultValue` → key.
|
|
75
|
+
Fallback text renders with the fallback locale's plural rules, loads in
|
|
76
|
+
parallel and silently, and is transferred to the client.
|
|
77
|
+
- **Missing-key reporting.** `onMissingKey(event)`, a `missingKeys` signal and
|
|
78
|
+
`clearMissingKeys()`, once per key per session and only after the current
|
|
79
|
+
language has a dictionary.
|
|
80
|
+
- **`reload(language?)`.** Stale-while-revalidate with per-language
|
|
81
|
+
generations; a response in flight when `reload()` runs is discarded.
|
|
82
|
+
- **ICU additions.** `selectordinal`, `offset:`, `{n, number}` with
|
|
83
|
+
`percent`/`integer`/`::currency/XXX`, `{d, date}` with
|
|
84
|
+
`short|medium|long|full`, and `Date` in `TranslateParams`.
|
|
85
|
+
- **`t(key, params?)` returns `Signal<string>`.** Function params are tracked.
|
|
86
|
+
- **Typed keys.** Augmentable `RiviniaI18nKeyRegistry`; the
|
|
87
|
+
`rivinia-i18n-keys` CLI generates it, with `--check` for CI.
|
|
88
|
+
|
|
89
|
+
Behaviour changes: `#` inside a plural uses the locale's digits
|
|
90
|
+
(`ar-EG`: `٣`), and an unresolved key warns once per session in dev mode.
|
|
91
|
+
|
|
92
|
+
## 0.3.0
|
|
93
|
+
|
|
94
|
+
- **Breaking:** the default `jsonLoader()` path is `i18n` (files in
|
|
95
|
+
`public/i18n/`), not `assets/i18n`. Pin the old layout with
|
|
96
|
+
`jsonLoader({ path: 'assets/i18n' })`.
|
|
97
|
+
- The language cookie gets `Secure` automatically on `https:` (never on
|
|
98
|
+
`localhost`); the server never sets cookies.
|
|
99
|
+
|
|
100
|
+
## 0.2.0
|
|
101
|
+
|
|
102
|
+
- ICU select/plural, locale-aware number and date formatting, browser language
|
|
103
|
+
detection, RTL direction, and the `rTranslate` pipe.
|
package/README.md
CHANGED
|
@@ -77,6 +77,33 @@ import {
|
|
|
77
77
|
} from '@rivinia/i18n';
|
|
78
78
|
```
|
|
79
79
|
|
|
80
|
+
## API stability
|
|
81
|
+
|
|
82
|
+
Every export is classified so the 1.0 freeze is predictable. **Internal** symbols
|
|
83
|
+
exist only so the package's own tests can import them; they may move to an
|
|
84
|
+
`@rivinia/i18n/internal` entry point (or disappear) before 1.0.
|
|
85
|
+
|
|
86
|
+
| Export | Kind | Tier |
|
|
87
|
+
| ------------------------------------------------------------------------------------- | ---------------- | ------------ |
|
|
88
|
+
| `RiviniaI18n` | service | Stable |
|
|
89
|
+
| `provideRiviniaI18n`, `defineRiviniaI18n`, `injectRiviniaI18n` | providers | Stable |
|
|
90
|
+
| `RTranslatePipe` | pipe | Stable |
|
|
91
|
+
| `RiviniaI18nConfig` | type | Stable |
|
|
92
|
+
| `Language`, `Direction`, `Translation`, `TranslateParams`, `StorageStrategy`, `SwitchStrategy` | types | Stable |
|
|
93
|
+
| `RiviniaLoadError` | class | Stable |
|
|
94
|
+
| `MissingKeyEvent`, `MissingParamEvent` | types | Stable |
|
|
95
|
+
| `TranslationLoader`, `LoaderDescriptor`, `LoaderContext` | types | Stable |
|
|
96
|
+
| `jsonLoader`, `httpLoader`, `remoteLoader`, `customLoader` | loader factories | Stable |
|
|
97
|
+
| `HttpLoaderOptions`, `RemoteLoaderOptions` | types | Stable |
|
|
98
|
+
| `formatIcu`, `IcuFormatOptions` | ICU API | Stable |
|
|
99
|
+
| `RegisteredI18nKey`, `RiviniaI18nKeyRegistry` | typed-keys types | Stable |
|
|
100
|
+
| `ViewTransitionConfig`, `ViewTransitionInfo` | types | Experimental |
|
|
101
|
+
| `ViewTransitionService` | service | Internal |
|
|
102
|
+
| `parseCookie`, `serializeCookie` | cookie helpers | Internal |
|
|
103
|
+
| `browserLanguages`, `detectBrowserLanguage` | helpers | Internal |
|
|
104
|
+
|
|
105
|
+
`languageChanged` is deprecated: `currentLanguage` is the same signal.
|
|
106
|
+
|
|
80
107
|
## Quick start
|
|
81
108
|
|
|
82
109
|
```ts
|
|
@@ -155,6 +182,9 @@ first content is available or initial loading has settled.
|
|
|
155
182
|
| `onLoadError` | `(language, error) => void` | none | Dictionary load failure. Initialization never rejects because of it. |
|
|
156
183
|
| `onMissingKey` | `(event) => void` | none | Unresolved key; suppresses the default warning. |
|
|
157
184
|
| `warnOnMissingKey` | `boolean` | `isDevMode() && !onMissingKey` | `console.warn` once per key. |
|
|
185
|
+
| `onMissingParam` | `(event) => void` | none | Missing message argument; suppresses the default warning. |
|
|
186
|
+
| `warnOnMissingParam` | `boolean` | `isDevMode() && !onMissingParam` | `console.warn` once per (key, param). |
|
|
187
|
+
| `persist` | `boolean` | `true` | Persist the language after an explicit switch. First load writes nothing. |
|
|
158
188
|
| `viewTransition` | `ViewTransitionConfig` | none | Document view transition on language change. |
|
|
159
189
|
|
|
160
190
|
## Dictionaries
|
|
@@ -175,8 +205,11 @@ remoteLoader({
|
|
|
175
205
|
});
|
|
176
206
|
```
|
|
177
207
|
|
|
178
|
-
Loader implementations are resolved lazily: `
|
|
179
|
-
|
|
208
|
+
Loader implementations are resolved lazily: `httpLoader` and `remoteLoader` are
|
|
209
|
+
separate chunks until first use. The default `jsonLoader` is part of the main
|
|
210
|
+
bundle — it runs in the app initializer, where a lazy chunk would put two extra
|
|
211
|
+
script requests between the main bundle and the dictionary fetch. A loader can
|
|
212
|
+
also be in-memory:
|
|
180
213
|
|
|
181
214
|
```ts
|
|
182
215
|
import { customLoader } from '@rivinia/i18n';
|
|
@@ -214,7 +247,7 @@ browser; `<base href>` resolved against the request on the server). `isServer` m
|
|
|
214
247
|
| ----------------------- | ----------------------------------- | -------------------------------------------------------------- |
|
|
215
248
|
| `currentLanguage` | `Signal<L>` | Active language id. |
|
|
216
249
|
| `currentLanguageObject` | `Signal<Language<L>>` | The active language entry. |
|
|
217
|
-
| `languageChanged` | `Signal<L>` |
|
|
250
|
+
| `languageChanged` | `Signal<L>` | **Deprecated** — same signal as `currentLanguage`. |
|
|
218
251
|
| `languages` | `Signal<readonly Language<L>[]>` | Supported languages. |
|
|
219
252
|
| `dir` / `isRtl` | `Signal<Direction>` / `Signal<boolean>` | Document direction. |
|
|
220
253
|
| `locale` | `Signal<string>` | BCP-47 locale driving `Intl` and plural rules. |
|
|
@@ -234,7 +267,7 @@ browser; `<base href>` resolved against the request on the server). `isServer` m
|
|
|
234
267
|
| `translate({ en: 'Hi', ar: 'أهلاً' })` | `string` | Inline map: current → fallback → first value. |
|
|
235
268
|
| `t(key, params?)` | `Signal<string>` | Same chain as a `computed`; params may be a function of signals. |
|
|
236
269
|
| `setLanguage(id)` / `setLanguageAsync(id)` | `void` / `Promise<void>` | Follows `switchStrategy`. |
|
|
237
|
-
| `toggle()` / `next()` / `previous()` | `void` |
|
|
270
|
+
| `toggle()` / `next()` / `previous()` | `void` | `toggle()` flips the first two languages (dev warning with more); `next()`/`previous()` cycle. |
|
|
238
271
|
| `loadTranslations(id, { silent? })` | `Promise<Record<…>>` | Preload without switching. |
|
|
239
272
|
| `reload(language?)` | `Promise<boolean>` | Invalidate + refetch; never rejects. |
|
|
240
273
|
| `formatNumber(value, options?)` | `string` | `Intl.NumberFormat` bound to `locale`. |
|
|
@@ -242,6 +275,7 @@ browser; `<base href>` resolved against the request on the server). `isServer` m
|
|
|
242
275
|
| `getLanguage(id)` | `Language<L> \| undefined` | Lookup. |
|
|
243
276
|
| `initialize()` | `Promise<void>` | Called by the provider; idempotent. |
|
|
244
277
|
| `clearMissingKeys()` | `void` | Reset the missing-key report. |
|
|
278
|
+
| `clearMissingParams()` | `void` | Reset the missing-parameter dedupe. |
|
|
245
279
|
|
|
246
280
|
`RTranslatePipe` (`rTranslate`) delegates to `translate()`. It is impure by necessity —
|
|
247
281
|
the service reads signals on every call — so prefer `t()` or component code for long
|
|
@@ -273,6 +307,14 @@ Supported subset (MF1): `{name}` interpolation, `{n, plural, …}` (with `offset
|
|
|
273
307
|
- Unsupported or malformed constructs never throw: the raw `{…}` segment is returned
|
|
274
308
|
as-is and parsing continues.
|
|
275
309
|
- `{name}` interpolation is `String(value)`; use `{n, number}` when formatting matters.
|
|
310
|
+
- `''` renders one apostrophe. A single apostrophe immediately before `{` or `}` (and
|
|
311
|
+
`#` inside a plural) starts a quoted literal that ends at the next apostrophe:
|
|
312
|
+
`It''s '{'x'}'` → `It's {x}`. A lone apostrophe elsewhere (`Don't`) is unchanged.
|
|
313
|
+
- `date` accepts a `Date`, epoch milliseconds, or a strict ISO-8601 string
|
|
314
|
+
(`2026-10-28`, `2026-10-28T12:00:00Z`). Invalid input keeps the raw segment. Plain
|
|
315
|
+
`{d}` on a `Date` uses `String()` — use `{d, date, …}` for localized output.
|
|
316
|
+
- Templates are compiled once into a cached AST, so a message rendered on every
|
|
317
|
+
change-detection pass is not re-parsed.
|
|
276
318
|
|
|
277
319
|
## Missing keys
|
|
278
320
|
|
|
@@ -300,6 +342,22 @@ provideRiviniaI18n({
|
|
|
300
342
|
Without `onMissingKey`, a `console.warn` is logged once per key in dev mode. Set
|
|
301
343
|
`warnOnMissingKey: false` to silence it, or `true` to keep it in production.
|
|
302
344
|
|
|
345
|
+
## Missing parameters
|
|
346
|
+
|
|
347
|
+
A message that needs `{name}` but receives no `name` keeps the placeholder — it is
|
|
348
|
+
never replaced with `undefined`. Report it the same way as missing keys:
|
|
349
|
+
|
|
350
|
+
```ts
|
|
351
|
+
provideRiviniaI18n({
|
|
352
|
+
// …
|
|
353
|
+
onMissingParam: ({ key, param, language }) => report(param, { key, language }),
|
|
354
|
+
});
|
|
355
|
+
```
|
|
356
|
+
|
|
357
|
+
Without `onMissingParam`, dev mode logs one warning per (key, param) pair. Set
|
|
358
|
+
`warnOnMissingParam: false` to silence it. The hook is delivered from a microtask,
|
|
359
|
+
so it may write signals, and `i18n.clearMissingParams()` resets the dedupe.
|
|
360
|
+
|
|
303
361
|
## Fallback language
|
|
304
362
|
|
|
305
363
|
Lookup order for `translate(key)`:
|
|
@@ -362,6 +420,7 @@ npx rivinia-i18n-keys
|
|
|
362
420
|
# → src/i18n-keys.d.ts
|
|
363
421
|
npx rivinia-i18n-keys --source public/i18n/en.json --out src/i18n-keys.d.ts
|
|
364
422
|
npx rivinia-i18n-keys --check # exit 1 when the file is stale (CI)
|
|
423
|
+
npx rivinia-i18n-keys --parity --dir public/i18n --base en
|
|
365
424
|
```
|
|
366
425
|
|
|
367
426
|
```ts
|
|
@@ -383,9 +442,16 @@ i18n.t('app.titel'); // TS error: not assignable to 'app.title' | …
|
|
|
383
442
|
i18n.translate(`status.${code}` as RegisteredI18nKey); // dynamic key, explicit
|
|
384
443
|
```
|
|
385
444
|
|
|
386
|
-
The CLI flattens nested objects to dot paths, keeps
|
|
387
|
-
|
|
388
|
-
|
|
445
|
+
The CLI flattens nested objects to dot paths, keeps literal dotted keys as-is, keeps
|
|
446
|
+
string leaves only, warns about non-string leaves and key collisions (the flat key
|
|
447
|
+
wins), sorts keys for stable diffs, and escapes quotes. It has no dependencies and
|
|
448
|
+
ships with the package (`rivinia-i18n-keys`).
|
|
449
|
+
|
|
450
|
+
`--parity` compares every `<language>.json` in `--dir` against `--base` and reports,
|
|
451
|
+
sorted: keys missing from a language, keys extra to it, and ICU placeholders used by
|
|
452
|
+
the base string but absent from the translation. Placeholders inside plural/select
|
|
453
|
+
branches are compared too; branch text itself is never read as a parameter. Any
|
|
454
|
+
mismatch exits 1, so CI fails on the common "added to `en.json`, forgot `ar.json`" bug.
|
|
389
455
|
|
|
390
456
|
## SSR
|
|
391
457
|
|
|
@@ -1,20 +1,25 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
/**
|
|
3
|
-
* `rivinia-i18n-keys` — generates the typed-key registry for `@rivinia/i18n
|
|
3
|
+
* `rivinia-i18n-keys` — generates the typed-key registry for `@rivinia/i18n`
|
|
4
|
+
* and checks key/placeholder parity across dictionaries.
|
|
4
5
|
*
|
|
5
6
|
* npx rivinia-i18n-keys
|
|
6
7
|
* npx rivinia-i18n-keys --source public/i18n/en.json --out src/i18n-keys.d.ts
|
|
7
8
|
* npx rivinia-i18n-keys --check # CI: exit 1 when the file is stale
|
|
9
|
+
* npx rivinia-i18n-keys --parity --dir public/i18n --base en
|
|
8
10
|
*
|
|
9
|
-
* Nested objects flatten to dot paths,
|
|
10
|
-
* are sorted for stable diffs, and quotes
|
|
11
|
+
* Nested objects flatten to dot paths, literal dotted keys are kept as-is,
|
|
12
|
+
* only string leaves become keys, keys are sorted for stable diffs, and quotes
|
|
13
|
+
* are escaped. No dependencies.
|
|
11
14
|
*/
|
|
12
|
-
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
13
|
-
import { dirname, relative, resolve } from 'node:path';
|
|
15
|
+
import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from 'node:fs';
|
|
16
|
+
import { dirname, basename, join, relative, resolve } from 'node:path';
|
|
14
17
|
|
|
15
18
|
const DEFAULTS = Object.freeze({
|
|
16
19
|
source: 'public/i18n/en.json',
|
|
17
20
|
out: 'src/i18n-keys.d.ts',
|
|
21
|
+
dir: 'public/i18n',
|
|
22
|
+
base: 'en',
|
|
18
23
|
});
|
|
19
24
|
|
|
20
25
|
const PREFIX = '[rivinia/i18n]';
|
|
@@ -30,26 +35,19 @@ function main(argv) {
|
|
|
30
35
|
printHelp();
|
|
31
36
|
return 0;
|
|
32
37
|
}
|
|
38
|
+
return args.parity ? runParity(args) : runGenerate(args);
|
|
39
|
+
}
|
|
33
40
|
|
|
41
|
+
function runGenerate(args) {
|
|
34
42
|
const sourcePath = resolve(args.source ?? DEFAULTS.source);
|
|
35
43
|
const outPath = resolve(args.out ?? DEFAULTS.out);
|
|
36
44
|
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
return 1;
|
|
40
|
-
}
|
|
45
|
+
const dictionary = readDictionary(sourcePath);
|
|
46
|
+
if (dictionary === null) return 1;
|
|
41
47
|
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
} catch (error) {
|
|
46
|
-
console.error(`${PREFIX} Could not parse ${sourcePath}: ${error.message}`);
|
|
47
|
-
return 1;
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
const keys = [];
|
|
51
|
-
flatten(dictionary, '', keys);
|
|
52
|
-
keys.sort();
|
|
48
|
+
const entries = new Map();
|
|
49
|
+
flatten(dictionary, '', entries);
|
|
50
|
+
const keys = [...entries.keys()].sort();
|
|
53
51
|
const output = render(keys);
|
|
54
52
|
|
|
55
53
|
if (args.check) {
|
|
@@ -72,25 +70,129 @@ function main(argv) {
|
|
|
72
70
|
return 0;
|
|
73
71
|
}
|
|
74
72
|
|
|
73
|
+
/**
|
|
74
|
+
* `--parity`: every `<lang>.json` in `--dir` must have the same keys as
|
|
75
|
+
* `--base`, and every placeholder used by the base string must appear in the
|
|
76
|
+
* translated string. Sorted output, exit 1 on any mismatch (CI-friendly).
|
|
77
|
+
*/
|
|
78
|
+
function runParity(args) {
|
|
79
|
+
const dir = resolve(args.dir ?? DEFAULTS.dir);
|
|
80
|
+
const base = args.base ?? DEFAULTS.base;
|
|
81
|
+
|
|
82
|
+
if (!existsSync(dir)) {
|
|
83
|
+
console.error(`${PREFIX} Dictionary directory not found: ${dir}`);
|
|
84
|
+
return 1;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
const files = readdirSync(dir)
|
|
88
|
+
.filter((file) => file.endsWith('.json'))
|
|
89
|
+
.sort();
|
|
90
|
+
if (files.length === 0) {
|
|
91
|
+
console.error(`${PREFIX} No JSON dictionaries in ${dir}`);
|
|
92
|
+
return 1;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
const dictionaries = new Map();
|
|
96
|
+
for (const file of files) {
|
|
97
|
+
const language = basename(file, '.json');
|
|
98
|
+
const path = join(dir, file);
|
|
99
|
+
const dictionary = readDictionary(path);
|
|
100
|
+
if (dictionary === null) return 1;
|
|
101
|
+
const entries = new Map();
|
|
102
|
+
flatten(dictionary, '', entries);
|
|
103
|
+
dictionaries.set(language, entries);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
const baseEntries = dictionaries.get(base);
|
|
107
|
+
if (baseEntries === undefined) {
|
|
108
|
+
console.error(`${PREFIX} Base dictionary "${base}.json" not found in ${dir}`);
|
|
109
|
+
return 1;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
const problems = [];
|
|
113
|
+
for (const language of [...dictionaries.keys()].sort()) {
|
|
114
|
+
if (language === base) continue;
|
|
115
|
+
const entries = dictionaries.get(language);
|
|
116
|
+
|
|
117
|
+
for (const key of [...baseEntries.keys()].sort()) {
|
|
118
|
+
if (!entries.has(key)) {
|
|
119
|
+
problems.push(
|
|
120
|
+
`${PREFIX} MISSING ${language} key "${key}" (present in "${base}")`,
|
|
121
|
+
);
|
|
122
|
+
continue;
|
|
123
|
+
}
|
|
124
|
+
const expected = placeholders(baseEntries.get(key).value);
|
|
125
|
+
const actual = placeholders(entries.get(key).value);
|
|
126
|
+
for (const name of [...expected].sort()) {
|
|
127
|
+
if (!actual.has(name)) {
|
|
128
|
+
problems.push(
|
|
129
|
+
`${PREFIX} PLACEHOLDER ${language} key "${key}": ` +
|
|
130
|
+
`{${name}} is used in "${base}" but absent from "${language}"`,
|
|
131
|
+
);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
for (const key of [...entries.keys()].sort()) {
|
|
137
|
+
if (!baseEntries.has(key)) {
|
|
138
|
+
problems.push(`${PREFIX} EXTRA ${language} key "${key}" (absent in "${base}")`);
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
if (problems.length === 0) {
|
|
144
|
+
console.log(
|
|
145
|
+
`${PREFIX} Parity OK (${dictionaries.size} dictionaries, ` +
|
|
146
|
+
`${baseEntries.size} keys in "${base}").`,
|
|
147
|
+
);
|
|
148
|
+
return 0;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
for (const line of problems) console.error(line);
|
|
152
|
+
console.error(
|
|
153
|
+
`${PREFIX} ${problems.length} parity problem(s) across ${dictionaries.size} dictionaries.`,
|
|
154
|
+
);
|
|
155
|
+
return 1;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function readDictionary(path) {
|
|
159
|
+
if (!existsSync(path)) {
|
|
160
|
+
console.error(`${PREFIX} Source dictionary not found: ${path}`);
|
|
161
|
+
return null;
|
|
162
|
+
}
|
|
163
|
+
try {
|
|
164
|
+
return JSON.parse(readFileSync(path, 'utf8'));
|
|
165
|
+
} catch (error) {
|
|
166
|
+
console.error(`${PREFIX} Could not parse ${path}: ${error.message}`);
|
|
167
|
+
return null;
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
|
|
75
171
|
function parseArgs(argv) {
|
|
76
172
|
const args = {};
|
|
77
173
|
for (let i = 0; i < argv.length; i++) {
|
|
78
174
|
const arg = argv[i];
|
|
79
175
|
if (arg === '--check') {
|
|
80
176
|
args.check = true;
|
|
177
|
+
} else if (arg === '--parity') {
|
|
178
|
+
args.parity = true;
|
|
81
179
|
} else if (arg === '--help' || arg === '-h') {
|
|
82
180
|
args.help = true;
|
|
83
|
-
} else if (arg === '--source' || arg === '--out') {
|
|
181
|
+
} else if (arg === '--source' || arg === '--out' || arg === '--dir' || arg === '--base') {
|
|
84
182
|
const value = argv[i + 1];
|
|
85
183
|
if (value === undefined || value.startsWith('--')) {
|
|
86
|
-
return { error: `${arg} needs a path.` };
|
|
184
|
+
return { error: `${arg} needs a ${arg === '--base' ? 'language' : 'path'}.` };
|
|
87
185
|
}
|
|
88
186
|
args[arg.slice(2)] = value;
|
|
89
187
|
i++;
|
|
90
|
-
} else if (
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
188
|
+
} else if (
|
|
189
|
+
arg.startsWith('--source=') ||
|
|
190
|
+
arg.startsWith('--out=') ||
|
|
191
|
+
arg.startsWith('--dir=') ||
|
|
192
|
+
arg.startsWith('--base=')
|
|
193
|
+
) {
|
|
194
|
+
const eq = arg.indexOf('=');
|
|
195
|
+
args[arg.slice(2, eq)] = arg.slice(eq + 1);
|
|
94
196
|
} else {
|
|
95
197
|
return { error: `Unknown option: ${arg}` };
|
|
96
198
|
}
|
|
@@ -98,22 +200,151 @@ function parseArgs(argv) {
|
|
|
98
200
|
return args;
|
|
99
201
|
}
|
|
100
202
|
|
|
101
|
-
|
|
203
|
+
/**
|
|
204
|
+
* Collects string leaves in `entries` (key → { value, flat, sourcePath }).
|
|
205
|
+
* A JSON key that itself contains dots (an export from many tools) is already
|
|
206
|
+
* a full key; when it collides with a nested path the literal key wins and a
|
|
207
|
+
* warning is printed.
|
|
208
|
+
*/
|
|
209
|
+
function flatten(value, prefix, entries) {
|
|
102
210
|
if (Array.isArray(value)) {
|
|
103
211
|
warn(`Skipping array at "${prefix || '(root)'}" — arrays are not keys.`);
|
|
104
212
|
return;
|
|
105
213
|
}
|
|
106
214
|
if (value !== null && typeof value === 'object') {
|
|
107
215
|
for (const [key, child] of Object.entries(value)) {
|
|
108
|
-
|
|
216
|
+
const path = prefix ? `${prefix}.${key}` : key;
|
|
217
|
+
if (child !== null && typeof child === 'object' && !Array.isArray(child)) {
|
|
218
|
+
flatten(child, path, entries);
|
|
219
|
+
continue;
|
|
220
|
+
}
|
|
221
|
+
if (typeof child === 'string') {
|
|
222
|
+
addEntry(entries, path, child, key.includes('.'), path);
|
|
223
|
+
continue;
|
|
224
|
+
}
|
|
225
|
+
if (Array.isArray(child)) {
|
|
226
|
+
warn(`Skipping array at "${path}" — arrays are not keys.`);
|
|
227
|
+
continue;
|
|
228
|
+
}
|
|
229
|
+
warn(`Skipping non-string value at "${path}" (${typeOf(child)}).`);
|
|
109
230
|
}
|
|
110
231
|
return;
|
|
111
232
|
}
|
|
112
|
-
|
|
113
|
-
|
|
233
|
+
warn(`Skipping non-string value at "${prefix || '(root)'}" (${typeOf(value)}).`);
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
function addEntry(entries, key, value, flat, sourcePath) {
|
|
237
|
+
const existing = entries.get(key);
|
|
238
|
+
if (existing === undefined) {
|
|
239
|
+
entries.set(key, { value, flat, sourcePath });
|
|
114
240
|
return;
|
|
115
241
|
}
|
|
116
|
-
|
|
242
|
+
if (existing.flat && !flat) {
|
|
243
|
+
warn(`Key collision at "${key}": keeping the flat key over "${sourcePath}".`);
|
|
244
|
+
return;
|
|
245
|
+
}
|
|
246
|
+
if (!existing.flat && flat) {
|
|
247
|
+
warn(`Key collision at "${key}": the flat key wins over "${existing.sourcePath}".`);
|
|
248
|
+
entries.set(key, { value, flat, sourcePath });
|
|
249
|
+
return;
|
|
250
|
+
}
|
|
251
|
+
warn(
|
|
252
|
+
`Key collision at "${key}" between "${existing.sourcePath}" and "${sourcePath}"; ` +
|
|
253
|
+
'keeping the first value.',
|
|
254
|
+
);
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
const NAME = /^[A-Za-z_][A-Za-z0-9_.-]*$/;
|
|
258
|
+
const BRANCH_TYPES = new Set(['plural', 'selectordinal', 'select']);
|
|
259
|
+
|
|
260
|
+
/**
|
|
261
|
+
* Named arguments of an ICU message: every `{name …}` argument at any nesting
|
|
262
|
+
* depth. Branch bodies are message text, not arguments, so their words are
|
|
263
|
+
* never reported — `=0 {No items}` must not yield a `{No}` parameter.
|
|
264
|
+
*/
|
|
265
|
+
function placeholders(message) {
|
|
266
|
+
const names = new Set();
|
|
267
|
+
if (typeof message !== 'string') return names;
|
|
268
|
+
collectPlaceholders(message, 0, message.length, names);
|
|
269
|
+
return names;
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
function collectPlaceholders(text, start, end, names) {
|
|
273
|
+
let i = start;
|
|
274
|
+
while (i < end) {
|
|
275
|
+
const char = text[i];
|
|
276
|
+
if (char === "'") {
|
|
277
|
+
i = skipQuote(text, i, end);
|
|
278
|
+
} else if (char === '{') {
|
|
279
|
+
i = readArgument(text, i, end, names);
|
|
280
|
+
} else {
|
|
281
|
+
i++;
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
/** ICU: `''` is one apostrophe; `'` before `{`, `}` or `#` quotes until `'`. */
|
|
287
|
+
function skipQuote(text, i, end) {
|
|
288
|
+
if (text[i + 1] === "'") return i + 2;
|
|
289
|
+
const next = text[i + 1];
|
|
290
|
+
if (next === '{' || next === '}' || next === '#') {
|
|
291
|
+
const close = text.indexOf("'", i + 2);
|
|
292
|
+
return close === -1 || close >= end ? end : close + 1;
|
|
293
|
+
}
|
|
294
|
+
return i + 1;
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
/** Index of the `}` closing the `{` at `open`; `end` when malformed. */
|
|
298
|
+
function matchBrace(text, open, end) {
|
|
299
|
+
let depth = 0;
|
|
300
|
+
for (let i = open; i < end; i++) {
|
|
301
|
+
const char = text[i];
|
|
302
|
+
if (char === "'") {
|
|
303
|
+
i = skipQuote(text, i, end) - 1;
|
|
304
|
+
} else if (char === '{') {
|
|
305
|
+
depth++;
|
|
306
|
+
} else if (char === '}' && --depth === 0) {
|
|
307
|
+
return i;
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
return end;
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
function readArgument(text, open, end, names) {
|
|
314
|
+
const close = matchBrace(text, open, end);
|
|
315
|
+
let i = open + 1;
|
|
316
|
+
while (i < close && /\s/.test(text[i])) i++;
|
|
317
|
+
const nameStart = i;
|
|
318
|
+
while (i < close && text[i] !== ',' && text[i] !== '}') i++;
|
|
319
|
+
const name = text.slice(nameStart, i).trim();
|
|
320
|
+
if (NAME.test(name)) names.add(name);
|
|
321
|
+
if (i >= close || text[i] === '}') return close + 1;
|
|
322
|
+
|
|
323
|
+
i++; // past the comma
|
|
324
|
+
while (i < close && /\s/.test(text[i])) i++;
|
|
325
|
+
const typeStart = i;
|
|
326
|
+
while (i < close && text[i] !== ',' && text[i] !== '}') i++;
|
|
327
|
+
if (BRANCH_TYPES.has(text.slice(typeStart, i).trim())) {
|
|
328
|
+
collectBranches(text, i, close, names);
|
|
329
|
+
}
|
|
330
|
+
return close + 1;
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
/** Selector words are ignored; each `{…}` branch body is a nested message. */
|
|
334
|
+
function collectBranches(text, start, end, names) {
|
|
335
|
+
let i = start;
|
|
336
|
+
while (i < end) {
|
|
337
|
+
const char = text[i];
|
|
338
|
+
if (char === "'") {
|
|
339
|
+
i = skipQuote(text, i, end);
|
|
340
|
+
} else if (char === '{') {
|
|
341
|
+
const close = matchBrace(text, i, end);
|
|
342
|
+
collectPlaceholders(text, i + 1, close, names);
|
|
343
|
+
i = close + 1;
|
|
344
|
+
} else {
|
|
345
|
+
i++;
|
|
346
|
+
}
|
|
347
|
+
}
|
|
117
348
|
}
|
|
118
349
|
|
|
119
350
|
function typeOf(value) {
|
|
@@ -152,11 +383,15 @@ function printHelp() {
|
|
|
152
383
|
'Usage:',
|
|
153
384
|
' rivinia-i18n-keys [--source <json>] [--out <d.ts>]',
|
|
154
385
|
' rivinia-i18n-keys --check',
|
|
386
|
+
' rivinia-i18n-keys --parity [--dir <folder>] [--base <language>]',
|
|
155
387
|
'',
|
|
156
388
|
'Options:',
|
|
157
|
-
` --source Dictionary to read
|
|
389
|
+
` --source Dictionary to read (default: ${DEFAULTS.source})`,
|
|
158
390
|
` --out Declaration file to write (default: ${DEFAULTS.out})`,
|
|
159
391
|
' --check Exit 1 when --out is missing or stale (for CI)',
|
|
392
|
+
` --parity Compare every dictionary against the base`,
|
|
393
|
+
` --dir Dictionary folder (default: ${DEFAULTS.dir})`,
|
|
394
|
+
` --base Reference language (default: ${DEFAULTS.base})`,
|
|
160
395
|
' --help Show this help',
|
|
161
396
|
].join('\n'),
|
|
162
397
|
);
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
var HttpLoader = class {
|
|
2
|
+
_options;
|
|
3
|
+
_resolveUrl;
|
|
4
|
+
_createError;
|
|
5
|
+
constructor(_options, _resolveUrl, _createError) {
|
|
6
|
+
this._options = _options;
|
|
7
|
+
this._resolveUrl = _resolveUrl;
|
|
8
|
+
this._createError = _createError;
|
|
9
|
+
}
|
|
10
|
+
async load(language, context) {
|
|
11
|
+
const built = this._options.buildUrl?.(language) ?? `${this._options.endpoint}/${language}`;
|
|
12
|
+
const url = this._resolveUrl(built, context);
|
|
13
|
+
const response = await fetch(url, { method: this._options.method ?? "GET" });
|
|
14
|
+
if (!response.ok) throw this._createError(url, response.status, language);
|
|
15
|
+
return response.json();
|
|
16
|
+
}
|
|
17
|
+
};
|
|
18
|
+
export { HttpLoader };
|
|
19
|
+
|
|
20
|
+
//# sourceMappingURL=rivinia-i18n-http-loader.impl-sLjTazQZ.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"rivinia-i18n-http-loader.impl-sLjTazQZ.mjs","names":[],"sources":["../../../projects/i18n/src/lib/services/http-loader.impl.ts"],"sourcesContent":["import type { HttpLoaderOptions, LoaderContext, TranslationLoader } from '../models/loaders';\n\ntype ResolveUrl = (url: string, context?: LoaderContext) => string;\ntype CreateError = (url: string, status: number, language: string) => Error;\n\nexport class HttpLoader<L extends string = string> implements TranslationLoader<L> {\n constructor(\n private readonly _options: HttpLoaderOptions,\n private readonly _resolveUrl: ResolveUrl,\n private readonly _createError: CreateError,\n ) {}\n\n async load(language: L, context?: LoaderContext): Promise<Record<string, unknown>> {\n const built = this._options.buildUrl?.(language) ?? `${this._options.endpoint}/${language}`;\n const url = this._resolveUrl(built, context);\n const response = await fetch(url, { method: this._options.method ?? 'GET' });\n if (!response.ok) {\n throw this._createError(url, response.status, language);\n }\n return response.json();\n }\n}\n"],"mappings":"AAKA,IAAa,aAAb,MAAuB;CAEF;CACA;CACA;CAHnB,YACmB,UACA,aACA,cAAyB;EAFzB,KAAA,WAAA;EACA,KAAA,cAAA;EACA,KAAA,eAAA;CAChB;CAEH,MAAM,KAAK,UAAa,SAAuB;EAC7C,MAAM,QAAQ,KAAK,SAAS,WAAW,QAAQ,KAAK,GAAG,KAAK,SAAS,SAAQ,GAAI;EACjF,MAAM,MAAM,KAAK,YAAY,OAAO,OAAO;EAC3C,MAAM,WAAW,MAAM,MAAM,KAAK,EAAE,QAAQ,KAAK,SAAS,UAAU,MAAK,CAAE;EAC3E,IAAI,CAAC,SAAS,IACZ,MAAM,KAAK,aAAa,KAAK,SAAS,QAAQ,QAAQ;EAExD,OAAO,SAAS,KAAI;CACtB;AACD"}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
var RemoteLoader = class {
|
|
2
|
+
_options;
|
|
3
|
+
_resolveUrl;
|
|
4
|
+
_createError;
|
|
5
|
+
constructor(_options, _resolveUrl, _createError) {
|
|
6
|
+
this._options = _options;
|
|
7
|
+
this._resolveUrl = _resolveUrl;
|
|
8
|
+
this._createError = _createError;
|
|
9
|
+
}
|
|
10
|
+
async load(language, context) {
|
|
11
|
+
const url = this._resolveUrl(this._options.url(language), context);
|
|
12
|
+
const response = await fetch(url, { headers: this._options.headers });
|
|
13
|
+
if (!response.ok) throw this._createError(url, response.status, language);
|
|
14
|
+
return response.json();
|
|
15
|
+
}
|
|
16
|
+
};
|
|
17
|
+
export { RemoteLoader };
|
|
18
|
+
|
|
19
|
+
//# sourceMappingURL=rivinia-i18n-remote-loader.impl-DE90KQn_.mjs.map
|