@rivinia/i18n 0.4.0 → 0.6.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 ADDED
@@ -0,0 +1,131 @@
1
+ # @rivinia/i18n
2
+
3
+ Pre-1.0 policy: a minor bump may break, a patch is a bug fix.
4
+
5
+ ## 0.6.0 (unreleased)
6
+
7
+ The core split (RIV-18) and the pre-release API cleanup. Breaking, as a pre-1.0 minor
8
+ may be: the library never had a released compatibility contract, so the transitional
9
+ names were removed instead of carried to 1.0.
10
+
11
+ - **RIV-18 (internal):** `RiviniaI18n` (915 lines, eight responsibilities) is now a
12
+ facade over five plain collaborators: `MessageFormatter` (ICU render + bounded
13
+ `Intl` memo), `MissingKeyReporter` (dedupe, microtask flush, `missingKeys`),
14
+ `LanguageStorage` (local/session/cookie, persist-after-switch, initial language),
15
+ `DocumentDirectionApplier` (`<html dir/lang>`, view transition) and
16
+ `DictionaryStore` (cache, shared in-flight fetch, generations, TransferState,
17
+ loading counter, fallback slot). None is exported; they take constructor
18
+ arguments instead of DI tokens, and each has direct unit tests.
19
+ - **`rvTranslate` replaces `rTranslate` (breaking):** `RvTranslatePipe` keeps the
20
+ package prefix (`angular.json` already sets `prefix: "rv"`). `RTranslatePipe` and
21
+ the `rTranslate` selector were removed — no alias, no deprecation window.
22
+ - **`languageChanged` removed (breaking):** it was the same signal as
23
+ `currentLanguage`.
24
+ - **`loadTranslations(id, { silent })` → `loadTranslations(id)` (breaking):** the
25
+ option was declared but never read; background loads are internal.
26
+ - **Unbounded map removed:** the `Intl` number/date memo is now a 40-entry LRU, the
27
+ same ceiling as the `formatIcu` caches; the emitted output is unchanged.
28
+ - **`loadedTranslations` is `readonly`:** a public `Signal` was assignable before;
29
+ no consumer can reasonably depend on writing it.
30
+ - **Behaviour:** none intended. The characterization test (`fallback-after-init`)
31
+ and the SSR smoke suite were added before the split and pass unchanged after it.
32
+
33
+ ## 0.5.0
34
+
35
+ The 0.4.0 code-review set. 0.4.1 was never published, so its fixes ship here;
36
+ RIV-18 (the internal split) moves to 0.6.0.
37
+
38
+ - **RIV-01 (fix):** compact ICU templates parse. `one{# item}` (no space
39
+ before `{`) was read as the selector `one{# item`, so translation-tool
40
+ output was returned raw. Plural, select, selectordinal and exact `=N` are
41
+ covered, including the Arabic six forms.
42
+ - **RIV-02 (fix):** an in-flight load shares the FETCH, not the decision to
43
+ apply it. A background fallback load joined by an explicit language switch
44
+ used to finish silently and never reach the UI; the dictionary is now
45
+ applied against the state at resolution time. `loadingState` follows a
46
+ counter of non-background loads, and `onLoadError` fires once per failed
47
+ fetch.
48
+ - **RIV-03 (packaging):** `@angular-devkit/schematics` is an OPTIONAL peer
49
+ (`peerDependenciesMeta`). `ng add` still requires it — the Angular CLI
50
+ provides it — but a plain install no longer warns.
51
+ - **RIV-04 (performance):** the default `jsonLoader` and its URL helper ship in
52
+ the main bundle. The app initializer used to fetch two extra chunks before
53
+ the first dictionary; `httpLoader`/`remoteLoader` stay lazy.
54
+ - **RIV-05 (fix):** `onMissingKey` runs from the deferred missing-key flush,
55
+ not inside `t()`'s computed. A handler that writes a signal no longer
56
+ throws NG0600; once-per-key dedupe and lookup order are unchanged.
57
+ - **RIV-06 (performance):** ICU templates compile once into a cached AST.
58
+ Rendering the same plural 100k times is ~13x faster; output is unchanged.
59
+ - **RIV-07 (feature):** loader failures throw `RiviniaLoadError`
60
+ (`url`, `status`, `language`) with the message
61
+ `[rivinia/i18n] Failed to load 'URL' (HTTP STATUS)`. HTTP/2 leaves
62
+ `statusText` empty, so the numeric status is always present.
63
+ - **RIV-08 (feature, behavior change):** ICU apostrophe quoting. `''` renders
64
+ one apostrophe (it previously rendered two), and `'{'`…`'}'` quotes literal
65
+ braces.
66
+ - **RIV-09 (DX):** missing message arguments are reported via `onMissingParam`
67
+ (once per key/param, from a microtask) with a dev-mode warning controlled by
68
+ `warnOnMissingParam`. Output keeps the placeholder.
69
+ - **RIV-10 (feature):** `date` arguments accept strict ISO-8601 strings.
70
+ Invalid strings still render raw.
71
+ - **RIV-11 (behavior change):** `<html lang>` now uses the language `locale`
72
+ when configured (`ar` + `ar-EG` → `lang="ar-EG"`); without a locale the id is
73
+ used, as before.
74
+ - **RIV-12 (feature):** dictionaries may keep dotted keys flat
75
+ (`{ "app.title": "…" }`). A flat key wins over a nested path on collision, and
76
+ the CLI warns.
77
+ - **RIV-13 (DX):** `toggle()` is documented as a two-language flip and warns in
78
+ dev mode when more than two languages are configured.
79
+ - **RIV-14 (packaging):** `repository`, `homepage`, `bugs`, `author`,
80
+ `engines` (Angular 22's supported Node range), `publishConfig.access`, and
81
+ this changelog are part of the published tarball.
82
+ - **RIV-15 (API):** every export is classified Stable/Experimental/Internal in
83
+ the README; internal helpers carry `@internal`; `languageChanged` is
84
+ deprecated in favour of `currentLanguage`.
85
+ - **RIV-16 (feature):** `rivinia-i18n-keys --parity --dir public/i18n --base en`
86
+ reports missing keys, extra keys and placeholder mismatches (including
87
+ arguments nested in plural/select branches), and exits 1 for CI.
88
+ - **RIV-17 (privacy):** the language is persisted only after an explicit
89
+ switch, never on first load; writes already reflected in storage are skipped.
90
+ `persist: false` disables persistence.
91
+ - **Fix:** switching to a cached language after a failed load left
92
+ `loadingState` at `'error'`; it now returns to `'idle'`.
93
+
94
+ ## 0.4.0
95
+
96
+ The production-hardening release. Additive API; two behaviour changes.
97
+
98
+ - **SSR-safe loaders.** `LoaderContext` (`baseUrl`, `isServer`) built from
99
+ `REQUEST` + `<base href>` on the server and `document.baseURI` in the
100
+ browser. The built-in loaders absolutize only on the server, so a custom SSR
101
+ host must provide `REQUEST`.
102
+ - **`fallbackLanguage`.** Lookup is current → fallback → `defaultValue` → key.
103
+ Fallback text renders with the fallback locale's plural rules, loads in
104
+ parallel and silently, and is transferred to the client.
105
+ - **Missing-key reporting.** `onMissingKey(event)`, a `missingKeys` signal and
106
+ `clearMissingKeys()`, once per key per session and only after the current
107
+ language has a dictionary.
108
+ - **`reload(language?)`.** Stale-while-revalidate with per-language
109
+ generations; a response in flight when `reload()` runs is discarded.
110
+ - **ICU additions.** `selectordinal`, `offset:`, `{n, number}` with
111
+ `percent`/`integer`/`::currency/XXX`, `{d, date}` with
112
+ `short|medium|long|full`, and `Date` in `TranslateParams`.
113
+ - **`t(key, params?)` returns `Signal<string>`.** Function params are tracked.
114
+ - **Typed keys.** Augmentable `RiviniaI18nKeyRegistry`; the
115
+ `rivinia-i18n-keys` CLI generates it, with `--check` for CI.
116
+
117
+ Behaviour changes: `#` inside a plural uses the locale's digits
118
+ (`ar-EG`: `٣`), and an unresolved key warns once per session in dev mode.
119
+
120
+ ## 0.3.0
121
+
122
+ - **Breaking:** the default `jsonLoader()` path is `i18n` (files in
123
+ `public/i18n/`), not `assets/i18n`. Pin the old layout with
124
+ `jsonLoader({ path: 'assets/i18n' })`.
125
+ - The language cookie gets `Secure` automatically on `https:` (never on
126
+ `localhost`); the server never sets cookies.
127
+
128
+ ## 0.2.0
129
+
130
+ - ICU select/plural, locale-aware number and date formatting, browser language
131
+ detection, RTL direction, and the `rTranslate` pipe.
package/README.md CHANGED
@@ -68,7 +68,7 @@ import {
68
68
  defineRiviniaI18n,
69
69
  injectRiviniaI18n,
70
70
  RiviniaI18n,
71
- RTranslatePipe,
71
+ RvTranslatePipe,
72
72
  jsonLoader,
73
73
  httpLoader,
74
74
  remoteLoader,
@@ -77,6 +77,31 @@ 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
+ | `RvTranslatePipe` (`rvTranslate`) | 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
+
80
105
  ## Quick start
81
106
 
82
107
  ```ts
@@ -106,15 +131,15 @@ export const appConfig: ApplicationConfig = {
106
131
  ```ts
107
132
  // src/app/header.ts
108
133
  import { Component } from '@angular/core';
109
- import { RTranslatePipe } from '@rivinia/i18n';
134
+ import { RvTranslatePipe } from '@rivinia/i18n';
110
135
  import { i18n } from './i18n.config';
111
136
 
112
137
  @Component({
113
138
  selector: 'app-header',
114
- imports: [RTranslatePipe],
139
+ imports: [RvTranslatePipe],
115
140
  template: `
116
141
  <h1>{{ title() }}</h1>
117
- <p>{{ 'booking.seats' | rTranslate: { count: seats } }}</p>
142
+ <p>{{ 'booking.seats' | rvTranslate: { count: seats } }}</p>
118
143
  <button type="button" (click)="use('en')">English</button>
119
144
  `,
120
145
  })
@@ -155,6 +180,9 @@ first content is available or initial loading has settled.
155
180
  | `onLoadError` | `(language, error) => void` | none | Dictionary load failure. Initialization never rejects because of it. |
156
181
  | `onMissingKey` | `(event) => void` | none | Unresolved key; suppresses the default warning. |
157
182
  | `warnOnMissingKey` | `boolean` | `isDevMode() && !onMissingKey` | `console.warn` once per key. |
183
+ | `onMissingParam` | `(event) => void` | none | Missing message argument; suppresses the default warning. |
184
+ | `warnOnMissingParam` | `boolean` | `isDevMode() && !onMissingParam` | `console.warn` once per (key, param). |
185
+ | `persist` | `boolean` | `true` | Persist the language after an explicit switch. First load writes nothing. |
158
186
  | `viewTransition` | `ViewTransitionConfig` | none | Document view transition on language change. |
159
187
 
160
188
  ## Dictionaries
@@ -175,8 +203,11 @@ remoteLoader({
175
203
  });
176
204
  ```
177
205
 
178
- Loader implementations are resolved lazily: `jsonLoader`, `httpLoader` and
179
- `remoteLoader` are separate chunks until first use. A loader can also be in-memory:
206
+ Loader implementations are resolved lazily: `httpLoader` and `remoteLoader` are
207
+ separate chunks until first use. The default `jsonLoader` is part of the main
208
+ bundle — it runs in the app initializer, where a lazy chunk would put two extra
209
+ script requests between the main bundle and the dictionary fetch. A loader can
210
+ also be in-memory:
180
211
 
181
212
  ```ts
182
213
  import { customLoader } from '@rivinia/i18n';
@@ -214,7 +245,6 @@ browser; `<base href>` resolved against the request on the server). `isServer` m
214
245
  | ----------------------- | ----------------------------------- | -------------------------------------------------------------- |
215
246
  | `currentLanguage` | `Signal<L>` | Active language id. |
216
247
  | `currentLanguageObject` | `Signal<Language<L>>` | The active language entry. |
217
- | `languageChanged` | `Signal<L>` | Alias of `currentLanguage` for effects. |
218
248
  | `languages` | `Signal<readonly Language<L>[]>` | Supported languages. |
219
249
  | `dir` / `isRtl` | `Signal<Direction>` / `Signal<boolean>` | Document direction. |
220
250
  | `locale` | `Signal<string>` | BCP-47 locale driving `Intl` and plural rules. |
@@ -234,16 +264,17 @@ browser; `<base href>` resolved against the request on the server). `isServer` m
234
264
  | `translate({ en: 'Hi', ar: 'أهلاً' })` | `string` | Inline map: current → fallback → first value. |
