@hakistack/i18n 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +302 -2
- package/cli/bin.cjs +1411 -0
- package/fesm2022/hakistack-i18n-engine.mjs +394 -0
- package/fesm2022/hakistack-i18n-engine.mjs.map +1 -0
- package/fesm2022/hakistack-i18n.mjs +685 -0
- package/fesm2022/hakistack-i18n.mjs.map +1 -0
- package/package.json +68 -4
- package/schematics/collection.json +15 -0
- package/schematics/ng-add/index.cjs +276 -0
- package/schematics/ng-add/index.cjs.map +1 -0
- package/schematics/ng-add/schema.js +3 -0
- package/schematics/ng-add/schema.js.map +1 -0
- package/schematics/ng-add/schema.json +37 -0
- package/types/hakistack-i18n-engine.d.ts +324 -0
- package/types/hakistack-i18n.d.ts +508 -0
|
@@ -0,0 +1,685 @@
|
|
|
1
|
+
import { buildLanguageTree, buildScopedTree, buildKeysTree } from '@hakistack/i18n/engine';
|
|
2
|
+
export { SOURCE_LANG, TRANSLATION_BRAND, buildEagerTree, buildKeysTree, buildLanguageTree, buildScopedTree, defineTranslations, extractLanguage, findKeyConflicts, getTranslation, isTranslationValue, mergeKeys, normalizeScope, scopeToFilesystemPath, setAtScope, t } from '@hakistack/i18n/engine';
|
|
3
|
+
import * as i0 from '@angular/core';
|
|
4
|
+
import { Injectable, InjectionToken, inject, PendingTasks, DOCUMENT, REQUEST, signal, computed, isDevMode, provideAppInitializer, makeEnvironmentProviders, TemplateRef, ViewContainerRef, Directive } from '@angular/core';
|
|
5
|
+
import { TranslocoService, provideTransloco, provideTranslocoInterceptor, provideTranslocoMissingHandler, translateSignal as translateSignal$1 } from '@jsverse/transloco';
|
|
6
|
+
export { translateObjectSignal } from '@jsverse/transloco';
|
|
7
|
+
import { HttpClient } from '@angular/common/http';
|
|
8
|
+
import { from, firstValueFrom, of, switchMap, map, catchError } from 'rxjs';
|
|
9
|
+
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Strips translator-comment siblings before translations enter Transloco's store.
|
|
13
|
+
*
|
|
14
|
+
* Translator-context comments (added via `t('en', { es: '…' }, { comment })`)
|
|
15
|
+
* are written into the generated JSON as a `<key>.comment` sibling of their
|
|
16
|
+
* key. The registry loader never emits them; this interceptor removes them
|
|
17
|
+
* when the JSON is served over HTTP.
|
|
18
|
+
*
|
|
19
|
+
* Transloco hands this hook the **flattened** translation, so a real key whose
|
|
20
|
+
* last segment is `comment` (`post.comment`) also ends in `.comment`. The two
|
|
21
|
+
* are told apart structurally: a comment sibling `x.comment` only exists next
|
|
22
|
+
* to a translation `x`, while a real `post.comment` means `post` is a group and
|
|
23
|
+
* therefore never a flat key itself.
|
|
24
|
+
*/
|
|
25
|
+
class TranslocoCommentInterceptor {
|
|
26
|
+
preSaveTranslation(translation) {
|
|
27
|
+
return stripCommentKeys(translation);
|
|
28
|
+
}
|
|
29
|
+
preSaveTranslationKey(_key, value) {
|
|
30
|
+
return value;
|
|
31
|
+
}
|
|
32
|
+
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.10", ngImport: i0, type: TranslocoCommentInterceptor, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
|
|
33
|
+
static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.2.10", ngImport: i0, type: TranslocoCommentInterceptor });
|
|
34
|
+
}
|
|
35
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.10", ngImport: i0, type: TranslocoCommentInterceptor, decorators: [{
|
|
36
|
+
type: Injectable
|
|
37
|
+
}] });
|
|
38
|
+
const COMMENT_SUFFIX = '.comment';
|
|
39
|
+
/** Exported for tests. Expects a flattened translation (what Transloco passes). */
|
|
40
|
+
function stripCommentKeys(flat) {
|
|
41
|
+
const out = {};
|
|
42
|
+
for (const [key, value] of Object.entries(flat)) {
|
|
43
|
+
const commentOf = key.endsWith(COMMENT_SUFFIX) ? key.slice(0, -COMMENT_SUFFIX.length) : null;
|
|
44
|
+
if (commentOf !== null && typeof flat[commentOf] === 'string')
|
|
45
|
+
continue;
|
|
46
|
+
out[key] = value;
|
|
47
|
+
}
|
|
48
|
+
return out;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* The merged keys tree (`TK`) provided by {@link provideI18n}.
|
|
53
|
+
*
|
|
54
|
+
* Holds the consumer's nested object of dot-path key strings — the exact shape
|
|
55
|
+
* the scanner emits as the typed `TK` literal. `TranslateDirectiveBase` injects
|
|
56
|
+
* this instead of importing `TK` directly, so the library never depends on a
|
|
57
|
+
* consumer-generated symbol. Casing of keys is irrelevant at runtime: the
|
|
58
|
+
* directive reads string leaves and calls `transloco.translate(leaf)`.
|
|
59
|
+
*/
|
|
60
|
+
const I18N_KEYS = new InjectionToken('I18N_KEYS');
|
|
61
|
+
/** Fully-resolved runtime config, shared with the loader and missing handler. */
|
|
62
|
+
const I18N_RUNTIME_CONFIG = new InjectionToken('I18N_RUNTIME_CONFIG');
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* HTTP-based translation loader — fetches `<assetsPath>/<lang>.json` over HTTP.
|
|
66
|
+
*
|
|
67
|
+
* Selected via `provideI18n({ loader: 'http' })`. Consumes the same JSON files
|
|
68
|
+
* the generator emits, so switching loaders requires no other change.
|
|
69
|
+
*
|
|
70
|
+
* **Prefer the registry loader unless ANY of these are true:**
|
|
71
|
+
* - Translation payload exceeds ~50KB per language (JS bundle bloat matters).
|
|
72
|
+
* - The translation team needs to push updates without a code deploy.
|
|
73
|
+
* - 5+ locales where CDN-cached per-locale loading matters.
|
|
74
|
+
* - `provideTranslocoScope` lazy loading is adopted per route.
|
|
75
|
+
*
|
|
76
|
+
* **Costs:** reintroduces the runtime HTTP fetch (network race, offline issues),
|
|
77
|
+
* SSR needs absolute URLs, and the "JSON drifted from TS" mode returns unless
|
|
78
|
+
* the generator runs in the deploy pipeline.
|
|
79
|
+
*/
|
|
80
|
+
class TranslocoHttpLoader {
|
|
81
|
+
http = inject(HttpClient);
|
|
82
|
+
config = inject(I18N_RUNTIME_CONFIG);
|
|
83
|
+
getTranslation(lang) {
|
|
84
|
+
// Transloco passes scoped requests as `<scope>/<lang>`; our generator emits
|
|
85
|
+
// dotted scopes as nested dirs (`administration.users` → `administration/users/<lang>.json`),
|
|
86
|
+
// so map dots to slashes. Lang codes never contain dots, so this is safe.
|
|
87
|
+
const path = lang.replace(/\./g, '/');
|
|
88
|
+
return this.http.get(`${this.config.assetsPath}/${path}.json`);
|
|
89
|
+
}
|
|
90
|
+
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.10", ngImport: i0, type: TranslocoHttpLoader, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
|
|
91
|
+
static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.2.10", ngImport: i0, type: TranslocoHttpLoader });
|
|
92
|
+
}
|
|
93
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.10", ngImport: i0, type: TranslocoHttpLoader, decorators: [{
|
|
94
|
+
type: Injectable
|
|
95
|
+
}] });
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Translation loader backed by the generated `TRANSLATIONS` loaders: each
|
|
99
|
+
* language (and each scoped scope) is a separate chunk, dynamically imported
|
|
100
|
+
* the first time it is needed.
|
|
101
|
+
*
|
|
102
|
+
* The import runs as an Angular pending task, so server rendering waits for it
|
|
103
|
+
* and serializes translated HTML (no flash or hydration mismatch).
|
|
104
|
+
*/
|
|
105
|
+
class TranslocoLazyLoader {
|
|
106
|
+
config = inject(I18N_RUNTIME_CONFIG);
|
|
107
|
+
pendingTasks = inject(PendingTasks);
|
|
108
|
+
getTranslation(input) {
|
|
109
|
+
// Transloco requests scopes as `<scope>/<lang>` (e.g. `'admin/users/es'`); plain `'es'` is the root.
|
|
110
|
+
const slash = input.lastIndexOf('/');
|
|
111
|
+
const lang = slash === -1 ? input : input.slice(slash + 1);
|
|
112
|
+
const translations = this.config.translations;
|
|
113
|
+
const table = slash === -1 ? translations?.root : translations?.scopes?.[input.slice(0, slash)];
|
|
114
|
+
const load = table?.[lang];
|
|
115
|
+
if (!load) {
|
|
116
|
+
// Rejecting lets Transloco fall back (fallback language / missing handler).
|
|
117
|
+
return from(Promise.reject(new Error(`@hakistack/i18n: no translations generated for '${input}'.`)));
|
|
118
|
+
}
|
|
119
|
+
const done = this.pendingTasks.add();
|
|
120
|
+
return from(load()
|
|
121
|
+
.then((mod) => mod.default)
|
|
122
|
+
.finally(done));
|
|
123
|
+
}
|
|
124
|
+
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.10", ngImport: i0, type: TranslocoLazyLoader, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
|
|
125
|
+
static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.2.10", ngImport: i0, type: TranslocoLazyLoader });
|
|
126
|
+
}
|
|
127
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.10", ngImport: i0, type: TranslocoLazyLoader, decorators: [{
|
|
128
|
+
type: Injectable
|
|
129
|
+
}] });
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* Locale helpers built on the standard `Intl` APIs (no locale data shipped).
|
|
133
|
+
*
|
|
134
|
+
* A *language* is what the translations are written in (`es`); a *locale* is
|
|
135
|
+
* the BCP 47 tag that drives formatting and `<html lang>` (`es-PR`). They
|
|
136
|
+
* default to the same tag but are configured separately per language option.
|
|
137
|
+
*/
|
|
138
|
+
/** Scripts written right-to-left (ISO 15924). */
|
|
139
|
+
const RTL_SCRIPTS = new Set(['Arab', 'Hebr', 'Thaa', 'Syrc', 'Nkoo', 'Adlm', 'Rohg', 'Mand', 'Samr', 'Mend']);
|
|
140
|
+
/**
|
|
141
|
+
* Text direction of a BCP 47 tag: `'rtl'` for Arabic, Hebrew, Persian, Urdu,
|
|
142
|
+
* Sorani (`ckb`), `pa-Arab`… and `'ltr'` otherwise. Uses `Intl.Locale` text
|
|
143
|
+
* info when the runtime has it, else the likely script (`maximize()`).
|
|
144
|
+
*/
|
|
145
|
+
function textDirection(tag) {
|
|
146
|
+
try {
|
|
147
|
+
const locale = new Intl.Locale(tag);
|
|
148
|
+
const direction = locale.getTextInfo?.().direction ?? locale.textInfo?.direction;
|
|
149
|
+
if (direction === 'rtl' || direction === 'ltr')
|
|
150
|
+
return direction;
|
|
151
|
+
const script = locale.maximize().script;
|
|
152
|
+
return script && RTL_SCRIPTS.has(script) ? 'rtl' : 'ltr';
|
|
153
|
+
}
|
|
154
|
+
catch {
|
|
155
|
+
return 'ltr'; // not a valid tag
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
/** Language tags of an `Accept-Language` header, most preferred first (`q=0` dropped). */
|
|
159
|
+
function parseAcceptLanguage(header) {
|
|
160
|
+
if (!header)
|
|
161
|
+
return [];
|
|
162
|
+
return header
|
|
163
|
+
.split(',')
|
|
164
|
+
.map((part, index) => {
|
|
165
|
+
const [tag, ...attrs] = part.trim().split(';');
|
|
166
|
+
const q = attrs.map((a) => a.trim()).find((a) => a.startsWith('q='));
|
|
167
|
+
return { tag: tag.trim(), q: q ? Number(q.slice(2)) : 1, index };
|
|
168
|
+
})
|
|
169
|
+
.filter((entry) => entry.tag && entry.tag !== '*' && entry.q > 0)
|
|
170
|
+
.sort((a, b) => b.q - a.q || a.index - b.index)
|
|
171
|
+
.map((entry) => entry.tag);
|
|
172
|
+
}
|
|
173
|
+
/**
|
|
174
|
+
* Best available language for a preference list: an exact tag match first
|
|
175
|
+
* (case-insensitive), then the same base language (`fr-CA` → `fr`, `es` → `es-MX`).
|
|
176
|
+
*/
|
|
177
|
+
function negotiateLanguage(preferred, available) {
|
|
178
|
+
const base = (tag) => tag.toLowerCase().split('-')[0];
|
|
179
|
+
for (const tag of preferred) {
|
|
180
|
+
const exact = available.find((a) => a.toLowerCase() === tag.toLowerCase());
|
|
181
|
+
if (exact)
|
|
182
|
+
return exact;
|
|
183
|
+
const sameBase = available.find((a) => base(a) === base(tag));
|
|
184
|
+
if (sameBase)
|
|
185
|
+
return sameBase;
|
|
186
|
+
}
|
|
187
|
+
return null;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/** Name of the localStorage entry and of the cookie that remember the chosen language. */
|
|
191
|
+
const STORAGE_KEY = 'hakistack_i18n_lang';
|
|
192
|
+
const COOKIE_MAX_AGE = 60 * 60 * 24 * 365;
|
|
193
|
+
/**
|
|
194
|
+
* App-level active-language service on top of `TranslocoService`:
|
|
195
|
+
*
|
|
196
|
+
* - `language()` — the translation language; `locale()` — its BCP 47
|
|
197
|
+
* formatting locale (`es` + `locale: 'es-PR'`); `dir()` — `'ltr' | 'rtl'`.
|
|
198
|
+
* All follow Transloco's active language however it changes.
|
|
199
|
+
* - `<html lang>` (the locale) and `<html dir>` are kept in sync, on the
|
|
200
|
+
* server too.
|
|
201
|
+
* - {@link setLanguage} loads, activates and remembers a language
|
|
202
|
+
* (`localStorage`, or a cookie that SSR can read — `persistLanguage`).
|
|
203
|
+
* - On bootstrap ({@link initializeLanguage}, wired by `provideI18n` when
|
|
204
|
+
* `persistLanguage` or `detectLanguage` is set): the remembered language,
|
|
205
|
+
* else the best match for `Accept-Language` / `navigator.languages`
|
|
206
|
+
* (`detectLanguage`), else `defaultLang`.
|
|
207
|
+
*
|
|
208
|
+
* One instance per application (per request during SSR): no state is shared
|
|
209
|
+
* between users.
|
|
210
|
+
*
|
|
211
|
+
* ```ts
|
|
212
|
+
* private readonly i18nLang = inject(LanguageService);
|
|
213
|
+
* switch(lang: string) { this.i18nLang.setLanguage(lang); }
|
|
214
|
+
* ```
|
|
215
|
+
*/
|
|
216
|
+
class LanguageService {
|
|
217
|
+
transloco = inject(TranslocoService);
|
|
218
|
+
document = inject(DOCUMENT);
|
|
219
|
+
request = inject(REQUEST, { optional: true });
|
|
220
|
+
config = inject(I18N_RUNTIME_CONFIG, { optional: true });
|
|
221
|
+
defaultLanguage = this.transloco.getDefaultLang();
|
|
222
|
+
persistence = this.config?.persistence ?? 'local-storage';
|
|
223
|
+
/** Available languages from Transloco config. */
|
|
224
|
+
availableLanguages = this.transloco.getAvailableLangs();
|
|
225
|
+
/** Current active translation language (kept in sync with Transloco). */
|
|
226
|
+
language = signal(this.transloco.getActiveLang(), ...(ngDevMode ? [{ debugName: "language" }] : /* istanbul ignore next */ []));
|
|
227
|
+
/** Formatting locale of the active language (its `locale` option, else its id) — for `Intl.*` and locale pipes. */
|
|
228
|
+
locale = computed(() => this.option(this.language())?.locale ?? this.language(), ...(ngDevMode ? [{ debugName: "locale" }] : /* istanbul ignore next */ []));
|
|
229
|
+
/** Text direction of the active language (its `dir` option, else derived from the locale). */
|
|
230
|
+
dir = computed(() => this.option(this.language())?.dir ?? textDirection(this.locale()), ...(ngDevMode ? [{ debugName: "dir" }] : /* istanbul ignore next */ []));
|
|
231
|
+
constructor() {
|
|
232
|
+
this.transloco.langChanges$.pipe(takeUntilDestroyed()).subscribe((lang) => {
|
|
233
|
+
this.language.set(lang);
|
|
234
|
+
const html = this.document.documentElement;
|
|
235
|
+
html.setAttribute('lang', this.locale());
|
|
236
|
+
html.setAttribute('dir', this.dir());
|
|
237
|
+
});
|
|
238
|
+
}
|
|
239
|
+
/**
|
|
240
|
+
* Bootstrap: the remembered language, else (with `detectLanguage`) the user's
|
|
241
|
+
* preference, else the default. Nothing is written: only an explicit
|
|
242
|
+
* {@link setLanguage} choice is remembered, so detection keeps following the
|
|
243
|
+
* user's preferences until they pick a language.
|
|
244
|
+
*/
|
|
245
|
+
async initializeLanguage() {
|
|
246
|
+
const remembered = this.rememberedLanguage();
|
|
247
|
+
const detected = remembered ?? (this.config?.detectLanguage ? this.preferredLanguage() : null);
|
|
248
|
+
await this.setLanguage(detected ?? this.defaultLanguage, { remember: false });
|
|
249
|
+
}
|
|
250
|
+
/**
|
|
251
|
+
* Load and activate `lang`, then remember it. Languages that are not in the
|
|
252
|
+
* configured `languages` list are ignored (with a dev-mode warning) so they
|
|
253
|
+
* can never become the active or stored language.
|
|
254
|
+
*/
|
|
255
|
+
async setLanguage(lang, options = {}) {
|
|
256
|
+
if (!this.isAvailable(lang)) {
|
|
257
|
+
if (isDevMode())
|
|
258
|
+
console.warn(`[@hakistack/i18n] setLanguage('${lang}') ignored — not one of the configured languages.`);
|
|
259
|
+
return;
|
|
260
|
+
}
|
|
261
|
+
try {
|
|
262
|
+
await firstValueFrom(this.transloco.load(lang));
|
|
263
|
+
this.transloco.setActiveLang(lang);
|
|
264
|
+
if (options.remember ?? true)
|
|
265
|
+
this.remember(lang);
|
|
266
|
+
}
|
|
267
|
+
catch (error) {
|
|
268
|
+
console.warn(`Failed to load language '${lang}', falling back to default`, error);
|
|
269
|
+
if (lang !== this.defaultLanguage) {
|
|
270
|
+
await this.setLanguage(this.defaultLanguage);
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
/** Is `lang` one of the configured available languages? */
|
|
275
|
+
isAvailable(lang) {
|
|
276
|
+
return this.languageIds().includes(lang);
|
|
277
|
+
}
|
|
278
|
+
languageIds() {
|
|
279
|
+
return this.availableLanguages.map((l) => (typeof l === 'string' ? l : l.id));
|
|
280
|
+
}
|
|
281
|
+
option(lang) {
|
|
282
|
+
return this.config?.languages.find((l) => l.id === lang);
|
|
283
|
+
}
|
|
284
|
+
/**
|
|
285
|
+
* The remembered language when it is still available — never a stale or
|
|
286
|
+
* garbage value. `null` when nothing (usable) is stored.
|
|
287
|
+
*/
|
|
288
|
+
rememberedLanguage() {
|
|
289
|
+
const stored = this.persistence === 'cookie' ? this.readCookie() : this.readLocalStorage();
|
|
290
|
+
return stored && this.isAvailable(stored) ? stored : null;
|
|
291
|
+
}
|
|
292
|
+
/** Best configured language for the request's `Accept-Language` (SSR) or `navigator.languages` (browser). */
|
|
293
|
+
preferredLanguage() {
|
|
294
|
+
const preferred = this.request
|
|
295
|
+
? parseAcceptLanguage(this.request.headers.get('accept-language'))
|
|
296
|
+
: typeof navigator !== 'undefined'
|
|
297
|
+
? [...(navigator.languages ?? [navigator.language])].filter(Boolean)
|
|
298
|
+
: [];
|
|
299
|
+
return negotiateLanguage(preferred, this.languageIds());
|
|
300
|
+
}
|
|
301
|
+
remember(lang) {
|
|
302
|
+
if (this.persistence === 'cookie')
|
|
303
|
+
this.writeCookie(lang);
|
|
304
|
+
else
|
|
305
|
+
this.writeLocalStorage(lang);
|
|
306
|
+
}
|
|
307
|
+
/** The request's `Cookie` header during SSR, `document.cookie` in the browser. */
|
|
308
|
+
readCookie() {
|
|
309
|
+
const header = this.request ? this.request.headers.get('cookie') : this.document.cookie;
|
|
310
|
+
for (const part of (header ?? '').split(';')) {
|
|
311
|
+
const [name, ...value] = part.trim().split('=');
|
|
312
|
+
if (name === STORAGE_KEY)
|
|
313
|
+
return decodeURIComponent(value.join('='));
|
|
314
|
+
}
|
|
315
|
+
return null;
|
|
316
|
+
}
|
|
317
|
+
writeCookie(lang) {
|
|
318
|
+
if (this.request)
|
|
319
|
+
return; // server: the browser keeps the cookie it sent
|
|
320
|
+
const secure = this.document.location?.protocol === 'https:' ? '; Secure' : '';
|
|
321
|
+
this.document.cookie = `${STORAGE_KEY}=${encodeURIComponent(lang)}; Path=/; Max-Age=${COOKIE_MAX_AGE}; SameSite=Lax${secure}`;
|
|
322
|
+
}
|
|
323
|
+
readLocalStorage() {
|
|
324
|
+
try {
|
|
325
|
+
return typeof localStorage === 'undefined' ? null : localStorage.getItem(STORAGE_KEY);
|
|
326
|
+
}
|
|
327
|
+
catch (error) {
|
|
328
|
+
console.warn('Failed to read language from localStorage:', error);
|
|
329
|
+
return null;
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
writeLocalStorage(lang) {
|
|
333
|
+
try {
|
|
334
|
+
if (typeof localStorage !== 'undefined')
|
|
335
|
+
localStorage.setItem(STORAGE_KEY, lang);
|
|
336
|
+
}
|
|
337
|
+
catch (error) {
|
|
338
|
+
console.warn('Failed to save language to localStorage:', error);
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.10", ngImport: i0, type: LanguageService, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
|
|
342
|
+
static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.2.10", ngImport: i0, type: LanguageService, providedIn: 'root' });
|
|
343
|
+
}
|
|
344
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.10", ngImport: i0, type: LanguageService, decorators: [{
|
|
345
|
+
type: Injectable,
|
|
346
|
+
args: [{ providedIn: 'root' }]
|
|
347
|
+
}], ctorParameters: () => [] });
|
|
348
|
+
|
|
349
|
+
/**
|
|
350
|
+
* Missing-key handler that surfaces failures in dev mode.
|
|
351
|
+
*
|
|
352
|
+
* Default Transloco behavior returns `''` for missing keys, making typos
|
|
353
|
+
* invisible in the UI. With `missingKeyInDev: 'show'` (the default) this returns
|
|
354
|
+
* `[scope.key]` in dev so missing-key bugs jump out immediately. In production,
|
|
355
|
+
* behavior is always `''`.
|
|
356
|
+
*
|
|
357
|
+
* Providing a handler replaces Transloco's default one, which is where the
|
|
358
|
+
* `missingHandler.logMissingKey` console warning lives — so this handler warns
|
|
359
|
+
* too (once per key, outside prod mode).
|
|
360
|
+
*
|
|
361
|
+
* The build-time validator remains the source of truth for *static* keys; this
|
|
362
|
+
* handler catches dynamic / `selectTranslate(varKey)` / typo cases.
|
|
363
|
+
*/
|
|
364
|
+
class TranslocoVisibleMissingHandler {
|
|
365
|
+
config = inject(I18N_RUNTIME_CONFIG);
|
|
366
|
+
warned = new Set();
|
|
367
|
+
handle(key, data) {
|
|
368
|
+
if (data.missingHandler?.logMissingKey && !data.prodMode && !this.warned.has(key)) {
|
|
369
|
+
this.warned.add(key);
|
|
370
|
+
console.warn(`[@hakistack/i18n] Missing translation for '${key}' (${data.activeLang})`);
|
|
371
|
+
}
|
|
372
|
+
if (isDevMode() && this.config.missingKeyInDev === 'show') {
|
|
373
|
+
return `[${key}]`;
|
|
374
|
+
}
|
|
375
|
+
return '';
|
|
376
|
+
}
|
|
377
|
+
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.10", ngImport: i0, type: TranslocoVisibleMissingHandler, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
|
|
378
|
+
static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.2.10", ngImport: i0, type: TranslocoVisibleMissingHandler });
|
|
379
|
+
}
|
|
380
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.10", ngImport: i0, type: TranslocoVisibleMissingHandler, decorators: [{
|
|
381
|
+
type: Injectable
|
|
382
|
+
}] });
|
|
383
|
+
|
|
384
|
+
/** Translator comments are for the JSON files only; the runtime store never needs them. */
|
|
385
|
+
const NO_COMMENTS = { comments: false };
|
|
386
|
+
/**
|
|
387
|
+
* Translation loader backed by the in-memory module registry.
|
|
388
|
+
*
|
|
389
|
+
* Reads directly from the registry passed to {@link provideI18n} and assembles
|
|
390
|
+
* a per-language tree on demand. No HTTP request, no `assets/i18n/<lang>.json`
|
|
391
|
+
* fetch at runtime — those JSON files are translator-facing build artifacts only.
|
|
392
|
+
*
|
|
393
|
+
* Wins:
|
|
394
|
+
* - Synchronous-after-import. No race between bootstrap and translation load.
|
|
395
|
+
* - Single source of truth at runtime — the "JSON drifted from TS" failure
|
|
396
|
+
* mode becomes structurally impossible.
|
|
397
|
+
* - Works offline; no service-worker config needed for i18n.
|
|
398
|
+
* - SSR-safe: no absolute-URL gotchas.
|
|
399
|
+
*/
|
|
400
|
+
class TranslocoRegistryLoader {
|
|
401
|
+
config = inject(I18N_RUNTIME_CONFIG);
|
|
402
|
+
getTranslation(input) {
|
|
403
|
+
// Transloco constructs scoped requests as `<scope>/<lang>` (e.g. `'home/en'`).
|
|
404
|
+
// Plain `'en'` is the unscoped root request.
|
|
405
|
+
const slashIdx = input.lastIndexOf('/');
|
|
406
|
+
if (slashIdx === -1) {
|
|
407
|
+
// No scope provider in play — return the full tree (eager + every scoped
|
|
408
|
+
// module merged at its scope path).
|
|
409
|
+
return of(buildLanguageTree(this.config.registry, input, this.config.fallbackLang, NO_COMMENTS));
|
|
410
|
+
}
|
|
411
|
+
// Scoped request — return ONLY that scope's data, unwrapped (Transloco
|
|
412
|
+
// namespaces it back under the scope key in its internal store). The scope
|
|
413
|
+
// arrives in slash form (`administration/users`); `buildScopedTree`
|
|
414
|
+
// normalizes it against the registry's dotted scopes.
|
|
415
|
+
const scope = input.substring(0, slashIdx);
|
|
416
|
+
const lang = input.substring(slashIdx + 1);
|
|
417
|
+
const tree = buildScopedTree(this.config.registry, lang, this.config.fallbackLang, scope, NO_COMMENTS);
|
|
418
|
+
return of((tree ?? {}));
|
|
419
|
+
}
|
|
420
|
+
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.10", ngImport: i0, type: TranslocoRegistryLoader, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
|
|
421
|
+
static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.2.10", ngImport: i0, type: TranslocoRegistryLoader });
|
|
422
|
+
}
|
|
423
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.10", ngImport: i0, type: TranslocoRegistryLoader, decorators: [{
|
|
424
|
+
type: Injectable
|
|
425
|
+
}] });
|
|
426
|
+
|
|
427
|
+
/**
|
|
428
|
+
* One-call i18n setup for a consumer app.
|
|
429
|
+
*
|
|
430
|
+
* Collapses what used to be a hand-written `provideTransloco(...)` config plus
|
|
431
|
+
* a list of custom hooks (`provideTranslocoInterceptor`,
|
|
432
|
+
* `provideTranslocoMissingHandler`) into a single provider. Wires:
|
|
433
|
+
* - Transloco with the registry, lazy (per-language chunks) or HTTP loader.
|
|
434
|
+
* - The comment-stripping interceptor + the visible missing-key handler.
|
|
435
|
+
* - `I18N_KEYS` (the runtime `TK` tree) for the translate directive.
|
|
436
|
+
* - `I18N_RUNTIME_CONFIG` (resolved defaults) for the loader/handler.
|
|
437
|
+
* - Optional `LanguageService` localStorage restore on bootstrap.
|
|
438
|
+
*
|
|
439
|
+
* The consumer still imports the generated typed directive and
|
|
440
|
+
* `translateSignal`/`TK` from their local barrel.
|
|
441
|
+
*
|
|
442
|
+
* @example
|
|
443
|
+
* export const appConfig: ApplicationConfig = {
|
|
444
|
+
* providers: [
|
|
445
|
+
* provideI18n({
|
|
446
|
+
* registry: ALL_TRANSLATIONS,
|
|
447
|
+
* languages: [
|
|
448
|
+
* { id: 'en', label: 'English' },
|
|
449
|
+
* { id: 'es', label: 'Español' },
|
|
450
|
+
* ],
|
|
451
|
+
* defaultLang: 'es',
|
|
452
|
+
* fallbackLang: 'en',
|
|
453
|
+
* persistLanguage: true,
|
|
454
|
+
* }),
|
|
455
|
+
* ],
|
|
456
|
+
* };
|
|
457
|
+
*
|
|
458
|
+
* @example Lazy: one chunk per language, no translation in the initial bundle
|
|
459
|
+
* import { TK } from './i18n/definitions/keys.generated';
|
|
460
|
+
* import { TRANSLATIONS } from './i18n/definitions/translations.generated';
|
|
461
|
+
*
|
|
462
|
+
* provideI18n({ keys: TK, translations: TRANSLATIONS, languages: [...] })
|
|
463
|
+
*/
|
|
464
|
+
function provideI18n(config) {
|
|
465
|
+
const defaultLang = config.defaultLang ?? config.languages[0]?.id;
|
|
466
|
+
if (!defaultLang) {
|
|
467
|
+
throw new Error('provideI18n: `languages` must contain at least one entry (or set `defaultLang`).');
|
|
468
|
+
}
|
|
469
|
+
if (!config.keys && !config.registry) {
|
|
470
|
+
throw new Error('provideI18n: pass `keys` (the generated TK) or `registry` (ALL_TRANSLATIONS).');
|
|
471
|
+
}
|
|
472
|
+
const loader = config.loader ?? (config.translations ? 'lazy' : 'registry');
|
|
473
|
+
if (loader === 'registry' && !config.registry) {
|
|
474
|
+
throw new Error("provideI18n: the 'registry' loader needs `registry` (ALL_TRANSLATIONS). For lazy loading pass `translations` (TRANSLATIONS).");
|
|
475
|
+
}
|
|
476
|
+
if (loader === 'lazy' && !config.translations) {
|
|
477
|
+
throw new Error("provideI18n: the 'lazy' loader needs `translations` (the generated TRANSLATIONS).");
|
|
478
|
+
}
|
|
479
|
+
const resolved = {
|
|
480
|
+
registry: config.registry ?? [],
|
|
481
|
+
translations: config.translations ?? null,
|
|
482
|
+
languages: config.languages,
|
|
483
|
+
persistence: config.persistLanguage === 'cookie' ? 'cookie' : 'local-storage',
|
|
484
|
+
detectLanguage: !!config.detectLanguage,
|
|
485
|
+
defaultLang,
|
|
486
|
+
fallbackLang: config.fallbackLang ?? 'en',
|
|
487
|
+
missingKeyInDev: config.missingKeyInDev ?? 'show',
|
|
488
|
+
assetsPath: (config.assetsPath ?? '/assets/i18n').replace(/\/$/, ''),
|
|
489
|
+
};
|
|
490
|
+
const loaderClass = { registry: TranslocoRegistryLoader, lazy: TranslocoLazyLoader, http: TranslocoHttpLoader }[loader];
|
|
491
|
+
const providers = [
|
|
492
|
+
provideTransloco({
|
|
493
|
+
config: {
|
|
494
|
+
availableLangs: config.languages,
|
|
495
|
+
defaultLang,
|
|
496
|
+
fallbackLang: resolved.fallbackLang,
|
|
497
|
+
reRenderOnLangChange: true,
|
|
498
|
+
prodMode: !isDevMode(),
|
|
499
|
+
missingHandler: {
|
|
500
|
+
// Every generated tree (registry, lazy modules, JSON) already resolves each key to the
|
|
501
|
+
// fallback language, so Transloco must not load the fallback language as well.
|
|
502
|
+
useFallbackTranslation: false,
|
|
503
|
+
logMissingKey: isDevMode(),
|
|
504
|
+
},
|
|
505
|
+
},
|
|
506
|
+
loader: loaderClass,
|
|
507
|
+
}),
|
|
508
|
+
provideTranslocoInterceptor(TranslocoCommentInterceptor),
|
|
509
|
+
provideTranslocoMissingHandler(TranslocoVisibleMissingHandler),
|
|
510
|
+
{ provide: I18N_RUNTIME_CONFIG, useValue: resolved },
|
|
511
|
+
{ provide: I18N_KEYS, useValue: config.keys ?? buildKeysTree(config.registry ?? []) },
|
|
512
|
+
];
|
|
513
|
+
if (config.persistLanguage || config.detectLanguage) {
|
|
514
|
+
providers.push(provideAppInitializer(() => {
|
|
515
|
+
const languageService = inject(LanguageService);
|
|
516
|
+
return languageService.initializeLanguage();
|
|
517
|
+
}));
|
|
518
|
+
}
|
|
519
|
+
return makeEnvironmentProviders(providers);
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
// =============================================================================
|
|
523
|
+
// Directive base
|
|
524
|
+
// =============================================================================
|
|
525
|
+
/**
|
|
526
|
+
* Untyped/generic core of the structural translate directive.
|
|
527
|
+
*
|
|
528
|
+
* The library can't reference a consumer-generated `TK`, so this base injects
|
|
529
|
+
* the keys object via the {@link I18N_KEYS} token (provided by `provideI18n`)
|
|
530
|
+
* and builds its lazy proxy over it. Casing is irrelevant — it reads string
|
|
531
|
+
* leaves and calls `transloco.translate(leaf)`.
|
|
532
|
+
*
|
|
533
|
+
* Consumers don't use this directly. The codegen emits a small wrapper that
|
|
534
|
+
* extends this base, declares the `<selector>Prefix` input (Angular's
|
|
535
|
+
* microsyntax binds `*appTranslate="let t; prefix: 'x'"` to `appTranslatePrefix`,
|
|
536
|
+
* so the input's name must follow the configured selector), and pins the
|
|
537
|
+
* template context type to *their* `typeof TK`:
|
|
538
|
+
*
|
|
539
|
+
* ```ts
|
|
540
|
+
* import { TK } from './definitions';
|
|
541
|
+
* @Directive({ selector: '[appTranslate]' })
|
|
542
|
+
* export class AppTranslateDirective extends TranslateDirectiveBase {
|
|
543
|
+
* readonly appTranslatePrefix = input<string | undefined>(undefined);
|
|
544
|
+
* protected override prefix(): string | undefined {
|
|
545
|
+
* return this.appTranslatePrefix();
|
|
546
|
+
* }
|
|
547
|
+
* static ngTemplateContextGuard(_d: AppTranslateDirective, ctx: unknown): ctx is TranslateContext<typeof TK> {
|
|
548
|
+
* return true;
|
|
549
|
+
* }
|
|
550
|
+
* }
|
|
551
|
+
* ```
|
|
552
|
+
*
|
|
553
|
+
* **Loading:** the directive loads the active language itself (like
|
|
554
|
+
* Transloco's own `*transloco`), creates its view once that load settles, and
|
|
555
|
+
* re-renders after every language switch has loaded — no app initializer or
|
|
556
|
+
* other translation consumer is required.
|
|
557
|
+
*
|
|
558
|
+
* **Optimizations:**
|
|
559
|
+
* - JS Proxy for lazy property access (no upfront tree building).
|
|
560
|
+
* - Proxy objects cached via WeakMap; translate fns cached per key via Map.
|
|
561
|
+
* - One `markForCheck` per language change; no work in between.
|
|
562
|
+
*/
|
|
563
|
+
class TranslateDirectiveBase {
|
|
564
|
+
transloco = inject(TranslocoService);
|
|
565
|
+
keys = inject(I18N_KEYS);
|
|
566
|
+
templateRef = inject((TemplateRef));
|
|
567
|
+
viewContainer = inject(ViewContainerRef);
|
|
568
|
+
viewRef = null;
|
|
569
|
+
proxyCache = new WeakMap();
|
|
570
|
+
translateFnCache = new Map();
|
|
571
|
+
isDev = typeof ngDevMode !== 'undefined' && !!ngDevMode;
|
|
572
|
+
/**
|
|
573
|
+
* Optional prefix prepended to every key (for scoped translations).
|
|
574
|
+
*
|
|
575
|
+
* The base has no input of its own: the microsyntax binding name depends on
|
|
576
|
+
* the selector, so the generated wrapper declares `<selector>Prefix` and
|
|
577
|
+
* overrides this hook to return it. Read lazily (never during construction).
|
|
578
|
+
*/
|
|
579
|
+
prefix() {
|
|
580
|
+
return undefined;
|
|
581
|
+
}
|
|
582
|
+
withPrefix(key) {
|
|
583
|
+
const prefix = this.prefix();
|
|
584
|
+
return prefix ? `${prefix}.${key}` : key;
|
|
585
|
+
}
|
|
586
|
+
constructor() {
|
|
587
|
+
this.transloco.langChanges$
|
|
588
|
+
.pipe(
|
|
589
|
+
// A failed load still renders: Transloco's fallback / missing handler take over.
|
|
590
|
+
switchMap((lang) => this.transloco.load(lang).pipe(map(() => lang), catchError(() => of(lang)))), takeUntilDestroyed())
|
|
591
|
+
.subscribe((lang) => this.render(lang));
|
|
592
|
+
}
|
|
593
|
+
createLazyTranslationProxy(keysObject) {
|
|
594
|
+
const createProxy = (obj) => {
|
|
595
|
+
const cached = this.proxyCache.get(obj);
|
|
596
|
+
if (cached)
|
|
597
|
+
return cached;
|
|
598
|
+
const proxy = new Proxy(obj, {
|
|
599
|
+
get: (target, prop) => {
|
|
600
|
+
const value = target[prop];
|
|
601
|
+
if (typeof value === 'string') {
|
|
602
|
+
const fullKey = this.withPrefix(value);
|
|
603
|
+
const cachedFn = this.translateFnCache.get(fullKey);
|
|
604
|
+
if (cachedFn)
|
|
605
|
+
return cachedFn;
|
|
606
|
+
// Missing keys are reported by the missing handler (dev warning + `[key]`).
|
|
607
|
+
const translateFn = ((params) => this.transloco.translate(fullKey, params));
|
|
608
|
+
if (this.isDev) {
|
|
609
|
+
Object.defineProperty(translateFn, 'key', { value, writable: false, enumerable: false });
|
|
610
|
+
}
|
|
611
|
+
this.translateFnCache.set(fullKey, translateFn);
|
|
612
|
+
return translateFn;
|
|
613
|
+
}
|
|
614
|
+
if (typeof value === 'object' && value !== null) {
|
|
615
|
+
return createProxy(value);
|
|
616
|
+
}
|
|
617
|
+
if (this.isDev) {
|
|
618
|
+
console.warn(`[TranslateDirective] Invalid property "${String(prop)}" on translation object`);
|
|
619
|
+
}
|
|
620
|
+
return undefined;
|
|
621
|
+
},
|
|
622
|
+
});
|
|
623
|
+
this.proxyCache.set(obj, proxy);
|
|
624
|
+
return proxy;
|
|
625
|
+
};
|
|
626
|
+
return createProxy(keysObject);
|
|
627
|
+
}
|
|
628
|
+
render(lang) {
|
|
629
|
+
if (this.viewRef) {
|
|
630
|
+
this.viewRef.context.lang = lang;
|
|
631
|
+
this.viewRef.markForCheck();
|
|
632
|
+
return;
|
|
633
|
+
}
|
|
634
|
+
const context = {
|
|
635
|
+
$implicit: this.createLazyTranslationProxy(this.keys),
|
|
636
|
+
lang,
|
|
637
|
+
translate: (key, params) => this.transloco.translate(this.withPrefix(key), params),
|
|
638
|
+
};
|
|
639
|
+
this.viewRef = this.viewContainer.createEmbeddedView(this.templateRef, context);
|
|
640
|
+
}
|
|
641
|
+
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.10", ngImport: i0, type: TranslateDirectiveBase, deps: [], target: i0.ɵɵFactoryTarget.Directive });
|
|
642
|
+
static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "21.2.10", type: TranslateDirectiveBase, isStandalone: true, ngImport: i0 });
|
|
643
|
+
}
|
|
644
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.10", ngImport: i0, type: TranslateDirectiveBase, decorators: [{
|
|
645
|
+
type: Directive
|
|
646
|
+
}], ctorParameters: () => [] });
|
|
647
|
+
|
|
648
|
+
/**
|
|
649
|
+
* Transloco's `translateSignal`, with interpolation params checked against the
|
|
650
|
+
* key: for `TK.home.welcome` generated from `t('Welcome, {{username}}!')`,
|
|
651
|
+
* `translateSignal(TK.home.welcome)` is a compile error and
|
|
652
|
+
* `translateSignal(TK.home.welcome, { username })` is required. Plain keys,
|
|
653
|
+
* key arrays and key signals keep Transloco's signature. Runtime behavior is
|
|
654
|
+
* Transloco's (same arguments, same reactivity).
|
|
655
|
+
*/
|
|
656
|
+
function translateSignal(key, ...args) {
|
|
657
|
+
const [params, lang, injector] = args;
|
|
658
|
+
return translateSignal$1(key, params, lang, injector);
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
/*
|
|
662
|
+
* @hakistack/i18n
|
|
663
|
+
*
|
|
664
|
+
* TypeScript-first, build-time-generated, type-safe i18n for Angular on top of
|
|
665
|
+
* Transloco. Author translations in `.ts`, get typed keys + JSON for free.
|
|
666
|
+
*
|
|
667
|
+
* Consumer surface:
|
|
668
|
+
* - Authoring: `defineTranslations`, `t`
|
|
669
|
+
* - Runtime: `provideI18n`, `LanguageService`, `translateSignal`
|
|
670
|
+
* - Templates: `TranslateDirectiveBase` + `TranslateContext` (the codegen
|
|
671
|
+
* emits a typed wrapper that extends the base)
|
|
672
|
+
* - Locale type: augment the `I18nLocales` interface to declare your locales.
|
|
673
|
+
*/
|
|
674
|
+
// ============================================================================
|
|
675
|
+
// Authoring engine — re-exported from the Angular-free `/engine` entry point
|
|
676
|
+
// for convenience. Author your *.i18n.ts against `@hakistack/i18n/engine`
|
|
677
|
+
// directly (it loads in Node, which the codegen CLI relies on).
|
|
678
|
+
// ============================================================================
|
|
679
|
+
|
|
680
|
+
/**
|
|
681
|
+
* Generated bundle index. Do not edit.
|
|
682
|
+
*/
|
|
683
|
+
|
|
684
|
+
export { I18N_KEYS, I18N_RUNTIME_CONFIG, LanguageService, TranslateDirectiveBase, TranslocoCommentInterceptor, TranslocoHttpLoader, TranslocoLazyLoader, TranslocoRegistryLoader, TranslocoVisibleMissingHandler, negotiateLanguage, parseAcceptLanguage, provideI18n, textDirection, translateSignal };
|
|
685
|
+
//# sourceMappingURL=hakistack-i18n.mjs.map
|