@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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Hakistack
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,303 @@
1
- # Temporary Holding Version
1
+ # @hakistack/i18n
2
+
3
+ TypeScript-first, build-time-generated, **type-safe i18n for Angular** on top of
4
+ [Transloco](https://jsverse.github.io/transloco/). Author translations in `.ts`
5
+ files; the codegen derives the JSON files, the typed key object (`TK`), and a
6
+ typed template directive. There is no "JSON drifted from code" failure mode —
7
+ JSON is an output, not an input.
8
+
9
+ > Transloco is the runtime translation engine (active language, interpolation,
10
+ > fallback). Everything you interact with — authoring, key generation,
11
+ > validation, autocomplete — is this library's layer on top.
12
+
13
+ ## Install
14
+
15
+ ```bash
16
+ npm i @hakistack/i18n @jsverse/transloco
17
+ ```
18
+
19
+ `@jsverse/transloco` is a peer dependency (you control its version). The CLI
20
+ depends on `jiti` (installed automatically), parses `*.i18n.ts` with your
21
+ project's `typescript` (an optional peer — every Angular project already has
22
+ it) and, for the `watch` command only, uses `chokidar` (an optional dependency).
23
+
24
+ ## 1. Author translations (`*.i18n.ts`)
25
+
26
+ Author against the Angular-free `/engine` entry point:
27
+
28
+ ```ts
29
+ // src/app/features/home/home.i18n.ts
30
+ import { defineTranslations, t } from '@hakistack/i18n/engine';
31
+
32
+ export const HOME = defineTranslations('home', {
33
+ welcome: t('Welcome, Admin!', { es: '¡Bienvenido, Administrador!' }),
34
+ }, { scoped: true });
35
+ ```
36
+
37
+ - `t(en, others?, { comment? })` — English (source) required, other locales
38
+ optional, optional translator comment.
39
+ - Bare strings are shorthand for English-only (`reset: 'Reset'` ≡ `t('Reset')`).
40
+ - Only `t()` and bare strings are leaves. A hand-written object is always a
41
+ *group*, so `languages: { en: 'English', es: 'Español' }` yields the two keys
42
+ `languages.en` and `languages.es` — handy for language pickers.
43
+ - `en` is the fixed source locale: it is what `t()`'s first argument fills and
44
+ what every other locale falls back to at build time and at runtime.
45
+ - `{ scoped: true }` emits a per-scope JSON file (forward-compat for
46
+ `provideTranslocoScope` lazy loading); eager modules merge into the root JSON.
47
+
48
+ Locales are declared once, in `i18n.config` (`locales`). `scan` turns them into
49
+ an `I18nLocales` augmentation (`i18n-locales.generated.d.ts`), so `t()`
50
+ autocompletes exactly those locales and `languages[].id` in `provideI18n`
51
+ suggests them. A hand-written `I18nLocales` augmentation from an older setup
52
+ can stay (identical declarations merge) or be deleted.
53
+
54
+ ## 2. Configure the codegen (`i18n.config.json`)
55
+
56
+ ```jsonc
57
+ {
58
+ "srcRoot": "src",
59
+ "definitionsDir": "src/i18n/definitions",
60
+ "outputDir": "src/assets/i18n",
61
+ "locales": ["en", "es"]
62
+ }
63
+ ```
64
+
65
+ (A `.ts`/`.js` config with a default export works too. `en` is always part of
66
+ `locales`; optional `directiveSelector` / `directiveClassName` rename the
67
+ generated directive.)
68
+
69
+ ## 3. Run the codegen
70
+
71
+ ```bash
72
+ npx hakistack-i18n check # scan + validate + generate — the everyday command (prebuild, CI)
73
+ npx hakistack-i18n watch # the same on every *.i18n.ts change (run next to ng serve)
74
+ npx hakistack-i18n find-unused # report keys with no reference (--strict fails on them)
75
+ ```
76
+
77
+ The steps are also available alone: `scan` (barrel, `TK`, directive, locale
78
+ types), `validate` (missing / empty / placeholder-mismatched translations) and
79
+ `generate` (JSON + per-language modules). `check` stops at the first step that
80
+ fails and exits with code 1; `watch` prints errors and keeps running.
81
+
82
+ `scan` parses the files (TypeScript AST, nothing is executed). It finds
83
+ `export const X = defineTranslations('scope', …)`, local constants exported
84
+ with `export { X }` / `export { X as Y }`, and aliased or namespace imports of
85
+ `defineTranslations`; commented-out code never counts. The scope must be a
86
+ string literal. Problems are reported as `file:line`, and on an error (duplicate
87
+ export names, a key defined twice, a key that is both a translation and a
88
+ group) nothing is written and the command exits with code 1. `validate` and
89
+ `generate` re-check the executed registry, which also catches conflicts hidden
90
+ behind spreads or references.
91
+
92
+ Outputs are written atomically and only when their content changed, so dev
93
+ servers don't rebuild for nothing. Files a previous run wrote that are no
94
+ longer produced — a removed locale or scoped module, a renamed directive — are
95
+ deleted; the CLI only ever deletes files it wrote itself (tracked in
96
+ `node_modules/.cache/hakistack-i18n/`).
97
+
98
+ Typical `package.json` wiring:
99
+
100
+ ```jsonc
101
+ {
102
+ "scripts": {
103
+ "i18n:check": "hakistack-i18n check",
104
+ "i18n:watch": "hakistack-i18n watch",
105
+ "prestart": "npm run i18n:check",
106
+ "prebuild": "npm run i18n:check"
107
+ }
108
+ }
109
+ ```
110
+
111
+ Generated into `definitionsDir` (never hand-edited):
112
+
113
+ | File | From | Contents |
114
+ |------|------|----------|
115
+ | `keys.generated.ts` | `scan` | `TK` — `TK.home.welcome === 'home.welcome'`, typed as that literal |
116
+ | `index.generated.ts` | `scan` | `ALL_TRANSLATIONS`, the registry of every module |
117
+ | `appTranslate.directive.ts` | `scan` | the typed template directive |
118
+ | `i18n-locales.generated.d.ts` | `scan` | the `I18nLocales` augmentation from `locales` |
119
+ | `translations.generated.ts` + `translations/` | `generate` | `TRANSLATIONS`: one lazily imported module per language (and per scoped scope) |
120
+
121
+ `TK` holds the key strings themselves for every module `scan` can read
122
+ statically, so importing `TK` does not import any `*.i18n.ts` module. A module
123
+ built with spreads or references is referenced as `NAME.keys` instead (and is
124
+ bundled with `TK`).
125
+
126
+ Several modules may share a scope, and a module may nest under another one's
127
+ scope (`admin` + `admin.users`): their keys are deep-merged (`mergeKeys` in the
128
+ generated `TK`, the same merge the runtime and the JSON use). A key defined
129
+ twice, or a key that is both a translation and a group, is an error:
130
+ `validate` and `generate` list each conflict with its scopes and exit with code
131
+ 1, and the runtime throws instead of letting one module silently win. Export
132
+ names must be unique across `*.i18n.ts` files (`scan` refuses duplicates).
133
+
134
+ ## 4. Wire it up (one call)
135
+
136
+ ```ts
137
+ // app.config.ts
138
+ import { provideI18n } from '@hakistack/i18n';
139
+ import { ALL_TRANSLATIONS } from './i18n/definitions/index.generated';
140
+
141
+ export const appConfig: ApplicationConfig = {
142
+ providers: [
143
+ provideI18n({
144
+ registry: ALL_TRANSLATIONS,
145
+ languages: [
146
+ { id: 'en', label: 'English' },
147
+ { id: 'es', label: 'Español' },
148
+ ],
149
+ defaultLang: 'es', // active language on bootstrap
150
+ fallbackLang: 'en', // untranslated keys fall back here
151
+ persistLanguage: true, // restore last language from localStorage
152
+ }),
153
+ ],
154
+ };
155
+ ```
156
+
157
+ The registry loader serves every language from memory (no HTTP, SSR-safe,
158
+ offline-friendly) — simplest for small apps, but every language is in the
159
+ initial bundle. For larger apps load one language at a time:
160
+
161
+ ```ts
162
+ import { TK } from './i18n/definitions/keys.generated';
163
+ import { TRANSLATIONS } from './i18n/definitions/translations.generated';
164
+
165
+ provideI18n({
166
+ keys: TK, // instead of registry: no *.i18n.ts module is imported
167
+ translations: TRANSLATIONS, // one chunk per language, imported when first needed
168
+ languages: [...],
169
+ })
170
+ ```
171
+
172
+ The lazy loader is SSR-safe (server rendering waits for the import) and needs
173
+ no HTTP setup. Only the active language is downloaded: every generated tree
174
+ already resolves untranslated keys to the fallback language, so the fallback
175
+ language itself is never loaded alongside. `loader: 'http'` with `keys: TK` fetches the generated
176
+ `<assetsPath>/<lang>.json` instead, so translations can change without a
177
+ rebuild.
178
+
179
+ Measured on a production build with 2,000+ keys in 4 languages: the initial
180
+ JS goes from 604.0 kB / 126.8 kB gzip (registry) to 184.9 kB / 56.9 kB gzip
181
+ (lazy), plus a ~18.7 kB gzip chunk for the active language only.
182
+
183
+ `persistLanguage` only controls localStorage persistence: the generated
184
+ directive and `translateSignal` load the active language themselves.
185
+ `LanguageService.language()` and `<html lang>` follow Transloco's active
186
+ language however it is changed; `setLanguage()` ignores languages that are not
187
+ in `languages`.
188
+
189
+ In dev mode a missing key renders as `[scope.key]` and logs one console warning
190
+ per key (`missingKeyInDev: 'empty'` renders `''`); production renders `''`.
191
+
192
+ ## 5. Use translations
193
+
194
+ ```ts
195
+ // component
196
+ import { translateSignal } from '@hakistack/i18n';
197
+ import { TK } from '../../i18n/definitions/keys.generated';
198
+
199
+ protected readonly welcome = translateSignal(TK.home.welcome);
200
+ ```
201
+
202
+ ```html
203
+ <!-- template — import the generated AppTranslateDirective, fully typed -->
204
+ <div *appTranslate="let t">{{ t.home.welcome() }}</div>
205
+ <p>{{ t.common.validation.minLength({ min: 3 }) }}</p>
206
+ <!-- optional key prefix (the input is named <selector>Prefix) -->
207
+ <div *appTranslate="let t; prefix: 'admin'">{{ t.users.title() }}</div>
208
+ ```
209
+
210
+ ### Typed interpolation params
211
+
212
+ For every `t('…')` whose source text has `{{…}}` placeholders, `scan` types the
213
+ key with its params (`I18nKey<'home.greeting', 'username'>` — still the plain
214
+ string `'home.greeting'` at runtime). The compiler then checks them, in
215
+ components and in strict templates:
216
+
217
+ ```ts
218
+ // home.i18n.ts: greeting: t('Welcome back, {{ username }}!', { es: '¡Hola de nuevo, {{username}}!' })
219
+ translateSignal(TK.home.greeting, { username }); // ✓
220
+ translateSignal(TK.home.greeting, computed(() => ({ username: name() }))); // ✓ reactive params
221
+ translateSignal(TK.home.greeting); // ✗ params required
222
+ translateSignal(TK.home.greeting, { user: 'x' }); // ✗ unknown param
223
+ ```
224
+
225
+ ```html
226
+ {{ t.home.greeting({ username: user.name }) }} <!-- ✗ without the param under strictTemplates -->
227
+ ```
228
+
229
+ `translateSignal` is Transloco's own (same arguments and behavior) with this
230
+ check added; plain string keys stay untyped. Params come from the source
231
+ (`en`) text — `validate` keeps every locale in parity — and a nested
232
+ `{{ user.name }}` requires `user`. They are read once by the codegen rather than
233
+ parsed by the type system: on a 5,000-key project, template-literal parsing made
234
+ type-checking 4–6× slower, while the generated `TK` adds ~0.3 s.
235
+
236
+ ## 6. Language, locale and direction
237
+
238
+ A language option can carry its formatting locale and text direction:
239
+
240
+ ```ts
241
+ languages: [
242
+ { id: 'en', label: 'English' },
243
+ { id: 'es', label: 'Español', locale: 'es-PR' }, // Spanish texts, Puerto Rico formats
244
+ { id: 'ar', label: 'العربية' }, // dir: 'rtl' derived from the locale
245
+ ],
246
+ ```
247
+
248
+ `LanguageService` exposes `language()` (translations), `locale()` (BCP 47, for
249
+ `Intl.*` or locale pipes) and `dir()`, and keeps `<html lang>` (the locale) and
250
+ `<html dir>` in sync — also during SSR:
251
+
252
+ ```ts
253
+ private readonly lang = inject(LanguageService);
254
+ readonly price = computed(() => new Intl.NumberFormat(this.lang.locale(), { style: 'currency', currency: 'USD' }).format(19.9));
255
+ ```
256
+
257
+ For pipes, `@jsverse/transloco-locale` works alongside: map languages to
258
+ locales with `langToLocaleMapping: { es: 'es-PR' }`. Pluralization and ICU
259
+ messages are Transloco's (`@jsverse/transloco-messageformat`); nothing here
260
+ replaces them.
261
+
262
+ ## 7. SSR
263
+
264
+ `persistLanguage: 'cookie'` remembers the user's choice in a
265
+ `hakistack_i18n_lang` cookie that the server reads from the request, so the
266
+ server renders the user's language and hydration shows no switch.
267
+ `detectLanguage: true` picks the best match for `Accept-Language` (server) or
268
+ `navigator.languages` (browser) when nothing is remembered; a detected language
269
+ is not stored. Every piece of state lives in the application's injector, so
270
+ concurrent requests never share a language. The `'lazy'` loader is an Angular
271
+ pending task: the server waits for the active language before serializing.
272
+
273
+ Verified with a real `renderApplication` (Angular 21.2): three concurrent
274
+ requests — cookie `es`, `Accept-Language: ar-EG`, no preference — render
275
+ `<html lang="es-PR" dir="ltr">`, `<html lang="ar" dir="rtl">` and
276
+ `<html lang="en" dir="ltr">` with their own texts, with both the registry and
277
+ the lazy loader.
278
+
279
+ ## Entry points
280
+
281
+ | Import | Contains |
282
+ |--------|----------|
283
+ | `@hakistack/i18n` | Runtime: `provideI18n`, `LanguageService`, `translateSignal`, `TranslateDirectiveBase`, loaders/hooks, `I18nTranslationLoaders`. (Re-exports the engine too.) |
284
+ | `@hakistack/i18n/engine` | Angular-free authoring/tree engine: `defineTranslations`, `t`, build-tree helpers. Loads in Node — this is what the codegen executes. |
285
+
286
+ ## Finding unused keys
287
+
288
+ `hakistack-i18n find-unused` classifies every key:
289
+
290
+ - **used** — `TK.home.welcome` (also through `import { TK as K }` or
291
+ `const home = TK.home; home.welcome`), the exact key as a string
292
+ (`translate('home.welcome')`), or `t.home.welcome()` in a template under
293
+ `*appTranslate="let t"` (with its `prefix:` applied);
294
+ - **possibly used** — only dynamic references that may reach it: a TK group
295
+ used as a value or indexed (`TK.home[name]`), a key prefix in a string
296
+ (`'home.' + name`, `` `home.${name}` ``), a group name passed to a
297
+ `translate*` call (`translateObject('home')`). Never reported as unused;
298
+ - **test-only** — referenced only from `*.spec.ts`;
299
+ - **claimed** — matched by a `/* i18n-used: home.dynamic.* */` comment;
300
+ - **unused** — everything else. `--strict` exits with code 1 when there are any.
301
+
302
+ Comments never count as references.
2
303
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.