@rivinia/i18n 0.1.1 → 0.3.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/README.md +56 -17
- package/fesm2022/{rivinia-i18n-json-loader.impl-CGzkWfF_.mjs → rivinia-i18n-json-loader.impl-VXwAmyWL.mjs} +2 -2
- package/fesm2022/rivinia-i18n-json-loader.impl-VXwAmyWL.mjs.map +1 -0
- package/fesm2022/rivinia-i18n.mjs +166 -32
- package/fesm2022/rivinia-i18n.mjs.map +1 -1
- package/package.json +1 -1
- package/schematics/ng-add/index.cjs +1 -0
- package/schematics/ng-add/schema.json +1 -1
- package/types/rivinia-i18n.d.ts +129 -15
- package/fesm2022/rivinia-i18n-json-loader.impl-CGzkWfF_.mjs.map +0 -1
package/README.md
CHANGED
|
@@ -7,7 +7,7 @@ Headless language manager for Angular 22+. Signals, RTL/LTR, lazy loaders,
|
|
|
7
7
|
ICU plurals (all six Arabic forms), browser detection, Intl formatting —
|
|
8
8
|
zero DOM opinions beyond `<html dir/lang>`, zero styling.
|
|
9
9
|
|
|
10
|
-
- Version: **0.
|
|
10
|
+
- Version: **0.3.0**
|
|
11
11
|
- Requires: **Angular `^22.0.0`**, `tslib`
|
|
12
12
|
|
|
13
13
|
## Install
|
|
@@ -20,11 +20,13 @@ ng add @rivinia/i18n # asks default language + browser detection, wires an ar/
|
|
|
20
20
|
## Dictionaries by convention (no config needed)
|
|
21
21
|
|
|
22
22
|
Key-based `translate('booking.seats')` works out of the box with the conventional
|
|
23
|
-
layout — the default loader fetches `
|
|
24
|
-
(`
|
|
23
|
+
layout — the default loader fetches `i18n/{language}.json`
|
|
24
|
+
(`public/i18n/ar.json`, `public/i18n/en.json`, … served from the site root;
|
|
25
|
+
modern Angular templates map `public/` via `{ "glob": "**/*", "input": "public" }`).
|
|
26
|
+
Override only when you differ:
|
|
25
27
|
|
|
26
28
|
```json
|
|
27
|
-
//
|
|
29
|
+
// public/i18n/ar.json
|
|
28
30
|
{ "booking": { "seats": "{count, plural, zero {لا مقاعد} one {مقعد واحد} other {# مقاعد}}" } }
|
|
29
31
|
```
|
|
30
32
|
|
|
@@ -37,6 +39,39 @@ provideRiviniaI18n({ loader: httpLoader({ endpoint: 'https://api.example.com/i18
|
|
|
37
39
|
|
|
38
40
|
Loaders code-split: fetch implementations load on first use only.
|
|
39
41
|
|
|
42
|
+
> **Migration (0.3.0 — breaking default):** the default
|
|
43
|
+
> loader path changed from `assets/i18n` to `i18n`. Move
|
|
44
|
+
> `src/assets/i18n/*.json` → `public/i18n/*.json` (served from the site root),
|
|
45
|
+
> or keep the old layout explicitly with
|
|
46
|
+
> `jsonLoader({ path: 'assets/i18n' })`.
|
|
47
|
+
|
|
48
|
+
## Startup loading (no raw keys on first paint)
|
|
49
|
+
|
|
50
|
+
`provideRiviniaI18n()` registers an app initializer that loads the initial
|
|
51
|
+
language before first paint (SSR waits via `PendingTasks`):
|
|
52
|
+
|
|
53
|
+
```ts
|
|
54
|
+
provideRiviniaI18n({
|
|
55
|
+
// ...
|
|
56
|
+
preload: false, // opt out: load manually instead
|
|
57
|
+
translations: { ar: { hello: 'مرحبا' } }, // inline seed: instant, zero network,
|
|
58
|
+
}); // a successful loader response still wins
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
Gate skeletons on the `ready` signal (true once initial content is available),
|
|
62
|
+
not on `isLoading`. Load failures never reject setup — they land on
|
|
63
|
+
`loadingError`/`onLoadError` with safe fallbacks preserved.
|
|
64
|
+
|
|
65
|
+
## Persistence and SSR
|
|
66
|
+
|
|
67
|
+
- `storageStrategy: 'cookie'` syncs SSR and browser through one cookie:
|
|
68
|
+
the server reads the request cookie (correct first paint, no hydration
|
|
69
|
+
mismatch), the browser writes it. `local`/`session` fall back to the
|
|
70
|
+
default language on the server.
|
|
71
|
+
- Dictionaries loaded on the server travel to the browser via `TransferState`
|
|
72
|
+
(no double fetch). The `<html dir/lang>` effect uses injected `DOCUMENT`,
|
|
73
|
+
so it renders on the server too.
|
|
74
|
+
|
|
40
75
|
```ts
|
|
41
76
|
// app.config.ts
|
|
42
77
|
import { provideRiviniaI18n } from '@rivinia/i18n';
|
|
@@ -63,7 +98,7 @@ export class Header {
|
|
|
63
98
|
```
|
|
64
99
|
|
|
65
100
|
```json
|
|
66
|
-
//
|
|
101
|
+
// public/i18n/en.json
|
|
67
102
|
{ "booking": { "seats": "{count, plural, one {# seat} other {# seats}}" } }
|
|
68
103
|
```
|
|
69
104
|
|
|
@@ -74,18 +109,22 @@ export class Header {
|
|
|
74
109
|
|
|
75
110
|
## API
|
|
76
111
|
|
|
77
|
-
| Export
|
|
78
|
-
|
|
79
|
-
| `provideRiviniaI18n(config)`
|
|
80
|
-
| `RiviniaI18n`
|
|
81
|
-
| `injectRiviniaI18n()`
|
|
82
|
-
| `jsonLoader/httpLoader/remoteLoader/customLoader` | loaders
|
|
83
|
-
| `formatIcu(template, params, locale)`
|
|
84
|
-
| `detectBrowserLanguage(ids, langs)`
|
|
85
|
-
| `
|
|
86
|
-
|
|
|
87
|
-
|
|
88
|
-
|
|
112
|
+
| Export | Kind | Purpose |
|
|
113
|
+
| ------------------------------------------------- | ------------ | ------------------------------------------------------------------------------------------------------------------------------------- |
|
|
114
|
+
| `provideRiviniaI18n(config)` | provider | languages, default, storage (+`cookie`), loader, `detectBrowser?` (off), `switchStrategy?`, `preload?`, `translations?` (inline seed) |
|
|
115
|
+
| `RiviniaI18n` | `@Service()` | signals (`locale`, `ready`) + `translate/setLanguage(toggle/next/previous)/loadTranslations/formatNumber/formatDate` |
|
|
116
|
+
| `injectRiviniaI18n()` | function | shorthand, preserves the language union; `defineRiviniaI18n(config)` binds config + accessors with inference |
|
|
117
|
+
| `jsonLoader/httpLoader/remoteLoader/customLoader` | loaders | lazy code-split dictionaries (fetch, no HttpClient) |
|
|
118
|
+
| `formatIcu(template, params, locale)` | util | ICU subset: plural/select/`#`/nesting via native `Intl.PluralRules` |
|
|
119
|
+
| `detectBrowserLanguage(ids, langs)` | util | in-order priority + base-tag fallback (`ar-EG` → `ar`), pure/testable |
|
|
120
|
+
| `parseCookie/serializeCookie` | utils | cookie strategy primitives (server header / browser cookie) |
|
|
121
|
+
| `RTranslatePipe` | pipe | `rTranslate` (impure by necessity — prefer `translate()` in code for lists) |
|
|
122
|
+
| types | types | `RiviniaI18nConfig`, `Language` (+`locale?`), `Translation`, `LoaderDescriptor`, … |
|
|
123
|
+
|
|
124
|
+
Dictionaries commit to visible signals only for the currently intended
|
|
125
|
+
language — out-of-order responses stay cached. `setLanguageAsync` aborts on
|
|
126
|
+
load failure (language, direction and dictionary untouched). ICU subset is
|
|
127
|
+
deliberately small (`plural`/`select` only) — full ICU belongs to
|
|
89
128
|
FormatJS, not to a 10 kB core. Malformed templates render raw, never throw.
|
|
90
129
|
Stored preference always beats browser detection; detection runs only when
|
|
91
130
|
nothing is stored. `switchStrategy: 'preload-first'` (or `setLanguageAsync`)
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const DEFAULT_BASE_PATH = "
|
|
1
|
+
const DEFAULT_BASE_PATH = "i18n";
|
|
2
2
|
var JsonLoader = class {
|
|
3
3
|
_options;
|
|
4
4
|
constructor(_options) {
|
|
@@ -13,4 +13,4 @@ var JsonLoader = class {
|
|
|
13
13
|
};
|
|
14
14
|
export { JsonLoader };
|
|
15
15
|
|
|
16
|
-
//# sourceMappingURL=rivinia-i18n-json-loader.impl-
|
|
16
|
+
//# sourceMappingURL=rivinia-i18n-json-loader.impl-VXwAmyWL.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"rivinia-i18n-json-loader.impl-VXwAmyWL.mjs","names":[],"sources":["../../../projects/i18n/src/lib/json-loader.impl.ts"],"sourcesContent":["import type { TranslationLoader } from './loaders';\n\nconst DEFAULT_BASE_PATH = 'i18n';\n\nexport class JsonLoader<L extends string = string> implements TranslationLoader<L> {\n constructor(private readonly _options?: { path?: string }) {}\n\n async load(language: L): Promise<Record<string, unknown>> {\n const basePath = this._options?.path ?? DEFAULT_BASE_PATH;\n const url = `${basePath}/${language}.json`;\n const response = await fetch(url);\n if (!response.ok) {\n throw new Error(`[rivinia/i18n] Failed to load \"${url}\": ${response.statusText}`);\n }\n return response.json();\n }\n}\n"],"mappings":"AAEA,MAAM,oBAAoB;AAE1B,IAAa,aAAb,MAAuB;CACQ;CAA7B,YAA6B,UAA4B;EAA5B,KAAA,WAAA;CAA+B;CAE5D,MAAM,KAAK,UAAW;EAEpB,MAAM,MAAM,GADK,KAAK,UAAU,QAAQ,kBACjB,GAAI,SAAQ;EACnC,MAAM,WAAW,MAAM,MAAM,GAAG;EAChC,IAAI,CAAC,SAAS,IACZ,MAAM,IAAI,MAAM,kCAAkC,IAAG,KAAM,SAAS,YAAY;EAElF,OAAO,SAAS,KAAI;CACtB;AACD"}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import * as i0 from "@angular/core";
|
|
2
|
-
import { InjectionToken, Pipe, Service, computed, effect, inject, makeEnvironmentProviders, signal } from "@angular/core";
|
|
2
|
+
import { DOCUMENT, InjectionToken, PendingTasks, Pipe, REQUEST, Service, TransferState, computed, effect, inject, makeEnvironmentProviders, makeStateKey, provideAppInitializer, signal } from "@angular/core";
|
|
3
3
|
function jsonLoader(options) {
|
|
4
4
|
return { async resolve() {
|
|
5
|
-
const { JsonLoader } = await import("./rivinia-i18n-json-loader.impl-
|
|
5
|
+
const { JsonLoader } = await import("./rivinia-i18n-json-loader.impl-VXwAmyWL.mjs");
|
|
6
6
|
return new JsonLoader(options);
|
|
7
7
|
} };
|
|
8
8
|
}
|
|
@@ -24,7 +24,7 @@ function customLoader(load) {
|
|
|
24
24
|
} };
|
|
25
25
|
}
|
|
26
26
|
function getStorage(strategy) {
|
|
27
|
-
if (strategy === "none") return null;
|
|
27
|
+
if (strategy === "none" || strategy === "cookie") return null;
|
|
28
28
|
if (typeof window === "undefined") return null;
|
|
29
29
|
try {
|
|
30
30
|
return strategy === "session" ? window.sessionStorage : window.localStorage;
|
|
@@ -56,12 +56,11 @@ function detectBrowserLanguage(supportedIds, browserLanguages) {
|
|
|
56
56
|
if (!tag) continue;
|
|
57
57
|
const exact = supported.indexOf(tag);
|
|
58
58
|
if (exact !== -1) return supportedIds[exact];
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
if (hit !== -1) return supportedIds[hit];
|
|
59
|
+
const base = tag.split(/[-_]/)[0];
|
|
60
|
+
if (base && base !== tag) {
|
|
61
|
+
const hit = supported.indexOf(base);
|
|
62
|
+
if (hit !== -1) return supportedIds[hit];
|
|
63
|
+
}
|
|
65
64
|
}
|
|
66
65
|
return null;
|
|
67
66
|
}
|
|
@@ -74,6 +73,33 @@ function browserLanguages() {
|
|
|
74
73
|
return;
|
|
75
74
|
}
|
|
76
75
|
}
|
|
76
|
+
function parseCookie(header, name) {
|
|
77
|
+
if (!header) return null;
|
|
78
|
+
const prefix = `${name}=`;
|
|
79
|
+
for (const part of header.split(";")) {
|
|
80
|
+
const trimmed = part.trim();
|
|
81
|
+
if (trimmed.startsWith(prefix)) try {
|
|
82
|
+
return decodeURIComponent(trimmed.slice(prefix.length));
|
|
83
|
+
} catch {
|
|
84
|
+
return trimmed.slice(prefix.length);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
return null;
|
|
88
|
+
}
|
|
89
|
+
function serializeCookie(name, value, options) {
|
|
90
|
+
const base = `${name}=${encodeURIComponent(value)}; Path=/; Max-Age=31536000; SameSite=Lax`;
|
|
91
|
+
return options?.secure ? `${base}; Secure` : base;
|
|
92
|
+
}
|
|
93
|
+
function shouldSecureCookie(location) {
|
|
94
|
+
try {
|
|
95
|
+
if (!location) return false;
|
|
96
|
+
if (location.protocol !== "https:") return false;
|
|
97
|
+
if (location.hostname === "localhost") return false;
|
|
98
|
+
return true;
|
|
99
|
+
} catch {
|
|
100
|
+
return false;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
77
103
|
function formatIcu(template, params, locale) {
|
|
78
104
|
return parseMessage(template, 0, template.length, params, locale, null).text;
|
|
79
105
|
}
|
|
@@ -262,9 +288,10 @@ function readSelector(src, i, end) {
|
|
|
262
288
|
}
|
|
263
289
|
const RIVINIA_I18N_CONFIG = new InjectionToken("RIVINIA_I18N_CONFIG");
|
|
264
290
|
var ViewTransitionService = class ViewTransitionService {
|
|
265
|
-
|
|
291
|
+
_doc = inject(DOCUMENT);
|
|
266
292
|
run(callback) {
|
|
267
|
-
|
|
293
|
+
const doc = this._doc;
|
|
294
|
+
if (typeof doc.startViewTransition === "function") doc.startViewTransition(callback);
|
|
268
295
|
else callback();
|
|
269
296
|
}
|
|
270
297
|
static ɵfac = i0.ɵɵngDeclareFactory({
|
|
@@ -295,6 +322,9 @@ var RiviniaI18n = class RiviniaI18n {
|
|
|
295
322
|
_storageKey = this._config.storageKey ?? "rivinia.i18n.language";
|
|
296
323
|
_storageStrategy = this._config.storageStrategy ?? "local";
|
|
297
324
|
_autoApplyDirection = this._config.autoApplyDirection ?? true;
|
|
325
|
+
_doc = inject(DOCUMENT);
|
|
326
|
+
_request = inject(REQUEST, { optional: true });
|
|
327
|
+
_transfer = inject(TransferState, { optional: true });
|
|
298
328
|
_currentLanguageId = signal(this._resolveInitialLanguage(), ...ngDevMode ? [{ debugName: "_currentLanguageId" }] : /* istanbul ignore next */ []);
|
|
299
329
|
_languages = signal(this._config.languages, ...ngDevMode ? [{ debugName: "_languages" }] : /* istanbul ignore next */ []);
|
|
300
330
|
_loadedTranslations = signal({}, ...ngDevMode ? [{ debugName: "_loadedTranslations" }] : /* istanbul ignore next */ []);
|
|
@@ -302,8 +332,9 @@ var RiviniaI18n = class RiviniaI18n {
|
|
|
302
332
|
_resolvedLoader = null;
|
|
303
333
|
_translationsCache = /* @__PURE__ */ new Map();
|
|
304
334
|
_inflight = /* @__PURE__ */ new Map();
|
|
305
|
-
_requestToken = 0;
|
|
306
335
|
_applyCount = 0;
|
|
336
|
+
_initialized = false;
|
|
337
|
+
_tasks = inject(PendingTasks, { optional: true });
|
|
307
338
|
languageChanged = computed(() => this._currentLanguageId(), ...ngDevMode ? [{ debugName: "languageChanged" }] : /* istanbul ignore next */ []);
|
|
308
339
|
languages = this._languages.asReadonly();
|
|
309
340
|
currentLanguage = this._currentLanguageId.asReadonly();
|
|
@@ -318,23 +349,46 @@ var RiviniaI18n = class RiviniaI18n {
|
|
|
318
349
|
loadingState = this._loadingState.asReadonly();
|
|
319
350
|
loadingError = this._loadingError.asReadonly();
|
|
320
351
|
isLoading = computed(() => this._loadingState() === "loading", ...ngDevMode ? [{ debugName: "isLoading" }] : /* istanbul ignore next */ []);
|
|
352
|
+
_ready = signal(false, ...ngDevMode ? [{ debugName: "_ready" }] : /* istanbul ignore next */ []);
|
|
353
|
+
ready = this._ready.asReadonly();
|
|
321
354
|
constructor() {
|
|
322
355
|
if (this._config.languages.length === 0) throw new Error("[rivinia/i18n] At least one language must be provided in the languages array.");
|
|
323
356
|
if (!this._config.languages.some((l) => l.id === this._config.defaultLanguage)) throw new Error(`[rivinia/i18n] defaultLanguage "${this._config.defaultLanguage}" must be one of the configured language IDs.`);
|
|
324
357
|
effect(() => {
|
|
325
358
|
const id = this._currentLanguageId();
|
|
326
|
-
|
|
359
|
+
this._writeStored(id);
|
|
327
360
|
});
|
|
328
361
|
if (this._autoApplyDirection) effect(() => {
|
|
329
|
-
if (typeof document === "undefined") return;
|
|
330
362
|
const lang = this.currentLanguageObject();
|
|
331
|
-
|
|
332
|
-
|
|
363
|
+
const root = this._doc.documentElement;
|
|
364
|
+
if (!root) return;
|
|
365
|
+
root.dir = lang.dir;
|
|
366
|
+
root.lang = lang.id;
|
|
333
367
|
});
|
|
334
368
|
}
|
|
335
369
|
getLanguage(id) {
|
|
336
370
|
return this._languages().find((l) => l.id === id);
|
|
337
371
|
}
|
|
372
|
+
async initialize() {
|
|
373
|
+
if (this._initialized) return;
|
|
374
|
+
this._initialized = true;
|
|
375
|
+
const done = this._tasks?.add();
|
|
376
|
+
try {
|
|
377
|
+
const current = this._currentLanguageId();
|
|
378
|
+
const transferred = this.readTransfer(current);
|
|
379
|
+
if (transferred) {
|
|
380
|
+
this._translationsCache.set(current, transferred);
|
|
381
|
+
this._loadedTranslations.set(transferred);
|
|
382
|
+
} else {
|
|
383
|
+
const inline = this._config.translations?.[current];
|
|
384
|
+
if (inline) this._loadedTranslations.set(inline);
|
|
385
|
+
if (this._config.preload ?? true) await this._loadTranslations(current);
|
|
386
|
+
}
|
|
387
|
+
} finally {
|
|
388
|
+
this._ready.set(true);
|
|
389
|
+
done?.();
|
|
390
|
+
}
|
|
391
|
+
}
|
|
338
392
|
translate(keyOrTranslations, defaultValueOrParams, maybeParams) {
|
|
339
393
|
if (typeof keyOrTranslations === "string") {
|
|
340
394
|
const { defaultValue, params } = normalizeKeyArgs(defaultValueOrParams, maybeParams);
|
|
@@ -348,7 +402,7 @@ var RiviniaI18n = class RiviniaI18n {
|
|
|
348
402
|
}
|
|
349
403
|
loadedTranslations = this._loadedTranslations.asReadonly();
|
|
350
404
|
async loadTranslations(languageId, opts) {
|
|
351
|
-
return this._loadTranslations(languageId, opts);
|
|
405
|
+
return (await this._loadTranslations(languageId, opts)).data;
|
|
352
406
|
}
|
|
353
407
|
toggle() {
|
|
354
408
|
const langs = this._languages();
|
|
@@ -378,14 +432,37 @@ var RiviniaI18n = class RiviniaI18n {
|
|
|
378
432
|
async setLanguageAsync(id) {
|
|
379
433
|
if (id === this._currentLanguageId()) return;
|
|
380
434
|
if (!this._languages().some((l) => l.id === id)) return;
|
|
381
|
-
await this._loadTranslations(id, { silent: true });
|
|
435
|
+
const { ok } = await this._loadTranslations(id, { silent: true });
|
|
436
|
+
if (!ok) return;
|
|
382
437
|
this.applyLanguage(id);
|
|
383
438
|
}
|
|
384
439
|
formatNumber(value, options) {
|
|
385
|
-
return
|
|
440
|
+
return this.numberFormatter(options).format(value);
|
|
386
441
|
}
|
|
387
442
|
formatDate(value, options) {
|
|
388
|
-
return
|
|
443
|
+
return this.dateTimeFormatter(options).format(value);
|
|
444
|
+
}
|
|
445
|
+
locale = computed(() => {
|
|
446
|
+
return this.currentLanguageObject().locale ?? this._currentLanguageId();
|
|
447
|
+
}, ...ngDevMode ? [{ debugName: "locale" }] : /* istanbul ignore next */ []);
|
|
448
|
+
_formatters = /* @__PURE__ */ new Map();
|
|
449
|
+
numberFormatter(options) {
|
|
450
|
+
const key = `n|${this.locale()}|${JSON.stringify(options ?? null)}`;
|
|
451
|
+
let formatter = this._formatters.get(key);
|
|
452
|
+
if (!formatter) {
|
|
453
|
+
formatter = new Intl.NumberFormat(this.locale(), options);
|
|
454
|
+
this._formatters.set(key, formatter);
|
|
455
|
+
}
|
|
456
|
+
return formatter;
|
|
457
|
+
}
|
|
458
|
+
dateTimeFormatter(options) {
|
|
459
|
+
const key = `d|${this.locale()}|${JSON.stringify(options ?? null)}`;
|
|
460
|
+
let formatter = this._formatters.get(key);
|
|
461
|
+
if (!formatter) {
|
|
462
|
+
formatter = new Intl.DateTimeFormat(this.locale(), options);
|
|
463
|
+
this._formatters.set(key, formatter);
|
|
464
|
+
}
|
|
465
|
+
return formatter;
|
|
389
466
|
}
|
|
390
467
|
applyLanguage(id, opts) {
|
|
391
468
|
if (id === this._currentLanguageId()) return;
|
|
@@ -407,39 +484,49 @@ var RiviniaI18n = class RiviniaI18n {
|
|
|
407
484
|
if (!params) return template;
|
|
408
485
|
if (!template.includes("{")) return template;
|
|
409
486
|
try {
|
|
410
|
-
return formatIcu(template, params, this.
|
|
487
|
+
return formatIcu(template, params, this.locale());
|
|
411
488
|
} catch {
|
|
412
489
|
return template;
|
|
413
490
|
}
|
|
414
491
|
}
|
|
415
492
|
async _loadTranslations(languageId, opts) {
|
|
493
|
+
const current = () => languageId === this._currentLanguageId();
|
|
416
494
|
const cached = this._translationsCache.get(languageId);
|
|
417
495
|
if (cached) {
|
|
418
|
-
if (!opts?.silent) this._loadedTranslations.set(cached);
|
|
419
|
-
return
|
|
496
|
+
if (!opts?.silent && current()) this._loadedTranslations.set(cached);
|
|
497
|
+
return {
|
|
498
|
+
data: cached,
|
|
499
|
+
ok: true
|
|
500
|
+
};
|
|
420
501
|
}
|
|
421
502
|
const inflight = this._inflight.get(languageId);
|
|
422
503
|
if (inflight) return inflight;
|
|
423
|
-
const myToken = ++this._requestToken;
|
|
424
504
|
this._loadingState.set("loading");
|
|
425
505
|
const task = (async () => {
|
|
426
506
|
try {
|
|
427
507
|
if (!this._resolvedLoader) this._resolvedLoader = await this._getLoader();
|
|
428
508
|
const translations = await this._resolvedLoader.load(languageId);
|
|
429
509
|
this._translationsCache.set(languageId, translations);
|
|
430
|
-
|
|
510
|
+
this.writeTransfer(languageId, translations);
|
|
511
|
+
if (!opts?.silent && current()) {
|
|
431
512
|
this._loadedTranslations.set(translations);
|
|
432
513
|
this._loadingError.set(null);
|
|
433
514
|
this._loadingState.set("idle");
|
|
434
515
|
}
|
|
435
|
-
return
|
|
516
|
+
return {
|
|
517
|
+
data: translations,
|
|
518
|
+
ok: true
|
|
519
|
+
};
|
|
436
520
|
} catch (error) {
|
|
437
|
-
if (
|
|
521
|
+
if (current()) {
|
|
438
522
|
this._loadingError.set(error);
|
|
439
523
|
this._loadingState.set("error");
|
|
440
524
|
}
|
|
441
525
|
this._config.onLoadError?.(languageId, error);
|
|
442
|
-
return {
|
|
526
|
+
return {
|
|
527
|
+
data: {},
|
|
528
|
+
ok: false
|
|
529
|
+
};
|
|
443
530
|
} finally {
|
|
444
531
|
this._inflight.delete(languageId);
|
|
445
532
|
if (this._inflight.size === 0 && this._loadingState() === "loading") this._loadingState.set("idle");
|
|
@@ -448,13 +535,52 @@ var RiviniaI18n = class RiviniaI18n {
|
|
|
448
535
|
this._inflight.set(languageId, task);
|
|
449
536
|
return task;
|
|
450
537
|
}
|
|
538
|
+
_readStored() {
|
|
539
|
+
if (this._storageStrategy === "cookie") {
|
|
540
|
+
const header = this._request?.headers.get("cookie") ?? null;
|
|
541
|
+
if (header !== null) return parseCookie(header, this._storageKey);
|
|
542
|
+
try {
|
|
543
|
+
return parseCookie(this._doc.cookie, this._storageKey);
|
|
544
|
+
} catch {
|
|
545
|
+
return null;
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
return safeGetItem(this._storageKey, this._storageStrategy);
|
|
549
|
+
}
|
|
550
|
+
_writeStored(id) {
|
|
551
|
+
if (this._storageStrategy === "cookie") {
|
|
552
|
+
if (this._request) return;
|
|
553
|
+
try {
|
|
554
|
+
const location = this._doc?.location;
|
|
555
|
+
this._doc.cookie = serializeCookie(this._storageKey, id, { secure: shouldSecureCookie(location) });
|
|
556
|
+
} catch {}
|
|
557
|
+
return;
|
|
558
|
+
}
|
|
559
|
+
safeSetItem(this._storageKey, id, this._storageStrategy);
|
|
560
|
+
}
|
|
561
|
+
transferKey(languageId) {
|
|
562
|
+
return makeStateKey(`rivinia.i18n.dict.${languageId}`);
|
|
563
|
+
}
|
|
564
|
+
readTransfer(languageId) {
|
|
565
|
+
const transfer = this._transfer;
|
|
566
|
+
if (!transfer) return null;
|
|
567
|
+
const key = this.transferKey(languageId);
|
|
568
|
+
if (!transfer.hasKey(key)) return null;
|
|
569
|
+
const dict = transfer.get(key, null);
|
|
570
|
+
transfer.remove(key);
|
|
571
|
+
return dict;
|
|
572
|
+
}
|
|
573
|
+
writeTransfer(languageId, dict) {
|
|
574
|
+
if (!this._request) return;
|
|
575
|
+
this._transfer?.set(this.transferKey(languageId), dict);
|
|
576
|
+
}
|
|
451
577
|
_resolveKey(obj, path) {
|
|
452
578
|
const value = path.split(".").reduce((acc, segment) => acc && typeof acc === "object" ? acc[segment] : void 0, obj);
|
|
453
579
|
if (typeof value === "string") return value;
|
|
454
580
|
if (typeof value === "number" || typeof value === "boolean") return String(value);
|
|
455
581
|
}
|
|
456
582
|
_resolveInitialLanguage() {
|
|
457
|
-
const stored =
|
|
583
|
+
const stored = this._readStored();
|
|
458
584
|
if (stored && this._config.languages.some((l) => l.id === stored)) return stored;
|
|
459
585
|
if (this._config.detectBrowser) {
|
|
460
586
|
const detected = detectBrowserLanguage(this._config.languages.map((l) => l.id), browserLanguages());
|
|
@@ -496,11 +622,20 @@ function provideRiviniaI18n(config) {
|
|
|
496
622
|
return makeEnvironmentProviders([{
|
|
497
623
|
provide: RIVINIA_I18N_CONFIG,
|
|
498
624
|
useValue: config
|
|
499
|
-
}
|
|
625
|
+
}, provideAppInitializer(() => {
|
|
626
|
+
return inject(RiviniaI18n).initialize();
|
|
627
|
+
})]);
|
|
500
628
|
}
|
|
501
629
|
function injectRiviniaI18n() {
|
|
502
630
|
return inject(RiviniaI18n);
|
|
503
631
|
}
|
|
632
|
+
function defineRiviniaI18n(config) {
|
|
633
|
+
return {
|
|
634
|
+
config,
|
|
635
|
+
provide: () => provideRiviniaI18n(config),
|
|
636
|
+
inject: () => injectRiviniaI18n()
|
|
637
|
+
};
|
|
638
|
+
}
|
|
504
639
|
var RTranslatePipe = class RTranslatePipe {
|
|
505
640
|
_i18n = inject(RiviniaI18n);
|
|
506
641
|
transform(keyOrTranslations, defaultValueOrParams, maybeParams) {
|
|
@@ -533,11 +668,10 @@ i0.ɵɵngDeclareClassMetadata({
|
|
|
533
668
|
type: Pipe,
|
|
534
669
|
args: [{
|
|
535
670
|
name: "rTranslate",
|
|
536
|
-
standalone: true,
|
|
537
671
|
pure: false
|
|
538
672
|
}]
|
|
539
673
|
}]
|
|
540
674
|
});
|
|
541
|
-
export { RTranslatePipe, RiviniaI18n, ViewTransitionService, browserLanguages, customLoader, detectBrowserLanguage, formatIcu, httpLoader, injectRiviniaI18n, jsonLoader, provideRiviniaI18n, remoteLoader };
|
|
675
|
+
export { RTranslatePipe, RiviniaI18n, ViewTransitionService, browserLanguages, customLoader, defineRiviniaI18n, detectBrowserLanguage, formatIcu, httpLoader, injectRiviniaI18n, jsonLoader, parseCookie, provideRiviniaI18n, remoteLoader, serializeCookie };
|
|
542
676
|
|
|
543
677
|
//# sourceMappingURL=rivinia-i18n.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rivinia-i18n.mjs","names":[],"sources":["../../../projects/i18n/src/lib/loaders.ts","../../../projects/i18n/src/lib/i18n-utils.ts","../../../projects/i18n/src/lib/icu.ts","../../../projects/i18n/src/lib/i18n-config.ts","../../../projects/i18n/src/lib/view-transition.service.ts","../../../projects/i18n/src/lib/rivinia-i18n.ts","../../../projects/i18n/src/lib/provide-i18n.ts","../../../projects/i18n/src/lib/translate.pipe.ts"],"sourcesContent":["/**\n * Pluggable key-dictionary loader. Returns a flat/nested JSON-compatible map\n * merged into `loadedTranslations` and read by key-based `translate(key)`.\n */\nexport interface TranslationLoader<L extends string = string> {\n load(language: L): Promise<Record<string, unknown>>;\n}\n\n/**\n * Lazy descriptor: `resolve()` dynamic-imports the real implementation, so\n * loader code splits out of the main bundle until first use. Resolved once\n * and cached by the service.\n */\nexport interface LoaderDescriptor<L extends string = string> {\n resolve(): Promise<TranslationLoader<L>>;\n}\n\nexport function jsonLoader(options?: { path?: string }): LoaderDescriptor<string> {\n return {\n async resolve() {\n const { JsonLoader } = await import('./json-loader.impl');\n return new JsonLoader(options);\n },\n };\n}\n\nexport interface HttpLoaderOptions {\n readonly endpoint: string;\n readonly method?: string;\n readonly buildUrl?: (language: string) => string;\n}\n\nexport function httpLoader(options: HttpLoaderOptions): LoaderDescriptor<string> {\n return {\n async resolve() {\n const { HttpLoader } = await import('./http-loader.impl');\n return new HttpLoader(options);\n },\n };\n}\n\nexport interface RemoteLoaderOptions {\n readonly url: (language: string) => string;\n readonly headers?: Record<string, string>;\n}\n\nexport function remoteLoader(options: RemoteLoaderOptions): LoaderDescriptor<string> {\n return {\n async resolve() {\n const { RemoteLoader } = await import('./remote-loader.impl');\n return new RemoteLoader(options);\n },\n };\n}\n\n/** Wraps any function as a loader (mocks, in-memory, third-party SDKs). */\nexport function customLoader<L extends string = string>(\n load: (language: L) => Promise<Record<string, unknown>>,\n): LoaderDescriptor<L> {\n return {\n async resolve() {\n return { load };\n },\n };\n}\n","import type { StorageStrategy } from './i18n-types';\n\nfunction getStorage(strategy: StorageStrategy): Storage | null {\n if (strategy === 'none') return null;\n if (typeof window === 'undefined') return null;\n try {\n return strategy === 'session' ? window.sessionStorage : window.localStorage;\n } catch {\n return null;\n }\n}\n\n/** SSR-safe read. Returns `null` off-browser, on denial, or when missing. */\nexport function safeGetItem(key: string, strategy: StorageStrategy): string | null {\n const storage = getStorage(strategy);\n if (!storage) return null;\n try {\n return storage.getItem(key);\n } catch {\n return null;\n }\n}\n\n/** SSR-safe write. Silently no-ops off-browser or on denial. */\nexport function safeSetItem(key: string, value: string, strategy: StorageStrategy): void {\n const storage = getStorage(strategy);\n if (!storage) return;\n try {\n storage.setItem(key, value);\n } catch {\n // Intentionally silent: persistence is best-effort.\n }\n}\n\n/**\n * Matches the browser language priority list against supported ids.\n * Exact (case-insensitive) matches win first; otherwise base tags match\n * (`ar-EG` → `ar`). Returns `null` when nothing matches or off-browser.\n * Pure and exported for testing — pass `navigator.languages` in app code.\n */\nexport function detectBrowserLanguage<T extends string>(\n supportedIds: readonly T[],\n browserLanguages: readonly string[] | undefined,\n): T | null {\n if (!browserLanguages || browserLanguages.length === 0) return null;\n const supported = supportedIds.map((id) => id.toLowerCase());\n for (const raw of browserLanguages) {\n const tag = raw.trim().toLowerCase();\n if (!tag) continue;\n const exact = supported.indexOf(tag);\n if (exact !== -1) return supportedIds[exact];\n }\n for (const raw of browserLanguages) {\n const base = raw.trim().toLowerCase().split(/[-_]/)[0];\n if (!base) continue;\n const hit = supported.indexOf(base);\n if (hit !== -1) return supportedIds[hit];\n }\n return null;\n}\n\n/** Browser language list, `undefined` off-browser (SSR-safe input for detection). */\nexport function browserLanguages(): readonly string[] | undefined {\n if (typeof window === 'undefined' || typeof navigator === 'undefined') return undefined;\n try {\n if (Array.isArray(navigator.languages) && navigator.languages.length > 0) {\n return [...navigator.languages];\n }\n return typeof navigator.language === 'string' ? [navigator.language] : undefined;\n } catch {\n return undefined;\n }\n}\n","import type { TranslateParams } from './i18n-types';\n\n/**\n * Minimal ICU MessageFormat subset: `{name}` interpolation, `{n, plural, …}`,\n * `{x, select, …}`, `#` inside plurals, and nesting. Categories resolve via\n * the native `Intl.PluralRules(locale)` — Arabic gets all six forms\n * (zero/one/two/few/many/other) with zero extra dependencies.\n *\n * Supported (and ONLY these — documented subset, translators beware):\n * - `{count, plural, =0 {none} one {# item} other {# items}}`\n * - `{gender, select, male {He} female {She} other {They}}`\n * - `{name}` plain interpolation (missing params keep the placeholder)\n *\n * Malformed input never throws: the raw segment is returned as-is.\n */\nexport function formatIcu(\n template: string,\n params: TranslateParams,\n locale: string,\n): string {\n return parseMessage(template, 0, template.length, params, locale, null).text;\n}\n\ninterface Parsed {\n text: string;\n /** Index of the closing `}` (or `end` when the level ran out). */\n next: number;\n ok: boolean;\n}\n\nfunction parseMessage(\n src: string,\n start: number,\n end: number,\n params: TranslateParams,\n locale: string,\n pluralValue: number | null,\n): Parsed {\n let out = '';\n let i = start;\n while (i < end) {\n const ch = src[i];\n if (ch === '{') {\n const arg = parseArgument(src, i, end, params, locale, pluralValue);\n if (!arg.ok) return { text: out + src.slice(i, end), next: end, ok: true };\n out += arg.text;\n i = arg.next;\n } else if (ch === '}') {\n return { text: out, next: i, ok: true };\n } else if (ch === '#' && pluralValue !== null) {\n out += String(pluralValue);\n i++;\n } else {\n out += ch;\n i++;\n }\n }\n return { text: out, next: i, ok: true };\n}\n\nfunction parseArgument(\n src: string,\n start: number,\n end: number,\n params: TranslateParams,\n locale: string,\n outerPlural: number | null,\n): Parsed {\n let i = skipSpaces(src, start + 1, end);\n const name = readWord(src, i, end);\n i = skipSpaces(src, name.next, end);\n if (i >= end) return { text: src.slice(start, end), next: end, ok: true };\n if (src[i] === '}') {\n const value = params[name.word];\n const rendered =\n value === undefined || value === null || name.word === ''\n ? src.slice(start, i + 1)\n : String(value);\n return { text: rendered, next: i + 1, ok: true };\n }\n if (src[i] !== ',' || name.word === '') {\n return { text: src.slice(start, end), next: end, ok: true };\n }\n i = skipSpaces(src, i + 1, end);\n const type = readWord(src, i, end);\n i = skipSpaces(src, type.next, end);\n if (i >= end || src[i] !== ',') return { text: src.slice(start, end), next: end, ok: true };\n if (type.word !== 'plural' && type.word !== 'select') {\n return { text: src.slice(start, end), next: end, ok: true };\n }\n i++;\n const numeric =\n type.word === 'plural' ? toFiniteNumber(params[name.word]) : null;\n const branches = new Map<string, string>();\n i = skipSpaces(src, i, end);\n let closed = false;\n while (i < end) {\n i = skipSpaces(src, i, end);\n if (i < end && src[i] === '}') {\n closed = true;\n break;\n }\n const sel = readSelector(src, i, end);\n if (sel.selector === null) return { text: src.slice(start, end), next: end, ok: true };\n i = skipSpaces(src, sel.next, end);\n if (i >= end || src[i] !== '{') {\n return { text: src.slice(start, end), next: end, ok: true };\n }\n // Bodies render immediately: '#' binds to THIS plural's number, or to an\n // outer plural when nested (select inherits, nested plural overrides).\n const body = parseMessage(\n src,\n i + 1,\n end,\n params,\n locale,\n numeric ?? outerPlural,\n );\n branches.set(sel.selector, body.text);\n i = body.next + 1;\n }\n if (!closed) return { text: src.slice(start, end), next: end, ok: true };\n if (type.word === 'select') {\n const raw = params[name.word];\n const key = raw === undefined || raw === null ? '' : String(raw);\n return { text: branches.get(key) ?? branches.get('other') ?? '', next: i + 1, ok: true };\n }\n if (numeric === null) return { text: branches.get('other') ?? '', next: i + 1, ok: true };\n const exact = branches.get(`=${numeric}`);\n if (exact !== undefined) return { text: exact, next: i + 1, ok: true };\n let category: string;\n try {\n category = new Intl.PluralRules(locale).select(numeric);\n } catch {\n category = 'other';\n }\n return { text: branches.get(category) ?? branches.get('other') ?? '', next: i + 1, ok: true };\n}\n\nfunction toFiniteNumber(value: string | number | boolean | undefined): number | null {\n if (typeof value === 'number') return Number.isFinite(value) ? value : null;\n if (typeof value === 'string' && value.trim() !== '') {\n const n = Number(value);\n return Number.isFinite(n) ? n : null;\n }\n return null;\n}\n\nfunction skipSpaces(src: string, i: number, end: number): number {\n while (i < end && /\\s/.test(src[i])) i++;\n return i;\n}\n\nfunction readWord(src: string, i: number, end: number): { word: string; next: number } {\n const start = skipSpaces(src, i, end);\n let j = start;\n while (j < end && /[^\\s,}]+/.test(src[j])) j++;\n return { word: src.slice(start, j), next: j };\n}\n\nfunction readSelector(\n src: string,\n i: number,\n end: number,\n): { selector: string | null; next: number } {\n i = skipSpaces(src, i, end);\n if (i < end && src[i] === '=') {\n let j = i + 1;\n if (j < end && src[j] === '-') j++;\n const digits = j;\n while (j < end && /[0-9]/.test(src[j])) j++;\n if (j < end && src[j] === '.' && j + 1 < end && /[0-9]/.test(src[j + 1])) {\n j++;\n while (j < end && /[0-9]/.test(src[j])) j++;\n }\n if (j === digits) return { selector: null, next: i };\n return { selector: src.slice(i, j), next: j };\n }\n const word = readWord(src, i, end);\n if (!word.word) return { selector: null, next: i };\n return { selector: word.word, next: word.next };\n}\n","import { InjectionToken } from '@angular/core';\nimport type {\n Language,\n StorageStrategy,\n SwitchStrategy,\n ViewTransitionConfig,\n} from './i18n-types';\nimport type { LoaderDescriptor } from './loaders';\n\n/**\n * Global configuration for `@rivinia/i18n`.\n */\nexport interface RiviniaI18nConfig<T extends string = string> {\n readonly languages: readonly Language<T>[];\n readonly defaultLanguage: T;\n readonly storageKey?: string;\n readonly storageStrategy?: StorageStrategy;\n readonly autoApplyDirection?: boolean;\n readonly viewTransition?: ViewTransitionConfig;\n /**\n * Dictionary source. Defaults to `jsonLoader()` — the conventional\n * `assets/i18n/{language}.json` layout. Override with any descriptor\n * (custom path, HTTP endpoint, in-memory). Inline-only apps that want zero\n * network traffic pass `customLoader(async () => ({}))`.\n */\n readonly loader?: LoaderDescriptor<T>;\n readonly switchStrategy?: SwitchStrategy;\n /** Called when a dictionary load fails. The service still falls back safely. */\n readonly onLoadError?: (language: T, error: unknown) => void;\n /**\n * Match `navigator.languages` against supported ids on first visit\n * (stored preference always wins; base tags match, e.g. `ar-EG` → `ar`).\n * @default false — explicit opt-in, no surprises.\n */\n readonly detectBrowser?: boolean;\n}\n\n/**\n * Internal configuration token. Consumers must use `provideRiviniaI18n()`.\n * @internal\n */\nexport const RIVINIA_I18N_CONFIG = new InjectionToken<RiviniaI18nConfig>(\n 'RIVINIA_I18N_CONFIG',\n);\n\nexport const DEFAULT_STORAGE_KEY = 'rivinia.i18n.language';\nexport const DEFAULT_STORAGE_STRATEGY: StorageStrategy = 'local';\nexport const DEFAULT_AUTO_APPLY_DIRECTION = true;\n","import { Service } from '@angular/core';\n\n/** Progressive-enhancement wrapper around the View Transition API. */\n@Service()\nexport class ViewTransitionService {\n private readonly _supported =\n typeof document !== 'undefined' && typeof document.startViewTransition === 'function';\n\n run(callback: () => void): void {\n if (this._supported) {\n document.startViewTransition(callback);\n } else {\n callback();\n }\n }\n}\n","import { Service, computed, effect, inject, signal } from '@angular/core';\nimport {\n DEFAULT_AUTO_APPLY_DIRECTION,\n DEFAULT_STORAGE_KEY,\n DEFAULT_STORAGE_STRATEGY,\n RIVINIA_I18N_CONFIG,\n type RiviniaI18nConfig,\n} from './i18n-config';\nimport type { Direction } from './i18n-types';\nimport type { Language } from './i18n-types';\nimport type { StorageStrategy } from './i18n-types';\nimport type { TranslateParams } from './i18n-types';\nimport type { Translation } from './i18n-types';\nimport type { TranslationLoader } from './loaders';\nimport { jsonLoader } from './loaders';\nimport { browserLanguages, detectBrowserLanguage, safeGetItem, safeSetItem } from './i18n-utils';\nimport { formatIcu } from './icu';\nimport { ViewTransitionService } from './view-transition.service';\n\n/**\n * Headless language owner. State (signals, readonly): current language,\n * direction, loader status, dictionaries. Changes only via the methods below.\n * Side effects (persistence + `<html dir/lang>`) run in effects; everything\n * SSR-guarded. No components, no pipes, no styles inside.\n */\n@Service()\nexport class RiviniaI18n<L extends string = string> {\n private readonly _config = inject<RiviniaI18nConfig<L>>(RIVINIA_I18N_CONFIG);\n private readonly _viewTransition = inject(ViewTransitionService, { optional: true });\n private readonly _storageKey = this._config.storageKey ?? DEFAULT_STORAGE_KEY;\n private readonly _storageStrategy: StorageStrategy =\n this._config.storageStrategy ?? DEFAULT_STORAGE_STRATEGY;\n private readonly _autoApplyDirection: boolean =\n this._config.autoApplyDirection ?? DEFAULT_AUTO_APPLY_DIRECTION;\n\n private readonly _currentLanguageId = signal<L>(this._resolveInitialLanguage());\n private readonly _languages = signal<readonly Language<L>[]>(this._config.languages);\n private readonly _loadedTranslations = signal<Record<string, unknown>>({});\n /**\n * Explicit loader wins; otherwise the conventional JSON layout\n * (`assets/i18n/{language}.json` unless the consumer overrides the path).\n * The descriptor still code-splits: the fetch implementation loads only on\n * first resolve.\n */\n private readonly _getLoader: () => Promise<TranslationLoader<L>> =\n this._config.loader?.resolve ?? (() => jsonLoader().resolve() as Promise<TranslationLoader<L>>);\n private _resolvedLoader: TranslationLoader<L> | null = null;\n private readonly _translationsCache = new Map<L, Record<string, unknown>>();\n private readonly _inflight = new Map<L, Promise<Record<string, unknown>>>();\n /**\n * Last-request-wins guard for rapid switches: each load captures a token;\n * stale out-of-order responses stay cached but never overwrite the signal.\n */\n private _requestToken = 0;\n private _applyCount = 0;\n\n readonly languageChanged = computed<L>(() => this._currentLanguageId());\n readonly languages = this._languages.asReadonly();\n readonly currentLanguage = this._currentLanguageId.asReadonly();\n\n readonly currentLanguageObject = computed<Language<L>>(() => {\n const id = this._currentLanguageId();\n return this._languages().find((l) => l.id === id) ?? this._languages()[0];\n });\n\n readonly dir = computed<Direction>(() => this.currentLanguageObject().dir);\n readonly isRtl = computed<boolean>(() => this.dir() === 'rtl');\n\n private readonly _loadingState = signal<'idle' | 'loading' | 'error'>('idle');\n private readonly _loadingError = signal<unknown>(null);\n\n /** Loader state for skeletons/spinners. */\n readonly loadingState = this._loadingState.asReadonly();\n readonly loadingError = this._loadingError.asReadonly();\n readonly isLoading = computed(() => this._loadingState() === 'loading');\n\n constructor() {\n if (this._config.languages.length === 0) {\n throw new Error('[rivinia/i18n] At least one language must be provided in the languages array.');\n }\n if (!this._config.languages.some((l) => l.id === this._config.defaultLanguage)) {\n throw new Error(\n `[rivinia/i18n] defaultLanguage \"${this._config.defaultLanguage}\" must be one of the configured language IDs.`,\n );\n }\n\n effect(() => {\n const id = this._currentLanguageId();\n safeSetItem(this._storageKey, id, this._storageStrategy);\n });\n\n if (this._autoApplyDirection) {\n effect(() => {\n if (typeof document === 'undefined') {\n return;\n }\n const lang = this.currentLanguageObject();\n document.documentElement.dir = lang.dir;\n document.documentElement.lang = lang.id;\n });\n }\n }\n\n getLanguage(id: L): Language<L> | undefined {\n return this._languages().find((l) => l.id === id);\n }\n\n translate(key: string, defaultValue?: string, params?: TranslateParams): string;\n translate(key: string, params?: TranslateParams): string;\n translate(translations: Translation<L>): string;\n\n translate(\n keyOrTranslations: string | Translation<L>,\n defaultValueOrParams?: string | TranslateParams,\n maybeParams?: TranslateParams,\n ): string {\n if (typeof keyOrTranslations === 'string') {\n const { defaultValue, params } = normalizeKeyArgs(defaultValueOrParams, maybeParams);\n const loaded = this._loadedTranslations();\n const resolved = this._resolveKey(loaded, keyOrTranslations);\n if (resolved !== undefined) {\n return this.render(resolved, params);\n }\n const fallback = defaultValue ?? keyOrTranslations;\n return params ? this.render(fallback, params) : fallback;\n }\n const currentId = this._currentLanguageId();\n return keyOrTranslations[currentId] ?? Object.values(keyOrTranslations)[0] ?? '';\n }\n\n loadedTranslations = this._loadedTranslations.asReadonly();\n\n /** Preload without switching (use in `APP_INITIALIZER` / route guards). */\n async loadTranslations(\n languageId: L,\n opts?: { silent?: boolean },\n ): Promise<Record<string, unknown>> {\n return this._loadTranslations(languageId, opts);\n }\n\n toggle(): void {\n const langs = this._languages();\n if (langs.length < 2) return;\n const currentId = this._currentLanguageId();\n const newId = currentId === langs[0].id ? langs[1].id : langs[0].id;\n this.applyLanguage(newId);\n }\n\n next(): void {\n const langs = this._languages();\n if (langs.length < 2) return;\n const currentIdx = langs.findIndex((l) => l.id === this._currentLanguageId());\n const nextIdx = (currentIdx + 1) % langs.length;\n this.applyLanguage(langs[nextIdx].id);\n }\n\n previous(): void {\n const langs = this._languages();\n if (langs.length < 2) return;\n const currentIdx = langs.findIndex((l) => l.id === this._currentLanguageId());\n const prevIdx = (currentIdx - 1 + langs.length) % langs.length;\n this.applyLanguage(langs[prevIdx].id);\n }\n\n setLanguage(id: L): void {\n if (this._config.switchStrategy === 'preload-first') {\n void this.setLanguageAsync(id);\n return;\n }\n this.applyLanguage(id);\n }\n\n /** Preload-first switch: await the dictionary, then flip — no raw-key flash. */\n async setLanguageAsync(id: L): Promise<void> {\n if (id === this._currentLanguageId()) return;\n if (!this._languages().some((l) => l.id === id)) return;\n await this._loadTranslations(id, { silent: true });\n this.applyLanguage(id);\n }\n\n /** Number formatting bound to the current language (pure Intl wrapper). */\n formatNumber(value: number, options?: Intl.NumberFormatOptions): string {\n return new Intl.NumberFormat(this._currentLanguageId(), options).format(value);\n }\n\n /** Date/time formatting bound to the current language (pure Intl wrapper). */\n formatDate(value: Date | number, options?: Intl.DateTimeFormatOptions): string {\n return new Intl.DateTimeFormat(this._currentLanguageId(), options).format(value);\n }\n\n private applyLanguage(id: L, opts?: { skipLoad?: boolean }): void {\n if (id === this._currentLanguageId()) return;\n\n const lang = this._languages().find((l) => l.id === id);\n if (!lang) return;\n\n this._applyCount++;\n\n const apply = () => this._currentLanguageId.set(id);\n const vt = this._config.viewTransition;\n const useTransition =\n vt?.enabled &&\n (!vt.skipInitialTransition || this._applyCount > 1) &&\n this._viewTransition != null;\n\n if (useTransition) {\n vt!.onViewTransitionCreated?.({ language: id, direction: lang.dir });\n this._viewTransition!.run(apply);\n } else {\n apply();\n }\n\n if (!opts?.skipLoad) {\n void this._loadTranslations(id);\n }\n }\n\n private render(template: string, params?: TranslateParams): string {\n if (!params) return template;\n if (!template.includes('{')) return template;\n try {\n return formatIcu(template, params, this._currentLanguageId());\n } catch {\n return template;\n }\n }\n\n private async _loadTranslations(\n languageId: L,\n opts?: { silent?: boolean },\n ): Promise<Record<string, unknown>> {\n const cached = this._translationsCache.get(languageId);\n if (cached) {\n if (!opts?.silent) {\n this._loadedTranslations.set(cached);\n }\n return cached;\n }\n\n const inflight = this._inflight.get(languageId);\n if (inflight) return inflight;\n\n const myToken = ++this._requestToken;\n this._loadingState.set('loading');\n\n const task = (async () => {\n try {\n if (!this._resolvedLoader) {\n this._resolvedLoader = await this._getLoader!();\n }\n const translations = await this._resolvedLoader.load(languageId);\n\n this._translationsCache.set(languageId, translations);\n\n if (myToken === this._requestToken && !opts?.silent) {\n this._loadedTranslations.set(translations);\n this._loadingError.set(null);\n this._loadingState.set('idle');\n }\n\n return translations;\n } catch (error) {\n if (myToken === this._requestToken) {\n this._loadingError.set(error);\n this._loadingState.set('error');\n }\n this._config.onLoadError?.(languageId, error);\n return {};\n } finally {\n this._inflight.delete(languageId);\n if (this._inflight.size === 0 && this._loadingState() === 'loading') {\n this._loadingState.set('idle');\n }\n }\n })();\n\n this._inflight.set(languageId, task);\n return task;\n }\n\n private _resolveKey(obj: Record<string, unknown>, path: string): string | undefined {\n const value = path.split('.').reduce<unknown>(\n (acc, segment) =>\n acc && typeof acc === 'object'\n ? (acc as Record<string, unknown>)[segment]\n : undefined,\n obj,\n );\n if (typeof value === 'string') return value;\n if (typeof value === 'number' || typeof value === 'boolean') return String(value);\n return undefined;\n }\n\n private _resolveInitialLanguage(): L {\n const stored = safeGetItem(this._storageKey, this._storageStrategy);\n if (stored && this._config.languages.some((l) => l.id === stored)) {\n return stored as L;\n }\n if (this._config.detectBrowser) {\n const detected = detectBrowserLanguage(\n this._config.languages.map((l) => l.id),\n browserLanguages(),\n );\n if (detected) return detected;\n }\n return this._config.defaultLanguage;\n }\n}\n\nfunction normalizeKeyArgs(\n second?: string | TranslateParams,\n third?: TranslateParams,\n): { defaultValue?: string; params?: TranslateParams } {\n if (second && typeof second === 'object') {\n return { params: second };\n }\n return { defaultValue: second, params: third };\n}\n","import { EnvironmentProviders, inject, makeEnvironmentProviders } from '@angular/core';\nimport { RIVINIA_I18N_CONFIG, type RiviniaI18nConfig } from './i18n-config';\nimport { RiviniaI18n } from './rivinia-i18n';\n\n/**\n * Configures `@rivinia/i18n` for the application. Call once at bootstrap.\n *\n * @example\n * ```ts\n * provideRiviniaI18n({\n * defaultLanguage: 'ar',\n * languages: [\n * { id: 'ar', nativeName: 'العربية', dir: 'rtl' },\n * { id: 'en', nativeName: 'English', dir: 'ltr' },\n * ],\n * })\n * ```\n */\nexport function provideRiviniaI18n<L extends string>(\n config: RiviniaI18nConfig<L>,\n): EnvironmentProviders {\n return makeEnvironmentProviders([{ provide: RIVINIA_I18N_CONFIG, useValue: config }]);\n}\n\n/** Shorthand for `inject(RiviniaI18n)`. */\nexport function injectRiviniaI18n(): RiviniaI18n<string> {\n return inject(RiviniaI18n);\n}\n","import { Pipe, inject } from '@angular/core';\nimport { RiviniaI18n } from './rivinia-i18n';\nimport type { TranslateParams } from './i18n-types';\nimport type { Translation } from './i18n-types';\n\n/**\n * Template pipe delegating to `RiviniaI18n.translate()`.\n *\n * Impure (`pure: false`) by necessity: the service reads signals on every\n * call, and a pure pipe would not re-evaluate on language switches. For long\n * lists prefer `translate()` in component code over this pipe.\n */\n@Pipe({\n name: 'rTranslate',\n standalone: true,\n pure: false,\n})\nexport class RTranslatePipe<L extends string = string> {\n private readonly _i18n = inject(RiviniaI18n<L>);\n\n transform(key: string, defaultValue?: string, params?: TranslateParams): string;\n transform(key: string, params?: TranslateParams): string;\n transform(translations: Translation<L>): string;\n\n transform(\n keyOrTranslations: string | Translation<L>,\n defaultValueOrParams?: string | TranslateParams,\n maybeParams?: TranslateParams,\n ): string {\n return this._i18n.translate(\n keyOrTranslations as string,\n defaultValueOrParams as string,\n maybeParams as TranslateParams,\n );\n }\n}\n"],"mappings":";;AAiBA,SAAgB,WAAW,SAA2B;CACpD,OAAO,EACL,MAAM,UAAO;EACX,MAAM,EAAE,eAAe,MAAM,OAAO;EACpC,OAAO,IAAI,WAAW,OAAO;CAC/B,EACD;AACH;AAQA,SAAgB,WAAW,SAA0B;CACnD,OAAO,EACL,MAAM,UAAO;EACX,MAAM,E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AE,SAAS;EAAqB,UAAU;CAAM,CAAE,CAAC;AACtF;AAGA,SAAgB,oBAAiB;CAC/B,OAAO,OAAO,WAAW;AAC3B;ACVA,IAAa,iBAAb,MAAa,eAAc;CACR,QAAQ,OAAO,WAAc;CAM9C,UACE,mBACA,sBACA,aAA6B;EAE7B,OAAO,KAAK,MAAM,UAChB,mBACA,sBACA,WAA8B;CAElC;CAjBW,OAAA,OAAA,GAAA,mBAAA;EAAA,YAAA;EAAA,SAAA;EAAA,UAAA;EAAA,MAAA;EAAc,MAAA,CAAA;EAAA,QAAA,GAAA,gBAAA;CAAA,CAAA;CAAd,OAAA,QAAA,GAAA,gBAAA;EAAA,YAAA;EAAA,SAAA;EAAA,UAAA;EAAA,MAAA;EAAc,cAAA;EAAA,MAAA;EAAA,MAAA;CAAA,CAAA;;AAAd,GAAA,yBAAA;CAAA,YAAA;CAAA,SAAA;CAAA,UAAA;CAAA,MAAA;CAAc,YAAA,CAAA;EAL1B,MAAA;EAAK,MAAA,CAAA;GACJ,MAAM;GACN,YAAY;GACZ,MAAM;EACP,CAAA"}
|
|
1
|
+
{"version":3,"file":"rivinia-i18n.mjs","names":[],"sources":["../../../projects/i18n/src/lib/loaders.ts","../../../projects/i18n/src/lib/i18n-utils.ts","../../../projects/i18n/src/lib/cookies.ts","../../../projects/i18n/src/lib/icu.ts","../../../projects/i18n/src/lib/i18n-config.ts","../../../projects/i18n/src/lib/view-transition.service.ts","../../../projects/i18n/src/lib/rivinia-i18n.ts","../../../projects/i18n/src/lib/provide-i18n.ts","../../../projects/i18n/src/lib/translate.pipe.ts"],"sourcesContent":["/**\n * Pluggable key-dictionary loader. Returns a flat/nested JSON-compatible map\n * merged into `loadedTranslations` and read by key-based `translate(key)`.\n */\nexport interface TranslationLoader<L extends string = string> {\n load(language: L): Promise<Record<string, unknown>>;\n}\n\n/**\n * Lazy descriptor: `resolve()` dynamic-imports the real implementation, so\n * loader code splits out of the main bundle until first use. Resolved once\n * and cached by the service.\n */\nexport interface LoaderDescriptor<L extends string = string> {\n resolve(): Promise<TranslationLoader<L>>;\n}\n\nexport function jsonLoader(options?: { path?: string }): LoaderDescriptor<string> {\n return {\n async resolve() {\n const { JsonLoader } = await import('./json-loader.impl');\n return new JsonLoader(options);\n },\n };\n}\n\nexport interface HttpLoaderOptions {\n readonly endpoint: string;\n readonly method?: string;\n readonly buildUrl?: (language: string) => string;\n}\n\nexport function httpLoader(options: HttpLoaderOptions): LoaderDescriptor<string> {\n return {\n async resolve() {\n const { HttpLoader } = await import('./http-loader.impl');\n return new HttpLoader(options);\n },\n };\n}\n\nexport interface RemoteLoaderOptions {\n readonly url: (language: string) => string;\n readonly headers?: Record<string, string>;\n}\n\nexport function remoteLoader(options: RemoteLoaderOptions): LoaderDescriptor<string> {\n return {\n async resolve() {\n const { RemoteLoader } = await import('./remote-loader.impl');\n return new RemoteLoader(options);\n },\n };\n}\n\n/** Wraps any function as a loader (mocks, in-memory, third-party SDKs). */\nexport function customLoader<L extends string = string>(\n load: (language: L) => Promise<Record<string, unknown>>,\n): LoaderDescriptor<L> {\n return {\n async resolve() {\n return { load };\n },\n };\n}\n","import type { StorageStrategy } from './i18n-types';\n\nfunction getStorage(strategy: StorageStrategy): Storage | null {\n // NOTE: 'cookie' resolves to null on purpose — cookies need request/document\n // context, so the service handles that strategy itself (server REQUEST\n // header, browser document.cookie). See RiviniaI18n storage methods.\n if (strategy === 'none' || strategy === 'cookie') return null;\n if (typeof window === 'undefined') return null;\n try {\n return strategy === 'session' ? window.sessionStorage : window.localStorage;\n } catch {\n return null;\n }\n}\n\n/** SSR-safe read. Returns `null` off-browser, on denial, or when missing. */\nexport function safeGetItem(key: string, strategy: StorageStrategy): string | null {\n const storage = getStorage(strategy);\n if (!storage) return null;\n try {\n return storage.getItem(key);\n } catch {\n return null;\n }\n}\n\n/** SSR-safe write. Silently no-ops off-browser or on denial. */\nexport function safeSetItem(key: string, value: string, strategy: StorageStrategy): void {\n const storage = getStorage(strategy);\n if (!storage) return;\n try {\n storage.setItem(key, value);\n } catch {\n // Intentionally silent: persistence is best-effort.\n }\n}\n\n/**\n * Matches the browser language priority list against supported ids, in order.\n * For each browser entry (highest preference first) tries the exact tag, then\n * its base subtag (`ar-EG` → `ar`). Returns the first hit, or `null`.\n * Pure and exported for testing — pass `navigator.languages` in app code.\n */\nexport function detectBrowserLanguage<T extends string>(\n supportedIds: readonly T[],\n browserLanguages: readonly string[] | undefined,\n): T | null {\n if (!browserLanguages || browserLanguages.length === 0) return null;\n const supported = supportedIds.map((id) => id.toLowerCase());\n for (const raw of browserLanguages) {\n const tag = raw.trim().toLowerCase();\n if (!tag) continue;\n const exact = supported.indexOf(tag);\n if (exact !== -1) return supportedIds[exact];\n const base = tag.split(/[-_]/)[0];\n if (base && base !== tag) {\n const hit = supported.indexOf(base);\n if (hit !== -1) return supportedIds[hit];\n }\n }\n return null;\n}\n\n/** Browser language list, `undefined` off-browser (SSR-safe input for detection). */\nexport function browserLanguages(): readonly string[] | undefined {\n if (typeof window === 'undefined' || typeof navigator === 'undefined') return undefined;\n try {\n if (Array.isArray(navigator.languages) && navigator.languages.length > 0) {\n return [...navigator.languages];\n }\n return typeof navigator.language === 'string' ? [navigator.language] : undefined;\n } catch {\n return undefined;\n }\n}\n","/**\n * Cookie helpers for the `'cookie'` storage strategy. Pure and SSR-testable:\n * the service supplies the header (server `REQUEST`) or `document.cookie`\n * (browser); these functions only parse and serialize.\n */\n\n/** Extracts a cookie value by name from a `Cookie` header or `document.cookie`. */\nexport function parseCookie(header: string | null | undefined, name: string): string | null {\n if (!header) return null;\n const prefix = `${name}=`;\n for (const part of header.split(';')) {\n const trimmed = part.trim();\n if (trimmed.startsWith(prefix)) {\n try {\n return decodeURIComponent(trimmed.slice(prefix.length));\n } catch {\n return trimmed.slice(prefix.length);\n }\n }\n }\n return null;\n}\n\n/** Serializes a language cookie (Lax, root path, one year). */\nexport function serializeCookie(\n name: string,\n value: string,\n options?: { secure?: boolean },\n): string {\n const base = `${name}=${encodeURIComponent(value)}; Path=/; Max-Age=31536000; SameSite=Lax`;\n return options?.secure ? `${base}; Secure` : base;\n}\n\n/**\n * Decides whether the language cookie gets `Secure`: only on `https:`, never\n * on `localhost` (dev TLS included — `Secure` there buys nothing and risks\n * silent persistence loss). Pure and SSR-safe: unknown locations → `false`.\n * The server never writes cookies regardless (app-owned responses).\n */\nexport function shouldSecureCookie(\n location: { protocol?: string; hostname?: string } | null | undefined,\n): boolean {\n try {\n if (!location) return false;\n if (location.protocol !== 'https:') return false;\n if (location.hostname === 'localhost') return false;\n return true;\n } catch {\n return false;\n }\n}\n","import type { TranslateParams } from './i18n-types';\n\n/**\n * Minimal ICU MessageFormat subset: `{name}` interpolation, `{n, plural, …}`,\n * `{x, select, …}`, `#` inside plurals, and nesting. Categories resolve via\n * the native `Intl.PluralRules(locale)` — Arabic gets all six forms\n * (zero/one/two/few/many/other) with zero extra dependencies.\n *\n * Supported (and ONLY these — documented subset, translators beware):\n * - `{count, plural, =0 {none} one {# item} other {# items}}`\n * - `{gender, select, male {He} female {She} other {They}}`\n * - `{name}` plain interpolation (missing params keep the placeholder)\n *\n * Malformed input never throws: the raw segment is returned as-is.\n */\nexport function formatIcu(\n template: string,\n params: TranslateParams,\n locale: string,\n): string {\n return parseMessage(template, 0, template.length, params, locale, null).text;\n}\n\ninterface Parsed {\n text: string;\n /** Index of the closing `}` (or `end` when the level ran out). */\n next: number;\n ok: boolean;\n}\n\nfunction parseMessage(\n src: string,\n start: number,\n end: number,\n params: TranslateParams,\n locale: string,\n pluralValue: number | null,\n): Parsed {\n let out = '';\n let i = start;\n while (i < end) {\n const ch = src[i];\n if (ch === '{') {\n const arg = parseArgument(src, i, end, params, locale, pluralValue);\n if (!arg.ok) return { text: out + src.slice(i, end), next: end, ok: true };\n out += arg.text;\n i = arg.next;\n } else if (ch === '}') {\n return { text: out, next: i, ok: true };\n } else if (ch === '#' && pluralValue !== null) {\n out += String(pluralValue);\n i++;\n } else {\n out += ch;\n i++;\n }\n }\n return { text: out, next: i, ok: true };\n}\n\nfunction parseArgument(\n src: string,\n start: number,\n end: number,\n params: TranslateParams,\n locale: string,\n outerPlural: number | null,\n): Parsed {\n let i = skipSpaces(src, start + 1, end);\n const name = readWord(src, i, end);\n i = skipSpaces(src, name.next, end);\n if (i >= end) return { text: src.slice(start, end), next: end, ok: true };\n if (src[i] === '}') {\n const value = params[name.word];\n const rendered =\n value === undefined || value === null || name.word === ''\n ? src.slice(start, i + 1)\n : String(value);\n return { text: rendered, next: i + 1, ok: true };\n }\n if (src[i] !== ',' || name.word === '') {\n return { text: src.slice(start, end), next: end, ok: true };\n }\n i = skipSpaces(src, i + 1, end);\n const type = readWord(src, i, end);\n i = skipSpaces(src, type.next, end);\n if (i >= end || src[i] !== ',') return { text: src.slice(start, end), next: end, ok: true };\n if (type.word !== 'plural' && type.word !== 'select') {\n return { text: src.slice(start, end), next: end, ok: true };\n }\n i++;\n const numeric =\n type.word === 'plural' ? toFiniteNumber(params[name.word]) : null;\n const branches = new Map<string, string>();\n i = skipSpaces(src, i, end);\n let closed = false;\n while (i < end) {\n i = skipSpaces(src, i, end);\n if (i < end && src[i] === '}') {\n closed = true;\n break;\n }\n const sel = readSelector(src, i, end);\n if (sel.selector === null) return { text: src.slice(start, end), next: end, ok: true };\n i = skipSpaces(src, sel.next, end);\n if (i >= end || src[i] !== '{') {\n return { text: src.slice(start, end), next: end, ok: true };\n }\n // Bodies render immediately: '#' binds to THIS plural's number, or to an\n // outer plural when nested (select inherits, nested plural overrides).\n const body = parseMessage(\n src,\n i + 1,\n end,\n params,\n locale,\n numeric ?? outerPlural,\n );\n branches.set(sel.selector, body.text);\n i = body.next + 1;\n }\n if (!closed) return { text: src.slice(start, end), next: end, ok: true };\n if (type.word === 'select') {\n const raw = params[name.word];\n const key = raw === undefined || raw === null ? '' : String(raw);\n return { text: branches.get(key) ?? branches.get('other') ?? '', next: i + 1, ok: true };\n }\n if (numeric === null) return { text: branches.get('other') ?? '', next: i + 1, ok: true };\n const exact = branches.get(`=${numeric}`);\n if (exact !== undefined) return { text: exact, next: i + 1, ok: true };\n let category: string;\n try {\n category = new Intl.PluralRules(locale).select(numeric);\n } catch {\n category = 'other';\n }\n return { text: branches.get(category) ?? branches.get('other') ?? '', next: i + 1, ok: true };\n}\n\nfunction toFiniteNumber(value: string | number | boolean | undefined): number | null {\n if (typeof value === 'number') return Number.isFinite(value) ? value : null;\n if (typeof value === 'string' && value.trim() !== '') {\n const n = Number(value);\n return Number.isFinite(n) ? n : null;\n }\n return null;\n}\n\nfunction skipSpaces(src: string, i: number, end: number): number {\n while (i < end && /\\s/.test(src[i])) i++;\n return i;\n}\n\nfunction readWord(src: string, i: number, end: number): { word: string; next: number } {\n const start = skipSpaces(src, i, end);\n let j = start;\n while (j < end && /[^\\s,}]+/.test(src[j])) j++;\n return { word: src.slice(start, j), next: j };\n}\n\nfunction readSelector(\n src: string,\n i: number,\n end: number,\n): { selector: string | null; next: number } {\n i = skipSpaces(src, i, end);\n if (i < end && src[i] === '=') {\n let j = i + 1;\n if (j < end && src[j] === '-') j++;\n const digits = j;\n while (j < end && /[0-9]/.test(src[j])) j++;\n if (j < end && src[j] === '.' && j + 1 < end && /[0-9]/.test(src[j + 1])) {\n j++;\n while (j < end && /[0-9]/.test(src[j])) j++;\n }\n if (j === digits) return { selector: null, next: i };\n return { selector: src.slice(i, j), next: j };\n }\n const word = readWord(src, i, end);\n if (!word.word) return { selector: null, next: i };\n return { selector: word.word, next: word.next };\n}\n","import { InjectionToken } from '@angular/core';\nimport type { Language, StorageStrategy, SwitchStrategy, ViewTransitionConfig } from './i18n-types';\nimport type { LoaderDescriptor } from './loaders';\n\n/**\n * Global configuration for `@rivinia/i18n`.\n */\nexport interface RiviniaI18nConfig<T extends string = string> {\n readonly languages: readonly Language<T>[];\n readonly defaultLanguage: T;\n readonly storageKey?: string;\n readonly storageStrategy?: StorageStrategy;\n readonly autoApplyDirection?: boolean;\n readonly viewTransition?: ViewTransitionConfig;\n /**\n * Dictionary source. Defaults to `jsonLoader()` — the conventional\n * `i18n/{language}.json` layout (files in `public/i18n/`, served from the\n * site root). Override with any descriptor\n * (custom path, HTTP endpoint, in-memory). Inline-only apps that want zero\n * network traffic pass `customLoader(async () => ({}))`.\n */\n readonly loader?: LoaderDescriptor<T>;\n readonly switchStrategy?: SwitchStrategy;\n /** Called when a dictionary load fails. The service still falls back safely. */\n readonly onLoadError?: (language: T, error: unknown) => void;\n /**\n * Load the initial language during provider setup (before first paint).\n * SSR waits via `PendingTasks`. Set `false` to skip (e.g. fully inline apps\n * that call `loadTranslations` themselves).\n * @default true\n */\n readonly preload?: boolean;\n /**\n * Inline per-language dictionaries. Seeded before any network load (zero\n * network + SSR-safe first paint); a successful loader response still wins.\n */\n readonly translations?: Partial<Record<T, Record<string, unknown>>>;\n /**\n * Match `navigator.languages` against supported ids on first visit\n * (stored preference always wins; base tags match, e.g. `ar-EG` → `ar`).\n * @default false — explicit opt-in, no surprises.\n */\n readonly detectBrowser?: boolean;\n}\n\n/**\n * Internal configuration token. Consumers must use `provideRiviniaI18n()`.\n * @internal\n */\nexport const RIVINIA_I18N_CONFIG = new InjectionToken<RiviniaI18nConfig>('RIVINIA_I18N_CONFIG');\n\nexport const DEFAULT_STORAGE_KEY = 'rivinia.i18n.language';\nexport const DEFAULT_STORAGE_STRATEGY: StorageStrategy = 'local';\nexport const DEFAULT_AUTO_APPLY_DIRECTION = true;\n","import { DOCUMENT, Service, inject } from '@angular/core';\n\n/** Progressive-enhancement wrapper around the View Transition API. */\n@Service()\nexport class ViewTransitionService {\n private readonly _doc = inject(DOCUMENT);\n\n run(callback: () => void): void {\n const doc = this._doc as Document & {\n startViewTransition?: (callback: () => void) => unknown;\n };\n if (typeof doc.startViewTransition === 'function') {\n doc.startViewTransition(callback);\n } else {\n callback();\n }\n }\n}\n","import {\n DOCUMENT,\n PendingTasks,\n REQUEST,\n Service,\n TransferState,\n computed,\n effect,\n inject,\n makeStateKey,\n signal,\n type StateKey,\n} from '@angular/core';\nimport {\n DEFAULT_AUTO_APPLY_DIRECTION,\n DEFAULT_STORAGE_KEY,\n DEFAULT_STORAGE_STRATEGY,\n RIVINIA_I18N_CONFIG,\n type RiviniaI18nConfig,\n} from './i18n-config';\nimport type { Direction } from './i18n-types';\nimport type { Language } from './i18n-types';\nimport type { StorageStrategy } from './i18n-types';\nimport type { TranslateParams } from './i18n-types';\nimport type { Translation } from './i18n-types';\nimport type { TranslationLoader } from './loaders';\nimport { jsonLoader } from './loaders';\nimport { browserLanguages, detectBrowserLanguage, safeGetItem, safeSetItem } from './i18n-utils';\nimport { parseCookie, serializeCookie, shouldSecureCookie } from './cookies';\nimport { formatIcu } from './icu';\nimport { ViewTransitionService } from './view-transition.service';\n\n/**\n * Headless language owner. State (signals, readonly): current language,\n * direction, loader status, dictionaries. Changes only via the methods below.\n * Side effects (persistence + `<html dir/lang>`) run in effects; everything\n * SSR-guarded. No components, no pipes, no styles inside.\n */\n@Service()\nexport class RiviniaI18n<L extends string = string> {\n private readonly _config = inject<RiviniaI18nConfig<L>>(RIVINIA_I18N_CONFIG);\n private readonly _viewTransition = inject(ViewTransitionService, { optional: true });\n private readonly _storageKey = this._config.storageKey ?? DEFAULT_STORAGE_KEY;\n private readonly _storageStrategy: StorageStrategy =\n this._config.storageStrategy ?? DEFAULT_STORAGE_STRATEGY;\n private readonly _autoApplyDirection: boolean =\n this._config.autoApplyDirection ?? DEFAULT_AUTO_APPLY_DIRECTION;\n /**\n * Injected (not global) document: the dir/lang effect renders on the\n * server too, avoiding an RTL first-paint shift on hydration.\n * Declared before any field initializer that reads storage.\n */\n private readonly _doc = inject(DOCUMENT);\n /** Present only on the server: used for cookie reads + transfer writes. */\n private readonly _request = inject(REQUEST, { optional: true });\n private readonly _transfer = inject(TransferState, { optional: true });\n\n private readonly _currentLanguageId = signal<L>(this._resolveInitialLanguage());\n private readonly _languages = signal<readonly Language<L>[]>(this._config.languages);\n private readonly _loadedTranslations = signal<Record<string, unknown>>({});\n /**\n * Explicit loader wins; otherwise the conventional JSON layout\n * (`i18n/{language}.json` — files in `public/i18n/`, served from the site\n * root — unless the consumer overrides the path).\n * The descriptor still code-splits: the fetch implementation loads only on\n * first resolve.\n */\n private readonly _getLoader: () => Promise<TranslationLoader<L>> =\n this._config.loader?.resolve ?? (() => jsonLoader().resolve() as Promise<TranslationLoader<L>>);\n private _resolvedLoader: TranslationLoader<L> | null = null;\n private readonly _translationsCache = new Map<L, Record<string, unknown>>();\n private readonly _inflight = new Map<\n L,\n Promise<{ data: Record<string, unknown>; ok: boolean }>\n >();\n /**\n * Out-of-order safety: a response reaches the visible signals only when it\n * belongs to the currently intended language (`_currentLanguageId()`).\n * Everything else stays cached. (A monotonic request token used to guard\n * this, but it over-constrained legitimate same-language loads.)\n */\n private _applyCount = 0;\n private _initialized = false;\n private readonly _tasks = inject(PendingTasks, { optional: true });\n\n readonly languageChanged = computed<L>(() => this._currentLanguageId());\n readonly languages = this._languages.asReadonly();\n readonly currentLanguage = this._currentLanguageId.asReadonly();\n\n readonly currentLanguageObject = computed<Language<L>>(() => {\n const id = this._currentLanguageId();\n return this._languages().find((l) => l.id === id) ?? this._languages()[0];\n });\n\n readonly dir = computed<Direction>(() => this.currentLanguageObject().dir);\n readonly isRtl = computed<boolean>(() => this.dir() === 'rtl');\n\n private readonly _loadingState = signal<'idle' | 'loading' | 'error'>('idle');\n private readonly _loadingError = signal<unknown>(null);\n\n /** Loader state for skeletons/spinners. */\n readonly loadingState = this._loadingState.asReadonly();\n readonly loadingError = this._loadingError.asReadonly();\n readonly isLoading = computed(() => this._loadingState() === 'loading');\n\n private readonly _ready = signal(false);\n /**\n * True once the initial language content is available (inline seed and/or\n * initial load settled) — or immediately when `preload: false` skips setup\n * loading. Gate first-paint skeletons on this, not on `isLoading`.\n */\n readonly ready = this._ready.asReadonly();\n\n constructor() {\n if (this._config.languages.length === 0) {\n throw new Error(\n '[rivinia/i18n] At least one language must be provided in the languages array.',\n );\n }\n if (!this._config.languages.some((l) => l.id === this._config.defaultLanguage)) {\n throw new Error(\n `[rivinia/i18n] defaultLanguage \"${this._config.defaultLanguage}\" must be one of the configured language IDs.`,\n );\n }\n\n effect(() => {\n const id = this._currentLanguageId();\n this._writeStored(id);\n });\n\n if (this._autoApplyDirection) {\n effect(() => {\n const lang = this.currentLanguageObject();\n const root = this._doc.documentElement;\n if (!root) return;\n root.dir = lang.dir;\n root.lang = lang.id;\n });\n }\n }\n\n getLanguage(id: L): Language<L> | undefined {\n return this._languages().find((l) => l.id === id);\n }\n\n /**\n * Runs the provider-setup loading: seeds inline dictionaries, then loads\n * the initial language (unless `preload: false`). Called automatically by\n * the `provideRiviniaI18n` app initializer; call manually only when driving\n * setup yourself. Idempotent. Never rejects (load failures land on\n * `loadingError`/`onLoadError`, inline seeds are preserved).\n */\n async initialize(): Promise<void> {\n if (this._initialized) return;\n this._initialized = true;\n const done = this._tasks?.add();\n try {\n const current = this._currentLanguageId();\n const transferred = this.readTransfer(current);\n if (transferred) {\n this._translationsCache.set(current, transferred);\n this._loadedTranslations.set(transferred);\n } else {\n const inline = this._config.translations?.[current];\n if (inline) {\n // Instant paint without touching the cache: the refresh below still\n // runs, so a successful loader response wins; on failure the seed\n // stays visible and the error surfaces on loadingState/onLoadError.\n this._loadedTranslations.set(inline);\n }\n if (this._config.preload ?? true) {\n await this._loadTranslations(current);\n }\n }\n } finally {\n this._ready.set(true);\n done?.();\n }\n }\n\n translate(key: string, defaultValue?: string, params?: TranslateParams): string;\n translate(key: string, params?: TranslateParams): string;\n translate(translations: Translation<L>): string;\n\n translate(\n keyOrTranslations: string | Translation<L>,\n defaultValueOrParams?: string | TranslateParams,\n maybeParams?: TranslateParams,\n ): string {\n if (typeof keyOrTranslations === 'string') {\n const { defaultValue, params } = normalizeKeyArgs(defaultValueOrParams, maybeParams);\n const loaded = this._loadedTranslations();\n const resolved = this._resolveKey(loaded, keyOrTranslations);\n if (resolved !== undefined) {\n return this.render(resolved, params);\n }\n const fallback = defaultValue ?? keyOrTranslations;\n return params ? this.render(fallback, params) : fallback;\n }\n const currentId = this._currentLanguageId();\n return keyOrTranslations[currentId] ?? Object.values(keyOrTranslations)[0] ?? '';\n }\n\n loadedTranslations = this._loadedTranslations.asReadonly();\n\n /** Preload without switching (use in `APP_INITIALIZER` / route guards). */\n async loadTranslations(\n languageId: L,\n opts?: { silent?: boolean },\n ): Promise<Record<string, unknown>> {\n return (await this._loadTranslations(languageId, opts)).data;\n }\n\n toggle(): void {\n const langs = this._languages();\n if (langs.length < 2) return;\n const currentId = this._currentLanguageId();\n const newId = currentId === langs[0].id ? langs[1].id : langs[0].id;\n this.applyLanguage(newId);\n }\n\n next(): void {\n const langs = this._languages();\n if (langs.length < 2) return;\n const currentIdx = langs.findIndex((l) => l.id === this._currentLanguageId());\n const nextIdx = (currentIdx + 1) % langs.length;\n this.applyLanguage(langs[nextIdx].id);\n }\n\n previous(): void {\n const langs = this._languages();\n if (langs.length < 2) return;\n const currentIdx = langs.findIndex((l) => l.id === this._currentLanguageId());\n const prevIdx = (currentIdx - 1 + langs.length) % langs.length;\n this.applyLanguage(langs[prevIdx].id);\n }\n\n setLanguage(id: L): void {\n if (this._config.switchStrategy === 'preload-first') {\n void this.setLanguageAsync(id);\n return;\n }\n this.applyLanguage(id);\n }\n\n /** Preload-first switch: await the dictionary, then flip — no raw-key flash.\n * A failed load aborts: language, direction and dictionary stay untouched. */\n async setLanguageAsync(id: L): Promise<void> {\n if (id === this._currentLanguageId()) return;\n if (!this._languages().some((l) => l.id === id)) return;\n const { ok } = await this._loadTranslations(id, { silent: true });\n if (!ok) return;\n this.applyLanguage(id);\n }\n\n /** Number formatting bound to the current language locale (cached Intl). */\n formatNumber(value: number, options?: Intl.NumberFormatOptions): string {\n return this.numberFormatter(options).format(value);\n }\n\n /** Date/time formatting bound to the current language locale (cached Intl). */\n formatDate(value: Date | number, options?: Intl.DateTimeFormatOptions): string {\n return this.dateTimeFormatter(options).format(value);\n }\n\n /** BCP-47 locale driving Intl + ICU plural rules (falls back to the id). */\n readonly locale = computed<string>(() => {\n return this.currentLanguageObject().locale ?? this._currentLanguageId();\n });\n\n private readonly _formatters = new Map<string, Intl.NumberFormat | Intl.DateTimeFormat>();\n\n private numberFormatter(options?: Intl.NumberFormatOptions): Intl.NumberFormat {\n const key = `n|${this.locale()}|${JSON.stringify(options ?? null)}`;\n let formatter = this._formatters.get(key) as Intl.NumberFormat | undefined;\n if (!formatter) {\n formatter = new Intl.NumberFormat(this.locale(), options);\n this._formatters.set(key, formatter);\n }\n return formatter;\n }\n\n private dateTimeFormatter(options?: Intl.DateTimeFormatOptions): Intl.DateTimeFormat {\n const key = `d|${this.locale()}|${JSON.stringify(options ?? null)}`;\n let formatter = this._formatters.get(key) as Intl.DateTimeFormat | undefined;\n if (!formatter) {\n formatter = new Intl.DateTimeFormat(this.locale(), options);\n this._formatters.set(key, formatter);\n }\n return formatter;\n }\n\n private applyLanguage(id: L, opts?: { skipLoad?: boolean }): void {\n if (id === this._currentLanguageId()) return;\n\n const lang = this._languages().find((l) => l.id === id);\n if (!lang) return;\n\n this._applyCount++;\n\n const apply = () => this._currentLanguageId.set(id);\n const vt = this._config.viewTransition;\n const useTransition =\n vt?.enabled &&\n (!vt.skipInitialTransition || this._applyCount > 1) &&\n this._viewTransition != null;\n\n if (useTransition) {\n vt!.onViewTransitionCreated?.({ language: id, direction: lang.dir });\n this._viewTransition!.run(apply);\n } else {\n apply();\n }\n\n if (!opts?.skipLoad) {\n void this._loadTranslations(id);\n }\n }\n\n private render(template: string, params?: TranslateParams): string {\n if (!params) return template;\n if (!template.includes('{')) return template;\n try {\n return formatIcu(template, params, this.locale());\n } catch {\n return template;\n }\n }\n\n private async _loadTranslations(\n languageId: L,\n opts?: { silent?: boolean },\n ): Promise<{ data: Record<string, unknown>; ok: boolean }> {\n // A dictionary only ever reaches the visible signals when it belongs to\n // the currently intended language. Anything else (slow out-of-order\n // responses, explicit preloads of other languages) stays cached.\n const current = (): boolean => languageId === this._currentLanguageId();\n const cached = this._translationsCache.get(languageId);\n if (cached) {\n if (!opts?.silent && current()) {\n this._loadedTranslations.set(cached);\n }\n return { data: cached, ok: true };\n }\n\n const inflight = this._inflight.get(languageId);\n if (inflight) return inflight;\n\n this._loadingState.set('loading');\n\n const task: Promise<{ data: Record<string, unknown>; ok: boolean }> = (async () => {\n try {\n if (!this._resolvedLoader) {\n this._resolvedLoader = await this._getLoader!();\n }\n const translations = await this._resolvedLoader.load(languageId);\n\n this._translationsCache.set(languageId, translations);\n this.writeTransfer(languageId, translations);\n\n if (!opts?.silent && current()) {\n this._loadedTranslations.set(translations);\n this._loadingError.set(null);\n this._loadingState.set('idle');\n }\n\n return { data: translations, ok: true };\n } catch (error) {\n if (current()) {\n this._loadingError.set(error);\n this._loadingState.set('error');\n }\n this._config.onLoadError?.(languageId, error);\n return { data: {}, ok: false };\n } finally {\n this._inflight.delete(languageId);\n if (this._inflight.size === 0 && this._loadingState() === 'loading') {\n this._loadingState.set('idle');\n }\n }\n })();\n\n this._inflight.set(languageId, task);\n return task;\n }\n\n /**\n * Reads the persisted language. Cookie strategy: server reads the request\n * `Cookie` header (no hydration mismatch), browser reads `document.cookie`.\n * Everything else delegates to the SSR-safe storage helpers.\n */\n private _readStored(): string | null {\n if (this._storageStrategy === 'cookie') {\n const header = this._request?.headers.get('cookie') ?? null;\n if (header !== null) return parseCookie(header, this._storageKey);\n try {\n return parseCookie(this._doc.cookie, this._storageKey);\n } catch {\n return null;\n }\n }\n return safeGetItem(this._storageKey, this._storageStrategy);\n }\n\n /** Persists the language. Server never writes (response cookies are app-owned). */\n private _writeStored(id: L): void {\n if (this._storageStrategy === 'cookie') {\n if (this._request) return;\n try {\n const location = (\n this._doc as unknown as { location?: { protocol?: string; hostname?: string } }\n )?.location;\n this._doc.cookie = serializeCookie(this._storageKey, id, {\n secure: shouldSecureCookie(location),\n });\n } catch {\n // Best-effort persistence.\n }\n return;\n }\n safeSetItem(this._storageKey, id, this._storageStrategy);\n }\n\n private transferKey(languageId: L): StateKey<Record<string, unknown>> {\n return makeStateKey<Record<string, unknown>>(`rivinia.i18n.dict.${languageId}`);\n }\n\n /** Consumes server-rendered dictionaries so the client never refetches. */\n private readTransfer(languageId: L): Record<string, unknown> | null {\n const transfer = this._transfer;\n if (!transfer) return null;\n const key = this.transferKey(languageId);\n if (!transfer.hasKey(key)) return null;\n const dict = transfer.get(key, null);\n transfer.remove(key);\n return dict;\n }\n\n /** Stores freshly loaded dictionaries for hydration (server only). */\n private writeTransfer(languageId: L, dict: Record<string, unknown>): void {\n if (!this._request) return;\n this._transfer?.set(this.transferKey(languageId), dict);\n }\n\n private _resolveKey(obj: Record<string, unknown>, path: string): string | undefined {\n const value = path\n .split('.')\n .reduce<unknown>(\n (acc, segment) =>\n acc && typeof acc === 'object' ? (acc as Record<string, unknown>)[segment] : undefined,\n obj,\n );\n if (typeof value === 'string') return value;\n if (typeof value === 'number' || typeof value === 'boolean') return String(value);\n return undefined;\n }\n\n private _resolveInitialLanguage(): L {\n const stored = this._readStored();\n if (stored && this._config.languages.some((l) => l.id === stored)) {\n return stored as L;\n }\n if (this._config.detectBrowser) {\n const detected = detectBrowserLanguage(\n this._config.languages.map((l) => l.id),\n browserLanguages(),\n );\n if (detected) return detected;\n }\n return this._config.defaultLanguage;\n }\n}\n\nfunction normalizeKeyArgs(\n second?: string | TranslateParams,\n third?: TranslateParams,\n): { defaultValue?: string; params?: TranslateParams } {\n if (second && typeof second === 'object') {\n return { params: second };\n }\n return { defaultValue: second, params: third };\n}\n","import {\n EnvironmentProviders,\n inject,\n makeEnvironmentProviders,\n provideAppInitializer,\n} from '@angular/core';\nimport { RIVINIA_I18N_CONFIG, type RiviniaI18nConfig } from './i18n-config';\nimport { RiviniaI18n } from './rivinia-i18n';\n\n/**\n * Configures `@rivinia/i18n` for the application. Call once at bootstrap.\n * Also registers an app initializer that loads the initial language before\n * first paint (opt out with `preload: false`).\n *\n * @example\n * ```ts\n * provideRiviniaI18n({\n * defaultLanguage: 'ar',\n * languages: [\n * { id: 'ar', nativeName: 'العربية', dir: 'rtl' },\n * { id: 'en', nativeName: 'English', dir: 'ltr' },\n * ],\n * })\n * ```\n */\nexport function provideRiviniaI18n<L extends string>(\n config: RiviniaI18nConfig<L>,\n): EnvironmentProviders {\n return makeEnvironmentProviders([\n { provide: RIVINIA_I18N_CONFIG, useValue: config },\n provideAppInitializer(() => {\n const i18n = inject(RiviniaI18n) as RiviniaI18n<string>;\n return i18n.initialize();\n }),\n ]);\n}\n\n/** Shorthand for `inject(RiviniaI18n)` — preserves the configured language union. */\nexport function injectRiviniaI18n<L extends string = string>(): RiviniaI18n<L> {\n return inject(RiviniaI18n) as unknown as RiviniaI18n<L>;\n}\n\n/**\n * Binds a config and its typed accessors together so `L` is inferred once\n * from the configuration instead of being lost at the injection site.\n *\n * @example\n * ```ts\n * export const i18n = defineRiviniaI18n({\n * defaultLanguage: 'ar',\n * languages: [\n * { id: 'ar', nativeName: 'العربية', dir: 'rtl' },\n * { id: 'en', nativeName: 'English', dir: 'ltr' },\n * ],\n * });\n * // app.config.ts\n * providers: [i18n.provide()]\n * // anywhere (typed 'ar' | 'en'):\n * const lang = i18n.inject();\n * ```\n */\nexport function defineRiviniaI18n<L extends string>(config: RiviniaI18nConfig<L>): {\n readonly config: RiviniaI18nConfig<L>;\n provide: () => EnvironmentProviders;\n inject: () => RiviniaI18n<L>;\n} {\n return {\n config,\n provide: () => provideRiviniaI18n(config),\n inject: () => injectRiviniaI18n<L>(),\n };\n}\n","import { Pipe, inject } from '@angular/core';\nimport { RiviniaI18n } from './rivinia-i18n';\nimport type { TranslateParams } from './i18n-types';\nimport type { Translation } from './i18n-types';\n\n/**\n * Template pipe delegating to `RiviniaI18n.translate()`.\n *\n * Impure (`pure: false`) by necessity: the service reads signals on every\n * call, and a pure pipe would not re-evaluate on language switches. For long\n * lists prefer `translate()` in component code over this pipe.\n */\n@Pipe({\n name: 'rTranslate',\n pure: false,\n})\nexport class RTranslatePipe<L extends string = string> {\n private readonly _i18n = inject(RiviniaI18n<L>);\n\n transform(key: string, defaultValue?: string, params?: TranslateParams): string;\n transform(key: string, params?: TranslateParams): string;\n transform(translations: Translation<L>): string;\n\n transform(\n keyOrTranslations: string | Translation<L>,\n defaultValueOrParams?: string | TranslateParams,\n maybeParams?: TranslateParams,\n ): string {\n return this._i18n.translate(\n keyOrTranslations as string,\n defaultValueOrParams as string,\n maybeParams as TranslateParams,\n );\n }\n}\n"],"mappings":";;AAiBA,SAAgB,WAAW,SAA2B;CACpD,OAAO,EACL,MAAM,UAAO;EACX,MAAM,EAAE,eAAe,MAAM,OAAO;EACpC,OAAO,IAAI,WAAW,OAAO;CAC/B,EACD;AACH;AAQA,SAAgB,WAAW,SAA0B;CACnD,OAAO,EACL,MAAM,UAAO;EACX,MAAM,EAAE,eAAe,MAAM,OAAO;EACpC,OAAO,IAAI,WAAW,OAAO;CAC/B,EACD;AACH;AAOA,SAAgB,aAAa,SAA4B;CACvD,OAAO,EACL,MAAM,UAAO;EACX,MAAM,EAAE,iBAAiB,MAAM,OAAO;EACtC,OAAO,IAAI,aAAa,OAAO;CACjC,EACD;AACH;AAGA,SAAgB,aACd,MAAuD;CAEvD,OAAO,EACL,MAAM,UAAO;EACX,OAAO,EAAE,KAAI;CACf,EACD;AACH;AC9DA,SAAS,WAAW,UAAyB;CAI3C,IAAI,aAAa,UAAU,aAAa,UAAU,OAAO;CACzD,IAAI,OAAO,WAAW,aAAa,OAAO;CAC1C,IAAI;EACF,OAAO,aAAa,YAAY,OAAO,iBAAiB,OAAO;CACjE,QAAQ;EACN,OAAO;CACT;AACF;AAGA,SAAgB,YAAY,KAAa,UAAyB;CAChE,MAAM,UAAU,WAAW,QAAQ;CACnC,IAAI,CAAC,SAAS,OAAO;CACrB,IAAI;EACF,OAAO,QAAQ,QAAQ,GAAG;CAC5B,QAAQ;EACN,OAAO;CACT;AACF;AAGA,SAAgB,YAAY,KAAa,OAAe,UAAyB;CAC/E,MAAM,UAAU,WAAW,QAAQ;CACnC,IAAI,CAAC,SAAS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B;CAE5B,OAAO,yBAAyB,CAC9B;EAAE,SAAS;EAAqB,UAAU;CAAM,GAChD,4BAA2B;EAEzB,OADa,OAAO,WACb,CAAA,CAAK,WAAU;CACxB,CAAC,CACF,CAAA;AACH;AAGA,SAAgB,oBAAiB;CAC/B,OAAO,OAAO,WAAW;AAC3B;AAqBA,SAAgB,kBAAoC,QAA4B;CAK9E,OAAO;EACL;EACA,eAAe,mBAAmB,MAAM;EACxC,cAAc,kBAAiB;CAChC;AACH;ACvDA,IAAa,iBAAb,MAAa,eAAc;CACR,QAAQ,OAAO,WAAc;CAM9C,UACE,mBACA,sBACA,aAA6B;EAE7B,OAAO,KAAK,MAAM,UAChB,mBACA,sBACA,WAA8B;CAElC;CAjBW,OAAA,OAAA,GAAA,mBAAA;EAAA,YAAA;EAAA,SAAA;EAAA,UAAA;EAAA,MAAA;EAAc,MAAA,CAAA;EAAA,QAAA,GAAA,gBAAA;CAAA,CAAA;CAAd,OAAA,QAAA,GAAA,gBAAA;EAAA,YAAA;EAAA,SAAA;EAAA,UAAA;EAAA,MAAA;EAAc,cAAA;EAAA,MAAA;EAAA,MAAA;CAAA,CAAA;;AAAd,GAAA,yBAAA;CAAA,YAAA;CAAA,SAAA;CAAA,UAAA;CAAA,MAAA;CAAc,YAAA,CAAA;EAJ1B,MAAA;EAAK,MAAA,CAAA;GACJ,MAAM;GACN,MAAM;EACP,CAAA"}
|
package/package.json
CHANGED
|
@@ -27,6 +27,7 @@ const STARTER = (ids, detectBrowser) => {
|
|
|
27
27
|
.join('\n');
|
|
28
28
|
const detect = detectBrowser ? ',\n detectBrowser: true' : '';
|
|
29
29
|
return (`provideRiviniaI18n({\n` +
|
|
30
|
+
` // Dictionaries: public/i18n/{id}.json (default jsonLoader)\n` +
|
|
30
31
|
` defaultLanguage: '${ids[0]}',\n` +
|
|
31
32
|
` languages: [\n${languages}\n ],${detect}\n` +
|
|
32
33
|
` })`);
|
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
"properties": {
|
|
7
7
|
"languages": {
|
|
8
8
|
"type": "string",
|
|
9
|
-
"description": "Comma-separated language ids — bare (ar, en), quoted ('ar', 'en') or bracketed ([ar, en]). First id becomes the default language.",
|
|
9
|
+
"description": "Comma-separated language ids — bare (ar, en), quoted ('ar', 'en') or bracketed ([ar, en]). First id becomes the default language. Dictionaries load from public/i18n/{id}.json by default.",
|
|
10
10
|
"x-prompt": {
|
|
11
11
|
"message": "Language ids for this project (ar, en — brackets and quotes also fine)?",
|
|
12
12
|
"type": "input"
|
package/types/rivinia-i18n.d.ts
CHANGED
|
@@ -10,11 +10,18 @@ interface Language<T extends string = string> {
|
|
|
10
10
|
readonly id: T;
|
|
11
11
|
readonly nativeName?: string;
|
|
12
12
|
readonly dir: Direction;
|
|
13
|
+
/**
|
|
14
|
+
* BCP-47 locale for `Intl` formatting and plural rules (e.g. `ar-EG` for
|
|
15
|
+
* Arabic-Indic digits, `en-GB` vs `en-US`). Defaults to the language id —
|
|
16
|
+
* note a bare id like `ar` formats Latin digits, which is often NOT what
|
|
17
|
+
* Arabic readers expect.
|
|
18
|
+
*/
|
|
19
|
+
readonly locale?: string;
|
|
13
20
|
}
|
|
14
21
|
/** Inline typed translations: `{ ar: 'حفظ', en: 'Save' }`. */
|
|
15
22
|
type Translation<T extends string> = Record<T, string>;
|
|
16
23
|
/** Persistence backend. SSR-safe: everything degrades to no-op off-browser. */
|
|
17
|
-
type StorageStrategy = 'local' | 'session' | 'none';
|
|
24
|
+
type StorageStrategy = 'local' | 'session' | 'none' | 'cookie';
|
|
18
25
|
/** Interpolation + ICU params (`{count}`, `{gender}`). */
|
|
19
26
|
type TranslateParams = Record<string, string | number | boolean>;
|
|
20
27
|
interface ViewTransitionInfo {
|
|
@@ -71,7 +78,8 @@ interface RiviniaI18nConfig<T extends string = string> {
|
|
|
71
78
|
readonly viewTransition?: ViewTransitionConfig;
|
|
72
79
|
/**
|
|
73
80
|
* Dictionary source. Defaults to `jsonLoader()` — the conventional
|
|
74
|
-
* `
|
|
81
|
+
* `i18n/{language}.json` layout (files in `public/i18n/`, served from the
|
|
82
|
+
* site root). Override with any descriptor
|
|
75
83
|
* (custom path, HTTP endpoint, in-memory). Inline-only apps that want zero
|
|
76
84
|
* network traffic pass `customLoader(async () => ({}))`.
|
|
77
85
|
*/
|
|
@@ -79,6 +87,18 @@ interface RiviniaI18nConfig<T extends string = string> {
|
|
|
79
87
|
readonly switchStrategy?: SwitchStrategy;
|
|
80
88
|
/** Called when a dictionary load fails. The service still falls back safely. */
|
|
81
89
|
readonly onLoadError?: (language: T, error: unknown) => void;
|
|
90
|
+
/**
|
|
91
|
+
* Load the initial language during provider setup (before first paint).
|
|
92
|
+
* SSR waits via `PendingTasks`. Set `false` to skip (e.g. fully inline apps
|
|
93
|
+
* that call `loadTranslations` themselves).
|
|
94
|
+
* @default true
|
|
95
|
+
*/
|
|
96
|
+
readonly preload?: boolean;
|
|
97
|
+
/**
|
|
98
|
+
* Inline per-language dictionaries. Seeded before any network load (zero
|
|
99
|
+
* network + SSR-safe first paint); a successful loader response still wins.
|
|
100
|
+
*/
|
|
101
|
+
readonly translations?: Partial<Record<T, Record<string, unknown>>>;
|
|
82
102
|
/**
|
|
83
103
|
* Match `navigator.languages` against supported ids on first visit
|
|
84
104
|
* (stored preference always wins; base tags match, e.g. `ar-EG` → `ar`).
|
|
@@ -99,14 +119,35 @@ declare function safeGetItem(key: string, strategy: StorageStrategy): string | n
|
|
|
99
119
|
/** SSR-safe write. Silently no-ops off-browser or on denial. */
|
|
100
120
|
declare function safeSetItem(key: string, value: string, strategy: StorageStrategy): void;
|
|
101
121
|
/**
|
|
102
|
-
* Matches the browser language priority list against supported ids.
|
|
103
|
-
*
|
|
104
|
-
* (`ar-EG` → `ar`). Returns
|
|
122
|
+
* Matches the browser language priority list against supported ids, in order.
|
|
123
|
+
* For each browser entry (highest preference first) tries the exact tag, then
|
|
124
|
+
* its base subtag (`ar-EG` → `ar`). Returns the first hit, or `null`.
|
|
105
125
|
* Pure and exported for testing — pass `navigator.languages` in app code.
|
|
106
126
|
*/
|
|
107
127
|
export declare function detectBrowserLanguage<T extends string>(supportedIds: readonly T[], browserLanguages: readonly string[] | undefined): T | null;
|
|
108
128
|
/** Browser language list, `undefined` off-browser (SSR-safe input for detection). */
|
|
109
129
|
export declare function browserLanguages(): readonly string[] | undefined;
|
|
130
|
+
/**
|
|
131
|
+
* Cookie helpers for the `'cookie'` storage strategy. Pure and SSR-testable:
|
|
132
|
+
* the service supplies the header (server `REQUEST`) or `document.cookie`
|
|
133
|
+
* (browser); these functions only parse and serialize.
|
|
134
|
+
*/
|
|
135
|
+
/** Extracts a cookie value by name from a `Cookie` header or `document.cookie`. */
|
|
136
|
+
export declare function parseCookie(header: string | null | undefined, name: string): string | null;
|
|
137
|
+
/** Serializes a language cookie (Lax, root path, one year). */
|
|
138
|
+
export declare function serializeCookie(name: string, value: string, options?: {
|
|
139
|
+
secure?: boolean;
|
|
140
|
+
}): string;
|
|
141
|
+
/**
|
|
142
|
+
* Decides whether the language cookie gets `Secure`: only on `https:`, never
|
|
143
|
+
* on `localhost` (dev TLS included — `Secure` there buys nothing and risks
|
|
144
|
+
* silent persistence loss). Pure and SSR-safe: unknown locations → `false`.
|
|
145
|
+
* The server never writes cookies regardless (app-owned responses).
|
|
146
|
+
*/
|
|
147
|
+
declare function shouldSecureCookie(location: {
|
|
148
|
+
protocol?: string;
|
|
149
|
+
hostname?: string;
|
|
150
|
+
} | null | undefined): boolean;
|
|
110
151
|
/**
|
|
111
152
|
* Minimal ICU MessageFormat subset: `{name}` interpolation, `{n, plural, …}`,
|
|
112
153
|
* `{x, select, …}`, `#` inside plurals, and nesting. Categories resolve via
|
|
@@ -133,12 +174,22 @@ export declare class RiviniaI18n<L extends string = string> {
|
|
|
133
174
|
private readonly _storageKey;
|
|
134
175
|
private readonly _storageStrategy;
|
|
135
176
|
private readonly _autoApplyDirection;
|
|
177
|
+
/**
|
|
178
|
+
* Injected (not global) document: the dir/lang effect renders on the
|
|
179
|
+
* server too, avoiding an RTL first-paint shift on hydration.
|
|
180
|
+
* Declared before any field initializer that reads storage.
|
|
181
|
+
*/
|
|
182
|
+
private readonly _doc;
|
|
183
|
+
/** Present only on the server: used for cookie reads + transfer writes. */
|
|
184
|
+
private readonly _request;
|
|
185
|
+
private readonly _transfer;
|
|
136
186
|
private readonly _currentLanguageId;
|
|
137
187
|
private readonly _languages;
|
|
138
188
|
private readonly _loadedTranslations;
|
|
139
189
|
/**
|
|
140
190
|
* Explicit loader wins; otherwise the conventional JSON layout
|
|
141
|
-
* (`
|
|
191
|
+
* (`i18n/{language}.json` — files in `public/i18n/`, served from the site
|
|
192
|
+
* root — unless the consumer overrides the path).
|
|
142
193
|
* The descriptor still code-splits: the fetch implementation loads only on
|
|
143
194
|
* first resolve.
|
|
144
195
|
*/
|
|
@@ -147,11 +198,14 @@ export declare class RiviniaI18n<L extends string = string> {
|
|
|
147
198
|
private readonly _translationsCache;
|
|
148
199
|
private readonly _inflight;
|
|
149
200
|
/**
|
|
150
|
-
*
|
|
151
|
-
*
|
|
201
|
+
* Out-of-order safety: a response reaches the visible signals only when it
|
|
202
|
+
* belongs to the currently intended language (`_currentLanguageId()`).
|
|
203
|
+
* Everything else stays cached. (A monotonic request token used to guard
|
|
204
|
+
* this, but it over-constrained legitimate same-language loads.)
|
|
152
205
|
*/
|
|
153
|
-
private _requestToken;
|
|
154
206
|
private _applyCount;
|
|
207
|
+
private _initialized;
|
|
208
|
+
private readonly _tasks;
|
|
155
209
|
readonly languageChanged: import("@angular/core").Signal<L>;
|
|
156
210
|
readonly languages: import("@angular/core").Signal<readonly Language<L>[]>;
|
|
157
211
|
readonly currentLanguage: import("@angular/core").Signal<L>;
|
|
@@ -164,8 +218,23 @@ export declare class RiviniaI18n<L extends string = string> {
|
|
|
164
218
|
readonly loadingState: import("@angular/core").Signal<"idle" | "loading" | "error">;
|
|
165
219
|
readonly loadingError: import("@angular/core").Signal<unknown>;
|
|
166
220
|
readonly isLoading: import("@angular/core").Signal<boolean>;
|
|
221
|
+
private readonly _ready;
|
|
222
|
+
/**
|
|
223
|
+
* True once the initial language content is available (inline seed and/or
|
|
224
|
+
* initial load settled) — or immediately when `preload: false` skips setup
|
|
225
|
+
* loading. Gate first-paint skeletons on this, not on `isLoading`.
|
|
226
|
+
*/
|
|
227
|
+
readonly ready: import("@angular/core").Signal<boolean>;
|
|
167
228
|
constructor();
|
|
168
229
|
getLanguage(id: L): Language<L> | undefined;
|
|
230
|
+
/**
|
|
231
|
+
* Runs the provider-setup loading: seeds inline dictionaries, then loads
|
|
232
|
+
* the initial language (unless `preload: false`). Called automatically by
|
|
233
|
+
* the `provideRiviniaI18n` app initializer; call manually only when driving
|
|
234
|
+
* setup yourself. Idempotent. Never rejects (load failures land on
|
|
235
|
+
* `loadingError`/`onLoadError`, inline seeds are preserved).
|
|
236
|
+
*/
|
|
237
|
+
initialize(): Promise<void>;
|
|
169
238
|
translate(key: string, defaultValue?: string, params?: TranslateParams): string;
|
|
170
239
|
translate(key: string, params?: TranslateParams): string;
|
|
171
240
|
translate(translations: Translation<L>): string;
|
|
@@ -178,15 +247,34 @@ export declare class RiviniaI18n<L extends string = string> {
|
|
|
178
247
|
next(): void;
|
|
179
248
|
previous(): void;
|
|
180
249
|
setLanguage(id: L): void;
|
|
181
|
-
/** Preload-first switch: await the dictionary, then flip — no raw-key flash.
|
|
250
|
+
/** Preload-first switch: await the dictionary, then flip — no raw-key flash.
|
|
251
|
+
* A failed load aborts: language, direction and dictionary stay untouched. */
|
|
182
252
|
setLanguageAsync(id: L): Promise<void>;
|
|
183
|
-
/** Number formatting bound to the current language (
|
|
253
|
+
/** Number formatting bound to the current language locale (cached Intl). */
|
|
184
254
|
formatNumber(value: number, options?: Intl.NumberFormatOptions): string;
|
|
185
|
-
/** Date/time formatting bound to the current language (
|
|
255
|
+
/** Date/time formatting bound to the current language locale (cached Intl). */
|
|
186
256
|
formatDate(value: Date | number, options?: Intl.DateTimeFormatOptions): string;
|
|
257
|
+
/** BCP-47 locale driving Intl + ICU plural rules (falls back to the id). */
|
|
258
|
+
readonly locale: import("@angular/core").Signal<string>;
|
|
259
|
+
private readonly _formatters;
|
|
260
|
+
private numberFormatter;
|
|
261
|
+
private dateTimeFormatter;
|
|
187
262
|
private applyLanguage;
|
|
188
263
|
private render;
|
|
189
264
|
private _loadTranslations;
|
|
265
|
+
/**
|
|
266
|
+
* Reads the persisted language. Cookie strategy: server reads the request
|
|
267
|
+
* `Cookie` header (no hydration mismatch), browser reads `document.cookie`.
|
|
268
|
+
* Everything else delegates to the SSR-safe storage helpers.
|
|
269
|
+
*/
|
|
270
|
+
private _readStored;
|
|
271
|
+
/** Persists the language. Server never writes (response cookies are app-owned). */
|
|
272
|
+
private _writeStored;
|
|
273
|
+
private transferKey;
|
|
274
|
+
/** Consumes server-rendered dictionaries so the client never refetches. */
|
|
275
|
+
private readTransfer;
|
|
276
|
+
/** Stores freshly loaded dictionaries for hydration (server only). */
|
|
277
|
+
private writeTransfer;
|
|
190
278
|
private _resolveKey;
|
|
191
279
|
private _resolveInitialLanguage;
|
|
192
280
|
static ɵfac: i0.ɵɵFactoryDeclaration<RiviniaI18n<any>, never>;
|
|
@@ -194,6 +282,8 @@ export declare class RiviniaI18n<L extends string = string> {
|
|
|
194
282
|
}
|
|
195
283
|
/**
|
|
196
284
|
* Configures `@rivinia/i18n` for the application. Call once at bootstrap.
|
|
285
|
+
* Also registers an app initializer that loads the initial language before
|
|
286
|
+
* first paint (opt out with `preload: false`).
|
|
197
287
|
*
|
|
198
288
|
* @example
|
|
199
289
|
* ```ts
|
|
@@ -207,11 +297,35 @@ export declare class RiviniaI18n<L extends string = string> {
|
|
|
207
297
|
* ```
|
|
208
298
|
*/
|
|
209
299
|
export declare function provideRiviniaI18n<L extends string>(config: RiviniaI18nConfig<L>): EnvironmentProviders;
|
|
210
|
-
/** Shorthand for `inject(RiviniaI18n)
|
|
211
|
-
export declare function injectRiviniaI18n(): RiviniaI18n<
|
|
300
|
+
/** Shorthand for `inject(RiviniaI18n)` — preserves the configured language union. */
|
|
301
|
+
export declare function injectRiviniaI18n<L extends string = string>(): RiviniaI18n<L>;
|
|
302
|
+
/**
|
|
303
|
+
* Binds a config and its typed accessors together so `L` is inferred once
|
|
304
|
+
* from the configuration instead of being lost at the injection site.
|
|
305
|
+
*
|
|
306
|
+
* @example
|
|
307
|
+
* ```ts
|
|
308
|
+
* export const i18n = defineRiviniaI18n({
|
|
309
|
+
* defaultLanguage: 'ar',
|
|
310
|
+
* languages: [
|
|
311
|
+
* { id: 'ar', nativeName: 'العربية', dir: 'rtl' },
|
|
312
|
+
* { id: 'en', nativeName: 'English', dir: 'ltr' },
|
|
313
|
+
* ],
|
|
314
|
+
* });
|
|
315
|
+
* // app.config.ts
|
|
316
|
+
* providers: [i18n.provide()]
|
|
317
|
+
* // anywhere (typed 'ar' | 'en'):
|
|
318
|
+
* const lang = i18n.inject();
|
|
319
|
+
* ```
|
|
320
|
+
*/
|
|
321
|
+
export declare function defineRiviniaI18n<L extends string>(config: RiviniaI18nConfig<L>): {
|
|
322
|
+
readonly config: RiviniaI18nConfig<L>;
|
|
323
|
+
provide: () => EnvironmentProviders;
|
|
324
|
+
inject: () => RiviniaI18n<L>;
|
|
325
|
+
};
|
|
212
326
|
/** Progressive-enhancement wrapper around the View Transition API. */
|
|
213
327
|
export declare class ViewTransitionService {
|
|
214
|
-
private readonly
|
|
328
|
+
private readonly _doc;
|
|
215
329
|
run(callback: () => void): void;
|
|
216
330
|
static ɵfac: i0.ɵɵFactoryDeclaration<ViewTransitionService, never>;
|
|
217
331
|
static ɵprov: i0.ɵɵInjectableDeclaration<any>;
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"rivinia-i18n-json-loader.impl-CGzkWfF_.mjs","names":[],"sources":["../../../projects/i18n/src/lib/json-loader.impl.ts"],"sourcesContent":["import type { TranslationLoader } from './loaders';\n\nconst DEFAULT_BASE_PATH = 'assets/i18n';\n\nexport class JsonLoader<L extends string = string> implements TranslationLoader<L> {\n constructor(private readonly _options?: { path?: string }) {}\n\n async load(language: L): Promise<Record<string, unknown>> {\n const basePath = this._options?.path ?? DEFAULT_BASE_PATH;\n const url = `${basePath}/${language}.json`;\n const response = await fetch(url);\n if (!response.ok) {\n throw new Error(`[rivinia/i18n] Failed to load \"${url}\": ${response.statusText}`);\n }\n return response.json();\n }\n}\n"],"mappings":"AAEA,MAAM,oBAAoB;AAE1B,IAAa,aAAb,MAAuB;CACQ;CAA7B,YAA6B,UAA4B;EAA5B,KAAA,WAAA;CAA+B;CAE5D,MAAM,KAAK,UAAW;EAEpB,MAAM,MAAM,GADK,KAAK,UAAU,QAAQ,kBACjB,GAAI,SAAQ;EACnC,MAAM,WAAW,MAAM,MAAM,GAAG;EAChC,IAAI,CAAC,SAAS,IACZ,MAAM,IAAI,MAAM,kCAAkC,IAAG,KAAM,SAAS,YAAY;EAElF,OAAO,SAAS,KAAI;CACtB;AACD"}
|