i18n-works 0.1.4 โ 0.1.5
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 +19 -1001
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,19 +1,23 @@
|
|
|
1
|
-
# ๐ i18n-works (AI i18n plugin)
|
|
1
|
+
# ๐ i18n-works (AI-powered i18n plugin) & CLI tools
|
|
2
2
|
|
|
3
|
-
**Build/Run-time localization for `t()` strings.** Wrap user-facing copy in `t("...")` imported from `virtual:i18n-works`. The compiler extracts each string, gives it a stable ID, and can translate it with an AI provider. Bonus: `tauto()` and `tpick()` helpers for context-aware and conditional translations.
|
|
3
|
+
**Build/Run-time localization for typical `t()` strings.** Wrap user-facing copy in `t("...")` imported from `virtual:i18n-works`. The compiler extracts each string, gives it a stable ID, and can translate it with an AI provider. Bonus: `tauto()` and `tpick()` helpers for context-aware and conditional translations.
|
|
4
4
|
|
|
5
5
|
> [!WARNING]
|
|
6
6
|
> **Beta.** Configuration options and `.i18n-works/` file formats are meant to stay stable, but review the [known limitations](#-known-limitations) before shipping to production. Pin the version while in beta.
|
|
7
7
|
|
|
8
|
-
---
|
|
9
8
|
|
|
10
|
-
|
|
9
|
+

|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
### TL;DR / Crash Course for impatient developers
|
|
11
13
|
|
|
12
14
|
The plugin extracts the strings passed to the exposed functions (like `t()`, `tt()`, `tauto()`, and `tpick()`), assigns stable IDs, and translates them with your chosen AI provider. Use the build or runtime delivery mode to get localized bundles.
|
|
13
15
|
|
|
16
|
+
**Remember**:
|
|
17
|
+
|
|
14
18
|
- Life is short, write anywhere, from root context to nested components.
|
|
15
19
|
- Configure Vite with the plugin in `vite.config.ts`, and put the options in `vite-i18n.config.js`. Add an AI key, configure the target languages and let it happen.
|
|
16
|
-
- Wrap your user-facing strings simply with `t()` and
|
|
20
|
+
- Wrap your user-facing strings simply with `t()` and don't worry about the rest.
|
|
17
21
|
|
|
18
22
|
**Imports** - _Use as needed_:
|
|
19
23
|
|
|
@@ -55,1006 +59,20 @@ tpick(
|
|
|
55
59
|
|
|
56
60
|
---
|
|
57
61
|
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-

|
|
61
|
-
|
|
62
|
-
## ๐ Contents
|
|
63
|
-
|
|
64
|
-
- [โจ Features](#-features)
|
|
65
|
-
- [๐ Overview](#-overview)
|
|
66
|
-
- [๐ How it works](#-how-it-works)
|
|
67
|
-
- [๐ฆ Installation](#-installation)
|
|
68
|
-
- [๐ Examples](#-examples)
|
|
69
|
-
- [๐ Delivery modes](#-delivery-modes)
|
|
70
|
-
- [๐ง Configuration](#-configuration)
|
|
71
|
-
- [๐ Providers](#-providers)
|
|
72
|
-
- [๐ Reliability](#-reliability)
|
|
73
|
-
- [๐งน Maintenance](#-maintenance)
|
|
74
|
-
- [๐งช Test coverage](#-test-coverage)
|
|
75
|
-
- [๐ง Known limitations](#-known-limitations)
|
|
76
|
-
- [๐งญ Design rules](#-design-rules)
|
|
77
|
-
|
|
78
|
-
## โจ Features
|
|
79
|
-
|
|
80
|
-
**Extraction**
|
|
81
|
-
|
|
82
|
-
- String literals passed to `t("...")` imported from `virtual:i18n-works`. Nothing else is extracted, so JSX text and attributes need `t()` too.
|
|
83
|
-
|
|
84
|
-
**Identity**
|
|
85
|
-
|
|
86
|
-
- Opaque, persistent message IDs stored in `.i18n-works/registry.json`
|
|
87
|
-
- Moving or renaming files and components does not change IDs
|
|
88
|
-
- Removed messages are kept as orphans for 30 days, so their IDs can come back
|
|
89
|
-
|
|
90
|
-
**Translation**
|
|
91
|
-
|
|
92
|
-
- Pluggable providers: Anthropic, Gemini, any OpenAI-compatible API (OpenAI, Mistral, Groq, Ollama and [many more](#choosing-a-provider))
|
|
93
|
-
- Only new or changed messages are sent to the provider
|
|
94
|
-
- Source English is always the fallback
|
|
95
|
-
|
|
96
|
-
**Delivery**
|
|
97
|
-
|
|
98
|
-
- `build`: one compiled bundle per locale
|
|
99
|
-
- `runtime`: one bundle, with locales loaded on demand
|
|
100
|
-
|
|
101
|
-
## ๐ Overview
|
|
102
|
-
|
|
103
|
-

|
|
104
|
-
|
|
105
|
-
```mermaid
|
|
106
|
-
flowchart LR
|
|
107
|
-
src["Your t(#quot;...#quot;) strings"] --> p1["1. Extract"]
|
|
108
|
-
p1 --> p2["2. Identify"]
|
|
109
|
-
reg[("registry.json<br/>message IDs")] <--> p2
|
|
110
|
-
p2 --> p3["3. Translate"]
|
|
111
|
-
cat[("locales/*.json<br/>translations + sources")] <--> p3
|
|
112
|
-
p3 <--> ai["Translation provider"]
|
|
113
|
-
p3 --> p4["4. Transform"]
|
|
114
|
-
p4 --> build["delivery: build<br/>one bundle per locale"]
|
|
115
|
-
p4 --> runtime["delivery: runtime<br/>one bundle + catalogues"]
|
|
116
|
-
```
|
|
117
|
-
|
|
118
|
-
Every build, and every save in the dev server, runs the same four phases. The next section follows one component through them.
|
|
119
|
-
|
|
120
|
-
## ๐ How it works
|
|
121
|
-
|
|
122
|
-
### Build at a glance
|
|
123
|
-
|
|
124
|
-
```mermaid
|
|
125
|
-
sequenceDiagram
|
|
126
|
-
autonumber
|
|
127
|
-
participant Src as Source files
|
|
128
|
-
participant Plugin as i18nWorks plugin
|
|
129
|
-
participant Reg as registry.json
|
|
130
|
-
participant Cat as locales/*.json
|
|
131
|
-
participant AI as Provider
|
|
132
|
-
|
|
133
|
-
Src->>Plugin: Files matching include
|
|
134
|
-
Plugin->>Plugin: Extract messages and fingerprints
|
|
135
|
-
Plugin->>Reg: Load previous IDs
|
|
136
|
-
Plugin->>Plugin: Reconcile IDs, mark orphans, prune expired
|
|
137
|
-
Plugin->>Cat: Load previous translations
|
|
138
|
-
Plugin->>AI: Send only new or changed messages (batches)
|
|
139
|
-
AI-->>Plugin: Translations
|
|
140
|
-
Plugin->>Cat: Write catalogues (atomic)
|
|
141
|
-
Plugin->>Reg: Write registry (atomic)
|
|
142
|
-
Plugin->>Src: Transform code for the delivery mode
|
|
143
|
-
```
|
|
144
|
-
|
|
145
|
-
The examples below follow one component through the phases. IDs are shortened for readability; real IDs look like `msg_6f5e12bdbc7a4804`.
|
|
146
|
-
|
|
147
|
-
### Phase 0: the source you write
|
|
148
|
-
|
|
149
|
-
```tsx
|
|
150
|
-
// src/Doc.tsx
|
|
151
|
-
import { t } from "virtual:i18n-works";
|
|
152
|
-
|
|
153
|
-
export function Doc({ count }: { count: number }) {
|
|
154
|
-
return (
|
|
155
|
-
<section>
|
|
156
|
-
<button title={t("Save the current document")}>{t("Save")}</button>
|
|
157
|
-
<p>
|
|
158
|
-
{t("You have")} {count} {count === 1 ? t("document") : t("documents")}
|
|
159
|
-
</p>
|
|
160
|
-
</section>
|
|
161
|
-
);
|
|
162
|
-
}
|
|
163
|
-
```
|
|
164
|
-
|
|
165
|
-
Each `t()` call takes one string literal. Keep variables outside the call and let the surrounding JSX combine the pieces. To fill in values, pass an object as the second argument and write the message in [ICU MessageFormat](https://unicode-org.github.io/icu/userguide/format_parse/messages/):
|
|
166
|
-
|
|
167
|
-
```tsx
|
|
168
|
-
<span>{t("{count, plural, one {# document selected} other {# documents selected}}", { count })}</span>
|
|
169
|
-
<span>{t("Hello {name}", { name: user.name })}</span>
|
|
170
|
-
```
|
|
171
|
-
|
|
172
|
-
For count templates where the target language should choose natural singular, zero and plural wording automatically, use `tt()`:
|
|
173
|
-
|
|
174
|
-
```tsx
|
|
175
|
-
<span>{tt("{count} items", { count })}</span>
|
|
176
|
-
```
|
|
177
|
-
|
|
178
|
-
An optional third argument adds free-form guidance for the AI provider:
|
|
179
|
-
|
|
180
|
-
```tsx
|
|
181
|
-
<span>{tt("{count} seconds ago", { count }, "Use 'Now' when count is zero; use 'Later' above five")}</span>
|
|
182
|
-
```
|
|
183
|
-
|
|
184
|
-
The hint is kept with the message and sent to LLM translation providers as extra context. It does not alter the runtime fallback formatter directly; providers use it to generate richer, locale-specific ICU branches. Hinted `tt()` messages can also receive a source-locale ICU catalogue entry, while other source text remains unchanged.
|
|
185
|
-
|
|
186
|
-
For a plain message that needs author context but no count wording, use `tauto()`. It takes the same arguments as `tt()`: the English pattern, optional values and an optional hint. Unlike `tt()`, it does not require a plural branch, so a translation such as `Hallo {name}, Euer Hoheit` is kept as written:
|
|
187
|
-
|
|
188
|
-
```tsx
|
|
189
|
-
<span>{tauto("Hello {name}", { name: user.name }, "Be very formal. This is for royalties.")}</span>
|
|
190
|
-
```
|
|
191
|
-
|
|
192
|
-
When the message has no values, the hint can be passed as the second argument: `tauto("Hello", "Be very formal")`.
|
|
193
|
-
|
|
194
|
-
The hint is sent to the provider as free-form context for tone and audience and must not change placeholders. The pattern is only a seed: the source-locale (English) text is rewritten by the provider with the hint applied, so the English output follows the hint too.
|
|
195
|
-
|
|
196
|
-
AI providers convert `tt()` sources into ICU plural messages for each target locale. For example, English fallback output is `No items`, `1 item` or `5 items`, while another language receives its own locale-specific categories and wording. The source text is shown as a simple count fallback when no provider or translation is available yet.
|
|
197
|
-
|
|
198
|
-
Plurals, `select` and simple `{name}` placeholders all work. Messages are checked at build time, so an invalid ICU string fails the build and names the file. At runtime the values are formatted for the active locale with [`intl-messageformat`](https://formatjs.io/docs/intl-messageformat/). That library is bundled only when a build uses values with `delivery: "build"`, but `delivery: "runtime"` always includes it, since the shared runtime module formats values. A missing value is logged and the message is shown unformatted.
|
|
199
|
-
|
|
200
|
-
### Phase 1: extract
|
|
201
|
-
|
|
202
|
-
The compiler parses each file in `include` and records every `t("...")` call with its component and a fingerprint. Nothing is written yet.
|
|
203
|
-
|
|
204
|
-
```jsonc
|
|
205
|
-
[
|
|
206
|
-
{ "source": "Save the current document", "component": "Doc", "fingerprint": "6e396974a738eb3f26898d35" },
|
|
207
|
-
{ "source": "Save", "component": "Doc", "fingerprint": "1509f561f2416598629b886a" },
|
|
208
|
-
{ "source": "You have", "component": "Doc", "fingerprint": "af3f12e161fdb1cbbb73000e" },
|
|
209
|
-
{ "source": "document", "component": "Doc", "fingerprint": "43cc23fa52b87b4cc1d02b5b" },
|
|
210
|
-
{ "source": "documents", "component": "Doc", "fingerprint": "9b16b44d0e0a5cac4f968bef" },
|
|
211
|
-
]
|
|
212
|
-
```
|
|
213
|
-
|
|
214
|
-
- Only calls to a `t` imported from `virtual:i18n-works` are extracted. An unrelated `t()` from another library is ignored.
|
|
215
|
-
- A call is ignored when its first argument is not a string literal, for example a variable or a template literal. A second argument that is a spread (`t("Hi", ...args)`) is ignored too, since its values cannot be read statically. Such calls are returned unchanged at runtime and are not translated.
|
|
216
|
-
- Strings with no letters, such as `t("โฆ")` or `t("12")`, are skipped.
|
|
217
|
-
|
|
218
|
-
### Phase 2: identify
|
|
219
|
-
|
|
220
|
-
Each extracted message is matched against `.i18n-works/registry.json`:
|
|
221
|
-
|
|
222
|
-
- A match keeps the existing ID.
|
|
223
|
-
- A new message gets a new opaque ID.
|
|
224
|
-
- A message that disappears is marked `orphaned`, not deleted, so its ID can come back.
|
|
225
|
-
|
|
226
|
-
```jsonc
|
|
227
|
-
// .i18n-works/registry.json (excerpt)
|
|
228
|
-
{
|
|
229
|
-
"version": 1,
|
|
230
|
-
"entries": {
|
|
231
|
-
"msg_a1": {
|
|
232
|
-
"id": "msg_a1",
|
|
233
|
-
"source": "Save the current document",
|
|
234
|
-
"component": "Doc",
|
|
235
|
-
"fingerprint": "6e396974a738eb3f26898d35",
|
|
236
|
-
"location": "/path/to/app/src/Doc.tsx:183",
|
|
237
|
-
"status": "active",
|
|
238
|
-
"firstSeen": "2026-11-02T17:28:36.128Z",
|
|
239
|
-
"lastSeen": "2026-11-14T14:54:42.201Z",
|
|
240
|
-
},
|
|
241
|
-
},
|
|
242
|
-
"costs": {},
|
|
243
|
-
}
|
|
244
|
-
```
|
|
245
|
-
|
|
246
|
-
The `costs` object holds one record per AI call, next to `entries`. It is written only when the [`costs`](#plugin-options-vite-i18nconfigjs) option is on, and is described under [Debugging](#debugging).
|
|
247
|
-
|
|
248
|
-
The fingerprint is a hash of the normalized source text only. Component names, file paths and positions are not part of it, so moving or renaming a file or component does not change the ID. Whitespace-only edits do not change it either. `location` is informational and is not part of identity.
|
|
249
|
-
|
|
250
|
-
#### Message lifecycle
|
|
251
|
-
|
|
252
|
-
```mermaid
|
|
253
|
-
stateDiagram-v2
|
|
254
|
-
[*] --> active: New text gets a new ID
|
|
255
|
-
active --> orphaned: Removed from source
|
|
256
|
-
orphaned --> active: Same text returns, same ID
|
|
257
|
-
orphaned --> [*]: Retention expired, deleted
|
|
258
|
-
```
|
|
259
|
-
|
|
260
|
-
A deleted message that returns later gets a new ID and is translated again.
|
|
261
|
-
|
|
262
|
-
### Phase 3: translate
|
|
263
|
-
|
|
264
|
-
Only new or changed messages (source text changed since the last build) are sent to the provider. Results are stored in `.i18n-works/locales/<locale>.json`, next to the source text each translation was made from.
|
|
265
|
-
|
|
266
|
-
```jsonc
|
|
267
|
-
// .i18n-works/locales/de.json
|
|
268
|
-
{
|
|
269
|
-
"messages": {
|
|
270
|
-
"msg_a1": "Dokument speichern",
|
|
271
|
-
"msg_a2": "Speichern",
|
|
272
|
-
"msg_a3": "Du hast",
|
|
273
|
-
},
|
|
274
|
-
"sources": {
|
|
275
|
-
"msg_a1": "Save the current document",
|
|
276
|
-
"msg_a2": "Save",
|
|
277
|
-
"msg_a3": "You have",
|
|
278
|
-
},
|
|
279
|
-
}
|
|
280
|
-
```
|
|
281
|
-
|
|
282
|
-
- Translations never overwrite an existing entry silently.
|
|
283
|
-
- If the source text changes, the stored `sources` entry no longer matches, so the message is translated again.
|
|
284
|
-
|
|
285
|
-
#### Provider fallback
|
|
286
|
-
|
|
287
|
-
```mermaid
|
|
288
|
-
flowchart TD
|
|
289
|
-
batch["Batch of messages"] --> primary["Primary provider"]
|
|
290
|
-
primary -->|"all translated"| store["Store translations"]
|
|
291
|
-
primary -->|"some missing or failed"| next["Next provider, in declaration order"]
|
|
292
|
-
next -->|"translated"| store
|
|
293
|
-
next -->|"still missing"| src["Keep source text, retry on next build"]
|
|
294
|
-
```
|
|
295
|
-
|
|
296
|
-
Fallback runs per batch. See [Multiple providers and fallback](#multiple-providers-and-fallback).
|
|
297
|
-
|
|
298
|
-
### Phase 4: transform
|
|
299
|
-
|
|
300
|
-
The source is rewritten according to `delivery`.
|
|
301
|
-
|
|
302
|
-
**`delivery: "build"`** bakes the German text into the code, and the `t()` call is replaced by a string literal. The `virtual:i18n-works` import is left in place:
|
|
303
|
-
|
|
304
|
-
```diff
|
|
305
|
-
// src/Doc.tsx
|
|
306
|
-
import { t } from "virtual:i18n-works";
|
|
307
|
-
|
|
308
|
-
export function Doc({ count }: { count: number }) {
|
|
309
|
-
return (
|
|
310
|
-
<section>
|
|
311
|
-
- <button title={t("Save the current document")}>{t("Save")}</button>
|
|
312
|
-
+ <button title={"Dokument speichern"}>{"Speichern"}</button>
|
|
313
|
-
<p>
|
|
314
|
-
- {t("You have")} {count} {count === 1 ? t("document") : t("documents")}
|
|
315
|
-
+ {"Du hast"} {count} {count === 1 ? "Dokument" : "Dokumente"}
|
|
316
|
-
</p>
|
|
317
|
-
</section>
|
|
318
|
-
);
|
|
319
|
-
}
|
|
320
|
-
```
|
|
321
|
-
|
|
322
|
-
**`delivery: "runtime"`** replaces each call with a lookup by ID. The source text stays in the code as the fallback. The plugin adds the `lookup` import at the top of the file:
|
|
323
|
-
|
|
324
|
-
```diff
|
|
325
|
-
+import { lookup as __i18nWorksT } from "virtual:i18n-works";
|
|
326
|
-
import { t } from "virtual:i18n-works";
|
|
327
|
-
|
|
328
|
-
export function Doc({ count }: { count: number }) {
|
|
329
|
-
return (
|
|
330
|
-
<section>
|
|
331
|
-
- <button title={t("Save the current document")}>{t("Save")}</button>
|
|
332
|
-
+ <button title={__i18nWorksT("msg_a1", "Save the current document")}>{__i18nWorksT("msg_a2", "Save")}</button>
|
|
333
|
-
<p>
|
|
334
|
-
- {t("You have")} {count} {count === 1 ? t("document") : t("documents")}
|
|
335
|
-
+ {__i18nWorksT("msg_a3", "You have")} {count} {count === 1 ? __i18nWorksT("msg_a4", "document") : __i18nWorksT("msg_a5", "documents")}
|
|
336
|
-
</p>
|
|
337
|
-
</section>
|
|
338
|
-
);
|
|
339
|
-
}
|
|
340
|
-
```
|
|
341
|
-
|
|
342
|
-
If a locale has no translation for an ID, the source text is shown. Nothing breaks while translations are missing.
|
|
343
|
-
|
|
344
|
-
### ๐ฅ Dev server
|
|
345
|
-
|
|
346
|
-
Saving a file re-reads only that file, reuses the cached extraction for the rest of the project, and pushes only the catalogues that changed to the browser, so the page updates without a reload.
|
|
347
|
-
|
|
348
|
-
```mermaid
|
|
349
|
-
sequenceDiagram
|
|
350
|
-
autonumber
|
|
351
|
-
actor Dev as Developer
|
|
352
|
-
participant Vite as Vite dev server
|
|
353
|
-
participant Plugin as i18nWorks plugin
|
|
354
|
-
participant Browser as Browser
|
|
355
|
-
|
|
356
|
-
Dev->>Vite: Saves src/Doc.tsx
|
|
357
|
-
Vite->>Plugin: File changed (debounced)
|
|
358
|
-
Plugin->>Plugin: Re-read saved file, reuse cached extractions
|
|
359
|
-
Plugin->>Plugin: Identify, translate new or changed messages
|
|
360
|
-
Plugin-->>Browser: i18n-works:update (changed locales only)
|
|
361
|
-
Browser->>Browser: Re-render with new text
|
|
362
|
-
```
|
|
363
|
-
|
|
364
|
-
Locales that did not change are not sent. Adding or removing a file runs a full project scan instead, debounced by 150 ms.
|
|
365
|
-
|
|
366
|
-
## ๐ฆ Installation
|
|
367
|
-
|
|
368
|
-
### 1๏ธโฃ Install the package
|
|
369
|
-
|
|
370
|
-
In your React + Vite project:
|
|
371
|
-
|
|
372
|
-
```sh
|
|
373
|
-
npm install -D i18n-works
|
|
374
|
-
```
|
|
375
|
-
|
|
376
|
-
Equivalent commands: `bun add -D`, `pnpm add -D`, or `yarn add -D`, with the same package name.
|
|
377
|
-
|
|
378
|
-
- Requires **Vite 8+** (peer dependency) and **Node.js 26+**.
|
|
379
|
-
- For React, also keep `@vitejs/plugin-react` in your Vite config.
|
|
380
|
-
|
|
381
|
-
### 2๏ธโฃ Add your API key
|
|
382
|
-
|
|
383
|
-
Put the key in `.env.local` and keep that file out of git:
|
|
384
|
-
|
|
385
|
-
| Provider | Variable |
|
|
386
|
-
| ----------------------------------- | ----------------------------------------------- |
|
|
387
|
-
| OpenAI or any OpenAI-compatible API | `OPENAI_API_KEY` |
|
|
388
|
-
| Anthropic (Claude) | `ANTHROPIC_API_KEY` |
|
|
389
|
-
| Gemini | `GEMINI_API_KEY` |
|
|
390
|
-
| Other services | See [Choosing a provider](#choosing-a-provider) |
|
|
391
|
-
|
|
392
|
-
### 3๏ธโฃ Configure Vite
|
|
393
|
-
|
|
394
|
-
All plugin options go in a `vite-i18n.config.js` file next to `vite.config.ts`. `vite.config.ts` only calls `i18nWorks()`, with no arguments. The config file can export an object, or a function that receives `{ mode }` and returns one. `loadEnv` reads `.env.local` for the config file:
|
|
395
|
-
|
|
396
|
-
```js
|
|
397
|
-
import { AnthropicProvider, OpenAICompatibleProvider } from "i18n-works";
|
|
398
|
-
// vite-i18n.config.js
|
|
399
|
-
import { loadEnv } from "vite";
|
|
400
|
-
|
|
401
|
-
export default ({ mode }) => {
|
|
402
|
-
const env = loadEnv(mode, process.cwd(), "");
|
|
403
|
-
|
|
404
|
-
return {
|
|
405
|
-
locales: ["en", "de", "fr"],
|
|
406
|
-
sourceLocale: "en",
|
|
407
|
-
provider: {
|
|
408
|
-
primary: "anthropic",
|
|
409
|
-
anthropic: new AnthropicProvider({
|
|
410
|
-
apiKey: env.ANTHROPIC_API_KEY,
|
|
411
|
-
model: "claude-haiku-5-5",
|
|
412
|
-
}),
|
|
413
|
-
openai: new OpenAICompatibleProvider({
|
|
414
|
-
apiKey: env.OPENAI_API_KEY,
|
|
415
|
-
model: "gpt-4.1-mini",
|
|
416
|
-
}),
|
|
417
|
-
},
|
|
418
|
-
};
|
|
419
|
-
};
|
|
420
|
-
```
|
|
421
|
-
|
|
422
|
-
```ts
|
|
423
|
-
// vite.config.ts
|
|
424
|
-
import react from "@vitejs/plugin-react";
|
|
425
|
-
import { defineConfig } from "vite";
|
|
426
|
-
import i18nWorks from "i18n-works";
|
|
427
|
-
],
|
|
428
|
-
});
|
|
429
|
-
```
|
|
430
|
-
|
|
431
|
-
If `vite-i18n.config.js` is missing or invalid, the build stops with a message that says what to add or fix. Unknown option names are rejected, so a typo such as `provder` for `provider` shows up immediately.
|
|
432
|
-
|
|
433
|
-
### 4๏ธโฃ Commit the generated files
|
|
434
|
-
|
|
435
|
-
The build writes `.i18n-works/` (registry and catalogues). Commit it so existing translations are reused instead of requested again. โ
|
|
436
|
-
|
|
437
|
-
Then wrap user-facing strings in `t()`:
|
|
438
|
-
|
|
439
|
-
```tsx
|
|
440
|
-
import { t } from "virtual:i18n-works";
|
|
441
|
-
|
|
442
|
-
<button title={t("Save the current document")}>{t("Save")}</button>;
|
|
443
|
-
```
|
|
444
|
-
|
|
445
|
-
### ๐ค Install with an AI agent
|
|
446
|
-
|
|
447
|
-
Two files help an AI coding agent set the plugin up in your project:
|
|
448
|
-
|
|
449
|
-
- [llms.txt](./llms.txt): a reference written for LLMs. It is also shipped in the npm package, so agents can read `node_modules/i18n-works/llms.txt`.
|
|
450
|
-
- [scripts/install-i18n-works.mjs](./scripts/install-i18n-works.mjs): a dependency-free Node script. Copy it into your repository and run `node install-i18n-works.mjs`. It installs the package with your package manager, adds `.env.local` to `.gitignore`, creates a template `.env.local`, and prints the setup steps (`vite-i18n.config.js` and `vite.config.ts`). Use `--dry-run` to preview and `--skip-install` to skip the install.
|
|
451
|
-
|
|
452
|
-
### ๐งช Try the bundled example
|
|
453
|
-
|
|
454
|
-
The `example/` folder contains a React document dashboard. It is a separate project with its own `package.json`, and it uses the published `i18n-works` package rather than this repository's source:
|
|
455
|
-
|
|
456
|
-
```sh
|
|
457
|
-
cd example
|
|
458
|
-
bun install
|
|
459
|
-
bun run dev # dev server
|
|
460
|
-
bun run build # production build into example/dist
|
|
461
|
-
```
|
|
462
|
-
|
|
463
|
-
The example reads provider keys from `example/.env.local`.
|
|
464
|
-
|
|
465
|
-
Each locale file has two parts: `messages` (the translations) and `sources` (the source text each translation was made from).
|
|
466
|
-
|
|
467
|
-
## ๐ Examples
|
|
468
|
-
|
|
469
|
-
### Minimal build with one locale per CI job
|
|
470
|
-
|
|
471
|
-
Set `locale` or the `I18N_WORKS_LOCALE` variable. Only that locale is translated and compiled:
|
|
472
|
-
|
|
473
|
-
```js
|
|
474
|
-
// vite-i18n.config.js
|
|
475
|
-
export default {
|
|
476
|
-
locales: ["en", "de", "fr"],
|
|
477
|
-
locale: process.env.I18N_WORKS_LOCALE, // undefined = all locales
|
|
478
|
-
provider: new OpenAICompatibleProvider({ apiKey: process.env.OPENAI_API_KEY, model: "gpt-4.1-mini" }),
|
|
479
|
-
failOnMissingProvider: true,
|
|
480
|
-
};
|
|
481
|
-
```
|
|
482
|
-
|
|
483
|
-
```yaml
|
|
484
|
-
# .github/workflows/build.yml (excerpt)
|
|
485
|
-
strategy:
|
|
486
|
-
matrix:
|
|
487
|
-
locale: [en, de, fr]
|
|
488
|
-
steps:
|
|
489
|
-
- run: I18N_WORKS_LOCALE=${{ matrix.locale }} npx vite build --outDir dist/${{ matrix.locale }}
|
|
490
|
-
```
|
|
491
|
-
|
|
492
|
-
### Runtime delivery with a locale switcher
|
|
493
|
-
|
|
494
|
-
```js
|
|
495
|
-
// vite-i18n.config.js
|
|
496
|
-
export default { locales: ["en", "de", "fr"], delivery: "runtime" }; // no provider: source text is shown until translations exist
|
|
497
|
-
```
|
|
498
|
-
|
|
499
|
-
```ts
|
|
500
|
-
import react from "@vitejs/plugin-react";
|
|
501
|
-
// vite.config.ts
|
|
502
|
-
import i18nWorks from "i18n-works";
|
|
503
|
-
|
|
504
|
-
export default { plugins: [i18nWorks(), react()] }; // keep i18nWorks before the React plugin
|
|
505
|
-
```
|
|
506
|
-
|
|
507
|
-
```tsx
|
|
508
|
-
// src/LocaleSwitcher.tsx
|
|
509
|
-
import { useSyncExternalStore } from "react";
|
|
510
|
-
import { getLocale, getVersion, locales, setLocale, subscribe } from "virtual:i18n-works";
|
|
511
|
-
|
|
512
|
-
export function LocaleSwitcher() {
|
|
513
|
-
// Re-render when the locale or any catalogue changes
|
|
514
|
-
useSyncExternalStore(subscribe, getVersion, getVersion);
|
|
515
|
-
return (
|
|
516
|
-
<select value={getLocale()} onChange={(e) => setLocale(e.target.value)}>
|
|
517
|
-
{locales.map((code) => (
|
|
518
|
-
<option key={code} value={code} translate="no">
|
|
519
|
-
{code}
|
|
520
|
-
</option>
|
|
521
|
-
))}
|
|
522
|
-
</select>
|
|
523
|
-
);
|
|
524
|
-
}
|
|
525
|
-
```
|
|
526
|
-
|
|
527
|
-
### Locale groups in practice
|
|
528
|
-
|
|
529
|
-

|
|
530
|
-
|
|
531
|
-
Groups from the `locales` export replace long lists of codes. Spread them into `locales`, and add any extra codes next to them:
|
|
532
|
-
|
|
533
|
-
```js
|
|
534
|
-
// vite-i18n.config.js
|
|
535
|
-
import { locales } from "i18n-works";
|
|
536
|
-
|
|
537
|
-
export default {
|
|
538
|
-
// A European product: all EU languages plus the major non-EU ones
|
|
539
|
-
locales: [...locales.EUROPE],
|
|
540
|
-
|
|
541
|
-
// A global app: Asia and the Americas (AMERICAS already includes English)
|
|
542
|
-
// locales: [...locales.ASIA, ...locales.AMERICAS],
|
|
543
|
-
|
|
544
|
-
// A Nordic site that also ships Estonian
|
|
545
|
-
// locales: [...locales.NORDIC, "et"],
|
|
546
|
-
};
|
|
547
|
-
```
|
|
548
|
-
|
|
549
|
-
The `locales` export from `virtual:i18n-works` (runtime delivery) is a different thing: it lists the codes this build ships, so it reflects whichever array you passed to the plugin.
|
|
550
|
-
|
|
551
|
-
### Keeping copy untranslated
|
|
552
|
-
|
|
553
|
-
Only `t()` calls are extracted. Anything not wrapped in `t()` stays in the source language, including JSX text, attributes and `translate="no"` elements.
|
|
554
|
-
|
|
555
|
-
### Marking strings
|
|
556
|
-
|
|
557
|
-
Wrap each literal in `t()`, imported from the virtual module:
|
|
558
|
-
|
|
559
|
-
```tsx
|
|
560
|
-
import { t } from "virtual:i18n-works";
|
|
561
|
-
|
|
562
|
-
export function Items() {
|
|
563
|
-
const items = [{ label: t("Shared with your team") }, { label: "Private" }];
|
|
564
|
-
return (
|
|
565
|
-
<ul>
|
|
566
|
-
{items.map((i) => (
|
|
567
|
-
<li key={i.label}>{i.label}</li>
|
|
568
|
-
))}
|
|
569
|
-
</ul>
|
|
570
|
-
);
|
|
571
|
-
}
|
|
572
|
-
```
|
|
573
|
-
|
|
574
|
-
Only `"Shared with your team"` is translated. `"Private"` is not wrapped in `t()` and stays English.
|
|
575
|
-
|
|
576
|
-
`t()` is recognised only when it is imported from `virtual:i18n-works`, so calls to other libraries' `t()` functions are left alone. A call is extracted when its first argument is a string literal, with an optional second argument of values. Variables, template literals and spread values are not translated, and at runtime `t(source, values)` formats its source with the values and otherwise returns it unchanged.
|
|
577
|
-
|
|
578
|
-
> [!NOTE]
|
|
579
|
-
> In runtime delivery, the lookup runs when the expression is evaluated. A `t()` call at module level runs at import time, so it needs the [module-level translations](#module-level-translations) setup to follow the locale.
|
|
580
|
-
|
|
581
|
-
### Writing your own provider
|
|
582
|
-
|
|
583
|
-
Any object with a `translate` method works:
|
|
584
|
-
|
|
585
|
-
```ts
|
|
586
|
-
import type { TranslationProvider } from "i18n-works";
|
|
587
|
-
|
|
588
|
-
const custom: TranslationProvider = {
|
|
589
|
-
async translate({ sourceLocale, targetLocale, messages }) {
|
|
590
|
-
const out: Record<string, string> = {};
|
|
591
|
-
for (const m of messages) {
|
|
592
|
-
out[m.id] = await callYourService(m.source, targetLocale);
|
|
593
|
-
}
|
|
594
|
-
return out;
|
|
595
|
-
},
|
|
596
|
-
};
|
|
597
|
-
```
|
|
598
|
-
|
|
599
|
-
Return only the IDs you translated. Empty or non-string values are dropped. Throw `PartialTranslationError` to keep a partial result.
|
|
600
|
-
|
|
601
|
-
## ๐ Delivery modes
|
|
602
|
-
|
|
603
|
-
```mermaid
|
|
604
|
-
flowchart TD
|
|
605
|
-
start["Transform source"] --> mode{"delivery?"}
|
|
606
|
-
mode -->|"build (default)"| b["Bake one locale's text into the code<br/>set by locale or I18N_WORKS_LOCALE"]
|
|
607
|
-
mode -->|"runtime"| r["Wrap text in lookups<br/>catalogues loaded on demand"]
|
|
608
|
-
b --> bout["One bundle per locale"]
|
|
609
|
-
r --> rout["One bundle, switch with setLocale()"]
|
|
610
|
-
```
|
|
611
|
-
|
|
612
|
-
| | `build` (default) | `runtime` |
|
|
613
|
-
| ------------------------------------ | ----------------------------------------------- | ------------------------------ |
|
|
614
|
-
| Bundles | One per locale | One for all locales |
|
|
615
|
-
| Locale chosen | At build time (`locale` or `I18N_WORKS_LOCALE`) | In the browser (`setLocale()`) |
|
|
616
|
-
| Only the chosen locale is translated | Yes, when a locale is set explicitly | No, all configured locales |
|
|
617
|
-
| Unknown locale | Fails the build | โ |
|
|
618
|
-
|
|
619
|
-
### Build delivery
|
|
620
|
-
|
|
621
|
-
Use `I18N_WORKS_LOCALE=de vite build` (on Windows, `cross-env I18N_WORKS_LOCALE=de vite build`) or `locale: "de"` in the plugin options, typically in a CI build matrix. When a locale is set explicitly, only that locale is translated during the build. Without one, all configured locales are translated. An unknown locale fails the build.
|
|
622
|
-
|
|
623
|
-
### Runtime delivery
|
|
624
|
-
|
|
625
|
-
Each `t("...")` string is replaced with a `lookup(id, source)` call, and catalogues are fetched on demand. Import the API from the virtual module:
|
|
626
|
-
|
|
627
|
-
```ts
|
|
628
|
-
import { getLocale, locales, resolveSupported, setLocale, subscribe, t } from "virtual:i18n-works";
|
|
629
|
-
|
|
630
|
-
setLocale(resolveSupported(navigator.languages)); // call before first render
|
|
631
|
-
```
|
|
632
|
-
|
|
633
|
-
- `tpick`, `createLocaleLoader` and `resolveLocale` are also exported from the `i18n-works/tools` subpath, which holds only the browser-safe runtime helpers, so plugin code stays out of client bundles. Import `tpick` from there in client code. `tpick(variable, options, fallback = "other")` returns the option whose key equals the value of a single variable, for example `tpick({ status }, { online: t("Online"), other: t("Unknown") })`.
|
|
634
|
-
- `subscribe(listener)` returns an unsubscribe function.
|
|
635
|
-
- `getVersion()` changes whenever the locale or the catalogues change, so `useSyncExternalStore(subscribe, getVersion, getVersion)` re-renders components that read `t()` during render.
|
|
636
|
-
|
|
637
|
-
### Module-level translations
|
|
638
|
-
|
|
639
|
-
A `t()` call outside any function, for example `const title = t("Documents");` at the top of a file, runs while the module is imported, before anything can call `setLocale()`. When the build contains such calls, the plugin changes how the locale is chosen:
|
|
640
|
-
|
|
641
|
-
- The locale is stored in `localStorage` under `i18n-works:locale`. On startup, the stored locale is applied if it is in `locales`, otherwise `resolveSupported(navigator.languages)` is used. This happens before any module is evaluated, using top-level await.
|
|
642
|
-
- `setLocale(code)` saves the choice and reloads the page, so module-level calls are re-evaluated in the new locale.
|
|
643
|
-
- Do not call `setLocale(...)` at startup. It would overwrite the saved choice on every load. Let the plugin choose the starting locale, and call `setLocale()` only from a language switcher.
|
|
644
|
-
- Top-level await must be supported by your build target. Apps without module-level calls keep the behaviour above.
|
|
645
|
-
- Components wrapped in `memo` must subscribe themselves, or they keep the old text until their props change.
|
|
646
|
-
- Add a type declaration for `virtual:i18n-works` (see [example/src/i18n-works-virtual.d.ts](example/src/i18n-works-virtual.d.ts)). The example app uses this mode with a locale switcher.
|
|
647
|
-
|
|
648
|
-
## ๐ง Configuration
|
|
649
|
-
|
|
650
|
-
### Plugin options (`vite-i18n.config.js`)
|
|
651
|
-
|
|
652
|
-
Every option is set in `vite-i18n.config.js`. `i18nWorks()` takes no arguments. Passing an object to it throws an error that says to move the options to the config file.
|
|
653
|
-
|
|
654
|
-
If you upgrade from a version that took options in `vite.config.ts` (`i18nWorks({...})`), move that object into `vite-i18n.config.js` as its default export and call `i18nWorks()` with no arguments.
|
|
655
|
-
|
|
656
|
-
| Option | Type | Default | Description |
|
|
657
|
-
| ------------------------ | ------------------------------------------------------------------------------- | --------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
658
|
-
| `locales` | `string[]` | _required_ | Locales the app ships, for example `["en", "de", "fr"]`. The source locale is never translated, so including it is harmless. |
|
|
659
|
-
| `sourceLocale` | `string` | `"en"` | Language the `t()` strings are written in. Used as the fallback when a translation is missing. |
|
|
660
|
-
| `delivery` | `"build" \| "runtime"` | `"build"` | `build` compiles one locale per build. `runtime` ships every catalogue and switches locale in the browser with `setLocale()`. |
|
|
661
|
-
| `locale` | `string` | `sourceLocale` | Locale to compile in `build` delivery. Also read from `I18N_WORKS_LOCALE`; the option wins when both are set. |
|
|
662
|
-
| `include` | `string[]` | `["src/**/*.{tsx,jsx,ts,js}"]` | Glob patterns of source files to scan, relative to the Vite root. |
|
|
663
|
-
| `exclude` | `string[]` | `["**/*.test.*", "**/node_modules/**"]` | Glob patterns of files to skip, relative to the Vite root. |
|
|
664
|
-
| `directory` | `string` | `".i18n-works"` | Folder for `registry.json` and `locales/`, relative to the Vite root. |
|
|
665
|
-
| `provider` | `TranslationProvider \| { primary?, [name]: TranslationProvider \| undefined }` | `undefined` | Translates missing and changed messages. One provider, or named providers with a `primary`. Without one, untranslated messages show the source text. |
|
|
666
|
-
| `failOnMissingProvider` | `boolean` | `false` | When `true`, the build fails if a locale has untranslated messages and no `provider` is set. |
|
|
667
|
-
| `onAmbiguous` | `"warn" \| "error"` | `"warn"` | What to do when duplicated identical texts change their occurrence count, so their IDs may have moved. `"error"` fails the build. |
|
|
668
|
-
| `orphanRetentionMinutes` | `number` | `43200` (30 days) | Minutes an orphaned message is kept before deletion. `0` deletes on the next build; `Infinity` keeps forever. |
|
|
669
|
-
| `localeConcurrency` | `number` | `2` | Locales translated at the same time. Values below 1 are raised to 1, and fractions are rounded down. |
|
|
670
|
-
| `debug` | `boolean` | `false` | Logs each message sent to the provider, each translation received, and each removed orphan, with timestamps. |
|
|
671
|
-
| `costs` | `boolean` | `false` | Logs each AI request that produced translations and stores it in `costs` in `registry.json`: time, message IDs, model, tokens and estimated cost. |
|
|
672
|
-
|
|
673
|
-
<details>
|
|
674
|
-
<summary><strong>Locale groups</strong>: ready-made lists for the <code>locales</code> option</summary>
|
|
675
|
-
|
|
676
|
-
The package exports a `locales` object with ready-made locale lists. Each group is a plain array of BCP 47 codes. Spread a group so the shared object stays unchanged:
|
|
677
|
-
|
|
678
|
-
```ts
|
|
679
|
-
import i18nWorks, { locales } from "i18n-works";
|
|
680
|
-
|
|
681
|
-
export default {
|
|
682
|
-
locales: [...locales.EUROPE], // or ["en", ...locales.ASIA]
|
|
683
|
-
};
|
|
684
|
-
```
|
|
685
|
-
|
|
686
|
-
| Group | Languages |
|
|
687
|
-
| --------------------------- | --------------------------------------------------------------------------------------------------------------------- |
|
|
688
|
-
| `EU` | 23 official EU languages |
|
|
689
|
-
| `EUROPE` | `EU` plus Norwegian, Icelandic, Albanian, Bosnian, Macedonian, Serbian, Ukrainian, Russian, Belarusian, Catalan |
|
|
690
|
-
| `NORDIC` | Danish, Finnish, Icelandic, Norwegian, Swedish |
|
|
691
|
-
| `BALTIC` | Estonian, Latvian, Lithuanian |
|
|
692
|
-
| `BALKANS` | Albanian, Bosnian, Bulgarian, Croatian, Greek, Macedonian, Romanian, Serbian, Slovenian |
|
|
693
|
-
| `BENELUX` | Dutch, French, Luxembourgish |
|
|
694
|
-
| `EAST_ASIA` | Chinese, Japanese, Korean, Mongolian |
|
|
695
|
-
| `SOUTH_ASIA` | Hindi, Bengali, Urdu, Punjabi, Tamil, Telugu, Marathi, Gujarati, Kannada, Malayalam, Nepali, Sinhala |
|
|
696
|
-
| `SOUTHEAST_ASIA` | Indonesian, Malay, Burmese, Khmer, Lao, Filipino, Thai, Vietnamese |
|
|
697
|
-
| `CENTRAL_ASIA` | Kazakh, Kyrgyz, Tajik, Turkmen, Uzbek |
|
|
698
|
-
| `CAUCASUS` | Armenian, Azerbaijani, Georgian |
|
|
699
|
-
| `ASIA` | `EAST_ASIA`, `SOUTH_ASIA`, `SOUTHEAST_ASIA`, `CENTRAL_ASIA`, `CAUCASUS` |
|
|
700
|
-
| `MIDDLE_EAST` | Arabic, Persian, Hebrew, Turkish, Kurdish |
|
|
701
|
-
| `AFRICA` | Arabic, French, Portuguese, Swahili, Amharic, Hausa, Yoruba, Igbo, Zulu, Xhosa, Afrikaans, Somali, Kinyarwanda, Wolof |
|
|
702
|
-
| `NORTH_AMERICA` | English, French, Spanish |
|
|
703
|
-
| `CENTRAL_AMERICA_CARIBBEAN` | Spanish, English, French, Haitian Creole, Dutch |
|
|
704
|
-
| `SOUTH_AMERICA` | Spanish, Portuguese, Quechua, Guarani, Aymara |
|
|
705
|
-
| `AMERICAS` | `NORTH_AMERICA`, `CENTRAL_AMERICA_CARIBBEAN`, `SOUTH_AMERICA` |
|
|
706
|
-
| `OCEANIA` | English, Maori, Samoan, Tongan |
|
|
707
|
-
| `ASEAN` | `SOUTHEAST_ASIA` languages plus English (working language) |
|
|
708
|
-
| `MERCOSUR` | Spanish, Portuguese, Guarani |
|
|
709
|
-
| `GCC` | Arabic, English |
|
|
710
|
-
| `CIS` | Russian, Belarusian, Armenian, Azerbaijani, Kazakh, Kyrgyz, Tajik, Uzbek |
|
|
711
|
-
| `G7` | English, French, German, Italian, Japanese |
|
|
712
|
-
| `FRANCOPHONE` | French, Haitian Creole, Wolof, Lingala, Kinyarwanda |
|
|
713
|
-
| `WORLDWIDE_POPULAR` | The 17 languages with the most speakers worldwide, including English, Chinese, Hindi, Spanish, and Arabic |
|
|
714
|
-
|
|
715
|
-
</details>
|
|
716
|
-
|
|
717
|
-
## ๐ Providers
|
|
718
|
-
|
|
719
|
-

|
|
720
|
-
|
|
721
|
-
### Choosing a provider
|
|
722
|
-
|
|
723
|
-
Every service is either a native API (Anthropic, Gemini), or speaks the OpenAI Chat Completions protocol and is used through `OpenAICompatibleProvider` with a different `baseURL`. The library reads no environment variables itself; the key names below are what the example config uses.
|
|
724
|
-
|
|
725
|
-
<details>
|
|
726
|
-
<summary><strong>All supported services</strong> (key variable, base URL, example model)</summary>
|
|
727
|
-
|
|
728
|
-
| Service | Class | Key variable | Base URL | Example default model |
|
|
729
|
-
| ---------------------------------------- | -------------------------- | --------------------- | -------------------------------------------------- | --------------------------------------------------- |
|
|
730
|
-
| Anthropic (Claude) | `AnthropicProvider` | `ANTHROPIC_API_KEY` | `https://api.anthropic.com/v1` | `claude-haiku-5-5` |
|
|
731
|
-
| Gemini | `GeminiProvider` | `GEMINI_API_KEY` | `https://generativelanguage.googleapis.com/v1beta` | `gemini-3.5-flash-lite` |
|
|
732
|
-
| OpenAI | `OpenAICompatibleProvider` | `OPENAI_API_KEY` | `https://api.openai.com/v1` (default) | `gpt-4.1-mini` |
|
|
733
|
-
| Mistral | `OpenAICompatibleProvider` | `MISTRAL_API_KEY` | `https://api.mistral.ai/v1` | `mistral-small-latest` |
|
|
734
|
-
| Groq | `OpenAICompatibleProvider` | `GROQ_API_KEY` | `https://api.groq.com/openai/v1` | `llama-3.3-70b-versatile` |
|
|
735
|
-
| DeepSeek | `OpenAICompatibleProvider` | `DEEPSEEK_API_KEY` | `https://api.deepseek.com/v1` | `deepseek-chat` |
|
|
736
|
-
| OpenRouter | `OpenAICompatibleProvider` | `OPENROUTER_API_KEY` | `https://openrouter.ai/api/v1` | `openai/gpt-4.1-mini` |
|
|
737
|
-
| xAI | `OpenAICompatibleProvider` | `XAI_API_KEY` | `https://api.x.ai/v1` | `grok-3-mini` |
|
|
738
|
-
| Cerebras | `OpenAICompatibleProvider` | `CEREBRAS_API_KEY` | `https://api.cerebras.ai/v1` | `llama-3.3-70b` |
|
|
739
|
-
| Perplexity | `OpenAICompatibleProvider` | `PERPLEXITY_API_KEY` | `https://api.perplexity.ai` | `sonar` |
|
|
740
|
-
| Together AI | `OpenAICompatibleProvider` | `TOGETHER_API_KEY` | `https://api.together.xyz/v1` | `meta-llama/Llama-3.3-70B-Instruct-Turbo` |
|
|
741
|
-
| Fireworks AI | `OpenAICompatibleProvider` | `FIREWORKS_API_KEY` | `https://api.fireworks.ai/inference/v1` | `accounts/fireworks/models/llama-v3p3-70b-instruct` |
|
|
742
|
-
| Hugging Face | `OpenAICompatibleProvider` | `HUGGINGFACE_API_KEY` | `https://router.huggingface.co/v1` | `meta-llama/Llama-3.3-70B-Instruct` |
|
|
743
|
-
| DeepInfra | `OpenAICompatibleProvider` | `DEEPINFRA_API_KEY` | `https://api.deepinfra.com/v1/openai` | `meta-llama/Meta-Llama-3.1-70B-Instruct` |
|
|
744
|
-
| SambaNova | `OpenAICompatibleProvider` | `SAMBANOVA_API_KEY` | `https://api.sambanova.ai/v1` | `Meta-Llama-3.3-70B-Instruct` |
|
|
745
|
-
| Moonshot (Kimi) | `OpenAICompatibleProvider` | `MOONSHOT_API_KEY` | `https://api.moonshot.ai/v1` | `moonshot-v1-8k` |
|
|
746
|
-
| Ollama (local, no key) | `OpenAICompatibleProvider` | none | `http://localhost:11434/v1` | none, you must set one |
|
|
747
|
-
| LM Studio (local, no key) | `OpenAICompatibleProvider` | none | `http://localhost:1234/v1` | none, you must set one |
|
|
748
|
-
| llama.cpp `llama-server` (local, no key) | `OpenAICompatibleProvider` | none | `http://localhost:8080/v1` | none, you must set one |
|
|
749
|
-
| vLLM (local, no key) | `OpenAICompatibleProvider` | none | `http://localhost:8000/v1` | none, you must set one |
|
|
750
|
-
| LocalAI (local, no key) | `OpenAICompatibleProvider` | none | `http://localhost:8080/v1` | none, you must set one |
|
|
751
|
-
| Docker Model Runner (local, no key) | `OpenAICompatibleProvider` | none | `http://localhost:12434/engines/v1` | none, you must set one |
|
|
752
|
-
|
|
753
|
-
</details>
|
|
754
|
-
|
|
755
|
-
- **Model names change often.** The defaults are examples; set `model` to any name the service currently offers.
|
|
756
|
-
- **Hosted services** are enabled in the example config only when their key variable is set. `<NAME>_MODEL` also overrides the default model (for example `MISTRAL_MODEL`).
|
|
757
|
-
- **Local runtimes** have no key. They are enabled by `<NAME>_MODEL` (the model you have loaded, for example `OLLAMA_MODEL` or `LMSTUDIO_MODEL`), with `<NAME>_BASE_URL` to override the server address (for example `LLAMACPP_BASE_URL`).
|
|
758
|
-
- **Keyless servers:** omit `apiKey`. The `Authorization` header is then not sent.
|
|
759
|
-
- **Use a model that reliably returns JSON.** Small local models often do not. Malformed replies are retried, then left untranslated.
|
|
760
|
-
- The Mistral, Groq, DeepSeek, OpenRouter, xAI, Cerebras, Ollama and other services added after them were checked against their documentation and with stubbed HTTP responses only, not against live services. Local runtimes default to their standard ports, which can differ per install.
|
|
761
|
-
|
|
762
|
-
```ts
|
|
763
|
-
new OpenAICompatibleProvider({
|
|
764
|
-
apiKey: env.GROQ_API_KEY!,
|
|
765
|
-
baseURL: "https://api.groq.com/openai/v1",
|
|
766
|
-
model: "llama-3.3-70b-versatile",
|
|
767
|
-
});
|
|
768
|
-
new OpenAICompatibleProvider({ baseURL: "http://localhost:11434/v1", model: "qwen2.5:7b" }); // Ollama, no key
|
|
769
|
-
```
|
|
770
|
-
|
|
771
|
-
### Built-in provider options
|
|
772
|
-
|
|
773
|
-
All three model providers send messages in batches, run requests in parallel, time out, and retry. Create them with `new OpenAICompatibleProvider(options)`, `new AnthropicProvider(options)` or `new GeminiProvider(options)`.
|
|
774
|
-
|
|
775
|
-
**Shared by all three:**
|
|
776
|
-
|
|
777
|
-
| Option | Default | Description |
|
|
778
|
-
| -------------- | ---------- | ---------------------------------------------------------------------------------- |
|
|
779
|
-
| `model` | _required_ | Model name sent in each request. |
|
|
780
|
-
| `batchSize` | `40` | Messages per request. Smaller batches keep responses within output limits. |
|
|
781
|
-
| `concurrency` | `4` | Batches sent in parallel across all locales of this provider instance. |
|
|
782
|
-
| `timeoutMs` | `60000` | Milliseconds before a single request is aborted. |
|
|
783
|
-
| `maxRetries` | `2` | Extra attempts for network errors, timeouts, 408/409/429/5xx and malformed output. |
|
|
784
|
-
| `retryDelayMs` | `500` | Delay before the first retry. It doubles on each attempt. |
|
|
785
|
-
|
|
786
|
-
**`OpenAICompatibleProvider`** calls `${baseURL}/chat/completions`.
|
|
787
|
-
|
|
788
|
-
| Option | Default | Description |
|
|
789
|
-
| --------- | ----------------------------- | -------------------------------------------------------------------------------------------------------------- |
|
|
790
|
-
| `apiKey` | _optional_ | Bearer token. Omit for servers that need no key, such as a local Ollama. Read it from an environment variable. |
|
|
791
|
-
| `baseURL` | `"https://api.openai.com/v1"` | Base URL of any OpenAI-compatible API. |
|
|
792
|
-
|
|
793
|
-
**`AnthropicProvider`** calls the [Anthropic Messages API](https://docs.anthropic.com/en/api/messages) at `${baseURL}/messages`.
|
|
794
|
-
|
|
795
|
-
| Option | Default | Description |
|
|
796
|
-
| ----------- | -------------------------------- | ------------------------------------------------------------------------------------------- |
|
|
797
|
-
| `apiKey` | _required_ | Anthropic API key, sent as `x-api-key`. Read it from an environment variable. |
|
|
798
|
-
| `baseURL` | `"https://api.anthropic.com/v1"` | Base URL of the Messages API. |
|
|
799
|
-
| `maxTokens` | `8192` | Maximum tokens the model may generate per batch. Lower it only if your model limits output. |
|
|
800
|
-
|
|
801
|
-
**`GeminiProvider`** calls the [Gemini `generateContent` endpoint](https://ai.google.dev/api/generate-content) at `${baseURL}/models/${model}:generateContent` in JSON output mode.
|
|
802
|
-
|
|
803
|
-
| Option | Default | Description |
|
|
804
|
-
| ----------------- | ---------------------------------------------------- | ------------------------------------------------------------------------------------------- |
|
|
805
|
-
| `apiKey` | _required_ | Gemini API key, sent as `x-goog-api-key`. Read it from an environment variable. |
|
|
806
|
-
| `baseURL` | `"https://generativelanguage.googleapis.com/v1beta"` | Base URL of the Gemini API. |
|
|
807
|
-
| `maxOutputTokens` | `8192` | Maximum tokens the model may generate per batch. Lower it only if your model limits output. |
|
|
808
|
-
|
|
809
|
-
Example: `new GeminiProvider({ apiKey: env.GEMINI_API_KEY!, model: "gemini-3.5-flash-lite" })`.
|
|
810
|
-
|
|
811
|
-
### Helpers for named provider maps
|
|
812
|
-
|
|
813
|
-
Instead of writing `env.X ? new Provider(...) : undefined` for each service, use the helpers exported from the package. Each returns `undefined` when its credentials are missing, so the entry is skipped. They take values, not environment names, so the library still reads no environment variables and never receives the whole `env` object: you pick the keys and pass only those values.
|
|
814
|
-
|
|
815
|
-
| Helper | Enum | Enabled by | Returns |
|
|
816
|
-
| --------------------------------------------------- | ----------------------------------------------- | ---------------------------- | -------------------------------------------------------------------- |
|
|
817
|
-
| `hosted(HostedService.X, apiKey, model?)` | `HostedService` (Anthropic and Gemini included) | `apiKey` | `AnthropicProvider`, `GeminiProvider`, or `OpenAICompatibleProvider` |
|
|
818
|
-
| `local(LocalService.X, model, baseURL?)` | `LocalService` | `model` (you have loaded it) | `OpenAICompatibleProvider` |
|
|
819
|
-
| `hostedFromEnv(HostedService.X, { apiKey, model })` | `HostedService` | `apiKey` | Same as `hosted` |
|
|
820
|
-
| `localFromEnv(LocalService.X, { model, baseURL })` | `LocalService` | `model` | Same as `local` |
|
|
821
|
-
|
|
822
|
-
The `*FromEnv` helpers are `hosted` and `local` with the values passed as an object, so you can pass only the variables you read.
|
|
823
|
-
|
|
824
|
-
```js
|
|
825
|
-
import { hosted, hostedFromEnv, HostedService, local, localFromEnv, LocalService } from "i18n-works";
|
|
826
|
-
// vite-i18n.config.js
|
|
827
|
-
import { loadEnv } from "vite";
|
|
828
|
-
|
|
829
|
-
export default ({ mode }) => {
|
|
830
|
-
const env = loadEnv(mode, process.cwd(), "");
|
|
831
|
-
|
|
832
|
-
return {
|
|
833
|
-
provider: {
|
|
834
|
-
primary: env.PRIMARY_PROVIDER || undefined,
|
|
835
|
-
mistral: hosted(HostedService.Mistral, env.MISTRAL_API_KEY, env.MISTRAL_MODEL),
|
|
836
|
-
ollama: local(LocalService.Ollama, env.OLLAMA_MODEL, env.OLLAMA_BASE_URL),
|
|
837
|
-
anthropic: hostedFromEnv(HostedService.Anthropic, { apiKey: env.ANTHROPIC_API_KEY, model: env.ANTHROPIC_MODEL }),
|
|
838
|
-
llamacpp: localFromEnv(LocalService.LlamaCpp, { model: env.LLAMACPP_MODEL, baseURL: env.LLAMACPP_BASE_URL }),
|
|
839
|
-
},
|
|
840
|
-
};
|
|
841
|
-
};
|
|
842
|
-
```
|
|
843
|
-
|
|
844
|
-
The `model` and `baseURL` arguments override the defaults. Passing `undefined` keeps the default.
|
|
845
|
-
|
|
846
|
-
### Multiple providers and fallback
|
|
847
|
-
|
|
848
|
-
Pass `provider` as an object with one entry per provider.
|
|
849
|
-
|
|
850
|
-
- **`primary`** names the provider tried first. It is never inferred: set it yourself, or leave it out to try providers in declaration order.
|
|
851
|
-
- Entries set to `undefined` are skipped, so you can keep every provider in the config and enable each one by its key.
|
|
852
|
-
|
|
853
|
-
```ts
|
|
854
|
-
provider: {
|
|
855
|
-
primary: "anthropic",
|
|
856
|
-
anthropic: env.ANTHROPIC_API_KEY ? new AnthropicProvider({ apiKey: env.ANTHROPIC_API_KEY, model: "claude-haiku-5-5" }) : undefined,
|
|
857
|
-
openai: env.OPENAI_API_KEY ? new OpenAICompatibleProvider({ apiKey: env.OPENAI_API_KEY, model: "gpt-4.1-mini" }) : undefined,
|
|
858
|
-
gemini: env.GEMINI_API_KEY ? new GeminiProvider({ apiKey: env.GEMINI_API_KEY, model: "gemini-3.5-flash-lite" }) : undefined
|
|
859
|
-
}
|
|
860
|
-
```
|
|
861
|
-
|
|
862
|
-
**How fallback works**
|
|
863
|
-
|
|
864
|
-
- If the primary fails (for example a bad key, an outage, or rate limits that survive the retries), the messages it did not translate go to the next configured provider, in declaration order.
|
|
865
|
-
- Fallback happens per batch. A partial result keeps the translations that came back, and only the missing messages move on.
|
|
866
|
-
- The build logs a warning each time it falls back.
|
|
867
|
-
- If every provider fails, the locale keeps its previous file, as with a single provider.
|
|
868
|
-
- Naming a `primary` that is not configured fails the build with a clear error.
|
|
869
|
-
- Passing a single provider instance (`provider: new AnthropicProvider(...)`) still works and needs no map.
|
|
870
|
-
|
|
871
|
-
### Custom providers
|
|
872
|
-
|
|
873
|
-
Any object with this shape can be passed as `provider`:
|
|
874
|
-
|
|
875
|
-
```ts
|
|
876
|
-
interface TranslationProvider {
|
|
877
|
-
translate(input: {
|
|
878
|
-
sourceLocale: string;
|
|
879
|
-
targetLocale: string;
|
|
880
|
-
messages: TranslationRequest[];
|
|
881
|
-
}): Promise<Record<string, string>>; // message ID -> translated text
|
|
882
|
-
}
|
|
883
|
-
|
|
884
|
-
interface TranslationRequest {
|
|
885
|
-
id: string; // opaque ID to echo back in the result
|
|
886
|
-
source: string; // English text
|
|
887
|
-
context: string; // component the call sits in, or "<module>" at top level
|
|
888
|
-
}
|
|
889
|
-
```
|
|
890
|
-
|
|
891
|
-
- Return only the IDs you translated. Omitted IDs stay in the source language and are requested again on the next build.
|
|
892
|
-
- To keep partial results, throw `PartialTranslationError` (exported from the package) with the translations you have and the number of failed messages.
|
|
893
|
-
- Any other error fails the whole locale, which keeps its previous file.
|
|
894
|
-
|
|
895
|
-
## ๐ Reliability
|
|
896
|
-
|
|
897
|
-
- **Batching and retries.** Built-in providers send messages in batches (`batchSize`, default 40), run up to `concurrency` batches at once (default 4), abort after `timeoutMs` (default 60000), and retry up to `maxRetries` times (default 2) with exponential backoff from `retryDelayMs` (default 500). Other 4xx errors fail immediately.
|
|
898
|
-
- **Limited parallelism.** The plugin translates up to `localeConcurrency` locales at once (default 2). The provider's `concurrency` is shared by all locales, so at most `concurrency` batches are in flight per provider instance, not `localeConcurrency ร concurrency`. Lower `concurrency` if your provider rate-limits your account.
|
|
899
|
-
- **Missing messages.** If a provider omits some messages, the rest are kept. The missing ones stay in the source language until the next build retries them, and the build logs how many were left untranslated.
|
|
900
|
-
- **Failed batches.** If a batch fails, the other batches are still stored, and the failed messages fall back to the source text until the next build. If every batch for a locale fails, that locale keeps its previous file, and the build reports the error after writing the other locales.
|
|
901
|
-
- **Missing provider.** With `failOnMissingProvider: true`, the build fails when a locale is missing translations and no provider is configured, instead of silently shipping English.
|
|
902
|
-
- **Ambiguous matches.** Duplicate identical strings whose count changed are logged as warnings. Set `onAmbiguous: "error"` to fail the build instead. When a message is paired by fingerprint, the component name breaks ties between identical strings, so reordering or renaming components keeps existing IDs.
|
|
903
|
-
- **Privacy in logs.** Provider errors report only the HTTP status (for example `Translation API failed (500)`). The response body is discarded so provider output is not written to logs.
|
|
904
|
-
- **Incremental writes.** In dev, saving an indexed source file re-reads only that file and reuses cached extractions for the rest of the project. Adding or removing a file runs a full scan. Catalogue and registry files are written only when their content actually changes.
|
|
905
|
-
- **Safe files.** Writes are atomic, so an interrupted build does not leave a truncated file. Corrupt `registry.json` or catalogue files are renamed to `<file>.corrupt-<timestamp>` with a warning, and the plugin continues with an empty state.
|
|
906
|
-
|
|
907
|
-
## ๐งน Maintenance
|
|
908
|
-
|
|
909
|
-
### Orphans and retention
|
|
910
|
-
|
|
911
|
-
Messages removed from the source are kept as orphans in `registry.json`, so their IDs can be reused if the text returns. Orphans not seen for `orphanRetentionMinutes` (default `43200`, i.e. 30 days) are deleted on the next build, and the build logs how many were removed. Use `0` to delete them immediately or `Infinity` to keep them forever. Once deleted, a returning message gets a new ID and is translated again.
|
|
912
|
-
|
|
913
|
-
### Prune CLI
|
|
914
|
-
|
|
915
|
-
### Command-line tool and programmatic API
|
|
916
|
-
|
|
917
|
-
The package ships one bin, `vite-i18n`, with two subcommands: `prune` and `browse`. Run them from the project with `npx vite-i18n <command>` and the options listed below. With no command, `npx vite-i18n` runs `browse`, and so does `npx vite-i18n --source-locale de`, which gives options without a command.
|
|
918
|
-
|
|
919
|
-
The same functions are exported from `i18n-works/cli` for scripts and tooling. They take the options as an object, return data, and never read `process.argv`, set `process.exitCode`, or print on their own:
|
|
920
|
-
|
|
921
|
-
```ts
|
|
922
|
-
import { listLanguages, prune, stats, translate } from "i18n-works/cli";
|
|
923
|
-
|
|
924
|
-
const result = await prune({ root: process.cwd(), retentionMinutes: 0 });
|
|
925
|
-
const { report } = await stats({ root: process.cwd() });
|
|
926
|
-
const { languages } = await listLanguages({ root: process.cwd() });
|
|
927
|
-
const { changedLocales, warnings } = await translate({ root: process.cwd() });
|
|
928
|
-
```
|
|
929
|
-
|
|
930
|
-
`prune` returns the removed entries, the catalogue keys removed per file and the removed locale files. `stats` returns the `StatsReport` (or `undefined` when there is no registry), the same figures that `browse` shows in its language list. `translate` translates every missing or stale message in every locale, the same way a build does, and returns the locales whose text changed and any warnings. A locale whose provider call fails rejects after the locales that finished are written. `browse` needs an interactive terminal, so use `listLanguages`, `stats` or `translate` for scripts.
|
|
931
|
-
|
|
932
|
-
### Prune CLI
|
|
933
|
-
|
|
934
|
-
Prunes orphans without running a build.
|
|
935
|
-
|
|
936
|
-
```sh
|
|
937
|
-
cd example
|
|
938
|
-
bun run prune # example app, --retention-minutes 0
|
|
939
|
-
bun run prune -- --retention-minutes 1440 --debug
|
|
940
|
-
```
|
|
941
|
-
|
|
942
|
-
| Option | Default | Description |
|
|
943
|
-
| --------------------- | ----------------- | ---------------------------------------------------------------------------------------- |
|
|
944
|
-
| `--root` | current directory | Vite root. `vite-i18n.config.js` is read from here, and `--directory` is relative to it. |
|
|
945
|
-
| `--directory` | `.i18n-works` | Relative to `--root`. |
|
|
946
|
-
| `--retention-minutes` | `43200` (30 days) | Same meaning as the plugin option. |
|
|
947
|
-
| `--debug` | off | Prints each removed entry, locale file and key, with its source text and last-seen time. |
|
|
948
|
-
|
|
949
|
-
- In `example/`, `bun run prune` runs the CLI on the example app's `.i18n-works/` with `--retention-minutes 0`, so every orphan is removed.
|
|
950
|
-
- The CLI also removes any key from the `messages` and `sources` maps of `locales/*.json` that is no longer an active registry entry, so the catalogues match the registry.
|
|
951
|
-
- The CLI deletes every `locales/*.json` file whose locale is not in the configuration: the `sourceLocale` (default `en`) and the `locales` list in `vite-i18n.config.js`. For example, removing `"ro"` from `locales` deletes `locales/ro.json` on the next prune.
|
|
952
|
-
- The configuration must load. If `vite-i18n.config.js` is missing or invalid, the CLI reports the error and changes nothing.
|
|
953
|
-
- If no registry exists at that path, the CLI says so and changes nothing.
|
|
954
|
-
- Installed packages run `npx vite-i18n prune` with the same options.
|
|
955
|
-
|
|
956
|
-
### Browse CLI
|
|
957
|
-
|
|
958
|
-
Moves between the translation files in an interactive terminal and shows two languages side by side. A third column, the details pane, describes the selected message: its component, status and first and last seen dates from `registry.json`, the file and line it sits at, and a numbered preview of that line in the source. The pane is hidden when the terminal is narrower than 56 columns, and `p` hides or shows it in the comparison.
|
|
959
|
-
|
|
960
|
-
```sh
|
|
961
|
-
cd example
|
|
962
|
-
bun run browse # example app
|
|
963
|
-
bun run browse -- --directory .i18n-works --source-locale en
|
|
964
|
-
bun run browse -- --directory .i18n-works --list # print languages, no terminal needed
|
|
965
|
-
bun run browse -- --directory .i18n-works --list --json # stats report for CI
|
|
966
|
-
```
|
|
967
|
-
|
|
968
|
-
| Option | Default | Description |
|
|
969
|
-
| ----------------- | ------------- | ----------------------------------------------------------------------------------------------------------------- |
|
|
970
|
-
| `--directory` | `.i18n-works` | Folder to read. |
|
|
971
|
-
| `--source-locale` | `en` | Language shown on the right when a comparison opens, and marked source. Excluded from the stats. |
|
|
972
|
-
| `--list` | off | Prints the registry totals, each language with its progress and coverage, and exits. |
|
|
973
|
-
| `--json` | off | With `--list`, prints the full stats report as JSON, including the missing, outdated and orphaned IDs per locale. |
|
|
974
|
-
|
|
975
|
-
The language list shows, when a `registry.json` exists, the registry totals (entries, active and orphaned, and average coverage across locales) and the active entries per component. Each translated language then shows its coverage of the active entries, with its missing, outdated and orphaned counts. Without a registry the list shows only the translated counts. `--json` without `--list` is ignored.
|
|
976
|
-
|
|
977
|
-
Keys in the language list: โ/โ move, Enter compares the selected language with the source, `x` prunes, `t` translates every locale, `c` opens the costs view, `q` quits. `t` translates the missing and stale messages in every locale, as a build does, then shows the changed locales and the first warning in a status line. The run cannot be cancelled, and keys are ignored until it finishes.
|
|
978
|
-
|
|
979
|
-
When `browse` starts it evaluates what `prune` would remove and shows the result above the language list: the orphaned registry entries, the stale catalogue keys and the unconfigured locale files, or "nothing to remove". Nothing is changed by this check. Press `x` to review the same summary, then `y` to prune now or any other key to cancel. Pruning reloads the list. The evaluation is read-only, so it is safe to start `browse` at any time.
|
|
980
|
-
|
|
981
|
-
The costs view (`c`) summarises the calls recorded in the `costs` object of `registry.json`, which needs the `costs` option to be enabled. It shows the totals (calls, input and output tokens, cost), a table per model with its calls, tokens and cost, and a table per month. Months are UTC, taken from the time of each call. A call without a known price still counts toward calls and tokens, and the cost shows as `+N unpriced`. When every call is unpriced, the cost shows as `unknown`. Use โ/โ and PgUp/PgDn to scroll, and Esc or Backspace to return to the list. The view is read-only. Without recorded calls it shows a hint to enable the `costs` option.
|
|
982
|
-
|
|
983
|
-
Keys in the comparison: โ/โ change the left language, Tab and Shift+Tab change the right one, โ/โ move one message, PgUp/PgDn move ten, Home/End jump, Esc or Backspace return to the list, `p` toggles the details pane, `q` quits.
|
|
984
|
-
|
|
985
|
-
A missing translation shows as `(missing)`. The interactive view needs a terminal, so use `--list` in scripts.
|
|
986
|
-
|
|
987
|
-
Output is coloured only when it goes to a terminal. Progress is green when complete, yellow when partial and red when empty, the two column headings are coloured, missing translations are red italic, the cursor row is inverted, and the target line in the details preview is bold yellow. Set `NO_COLOR` (any non-empty value) or `TERM=dumb` to turn colour off.
|
|
988
|
-
|
|
989
|
-
Installed packages run `npx vite-i18n browse` with the same options, or just `npx vite-i18n`, since `browse` is the default command.
|
|
990
|
-
|
|
991
|
-
### Debugging
|
|
992
|
-
|
|
993
|
-
Set `debug: true` to print every translation exchange to the console. Each line is prefixed with `[i18n-works debug]` and an ISO timestamp:
|
|
994
|
-
|
|
995
|
-
- `sent`: each message sent to the provider
|
|
996
|
-
- `received`: each translation received back
|
|
997
|
-
|
|
998
|
-
Set `costs: true` to log each AI request that produced translations, prefixed `[i18n-works costs]`. Each line gives the time, the locale pair, the message IDs, the provider and model, the input and output tokens, and the estimated USD cost. Costs come from a built-in price table for the default Anthropic and OpenAI models. Models without a price, Gemini, and custom providers that do not report usage show "cost unknown". Prices change, so treat the estimate as approximate. Requests that fail to parse are billed by the provider but not logged.
|
|
999
|
-
|
|
1000
|
-
The same request is also stored in the `costs` object of `registry.json`, keyed by a `call_` ID, with `at`, `sourceLocale`, `locale`, `provider`, `model`, `ids`, `inputTokens`, `outputTokens` and `cost` (omitted when the model has no price). Records are written only while `costs` is on. Nothing removes them, so the object grows with every call. Calls from custom providers that do not report usage are logged but not stored.
|
|
1001
|
-
|
|
1002
|
-
### Upgrading from an earlier version
|
|
1003
|
-
|
|
1004
|
-
Options moved from `i18nWorks({...})` in `vite.config.ts` to `vite-i18n.config.js`. Move the object to the config file's default export and change the call to `i18nWorks()`. The plugin throws if it still receives an argument.
|
|
1005
|
-
|
|
1006
|
-
Message matching now uses a fingerprint of the source text alone, so every stored entry stops matching once and gets a new ID. The first build after upgrading re-translates every message and calls your provider again, which costs API spend. The old flat locale files and `*.sources.json` sidecars are not read and are deleted. Registry entries from before the upgrade become orphans and are pruned after `orphanRetentionMinutes`.
|
|
1007
|
-
|
|
1008
|
-
### ๐ Provider requirement
|
|
1009
|
-
|
|
1010
|
-
Translations need a provider. Without one, untranslated messages show the source text; set `failOnMissingProvider: true` to make that a build error.
|
|
1011
|
-
|
|
1012
|
-
## ๐งช Test coverage
|
|
1013
|
-
|
|
1014
|
-
Run the suite with coverage (V8 provider, `src/**`):
|
|
1015
|
-
|
|
1016
|
-
```bash
|
|
1017
|
-
bunx vitest run --coverage --coverage.include='src/**' --coverage.reporter=text
|
|
1018
|
-
```
|
|
1019
|
-
|
|
1020
|
-
### Release pipeline
|
|
1021
|
-
|
|
1022
|
-
Every push to `main` runs [.github/workflows/release.yml](.github/workflows/release.yml):
|
|
1023
|
-
|
|
1024
|
-
1. **Verify.** The `verify` job runs first.
|
|
1025
|
-
2. **Version bump.** Computed from [conventional commits](https://www.conventionalcommits.org/) since the last `v*` tag: `fix`/`perf` โ patch, `feat` โ minor, `!` or `BREAKING CHANGE:` โ major.
|
|
1026
|
-
3. **Publish** to npm and create a GitHub Release whose notes list the changes since the previous tag.
|
|
1027
|
-
|
|
1028
|
-
Pushes without a releasable commit do nothing. The release commit is `chore(release): vX.Y.Z [skip ci]`.
|
|
1029
|
-
|
|
1030
|
-
The `verify` job also produces these artifacts:
|
|
1031
|
-
|
|
1032
|
-
- `coverage-summary`: from `bun run test:coverage`, which writes `coverage/coverage-summary.json`.
|
|
1033
|
-
- `package-pack`: from `npm pack --dry-run --json` after the build.
|
|
1034
|
-
|
|
1035
|
-
The GitHub Release notes end with three generated sections:
|
|
62
|
+
Want to find out more? Check out the detailed documentation below to explore features, installation steps, configuration options, and examples of how to use i18n-works effectively in your project.
|
|
1036
63
|
|
|
1037
|
-
- **Test coverage:** statements, branches, functions and lines for the released commit.
|
|
1038
|
-
- **Package:** tarball size, unpacked size, file count, and distribution by location and type.
|
|
1039
|
-
- **Dependencies:** runtime and peer dependencies from `package.json`. Dependencies are not bundled into `dist/`.
|
|
1040
64
|
|
|
1041
|
-
|
|
65
|
+
https://rand0mc0d3r.github.io/i18n-works/
|
|
1042
66
|
|
|
1043
|
-
## ๐ง Known limitations
|
|
1044
67
|
|
|
1045
|
-
|
|
68
|
+
## License
|
|
1046
69
|
|
|
1047
|
-
|
|
1048
|
-
2. **Duplicate identical strings.** Message IDs come from the source text alone, so identical text used in several places shares one ID. Occurrences are paired by stable source ordering. This handles ordinary line shifts, but cannot guarantee identity if indistinguishable duplicates are reordered or moved independently. Such cases are reported through `onAmbiguous`, not resolved automatically.
|
|
1049
|
-
3. **Full scan on add or remove.** Saving a file re-reads only that file. Adding or removing a source file triggers a full project scan (debounced by 150 ms), which may be slow in very large projects.
|
|
1050
|
-
4. **What gets extracted.** Only string literals passed to `t("...")` imported from `virtual:i18n-works`, with an optional second argument of values. JSX text, attributes, template literals, unmarked JS strings, Markdown, server-rendered content and rich-text components are not extracted and need `t()` or a separate policy.
|
|
1051
|
-
5. **Example setup.** The example uses a React plugin in its Vite config; install `@vitejs/plugin-react` in the consuming example.
|
|
1052
|
-
6. **Fingerprints are source-only.** Editing a message's text changes its ID and re-translates it. Changing its position or component does not.
|
|
70
|
+
i18n-works is licensed under the MIT License. See the [LICENSE](LICENSE) file for details.
|
|
1053
71
|
|
|
1054
|
-
##
|
|
72
|
+
## Known Limitations
|
|
1055
73
|
|
|
1056
|
-
-
|
|
1057
|
-
-
|
|
1058
|
-
-
|
|
1059
|
-
-
|
|
1060
|
-
-
|
|
74
|
+
- The plugin is currently in beta, so some configuration options and file formats may change.
|
|
75
|
+
- Only Vite is officially supported as a bundler.
|
|
76
|
+
- Most of your copy should not live in JSX, as only string literals passed to `t()` are extracted.
|
|
77
|
+
- AI-generated translations are only for new or changed messages; existing translations are never overwritten silently.
|
|
78
|
+
- Review the [documentation](https://rand0mc0d3r.github.io/i18n-works/) for the latest updates and limitations.
|