vite-plugin-ai-auto-i18n 0.1.0 → 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/README.md +137 -29
- package/dist/{chunk-ASK7BKZ3.js → chunk-LLL7ZSKW.js} +41 -7
- package/dist/chunk-ZDZ3YVET.js +38 -0
- package/dist/cli/prune.js +11 -9
- package/dist/index.js +258 -148
- package/dist/runtime/index.js +2 -19
- package/package.json +6 -2
- package/dist/chunk-DQHH7Y2U.js +0 -135
- package/dist/chunk-RVYJXXTU.js +0 -15
- package/dist/cli/prune.d.ts +0 -2
- package/dist/index.d.ts +0 -106
- package/dist/runtime/index.d.ts +0 -14
package/README.md
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
# vite-plugin-autoi18n — MVP sketch
|
|
1
|
+
# 🌍 vite-plugin-autoi18n — MVP sketch 🚀
|
|
2
2
|
|
|
3
3
|
Implicit build-time localization for JSX: author English directly, let the compiler extract user-facing copy, persist message identities, and optionally translate through an AI provider.
|
|
4
4
|
|
|
5
|
-
## Current MVP scope
|
|
5
|
+
## 🧩 Current MVP scope
|
|
6
6
|
|
|
7
7
|
- Extracts JSX text nodes and static string JSX attributes.
|
|
8
8
|
- Uses tag/attribute/semantic-attribute/handler context to form fingerprints; component names and file paths are excluded so ordinary moves and renames do not automatically invalidate IDs.
|
|
@@ -11,37 +11,70 @@ Implicit build-time localization for JSX: author English directly, let the compi
|
|
|
11
11
|
- Supports a pluggable translation provider; includes an OpenAI-compatible implementation.
|
|
12
12
|
- Writes locale JSON catalogues and keeps source English as fallback.
|
|
13
13
|
- Two delivery modes: `build` (one compiled bundle per locale) and `runtime` (one bundle, locales loaded on demand through `virtual:autoi18n`).
|
|
14
|
-
- Re-translates a message when its source text changes, tracked in `.autoi18n/locales/<locale>.
|
|
14
|
+
- Re-translates a message when its source text changes, tracked in the `sources` map of `.autoi18n/locales/<locale>.json`.
|
|
15
15
|
- Includes a deliberately varied document-dashboard example.
|
|
16
16
|
|
|
17
|
-
##
|
|
17
|
+
## 📦 Installation
|
|
18
18
|
|
|
19
|
-
|
|
19
|
+
### 1️⃣ Install the package
|
|
20
|
+
|
|
21
|
+
In your React + Vite project:
|
|
22
|
+
|
|
23
|
+
```sh
|
|
24
|
+
npm install -D vite-plugin-ai-auto-i18n
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
Works the same with `pnpm add -D vite-plugin-ai-auto-i18n` or `yarn add -D vite-plugin-ai-auto-i18n`. It requires Vite 5 or newer (a peer dependency). For React, also keep `@vitejs/plugin-react` in your Vite config.
|
|
28
|
+
|
|
29
|
+
### 2️⃣ Add your API key
|
|
30
|
+
|
|
31
|
+
Put the key in `.env.local` and keep that file out of git:
|
|
32
|
+
|
|
33
|
+
```sh
|
|
34
|
+
OPENAI_API_KEY=your-key-here
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
### 3️⃣ Configure Vite
|
|
38
|
+
|
|
39
|
+
Add the plugin to `vite.config.ts`. `loadEnv` reads `.env.local` for the config file:
|
|
20
40
|
|
|
21
41
|
```ts
|
|
22
|
-
import
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
42
|
+
import { defineConfig, loadEnv } from "vite";
|
|
43
|
+
import react from "@vitejs/plugin-react";
|
|
44
|
+
import autoI18n, { OpenAICompatibleProvider } from "vite-plugin-ai-auto-i18n";
|
|
45
|
+
|
|
46
|
+
export default defineConfig(({ mode }) => {
|
|
47
|
+
const env = loadEnv(mode, process.cwd(), "");
|
|
48
|
+
|
|
49
|
+
return {
|
|
50
|
+
plugins: [
|
|
51
|
+
autoI18n({
|
|
52
|
+
locales: ["en", "de", "fr"],
|
|
53
|
+
sourceLocale: "en",
|
|
54
|
+
provider: new OpenAICompatibleProvider({
|
|
55
|
+
apiKey: env.OPENAI_API_KEY!,
|
|
56
|
+
model: "gpt-4.1-mini"
|
|
57
|
+
})
|
|
58
|
+
}),
|
|
59
|
+
react() // in runtime delivery, keep autoI18n before the React plugin
|
|
60
|
+
]
|
|
61
|
+
};
|
|
35
62
|
});
|
|
36
63
|
```
|
|
37
64
|
|
|
65
|
+
### 4️⃣ Commit the generated files
|
|
66
|
+
|
|
67
|
+
The build writes `.autoi18n/` (registry and catalogues). Commit it so existing translations are reused instead of requested again. ✅
|
|
68
|
+
|
|
38
69
|
Then write ordinary JSX:
|
|
39
70
|
|
|
40
71
|
```tsx
|
|
41
72
|
<button title="Save the current document">Save</button>
|
|
42
73
|
```
|
|
43
74
|
|
|
44
|
-
|
|
75
|
+
### 🧪 Try the bundled example
|
|
76
|
+
|
|
77
|
+
A React document dashboard under `example/`:
|
|
45
78
|
|
|
46
79
|
```sh
|
|
47
80
|
npm install
|
|
@@ -49,25 +82,31 @@ npm run example:dev # dev server
|
|
|
49
82
|
npm run example:build # production build into example/dist
|
|
50
83
|
```
|
|
51
84
|
|
|
52
|
-
Run Vite. The plugin writes `.autoi18n/registry.json
|
|
85
|
+
Run Vite. The plugin writes `.autoi18n/registry.json` and `.autoi18n/locales/<locale>.json`. Each locale file has two parts: `messages` (the translations) and `sources` (the source text each translation was made from). If the source changes, that message is re-translated on the next build.
|
|
86
|
+
|
|
87
|
+
Upgrading from an earlier version: the old flat locale files and `*.sources.json` sidecars are not read. Every message is re-translated once on the first build, and the sidecars are deleted.
|
|
88
|
+
|
|
89
|
+
If a translation batch fails, the other batches are still stored. 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.
|
|
90
|
+
|
|
91
|
+
🔑 Translations require a provider. With `failOnMissingProvider: true` the build fails when a locale is missing translations and no provider is configured, instead of silently shipping English.
|
|
53
92
|
|
|
54
|
-
|
|
93
|
+
`OpenAICompatibleProvider` sends messages in batches (`batchSize`, default 40), runs up to `concurrency` batches at once (default 4), aborts a request after `timeoutMs` (default 60000), and retries network errors, timeouts, 408/409/429 and 5xx responses or malformed output up to `maxRetries` times (default 2) with exponential backoff from `retryDelayMs` (default 500). Other 4xx errors fail immediately. If the provider omits some messages, the rest are kept and the missing ones stay in the source language until the next build retries them; the build logs how many were left untranslated.
|
|
55
94
|
|
|
56
|
-
|
|
95
|
+
The plugin translates up to `localeConcurrency` locales at once (default 2). Total parallel requests are roughly `localeConcurrency × concurrency`, so lower one or both if your provider rate-limits your account.
|
|
57
96
|
|
|
58
97
|
Ambiguous identity matches (duplicate identical strings whose count changed) are logged as warnings. Set `onAmbiguous: "error"` to fail the build instead.
|
|
59
98
|
|
|
60
99
|
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` minutes (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.
|
|
61
100
|
|
|
62
|
-
To prune without running a build, use the CLI. In this repository, `npm run prune` builds and then runs it on the example app's `example/.autoi18n/` with `--retention-minutes 0`, so every orphan is removed. Pass options after `--` to override, for example `npm run prune -- --directory .autoi18n --retention-minutes 1440 --debug`. Options: `--directory` (default `.autoi18n`, relative to the current directory), `--retention-minutes` (default `43200`, i.e. 30 days, the plugin default) and `--debug` (prints each removed entry with its source text and last-seen time). The CLI also removes any key from `
|
|
101
|
+
🧹 To prune without running a build, use the CLI. In this repository, `npm run prune` builds and then runs it on the example app's `example/.autoi18n/` with `--retention-minutes 0`, so every orphan is removed. Pass options after `--` to override, for example `npm run prune -- --directory .autoi18n --retention-minutes 1440 --debug`. Options: `--directory` (default `.autoi18n`, relative to the current directory), `--retention-minutes` (default `43200`, i.e. 30 days, the plugin default) and `--debug` (prints each removed entry with its source text and last-seen time). 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. If no registry exists at that path, the CLI says so and changes nothing. Installed packages can run `node node_modules/vite-plugin-ai-auto-i18n/dist/cli/prune.js` with the same options.
|
|
63
102
|
|
|
64
|
-
Set `debug: true` (default `false`) to print every translation exchange to the console: each message sent to the provider (`sent`) and each translation received back (`received`), prefixed with `[autoi18n debug]` and an ISO timestamp.
|
|
103
|
+
🐞 Set `debug: true` (default `false`) to print every translation exchange to the console: each message sent to the provider (`sent`) and each translation received back (`received`), prefixed with `[autoi18n debug]` and an ISO timestamp.
|
|
65
104
|
|
|
66
|
-
To keep copy out of automatic translation, add `translate="no"` to the element (for example `<h2 translate="no">Sample code</h2>`). This is the standard HTML marker, and it also covers the element's descendants and attributes such as `title`.
|
|
105
|
+
🙈 To keep copy out of automatic translation, add `translate="no"` to the element (for example `<h2 translate="no">Sample code</h2>`). This is the standard HTML marker, and it also covers the element's descendants and attributes such as `title`.
|
|
67
106
|
|
|
68
107
|
Corrupt `registry.json` or catalogue files are renamed to `<file>.corrupt-<timestamp>` and a warning is logged; the plugin continues with an empty state. Writes are atomic, so an interrupted build does not leave a truncated file.
|
|
69
108
|
|
|
70
|
-
### Delivery modes
|
|
109
|
+
### 🚚 Delivery modes
|
|
71
110
|
|
|
72
111
|
- `delivery: "build"` (default): compiles one locale per build. Use `AUTOI18N_LOCALE=de vite build` (on Windows use `cross-env AUTOI18N_LOCALE=de vite build`) or `locale: "de"` in 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.
|
|
73
112
|
- `delivery: "runtime"`: one bundle for all locales. Text is wrapped in `t(id, source)` calls and catalogues are fetched on demand. Import the API from the virtual module:
|
|
@@ -78,13 +117,82 @@ import { locales, resolveSupported, setLocale, getLocale, subscribe, t } from "v
|
|
|
78
117
|
setLocale(resolveSupported(navigator.languages)); // call before first render
|
|
79
118
|
```
|
|
80
119
|
|
|
81
|
-
`createLocaleLoader` and `resolveLocale` are available from the `vite-plugin-
|
|
120
|
+
`createLocaleLoader` and `resolveLocale` are available from the `vite-plugin-ai-auto-i18n/runtime` subpath, not the main entry.
|
|
82
121
|
|
|
83
122
|
`subscribe(listener)` returns an unsubscribe function. `getVersion()` changes whenever the locale or the catalogues change, so `useSyncExternalStore(subscribe, getVersion, getVersion)` re-renders components that read `t()` during render. Components wrapped in `memo` must subscribe themselves, or they keep the old text until their props change. List `autoI18n()` before `@vitejs/plugin-react` in `plugins`. The React plugin rewrites JSX in dev before other pre-transforms run, so the plugin must see the original JSX. Add a type declaration for `virtual:autoi18n` (see [example/src/autoi18n-virtual.d.ts](/home/bogdan/git/vite-plugin-ai-i18n/example/src/autoi18n-virtual.d.ts)). The example app uses this mode with a locale switcher.
|
|
84
123
|
|
|
85
124
|
In dev, saving a source file re-indexes the project, translates only new or changed messages and pushes the updated catalogues to the browser over an `autoi18n:update` event. Files added or removed are indexed as well. The page is not reloaded, so new JSX text appears once its translation is ready.
|
|
86
125
|
|
|
87
|
-
##
|
|
126
|
+
## ⚙️ Configuration reference
|
|
127
|
+
|
|
128
|
+
### Plugin options (`autoI18n({...})`)
|
|
129
|
+
|
|
130
|
+
| Option | Type | Default | Description |
|
|
131
|
+
|---|---|---|---|
|
|
132
|
+
| `locales` | `string[]` | _required_ | Locales the app ships, for example `["en", "de", "fr"]`. The source locale is never translated, so including it is harmless. |
|
|
133
|
+
| `sourceLocale` | `string` | `"en"` | Language the JSX is written in. Used as the fallback when a translation is missing. |
|
|
134
|
+
| `delivery` | `"build" \| "runtime"` | `"build"` | `build` compiles one locale per build. `runtime` ships every catalogue and switches locale in the browser with `setLocale()` from `virtual:autoi18n`. |
|
|
135
|
+
| `locale` | `string` | `sourceLocale` | Locale to compile in `build` delivery. Also read from the `AUTOI18N_LOCALE` environment variable, which is handy for CI matrix builds. In `build` delivery during a non-dev build, only this locale is translated. |
|
|
136
|
+
| `include` | `string[]` | `["src/**/*.{tsx,jsx,ts,js}"]` | Glob patterns of source files to scan, relative to the Vite root. |
|
|
137
|
+
| `exclude` | `string[]` | `["**/*.test.*", "**/node_modules/**"]` | Glob patterns of files to skip, relative to the Vite root. |
|
|
138
|
+
| `directory` | `string` | `".autoi18n"` | Folder for `registry.json` and `locales/`, relative to the Vite root. |
|
|
139
|
+
| `provider` | `TranslationProvider` | `undefined` | Translates missing and changed messages. Without one, untranslated messages fall back to the source text. |
|
|
140
|
+
| `failOnMissingProvider` | `boolean` | `false` | When `true`, the build fails if a locale has untranslated messages and no `provider` is set. |
|
|
141
|
+
| `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. |
|
|
142
|
+
| `orphanRetentionMinutes` | `number` | `43200` (30 days) | Minutes an orphaned message is kept before it is deleted. `0` deletes on the next build; `Infinity` keeps forever. |
|
|
143
|
+
| `localeConcurrency` | `number` | `2` | Locales translated at the same time. Values below 1 are raised to 1, and fractions are rounded down. |
|
|
144
|
+
| `debug` | `boolean` | `false` | Logs each message sent to the provider, each translation received, and each removed orphan, with timestamps. |
|
|
145
|
+
|
|
146
|
+
### `OpenAICompatibleProvider` options
|
|
147
|
+
|
|
148
|
+
Create the provider with `new OpenAICompatibleProvider(options)`.
|
|
149
|
+
|
|
150
|
+
| Option | Type | Default | Description |
|
|
151
|
+
|---|---|---|---|
|
|
152
|
+
| `apiKey` | `string` | _required_ | Bearer token for the endpoint. Read it from an environment variable and do not commit it. |
|
|
153
|
+
| `model` | `string` | _required_ | Model name sent in each request, for example `"gpt-4.1-mini"`. |
|
|
154
|
+
| `baseURL` | `string` | `"https://api.openai.com/v1"` | Base URL of any OpenAI-compatible API. Requests go to `${baseURL}/chat/completions`. |
|
|
155
|
+
| `batchSize` | `number` | `40` | Messages per request. Smaller batches keep responses within output limits. |
|
|
156
|
+
| `concurrency` | `number` | `4` | Batches sent in parallel for one locale. |
|
|
157
|
+
| `timeoutMs` | `number` | `60000` | Milliseconds before a single request is aborted. |
|
|
158
|
+
| `maxRetries` | `number` | `2` | Extra attempts for network errors, timeouts, 408/409/429/5xx responses and malformed output. |
|
|
159
|
+
| `retryDelayMs` | `number` | `500` | Delay before the first retry. It doubles on each attempt. |
|
|
160
|
+
|
|
161
|
+
### Custom provider (`TranslationProvider`)
|
|
162
|
+
|
|
163
|
+
Any object with this shape can be passed as `provider`:
|
|
164
|
+
|
|
165
|
+
```ts
|
|
166
|
+
interface TranslationProvider {
|
|
167
|
+
translate(input: {
|
|
168
|
+
sourceLocale: string;
|
|
169
|
+
targetLocale: string;
|
|
170
|
+
messages: TranslationRequest[];
|
|
171
|
+
}): Promise<Record<string, string>>; // message ID -> translated text
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
interface TranslationRequest {
|
|
175
|
+
id: string; // opaque ID to echo back in the result
|
|
176
|
+
source: string; // English text
|
|
177
|
+
context: string; // for example "Toolbar > Save button"
|
|
178
|
+
kind: "text" | "attribute" | "mixed"; // text node, static attribute, or both in one message
|
|
179
|
+
placeholders?: string[]; // {name} placeholders that must survive translation
|
|
180
|
+
}
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
Return only the IDs you translated. Omitted IDs stay in the source language and are requested again on the next build. If your provider can only translate some batches, throw `PartialTranslationError` (exported from the package) with the translations you have and the number of failed messages, so the successful ones are still stored. Any other error fails the whole locale, which keeps its previous file.
|
|
184
|
+
|
|
185
|
+
### Environment variables
|
|
186
|
+
|
|
187
|
+
| Variable | Effect |
|
|
188
|
+
|---|---|
|
|
189
|
+
| `AUTOI18N_LOCALE` | Same as the `locale` option. The option wins when both are set. |
|
|
190
|
+
|
|
191
|
+
### Prune CLI
|
|
192
|
+
|
|
193
|
+
The `prune` CLI options (`--directory`, `--retention-minutes`, `--debug`) are described in the orphan paragraph of [Try the bundled example](#-try-the-bundled-example).
|
|
194
|
+
|
|
195
|
+
## ⚠️ Important prototype limitations
|
|
88
196
|
|
|
89
197
|
This is a compiler MVP, not production-ready localization yet:
|
|
90
198
|
|
|
@@ -96,7 +204,7 @@ This is a compiler MVP, not production-ready localization yet:
|
|
|
96
204
|
6. The example uses a React plugin in its Vite config; install `@vitejs/plugin-react` in the consuming example.
|
|
97
205
|
7. The initial fingerprint is a heuristic. It excludes file and line position, but component names and nearby semantic signals can still change during refactors.
|
|
98
206
|
|
|
99
|
-
## Design rules
|
|
207
|
+
## 🧭 Design rules
|
|
100
208
|
|
|
101
209
|
- IDs are opaque and persistent; never expose semantic fingerprints as runtime keys.
|
|
102
210
|
- AI suggestions never silently overwrite an existing translation.
|
|
@@ -2,9 +2,11 @@
|
|
|
2
2
|
var debugLog = (message) => console.log(`[autoi18n debug] ${(/* @__PURE__ */ new Date()).toISOString()} ${message}`);
|
|
3
3
|
|
|
4
4
|
// src/io.ts
|
|
5
|
-
import { randomUUID } from "crypto";
|
|
5
|
+
import { createHash, randomUUID } from "crypto";
|
|
6
6
|
import { mkdir, readFile, rename, writeFile } from "fs/promises";
|
|
7
7
|
import path from "path";
|
|
8
|
+
var toJson = (value) => JSON.stringify(value, null, 2) + "\n";
|
|
9
|
+
var hashContent = (text) => createHash("sha256").update(text).digest("hex");
|
|
8
10
|
async function readJsonFile(file, fallback, warn) {
|
|
9
11
|
let text;
|
|
10
12
|
try {
|
|
@@ -30,6 +32,28 @@ async function writeFileAtomic(file, content) {
|
|
|
30
32
|
await rename(temp, file);
|
|
31
33
|
}
|
|
32
34
|
|
|
35
|
+
// src/catalog.ts
|
|
36
|
+
import path2 from "path";
|
|
37
|
+
var emptyLocaleFile = () => ({ messages: {}, sources: {} });
|
|
38
|
+
function localeFilePath(outDir, locale) {
|
|
39
|
+
return path2.join(outDir, `${locale}.json`);
|
|
40
|
+
}
|
|
41
|
+
async function readLocaleFile(file, warn) {
|
|
42
|
+
const parsed = await readJsonFile(file, null, warn);
|
|
43
|
+
if (!parsed || typeof parsed.messages !== "object" || typeof parsed.sources !== "object") return emptyLocaleFile();
|
|
44
|
+
return { messages: parsed.messages, sources: parsed.sources };
|
|
45
|
+
}
|
|
46
|
+
var writeLocaleFile = (file, content) => writeFileAtomic(file, toJson(content));
|
|
47
|
+
function pruneCatalog(catalog, keep) {
|
|
48
|
+
const kept = {};
|
|
49
|
+
const removed = [];
|
|
50
|
+
for (const [id, text] of Object.entries(catalog)) {
|
|
51
|
+
if (keep.has(id)) kept[id] = text;
|
|
52
|
+
else removed.push(id);
|
|
53
|
+
}
|
|
54
|
+
return { catalog: kept, removed };
|
|
55
|
+
}
|
|
56
|
+
|
|
33
57
|
// src/identity/registry.ts
|
|
34
58
|
import { randomUUID as randomUUID2 } from "crypto";
|
|
35
59
|
var emptyRegistry = () => ({ version: 1, entries: {} });
|
|
@@ -63,6 +87,7 @@ function reconcile(registry, messages) {
|
|
|
63
87
|
list.push(message);
|
|
64
88
|
incoming.set(message.fingerprint, list);
|
|
65
89
|
}
|
|
90
|
+
const assigned = /* @__PURE__ */ new Map();
|
|
66
91
|
const seen = /* @__PURE__ */ new Set();
|
|
67
92
|
const ambiguous = [];
|
|
68
93
|
for (const [fingerprint, current] of incoming) {
|
|
@@ -76,7 +101,7 @@ function reconcile(registry, messages) {
|
|
|
76
101
|
const message = current[i];
|
|
77
102
|
const candidate = previous[i];
|
|
78
103
|
if (candidate) {
|
|
79
|
-
message
|
|
104
|
+
assigned.set(message, candidate.id);
|
|
80
105
|
candidate.status = "active";
|
|
81
106
|
candidate.lastSeen = now;
|
|
82
107
|
candidate.source = message.source;
|
|
@@ -84,7 +109,7 @@ function reconcile(registry, messages) {
|
|
|
84
109
|
seen.add(candidate.id);
|
|
85
110
|
} else {
|
|
86
111
|
const id = `msg_${randomUUID2().replaceAll("-", "").slice(0, 16)}`;
|
|
87
|
-
message
|
|
112
|
+
assigned.set(message, id);
|
|
88
113
|
registry.entries[id] = {
|
|
89
114
|
id,
|
|
90
115
|
source: message.source,
|
|
@@ -104,7 +129,12 @@ function reconcile(registry, messages) {
|
|
|
104
129
|
}
|
|
105
130
|
}
|
|
106
131
|
for (const entry of Object.values(registry.entries)) if (!seen.has(entry.id)) entry.status = "orphaned";
|
|
107
|
-
|
|
132
|
+
const resolved = messages.map((message) => {
|
|
133
|
+
const id = assigned.get(message);
|
|
134
|
+
if (id === void 0) throw new Error(`autoi18n: no message ID was assigned to ${message.file}:${message.start}`);
|
|
135
|
+
return { ...message, id };
|
|
136
|
+
});
|
|
137
|
+
return { registry, ambiguous, messages: resolved };
|
|
108
138
|
}
|
|
109
139
|
var MINUTE_MS = 60 * 1e3;
|
|
110
140
|
var DEFAULT_ORPHAN_RETENTION_MINUTES = 30 * 24 * 60;
|
|
@@ -120,13 +150,17 @@ function pruneOrphans(registry, retentionMinutes, now = Date.now()) {
|
|
|
120
150
|
return removed;
|
|
121
151
|
}
|
|
122
152
|
async function saveRegistry(file, registry) {
|
|
123
|
-
await writeFileAtomic(file,
|
|
153
|
+
await writeFileAtomic(file, toJson(registry));
|
|
124
154
|
}
|
|
125
155
|
|
|
126
156
|
export {
|
|
127
157
|
debugLog,
|
|
128
|
-
|
|
129
|
-
|
|
158
|
+
hashContent,
|
|
159
|
+
emptyLocaleFile,
|
|
160
|
+
localeFilePath,
|
|
161
|
+
readLocaleFile,
|
|
162
|
+
writeLocaleFile,
|
|
163
|
+
pruneCatalog,
|
|
130
164
|
loadRegistry,
|
|
131
165
|
reconcile,
|
|
132
166
|
DEFAULT_ORPHAN_RETENTION_MINUTES,
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
// src/runtime/loader.ts
|
|
2
|
+
function createLocaleLoader(loaders, fallback = "en") {
|
|
3
|
+
const cache = /* @__PURE__ */ new Map();
|
|
4
|
+
function loadLocale(locale) {
|
|
5
|
+
const selected = loaders[locale] ? locale : fallback;
|
|
6
|
+
const cached = cache.get(selected);
|
|
7
|
+
if (cached) return cached;
|
|
8
|
+
const loader = loaders[selected];
|
|
9
|
+
if (!loader) return Promise.reject(new Error(`No catalogue loader for locale "${selected}"`));
|
|
10
|
+
const pending = loader().then((module) => "default" in module ? module.default : module);
|
|
11
|
+
cache.set(selected, pending);
|
|
12
|
+
pending.catch(() => {
|
|
13
|
+
if (cache.get(selected) === pending) cache.delete(selected);
|
|
14
|
+
});
|
|
15
|
+
return pending;
|
|
16
|
+
}
|
|
17
|
+
loadLocale.prime = (locale, catalog) => {
|
|
18
|
+
cache.set(locale, Promise.resolve(catalog));
|
|
19
|
+
};
|
|
20
|
+
return loadLocale;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
// src/runtime/resolve.ts
|
|
24
|
+
function resolveLocale(preferred, supported, fallback = "en") {
|
|
25
|
+
for (const candidate of preferred) {
|
|
26
|
+
const exact = supported.find((x) => x.toLowerCase() === candidate.toLowerCase());
|
|
27
|
+
if (exact) return exact;
|
|
28
|
+
const base = candidate.split("-")[0].toLowerCase();
|
|
29
|
+
const language = supported.find((x) => x.split("-")[0].toLowerCase() === base);
|
|
30
|
+
if (language) return language;
|
|
31
|
+
}
|
|
32
|
+
return fallback;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export {
|
|
36
|
+
createLocaleLoader,
|
|
37
|
+
resolveLocale
|
|
38
|
+
};
|
package/dist/cli/prune.js
CHANGED
|
@@ -2,27 +2,29 @@ import {
|
|
|
2
2
|
DEFAULT_ORPHAN_RETENTION_MINUTES,
|
|
3
3
|
debugLog,
|
|
4
4
|
loadRegistry,
|
|
5
|
+
pruneCatalog,
|
|
5
6
|
pruneOrphans,
|
|
6
|
-
|
|
7
|
+
readLocaleFile,
|
|
7
8
|
saveRegistry,
|
|
8
|
-
|
|
9
|
-
} from "../chunk-
|
|
9
|
+
writeLocaleFile
|
|
10
|
+
} from "../chunk-LLL7ZSKW.js";
|
|
10
11
|
|
|
11
12
|
// src/cli/prune.ts
|
|
12
13
|
import { existsSync } from "fs";
|
|
13
14
|
import { readdir } from "fs/promises";
|
|
14
15
|
import path from "path";
|
|
15
|
-
async function
|
|
16
|
+
async function pruneLocaleFiles(localesDir, activeIds) {
|
|
16
17
|
if (!existsSync(localesDir)) return [];
|
|
17
18
|
const results = [];
|
|
18
19
|
for (const name of await readdir(localesDir)) {
|
|
19
20
|
if (!name.endsWith(".json")) continue;
|
|
20
21
|
const file = path.join(localesDir, name);
|
|
21
|
-
const
|
|
22
|
-
const
|
|
22
|
+
const current = await readLocaleFile(file, (message) => console.warn(message));
|
|
23
|
+
const messages = pruneCatalog(current.messages, activeIds);
|
|
24
|
+
const sources = pruneCatalog(current.sources, activeIds);
|
|
25
|
+
const removed = [.../* @__PURE__ */ new Set([...messages.removed, ...sources.removed])];
|
|
23
26
|
if (!removed.length) continue;
|
|
24
|
-
|
|
25
|
-
await writeFileAtomic(file, JSON.stringify(catalog, null, 2) + "\n");
|
|
27
|
+
await writeLocaleFile(file, { messages: messages.catalog, sources: sources.catalog });
|
|
26
28
|
results.push({ file, removed });
|
|
27
29
|
}
|
|
28
30
|
return results;
|
|
@@ -56,7 +58,7 @@ async function main() {
|
|
|
56
58
|
const removed = pruneOrphans(registry, args.retentionMinutes);
|
|
57
59
|
if (removed.length) await saveRegistry(registryFile, registry);
|
|
58
60
|
const activeIds = new Set(Object.values(registry.entries).filter((entry) => entry.status === "active").map((entry) => entry.id));
|
|
59
|
-
const catalogs = await
|
|
61
|
+
const catalogs = await pruneLocaleFiles(path.join(path.dirname(registryFile), "locales"), activeIds);
|
|
60
62
|
if (args.debug) {
|
|
61
63
|
for (const entry of removed) debugLog(`removed ${entry.id} ${JSON.stringify(entry.source)} (last seen ${entry.lastSeen})`);
|
|
62
64
|
for (const { file, removed: ids } of catalogs) {
|