235
265
  | `t(key, params?)` | `Signal<string>` | Same chain as a `computed`; params may be a function of signals. |
236
266
  | `setLanguage(id)` / `setLanguageAsync(id)` | `void` / `Promise<void>` | Follows `switchStrategy`. |
237
- | `toggle()` / `next()` / `previous()` | `void` | Cycle through `languages`. |
238
- | `loadTranslations(id, { silent? })` | `Promise<Record<…>>` | Preload without switching. |
267
+ | `toggle()` / `next()` / `previous()` | `void` | `toggle()` flips the first two languages (dev warning with more); `next()`/`previous()` cycle. |
268
+ | `loadTranslations(id)` | `Promise<Record<…>>` | Preload without switching. |
239
269
  | `reload(language?)` | `Promise<boolean>` | Invalidate + refetch; never rejects. |
240
270
  | `formatNumber(value, options?)` | `string` | `Intl.NumberFormat` bound to `locale`. |
241
271
  | `formatDate(value, options?)` | `string` | `Intl.DateTimeFormat` bound to `locale`. |
242
272
  | `getLanguage(id)` | `Language<L> \| undefined` | Lookup. |
243
273
  | `initialize()` | `Promise<void>` | Called by the provider; idempotent. |
244
274
  | `clearMissingKeys()` | `void` | Reset the missing-key report. |
275
+ | `clearMissingParams()` | `void` | Reset the missing-parameter dedupe. |
245
276
 
246
- `RTranslatePipe` (`rTranslate`) delegates to `translate()`. It is impure by necessity —
277
+ `RvTranslatePipe` (`rvTranslate`) delegates to `translate()`. It is impure by necessity —
247
278
  the service reads signals on every call — so prefer `t()` or component code for long
248
279
  lists.
249
280
 
@@ -273,6 +304,14 @@ Supported subset (MF1): `{name}` interpolation, `{n, plural, …}` (with `offset
273
304
  - Unsupported or malformed constructs never throw: the raw `{…}` segment is returned
274
305
  as-is and parsing continues.
275
306
  - `{name}` interpolation is `String(value)`; use `{n, number}` when formatting matters.
307
+ - `''` renders one apostrophe. A single apostrophe immediately before `{` or `}` (and
308
+ `#` inside a plural) starts a quoted literal that ends at the next apostrophe:
309
+ `It''s '{'x'}'` → `It's {x}`. A lone apostrophe elsewhere (`Don't`) is unchanged.
310
+ - `date` accepts a `Date`, epoch milliseconds, or a strict ISO-8601 string
311
+ (`2026-10-28`, `2026-10-28T12:00:00Z`). Invalid input keeps the raw segment. Plain
312
+ `{d}` on a `Date` uses `String()` — use `{d, date, …}` for localized output.
313
+ - Templates are compiled once into a cached AST, so a message rendered on every
314
+ change-detection pass is not re-parsed.
276
315
 
277
316
  ## Missing keys
278
317
 
@@ -300,6 +339,22 @@ provideRiviniaI18n({
300
339
  Without `onMissingKey`, a `console.warn` is logged once per key in dev mode. Set
301
340
  `warnOnMissingKey: false` to silence it, or `true` to keep it in production.
302
341
 
342
+ ## Missing parameters
343
+
344
+ A message that needs `{name}` but receives no `name` keeps the placeholder — it is
345
+ never replaced with `undefined`. Report it the same way as missing keys:
346
+
347
+ ```ts
348
+ provideRiviniaI18n({
349
+ // …
350
+ onMissingParam: ({ key, param, language }) => report(param, { key, language }),
351
+ });
352
+ ```
353
+
354
+ Without `onMissingParam`, dev mode logs one warning per (key, param) pair. Set
355
+ `warnOnMissingParam: false` to silence it. The hook is delivered from a microtask,
356
+ so it may write signals, and `i18n.clearMissingParams()` resets the dedupe.
357
+
303
358
  ## Fallback language
304
359
 
305
360
  Lookup order for `translate(key)`:
@@ -362,6 +417,7 @@ npx rivinia-i18n-keys
362
417
  # → src/i18n-keys.d.ts
363
418
  npx rivinia-i18n-keys --source public/i18n/en.json --out src/i18n-keys.d.ts
364
419
  npx rivinia-i18n-keys --check # exit 1 when the file is stale (CI)
420
+ npx rivinia-i18n-keys --parity --dir public/i18n --base en
365
421
  ```
366
422
 
367
423
  ```ts
@@ -383,9 +439,16 @@ i18n.t('app.titel'); // TS error: not assignable to 'app.title' | …
383
439
  i18n.translate(`status.${code}` as RegisteredI18nKey); // dynamic key, explicit
384
440
  ```
385
441
 
386
- The CLI flattens nested objects to dot paths, keeps string leaves only, warns about
387
- non-string leaves, sorts keys for stable diffs, and escapes quotes. It has no
388
- dependencies and ships with the package (`rivinia-i18n-keys`).
442
+ The CLI flattens nested objects to dot paths, keeps literal dotted keys as-is, keeps
443
+ string leaves only, warns about non-string leaves and key collisions (the flat key
444
+ wins), sorts keys for stable diffs, and escapes quotes. It has no dependencies and
445
+ ships with the package (`rivinia-i18n-keys`).
446
+
447
+ `--parity` compares every `<language>.json` in `--dir` against `--base` and reports,
448
+ sorted: keys missing from a language, keys extra to it, and ICU placeholders used by
449
+ the base string but absent from the translation. Placeholders inside plural/select
450
+ branches are compared too; branch text itself is never read as a parameter. Any
451
+ mismatch exits 1, so CI fails on the common "added to `en.json`, forgot `ar.json`" bug.
389
452
 
390
453
  ## SSR
391
454
 
@@ -416,6 +479,26 @@ A complete, runnable host lives in `projects/i18n-e2e` (`node:http` +
416
479
  `renderApplication`, no Express), with `e2e/ssr-smoke.mjs` asserting the raw HTML, the
417
480
  server log, the transfer payload, the absence of a client refetch, and hydration.
418
481
 
482
+ ## Migration: 0.5.0 → 0.6.0
483
+
484
+ 0.6.0 is a breaking minor (the pre-1.0 policy allows it). The core split (RIV-18) is
485
+ internal — no signature changed — but three compatibility names are gone:
486
+
487
+ 1. **The pipe is `rvTranslate`.** `RTranslatePipe` (`rTranslate`) was removed; the
488
+ package prefix is `rv`, and there is no alias to keep:
489
+
490
+ ```html
491
+ <!-- before -->
492
+ {{ 'booking.seats' | rTranslate: { count: seats } }}
493
+ <!-- after -->
494
+ {{ 'booking.seats' | rvTranslate: { count: seats } }}
495
+ ```
496
+
497
+ 2. **`languageChanged` is gone.** It was the same signal as `currentLanguage`; switch
498
+ your reads to `currentLanguage`.
499
+ 3. **`loadTranslations(id, { silent })` is now `loadTranslations(id)`.** `silent` never
500
+ did anything — background loads are an internal concern.
501
+
419
502
  ## Migration: 0.3.3 → 0.4.0
420
503
 
421
504
  Everything below is additive; no export was removed and no import path changed. Two