vite-bundled-i18n 0.2.14 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/README.md +173 -116
  2. package/dist/cli/index.js +8 -4
  3. package/dist/cli/index.js.map +1 -1
  4. package/dist/{walker-9pKaJgmJ.js → compiler-B8vL51ge.js} +150 -150
  5. package/dist/compiler-B8vL51ge.js.map +1 -0
  6. package/dist/core/args.d.ts +7 -5
  7. package/dist/core/compiled-runtime.d.ts +43 -0
  8. package/dist/core/createI18n.d.ts +4 -2
  9. package/dist/core/fetcher.d.ts +51 -0
  10. package/dist/core/getTranslations.d.ts +11 -0
  11. package/dist/core/runtime-env.d.ts +46 -0
  12. package/dist/core/services/bundle-loader.d.ts +121 -0
  13. package/dist/core/services/cache-manager.d.ts +182 -0
  14. package/dist/core/services/key-tracker.d.ts +48 -0
  15. package/dist/core/services/locale-manager.d.ts +56 -0
  16. package/dist/core/store.d.ts +1 -1
  17. package/dist/core/t.d.ts +6 -0
  18. package/dist/core/types.d.ts +34 -1
  19. package/dist/data-BtBbelxk.js +1359 -0
  20. package/dist/data-BtBbelxk.js.map +1 -0
  21. package/dist/devtools/dom-helpers.d.ts +90 -0
  22. package/dist/devtools/mountDevtools.d.ts +46 -0
  23. package/dist/devtools/panels/bundles.d.ts +30 -0
  24. package/dist/devtools/panels/footprint.d.ts +15 -0
  25. package/dist/devtools/panels/inspector.d.ts +13 -0
  26. package/dist/devtools/styles.d.ts +21 -0
  27. package/dist/{getTranslations-D3q3OBTn.js → getTranslations-BdfteEhG.js} +12 -1
  28. package/dist/getTranslations-BdfteEhG.js.map +1 -0
  29. package/dist/index.d.ts +2 -0
  30. package/dist/index.js +5 -5
  31. package/dist/mountDevtools-C42c9yW2.js +1063 -0
  32. package/dist/mountDevtools-C42c9yW2.js.map +1 -0
  33. package/dist/plugin/devDiagnostics.d.ts +43 -0
  34. package/dist/plugin/devPlugin.d.ts +13 -0
  35. package/dist/plugin.d.ts +17 -1
  36. package/dist/plugin.js +339 -26
  37. package/dist/plugin.js.map +1 -1
  38. package/dist/react/DevToolbar.d.ts +7 -19
  39. package/dist/react/I18nBoundary.d.ts +2 -1
  40. package/dist/react/I18nProvider.d.ts +25 -5
  41. package/dist/react/context.d.ts +1 -0
  42. package/dist/react.d.ts +5 -0
  43. package/dist/react.js +106 -282
  44. package/dist/react.js.map +1 -1
  45. package/dist/runtime-env-9tWVgvgm.js +50 -0
  46. package/dist/runtime-env-9tWVgvgm.js.map +1 -0
  47. package/dist/{server-Boo9FghP.js → server-U0rNpuWa.js} +17 -7
  48. package/dist/server-U0rNpuWa.js.map +1 -0
  49. package/dist/server.js +3 -3
  50. package/dist/vanilla.d.ts +5 -0
  51. package/dist/vanilla.js +11 -7
  52. package/dist/vanilla.js.map +1 -1
  53. package/dist/vue.d.ts +2 -0
  54. package/dist/vue.js +23 -9
  55. package/dist/vue.js.map +1 -1
  56. package/package.json +3 -5
  57. package/dist/data-CX4qW9_K.js +0 -912
  58. package/dist/data-CX4qW9_K.js.map +0 -1
  59. package/dist/getTranslations-D3q3OBTn.js.map +0 -1
  60. package/dist/server-Boo9FghP.js.map +0 -1
  61. package/dist/t-Bfb3ut7N.js +0 -75
  62. package/dist/t-Bfb3ut7N.js.map +0 -1
  63. package/dist/walker-9pKaJgmJ.js.map +0 -1
package/README.md CHANGED
@@ -1,31 +1,53 @@
1
1
  # vite-bundled-i18n
2
2
 
3
- Route-aware internationalization for Vite. Each page loads only the translations it uses. Keys are fully typed with progressive autocomplete. Production builds emit static, scope-matched bundles.
3
+ Make translations behave like code: split, scoped, and bundled per route.
4
4
 
5
5
  ```bash
6
6
  npm i vite-bundled-i18n
7
7
  ```
8
8
 
9
- Requires Node `>=20` and Vite. React, Vue, and vanilla adapters are included — framework peer dependencies are optional.
9
+ Traditional i18n treats translations as global runtime data — loaded all at once, resolved by key lookup, impossible to tree-shake. `vite-bundled-i18n` treats them as **code dependencies**. The Vite plugin walks your page components at build time, extracts the exact keys each route uses via AST analysis, and emits scope-matched bundles. Each page ships only the translations it needs.
10
+
11
+ The result: a 50-page admin panel with 3,000 translation keys loads ~40 keys on any given page instead of all 3,000. The rest are tree-shaken at build time and never sent to the client.
12
+
13
+ ## How It Works
14
+
15
+ ```
16
+ Source files Build pipeline Production output
17
+ ───────────── ───────────────── ──────────────────
18
+ ProductsPage.tsx ──→ AST extraction ──→ __i18n/en/products.index.json (12 keys)
19
+ CartPage.tsx ──→ Key tracking ──→ __i18n/en/cart.json (8 keys)
20
+ Layout.tsx ──→ Dictionary rules ──→ __i18n/en/_dict/global.json (shared keys)
21
+ Scope bundling
22
+ Type generation ──→ .i18n/i18n-generated.ts (full autocomplete)
23
+ ```
24
+
25
+ **Three layers:**
26
+
27
+ 1. **Build-time analysis** — AST extractor walks your import graph, finds every `t()`, `useI18n()`, `i18nKey()` call, and maps keys to routes. No code execution needed.
28
+ 2. **Bundle generation** — keys are grouped into scope bundles (per-page) and dictionary bundles (shared/global). Each bundle is a static JSON asset or compiled JS module.
29
+ 3. **Thin runtime** — minimal `t()` function that loads the right bundle on demand. React, Vue, and vanilla adapters are ~50 lines each.
10
30
 
11
31
  ## Features
12
32
 
13
- - **Scope bundles** — translations grouped by route (`products.index`) and loaded on demand
14
- - **Dictionary ownership** — named dictionaries claim keys by pattern, with `include`/`exclude` and priority
15
- - **Progressive autocomplete** — nested types let the IDE suggest one level at a time (`t('feedback.` → `pages`, `actions`, ...)
33
+ - **Scope bundles** — each route loads only its own translations, one HTTP request
34
+ - **Dictionary ownership** — named dictionaries claim keys by pattern (`include`/`exclude`/`priority`)
35
+ - **Progressive autocomplete** — generated types let the IDE suggest one key segment at a time
16
36
  - **Placeholder validation** — `t('cart.total', { amount: 9.99 })` is type-checked against `{{amount}}` in the JSON
17
- - **Compiled production output** — Vite plugin emits `__i18n/` assets as static JSON or compiled modules
37
+ - **Compiled production mode** — optional `Map`-based modules for O(1) lookups without JSON parsing
18
38
  - **Multi-framework** — React, Vue, and vanilla JS share a single core
19
- - **SSR** — server-side rendering with automatic client hydration
20
- - **AST extraction** — finds translation keys in source without execution, including `t()` passed as arguments to helper functions
21
- - **Custom URL resolution** — `resolveUrl` callback for CDN, API endpoints, or any non-standard deployment
39
+ - **SSR** — server-side rendering with automatic client hydration via `window.__I18N_RESOURCES__`
40
+ - **AST extraction** — finds keys in `t()`, `useI18n()`, `i18nKey()`, `defineI18nData()`, configurable `keyFields`, `as const` objects, string enums, and helper functions that receive `t` as a parameter
41
+ - **Dev toolbar** — dark-mode drawer showing per-page key usage, bundle efficiency (keys used vs loaded), missing translations, and namespace residency
22
42
 
23
43
  ## Setup
24
44
 
25
- Three files wire everything together: a config that declares your locale directory and dictionaries (bundles that group related keys under a name, like `global` for shared UI strings), a runtime instance that holds locale state, and a Vite plugin that handles extraction, type generation, and bundle emission.
45
+ Three files wire everything together:
46
+
47
+ ### 1. Config — declare dictionaries and locale directory
26
48
 
27
49
  ```ts
28
- // src/i18n.config.ts — declares dictionaries and where locale JSON files live
50
+ // src/i18n.config.ts
29
51
  import { defineI18nConfig } from 'vite-bundled-i18n'
30
52
 
31
53
  export const i18nConfig = defineI18nConfig({
@@ -33,7 +55,7 @@ export const i18nConfig = defineI18nConfig({
33
55
  dictionaries: {
34
56
  global: {
35
57
  include: ['shared.*', 'global.*', 'actions.*'],
36
- exclude: ['shared.validation.*'], // optional — carve out large sub-namespaces
58
+ exclude: ['shared.validation.*'],
37
59
  priority: 1,
38
60
  pinned: true,
39
61
  },
@@ -41,8 +63,10 @@ export const i18nConfig = defineI18nConfig({
41
63
  })
42
64
  ```
43
65
 
66
+ ### 2. Runtime instance — holds locale state
67
+
44
68
  ```ts
45
- // src/i18n.ts — runtime instance used by adapters and server code
69
+ // src/i18n.ts
46
70
  import { createI18n } from 'vite-bundled-i18n'
47
71
  import { i18nConfig } from './i18n.config'
48
72
 
@@ -55,8 +79,10 @@ export const i18n = createI18n({
55
79
  })
56
80
  ```
57
81
 
82
+ ### 3. Vite plugin — extraction, types, and bundle emission
83
+
58
84
  ```ts
59
- // vite.config.ts — plugin scans pages, extracts keys, emits bundles and types
85
+ // vite.config.ts
60
86
  import { defineConfig } from 'vite'
61
87
  import react from '@vitejs/plugin-react'
62
88
  import { i18nPlugin } from 'vite-bundled-i18n/plugin'
@@ -69,14 +95,12 @@ export default defineConfig({
69
95
  pages: ['src/pages/**/*.tsx'],
70
96
  locales: ['en', 'bg'],
71
97
  defaultLocale: 'en',
72
- generatedOutDir: '.i18n',
73
- // types are generated to .i18n/i18n-generated.ts by default
74
98
  }),
75
99
  ],
76
100
  })
77
101
  ```
78
102
 
79
- Types are generated automatically on `npm run dev` (on server start and when locale files change) and during `npm run build`. To enable autocomplete and type validation, add to your `tsconfig.json`:
103
+ ### 4. TypeScript — enable autocomplete
80
104
 
81
105
  ```json
82
106
  {
@@ -89,17 +113,17 @@ Types are generated automatically on `npm run dev` (on server start and when loc
89
113
  }
90
114
  ```
91
115
 
92
- ### React
116
+ Types are generated automatically during `npm run dev` and `npm run build`.
117
+
118
+ ## React
93
119
 
94
120
  ```tsx
95
- // src/main.tsx
96
- import { createRoot } from 'react-dom/client'
97
121
  import { I18nProvider } from 'vite-bundled-i18n/react'
98
122
  import { i18n } from './i18n'
99
- import App from './App'
100
123
 
101
- createRoot(document.getElementById('root')!).render(
102
- <I18nProvider instance={i18n}>
124
+ // Provider loads dictionaries, blocks until ready.
125
+ createRoot(root).render(
126
+ <I18nProvider instance={i18n} fallback={<Spinner />}>
103
127
  <App />
104
128
  </I18nProvider>,
105
129
  )
@@ -108,135 +132,144 @@ createRoot(document.getElementById('root')!).render(
108
132
  ```tsx
109
133
  import { useI18n } from 'vite-bundled-i18n/react'
110
134
 
111
- export function ProductsPage() {
112
- // t() has full autocomplete — type 't('products.' and the IDE suggests the next segment.
113
- // Placeholders are type-checked: t('cart.total', { amount }) enforces { amount: Primitive }.
114
- const { t, translations, ready } = useI18n('products.index')
115
-
116
- if (!ready) return <div>{t('shared.loading', 'Loading...')}</div>
135
+ function ProductsPage() {
136
+ const { t, ready } = useI18n('products.index')
137
+ if (!ready) return <Skeleton />
117
138
 
118
- return (
119
- <section>
120
- <h1>{t('products.index.heading', 'All Products')}</h1>
121
- <p>{t('products.index.subheading', { count: 24 }, 'Browse {{count}} items')}</p>
122
- </section>
123
- )
139
+ return <h1>{t('products.index.heading', 'All Products')}</h1>
124
140
  }
125
141
  ```
126
142
 
127
- Use `I18nBoundary` to avoid rules-of-hooks violations from early returns:
143
+ **`useI18n(scope)`** triggers a single HTTP request to load the scope bundle. Dictionaries are always available. Previously visited scopes are instant (cached). Missing-key warnings are automatically suppressed while a scope is loading — no need to guard every `useMemo`.
128
144
 
129
- ```tsx
130
- import { I18nBoundary } from 'vite-bundled-i18n/react'
145
+ **`I18nBoundary`** handles scope loading without early returns:
131
146
 
132
- <I18nBoundary scope="products.index" fallback={<Spinner />}>
147
+ ```tsx
148
+ <I18nBoundary scope="products.index" fallback={<Skeleton />}>
133
149
  <ProductsPage />
134
150
  </I18nBoundary>
135
151
  ```
136
152
 
137
- ### Vue
153
+ **Navigation lifecycle:** The provider persists across page navigations (Inertia, React Router, Next.js). Dictionaries load once. Each page scope loads on mount — only the page content waits, not the layout.
154
+
155
+ ## Vue
138
156
 
139
157
  ```ts
140
158
  import { createApp } from 'vue'
141
159
  import { createI18nPlugin } from 'vite-bundled-i18n/vue'
142
160
  import { i18n } from './i18n'
143
161
 
144
- const app = createApp(App)
145
- app.use(createI18nPlugin(i18n))
146
- app.mount('#app')
162
+ createApp(App).use(createI18nPlugin(i18n)).mount('#app')
147
163
  ```
148
164
 
149
- ## API
165
+ ```vue
166
+ <script setup lang="ts">
167
+ import { useI18n } from 'vite-bundled-i18n/vue'
168
+ const { t, ready } = useI18n('products.index')
169
+ </script>
170
+ ```
150
171
 
151
- The translator object returned by `useI18n` (React), `useI18n` (Vue), or `getTranslations` (vanilla):
172
+ ## Vanilla JS
152
173
 
153
174
  ```ts
154
- const translations = await getTranslations(i18n, 'products.index')
175
+ import { createI18n, getTranslations } from 'vite-bundled-i18n'
155
176
 
156
- translations.t('products.index.heading')
157
- translations.get('products.show.price', { amount: 29.99 })
158
- translations.tryGet('shared.ok')
159
- translations.has('actions.save')
160
- translations.namespace('global').get('nav.home')
177
+ const i18n = createI18n({ /* config */ })
178
+ const translations = await getTranslations(i18n, 'products.index')
179
+ translations.get('products.index.heading')
161
180
  ```
162
181
 
163
- ### Locale Switching
182
+ ## Translator API
183
+
184
+ The translator object (from `useI18n`, `getTranslations`, or `initServerI18n`):
164
185
 
165
186
  ```ts
166
- await i18n.changeLocale('bg')
187
+ t('products.index.heading') // resolve key
188
+ t('products.index.heading', 'Fallback') // with fallback string
189
+ t('cart.total', { amount: 9.99 }) // with interpolation
190
+ t('cart.total', { amount: 9.99 }, '{{amount}} EUR') // interpolation + fallback
191
+
192
+ translations.has('actions.save') // check existence
193
+ translations.tryGet('shared.ok') // undefined on miss (no fallback)
194
+ translations.require('shared.ok') // throws on miss
195
+ translations.namespace('global').get('nav.home') // namespace-scoped access
196
+ translations.forLocale('bg').get('shared.ok') // cross-locale lookup
167
197
  ```
168
198
 
169
- All React/Vue consumers re-render automatically.
170
-
171
- ### Package Entries
172
-
173
- | Entry | Purpose |
174
- |-------|---------|
175
- | `vite-bundled-i18n` | Core runtime and configuration |
176
- | `vite-bundled-i18n/react` | React adapter (`I18nProvider`, `useI18n`, `I18nBoundary`) |
177
- | `vite-bundled-i18n/vue` | Vue adapter (`createI18nPlugin`, `useI18n`) |
178
- | `vite-bundled-i18n/vanilla` | Framework-agnostic `getTranslations` |
179
- | `vite-bundled-i18n/server` | SSR utilities (`initServerI18n`) |
180
- | `vite-bundled-i18n/plugin` | Vite build plugin |
181
-
182
199
  ## Dictionaries
183
200
 
184
- Dictionaries define key ownership — which namespaces are preloaded and available globally:
201
+ Dictionaries define which translations are preloaded globally (layout, nav, shared UI):
185
202
 
186
203
  ```ts
187
204
  dictionaries: {
188
205
  global: {
189
206
  include: ['shared.*', 'global.*', 'actions.*'],
190
- exclude: ['shared.validation.*'], // carve out sub-namespaces you don't need client-side
207
+ exclude: ['shared.validation.*'],
191
208
  priority: 1,
192
209
  pinned: true,
193
210
  },
194
- admin: {
195
- include: ['admin.*'],
196
- priority: 10,
197
- },
198
211
  }
199
212
  ```
200
213
 
201
- - `include` accepts exact keys, namespace wildcards, and prefix patterns
202
- - `exclude` removes matching keys from the dictionary (applied after `include`)
203
- - Higher priority dictionaries claim keys first; lower priority dictionaries skip already-owned keys
204
- - Pinned dictionaries remain in memory and are never evicted
205
- - Dictionary bundles include ALL keys from matching namespaces — no tree-shaking. Scope bundles are the per-page optimization layer.
214
+ - `include` — key ownership patterns: `shared.*`, `checkout.summary.*`, `shared.ok`
215
+ - `exclude` — carve out sub-namespaces after include
216
+ - `priority` — higher priority claims matching keys first
217
+ - `pinned` — stays in memory, never evicted
218
+ - Dictionary bundles include **all** matching keys (the "always available" layer). Scope bundles are the per-page optimization.
206
219
 
207
- ## Custom URL Resolution
220
+ ## Key Tree-Shaking
208
221
 
209
- For non-standard deployments (custom API routes, CDN, single endpoint), use `resolveUrl`:
222
+ Traditional i18n ships every translation key to every page. `vite-bundled-i18n` automatically removes unused keys from scope bundles at build time — the same way a JS bundler tree-shakes unused exports.
223
+
224
+ ### How it works
225
+
226
+ 1. **AST extraction** — the Vite plugin parses your page components and their entire import graph. Every `t('key')`, `useI18n('scope')`, `i18nKey('key')`, and configured `keyField` property is recorded.
227
+
228
+ 2. **Key mapping** — extracted keys are mapped to their source namespace. `t('products.index.heading')` → namespace `products`, key path `index.heading`.
229
+
230
+ 3. **Scope bundle generation** — for each route, the plugin reads the full namespace JSON file (e.g. `locales/en/products.json` with 882 keys), then **prunes it to only the keys that route's AST extraction found** (e.g. 25 keys). The remaining 857 keys are dropped from that bundle entirely.
231
+
232
+ 4. **Dictionary bundles are not tree-shaken** — they include all keys matching the `include`/`exclude` patterns. Dictionaries are the "always available" layer for shared UI (nav, actions, validation). Tree-shaking only applies to scope bundles.
233
+
234
+ ### What you get
210
235
 
211
- ```ts
212
- const i18n = createI18n({
213
- ...i18nConfig,
214
- locale: 'en',
215
- defaultLocale: 'en',
216
- supportedLocales: ['en', 'bg'],
217
- resolveUrl: (locale, type, name) => {
218
- // type: 'dictionary' | 'scope' | 'namespace' | 'manifest'
219
- return `/api/translations/${locale}/${type}/${name}`
220
- },
221
- })
236
+ ```
237
+ locales/en/products.json → 882 keys (source file)
238
+ __i18n/en/products.index.json → 25 keys (scope bundle for products.index page)
239
+ __i18n/en/products.show.json → 18 keys (scope bundle for products.show page)
240
+ __i18n/en/_dict/global.json → 86 keys (dictionary bundle — not tree-shaken)
222
241
  ```
223
242
 
224
- When not set, the runtime uses the build-injected base path from Vite's `base` config automatically.
243
+ The devtools drawer shows the efficiency per namespace on every page:
225
244
 
226
- ## Data Files
245
+ ```
246
+ products: 25 / 882 keys used on this page — 857 keys treeshaken (97% smaller bundle)
247
+ shared: 12 / 86 keys used — loaded via dictionary (always available)
248
+ ```
227
249
 
228
- For configuration or navigation data that references translation keys, use the extraction helpers:
250
+ ### Build reports
229
251
 
230
- ```ts
231
- import { defineI18nData, i18nKey } from 'vite-bundled-i18n'
252
+ The build generates reports that show exactly what was extracted, what's missing, and what's unused:
253
+
254
+ - `missing.json` — keys referenced in your code that don't exist in locale files
255
+ - `unused.json` — keys in locale files that no route references (candidates for removal)
256
+ - `stats.json` — per-route and per-namespace extraction statistics
257
+ - `ownership.json` — which dictionary owns which key, with collision data
258
+
259
+ ### Edge cases
260
+
261
+ Keys that the AST extractor **cannot see** (dynamic concatenation, computed keys) won't appear in scope bundles. See the [Getting Started guide](./docs/getting-started.md#9-dynamic-keys-unsafe-patterns) for strategies to handle dynamic keys safely — typically by placing them in a dictionary instead.
262
+
263
+ ## Production Output
232
264
 
233
- export const nav = defineI18nData([
234
- { href: '/', labelKey: i18nKey('global.nav.home') },
235
- { href: '/cart', labelKey: i18nKey('global.nav.cart') },
236
- ])
265
+ ```
266
+ __i18n/{locale}/_dict/{name}.json — dictionary bundles (JSON)
267
+ __i18n/{locale}/{scope}.json — scope bundles (JSON)
268
+ __i18n/compiled/manifest.js — compiled module manifest
269
+ __i18n/compiled/{locale}/... — compiled Map modules (optional)
237
270
  ```
238
271
 
239
- The AST extractor recognizes these helpers and includes referenced keys in scope analysis. It also detects `t()` and `get()` calls in helper functions that receive the translation function as a parameter.
272
+ Compiled mode replaces JSON parsing with `Map` lookups — faster, cacheable by the browser's module loader. Falls back to JSON automatically if compiled modules aren't available.
240
273
 
241
274
  ## Server-Side Rendering
242
275
 
@@ -245,41 +278,55 @@ import { initServerI18n } from 'vite-bundled-i18n/server'
245
278
 
246
279
  const { translations, scriptTag } = await initServerI18n(config, 'products.show')
247
280
  const html = renderToString(<App translations={translations} />)
248
- // Inject scriptTag into the HTML response
281
+ // Inject scriptTag into HTML — client auto-hydrates from window.__I18N_RESOURCES__
249
282
  ```
250
283
 
251
- The React `I18nProvider` and Vue `createI18nPlugin` automatically detect and consume the injected `window.__I18N_RESOURCES__` on the client.
284
+ React and Vue adapters detect and consume the hydrated data automatically.
252
285
 
253
- ## Production Output
286
+ ## Dev Mode
254
287
 
255
- During `vite build`, the plugin emits:
288
+ Translation bundles are served via Vite middleware — no files written to disk. Types regenerate on locale file changes. The dev toolbar updates live on navigation.
256
289
 
257
- ```
258
- __i18n/{locale}/_dict/{name}.json
259
- __i18n/{locale}/{scope}.json
260
- __i18n/compiled/manifest.js
261
- __i18n/compiled/{locale}/...
290
+ For sidecar setups (Laravel serving assets from public/):
291
+
292
+ ```ts
293
+ i18nPlugin(i18nConfig, {
294
+ pages: ['src/pages/**/*.tsx'],
295
+ locales: ['en', 'bg'],
296
+ defaultLocale: 'en',
297
+ dev: { emitPublicAssets: true },
298
+ })
262
299
  ```
263
300
 
264
- The runtime resolves these assets automatically in production. For frameworks that serve built assets under a prefix (e.g. Laravel with `base: '/build/'`), the plugin reads Vite's resolved `base` config — no manual path configuration needed.
301
+ ## Data Files
265
302
 
266
- ## Fetch Options
303
+ For navigation, table columns, or config that references translation keys:
267
304
 
268
- Configure request behavior for translation loading:
305
+ ```ts
306
+ import { defineI18nData, i18nKey } from 'vite-bundled-i18n'
307
+
308
+ export const nav = defineI18nData([
309
+ { href: '/', labelKey: i18nKey('global.nav.home') },
310
+ { href: '/cart', labelKey: i18nKey('global.nav.cart') },
311
+ ])
312
+ ```
313
+
314
+ The AST extractor recognizes these helpers and includes referenced keys in scope analysis.
315
+
316
+ ## Custom URL Resolution
269
317
 
270
318
  ```ts
271
319
  createI18n({
272
320
  ...config,
321
+ resolveUrl: (locale, type, name) => `/api/translations/${locale}/${type}/${name}`,
273
322
  requestInit: { credentials: 'include' },
274
323
  })
275
324
  ```
276
325
 
277
- Accepts a static `RequestInit` object, a sync function, or an async function for dynamic auth tokens. Works alongside `resolveUrl` — `resolveUrl` controls WHERE to fetch, `requestInit` controls HOW.
326
+ `resolveUrl` controls WHERE to fetch. `requestInit` controls HOW (headers, credentials, cache).
278
327
 
279
328
  ## Cache
280
329
 
281
- In-memory translation cache with configurable eviction:
282
-
283
330
  ```ts
284
331
  cache: {
285
332
  runtime: {
@@ -291,12 +338,22 @@ cache: {
291
338
  }
292
339
  ```
293
340
 
341
+ ## Package Entries
342
+
343
+ | Entry | Purpose |
344
+ |-------|---------|
345
+ | `vite-bundled-i18n` | Core runtime, config helpers, type utilities |
346
+ | `vite-bundled-i18n/react` | `I18nProvider`, `useI18n`, `I18nBoundary`, `DevToolbar` |
347
+ | `vite-bundled-i18n/vue` | `createI18nPlugin`, `useI18n` |
348
+ | `vite-bundled-i18n/vanilla` | `getTranslations`, `initI18n` |
349
+ | `vite-bundled-i18n/server` | `initServerI18n` (SSR) |
350
+ | `vite-bundled-i18n/plugin` | Vite plugin (`i18nPlugin`) |
351
+
294
352
  ## Documentation
295
353
 
296
354
  - [Getting Started](./docs/getting-started.md)
297
355
  - [API Reference](./docs/api.md)
298
356
  - [Architecture](./docs/architecture.md)
299
- - [Examples](./docs/examples.md)
300
357
 
301
358
  ## License
302
359
 
package/dist/cli/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { a as writeTypes, i as generateReports, n as compileAll, r as flattenLocaleKeys, s as generateBundles, t as walkAll } from "../walker-9pKaJgmJ.js";
2
+ import { a as generateReports, l as generateBundles, n as walkAll, r as flattenLocaleKeys, s as writeTypes, t as compileAll } from "../compiler-B8vL51ge.js";
3
3
  import fs from "node:fs";
4
4
  import path from "node:path";
5
5
  //#region src/cli/commands.ts
@@ -24,6 +24,9 @@ function runWalker(config) {
24
24
  extractionScope
25
25
  });
26
26
  }
27
+ function collectScopeNames(analysis) {
28
+ return [...new Set(analysis.routes.flatMap((route) => route.scopes))].sort();
29
+ }
27
30
  /**
28
31
  * Pad a string to the given width.
29
32
  */
@@ -77,12 +80,13 @@ function analyze(config) {
77
80
  */
78
81
  function generate(config) {
79
82
  const { outDir, typesOutPath, localesDir } = resolveConfig(config);
80
- const bundles = generateBundles(runWalker(config), {
83
+ const analysis = runWalker(config);
84
+ const bundles = generateBundles(analysis, {
81
85
  localesDir,
82
86
  locales: config.locales,
83
87
  outDir
84
88
  });
85
- writeTypes(localesDir, config.defaultLocale, typesOutPath);
89
+ writeTypes(localesDir, config.defaultLocale, typesOutPath, collectScopeNames(analysis));
86
90
  console.log(`Generated ${bundles.length} bundle(s):`);
87
91
  for (const b of bundles) console.log(` ${b.locale}/${b.name} — ${b.keyCount} keys (${b.prunedCount} pruned)`);
88
92
  console.log(`Types written to ${typesOutPath}`);
@@ -145,7 +149,7 @@ function build(config) {
145
149
  locales: config.locales,
146
150
  outDir
147
151
  });
148
- writeTypes(localesDir, config.defaultLocale, typesOutPath);
152
+ writeTypes(localesDir, config.defaultLocale, typesOutPath, collectScopeNames(analysis));
149
153
  console.log(`\nGenerated ${bundles.length} bundle(s)`);
150
154
  console.log(`Types written to ${typesOutPath}`);
151
155
  const compiledOutDir = path.join(outDir, "compiled");
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../src/cli/commands.ts","../../src/cli/index.ts"],"sourcesContent":["import path from 'node:path';\nimport { walkAll } from '../extractor/walker';\nimport { generateBundles } from '../extractor/bundle-generator';\nimport { writeTypes } from '../extractor/type-generator';\nimport { generateReports } from '../extractor/reports';\nimport { compileAll } from '../extractor/compiler';\nimport type { ProjectAnalysis } from '../extractor/walker-types';\nimport type { DictionaryConfig } from '../core/types';\nimport { flattenLocaleKeys } from '../extractor/reports';\n\nexport interface CliConfig {\n /** Glob patterns for page entry points. */\n pages: string[];\n /** Locales directory (relative to rootDir). */\n localesDir: string;\n /** All supported locale codes. */\n locales: string[];\n /** Default locale. */\n defaultLocale: string;\n /** Root directory. Defaults to process.cwd(). */\n rootDir?: string;\n /** Output directory for generated bundles. Defaults to '.i18n'. */\n outDir?: string;\n /** Output path for generated types. Defaults to '.i18n/i18n.d.ts'. */\n typesOutPath?: string;\n /** Extraction scope. Defaults to 'global'. */\n extractionScope?: 'global' | 'scoped';\n /** Optional dictionary configurations for compiled mode. */\n dictionaries?: Record<string, DictionaryConfig>;\n}\n\nfunction resolveConfig(config: CliConfig) {\n const rootDir = config.rootDir ?? process.cwd();\n const outDir = config.outDir ?? path.join(rootDir, '.i18n');\n const typesOutPath =\n config.typesOutPath ?? path.join(outDir, 'i18n-generated.ts');\n const localesDir = path.isAbsolute(config.localesDir)\n ? config.localesDir\n : path.join(rootDir, config.localesDir);\n const extractionScope = config.extractionScope ?? 'global';\n\n return { rootDir, outDir, typesOutPath, localesDir, extractionScope } as const;\n}\n\nfunction runWalker(config: CliConfig): ProjectAnalysis {\n const { rootDir, localesDir, extractionScope } = resolveConfig(config);\n\n return walkAll({\n pages: config.pages,\n rootDir,\n localesDir,\n defaultLocale: config.defaultLocale,\n extractionScope,\n });\n}\n\n/**\n * Pad a string to the given width.\n */\nfunction pad(str: string, width: number): string {\n return str + ' '.repeat(Math.max(0, width - str.length));\n}\n\n/**\n * Print a simple ASCII table to stdout.\n */\nfunction printTable(\n headers: string[],\n rows: string[][],\n): void {\n const colWidths = headers.map((h, i) =>\n Math.max(h.length, ...rows.map((r) => (r[i] ?? '').length)),\n );\n\n const sep =\n '\\u250c' +\n colWidths.map((w) => '\\u2500'.repeat(w + 2)).join('\\u252c') +\n '\\u2510';\n const mid =\n '\\u251c' +\n colWidths.map((w) => '\\u2500'.repeat(w + 2)).join('\\u253c') +\n '\\u2524';\n const bot =\n '\\u2514' +\n colWidths.map((w) => '\\u2500'.repeat(w + 2)).join('\\u2534') +\n '\\u2518';\n\n const formatRow = (cells: string[]) =>\n '\\u2502' +\n cells.map((c, i) => ' ' + pad(c, colWidths[i]) + ' ').join('\\u2502') +\n '\\u2502';\n\n console.log(sep);\n console.log(formatRow(headers));\n console.log(mid);\n for (const row of rows) {\n console.log(formatRow(row));\n }\n console.log(bot);\n}\n\n/**\n * Run the walker and print a summary table to stdout.\n * Returns the ProjectAnalysis for programmatic use.\n */\nexport function analyze(config: CliConfig): ProjectAnalysis {\n const { localesDir } = resolveConfig(config);\n const analysis = runWalker(config);\n\n const availableKeys = flattenLocaleKeys(localesDir, config.defaultLocale);\n const totalAvailable = Array.from(availableKeys.values()).reduce(\n (sum, keys) => sum + keys.length,\n 0,\n );\n\n const rows = analysis.routes.map((route) => {\n const usedCount = route.keys.filter((k) => !k.dynamic).length;\n return [\n route.routeId,\n String(usedCount),\n String(totalAvailable),\n String(totalAvailable - usedCount),\n ];\n });\n\n printTable(['Route', 'Used Keys', 'Available', 'Pruned'], rows);\n\n console.log(\n `\\n${analysis.routes.length} route(s), ${analysis.allKeys.length} unique key(s), ${analysis.availableNamespaces.length} namespace(s)`,\n );\n\n return analysis;\n}\n\n/**\n * Run the walker, then generate bundles and types.\n * Prints what was generated to stdout.\n */\nexport function generate(config: CliConfig): void {\n const { outDir, typesOutPath, localesDir } = resolveConfig(config);\n const analysis = runWalker(config);\n\n const bundles = generateBundles(analysis, {\n localesDir,\n locales: config.locales,\n outDir,\n });\n\n writeTypes(localesDir, config.defaultLocale, typesOutPath);\n\n console.log(`Generated ${bundles.length} bundle(s):`);\n for (const b of bundles) {\n console.log(` ${b.locale}/${b.name} — ${b.keyCount} keys (${b.prunedCount} pruned)`);\n }\n console.log(`Types written to ${typesOutPath}`);\n}\n\n/**\n * Run the walker, then generate diagnostic reports.\n * Prints summary to stdout.\n */\nexport function report(config: CliConfig): void {\n const { outDir, localesDir } = resolveConfig(config);\n const analysis = runWalker(config);\n\n generateReports(analysis, localesDir, config.defaultLocale, outDir, config.dictionaries);\n\n console.log(`Reports written to ${outDir}:`);\n console.log(' manifest.json');\n console.log(' missing.json');\n console.log(' unused.json');\n console.log(' stats.json');\n}\n\n/**\n * Run the walker, then compile pre-resolved flat Map modules.\n * Prints a summary to stdout.\n */\nexport function compile(config: CliConfig): void {\n const { outDir, localesDir } = resolveConfig(config);\n const analysis = runWalker(config);\n const compiledOutDir = path.join(outDir, 'compiled');\n\n compileAll(analysis, {\n localesDir,\n locales: config.locales,\n defaultLocale: config.defaultLocale,\n outDir: compiledOutDir,\n dictionaries: config.dictionaries,\n });\n\n // Count generated modules: one per route per locale, plus dictionary modules\n const routeModules = analysis.routes.length * config.locales.length;\n const dictModules =\n config.dictionaries && Object.keys(config.dictionaries).length > 0\n ? config.locales.length\n : 0;\n const total = routeModules + dictModules + 1; // +1 for manifest\n\n console.log(`Compiled ${total} module(s) to ${compiledOutDir}`);\n}\n\n/**\n * Run analyze + generate + compile + report all at once.\n */\nexport function build(config: CliConfig): void {\n const { outDir, typesOutPath, localesDir } = resolveConfig(config);\n const analysis = runWalker(config);\n\n // Analyze: print table\n const availableKeys = flattenLocaleKeys(localesDir, config.defaultLocale);\n const totalAvailable = Array.from(availableKeys.values()).reduce(\n (sum, keys) => sum + keys.length,\n 0,\n );\n\n const rows = analysis.routes.map((route) => {\n const usedCount = route.keys.filter((k) => !k.dynamic).length;\n return [\n route.routeId,\n String(usedCount),\n String(totalAvailable),\n String(totalAvailable - usedCount),\n ];\n });\n\n printTable(['Route', 'Used Keys', 'Available', 'Pruned'], rows);\n\n // Generate bundles + types\n const bundles = generateBundles(analysis, {\n localesDir,\n locales: config.locales,\n outDir,\n });\n\n writeTypes(localesDir, config.defaultLocale, typesOutPath);\n\n console.log(`\\nGenerated ${bundles.length} bundle(s)`);\n console.log(`Types written to ${typesOutPath}`);\n\n // Compile\n const compiledOutDir = path.join(outDir, 'compiled');\n compileAll(analysis, {\n localesDir,\n locales: config.locales,\n defaultLocale: config.defaultLocale,\n outDir: compiledOutDir,\n dictionaries: config.dictionaries,\n });\n console.log(`Compiled modules written to ${compiledOutDir}`);\n\n // Reports\n generateReports(analysis, localesDir, config.defaultLocale, outDir, config.dictionaries);\n\n console.log(`Reports written to ${outDir}`);\n console.log(\n `\\nDone. ${analysis.routes.length} route(s), ${analysis.allKeys.length} unique key(s).`,\n );\n}\n","#!/usr/bin/env node\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport { analyze, generate, compile, report, build } from './commands';\nimport type { CliConfig } from './commands';\n\nconst COMMANDS = ['analyze', 'generate', 'compile', 'report', 'build'] as const;\ntype Command = (typeof COMMANDS)[number];\n\nfunction printUsage(): void {\n console.log('Usage: vite-bundled-i18n <command> [--config <path>]');\n console.log('');\n console.log('Commands:');\n console.log(' analyze — Walk imports and print a summary of key usage per route');\n console.log(' generate — Generate tree-shaken bundles and TypeScript types');\n console.log(' report — Generate diagnostic reports (manifest, missing, unused, stats)');\n console.log(' compile — Compile pre-resolved flat Map modules for production');\n console.log(' build — Run analyze + generate + compile + report in one step');\n console.log('');\n console.log('Options:');\n console.log(' --config <path> Path to config file (default: i18n.config.json)');\n}\n\nfunction loadConfig(configPath: string): CliConfig {\n const resolved = path.resolve(configPath);\n if (!fs.existsSync(resolved)) {\n console.error(`Config file not found: ${resolved}`);\n process.exit(1);\n }\n\n const raw = fs.readFileSync(resolved, 'utf-8');\n return JSON.parse(raw) as CliConfig;\n}\n\nfunction parseArgs(argv: string[]): { command: Command; configPath: string } {\n const args = argv.slice(2);\n let command: Command | undefined;\n let configPath = 'i18n.config.json';\n\n for (let i = 0; i < args.length; i++) {\n const arg = args[i];\n if (arg === '--config' && i + 1 < args.length) {\n configPath = args[++i];\n } else if (arg === '--help' || arg === '-h') {\n printUsage();\n process.exit(0);\n } else if (!command && COMMANDS.includes(arg as Command)) {\n command = arg as Command;\n } else {\n console.error(`Unknown argument: ${arg}`);\n printUsage();\n process.exit(1);\n }\n }\n\n if (!command) {\n printUsage();\n process.exit(1);\n }\n\n return { command: command!, configPath };\n}\n\nconst { command, configPath } = parseArgs(process.argv);\nconst config = loadConfig(configPath);\n\nconst commands: Record<Command, (cfg: CliConfig) => void> = {\n analyze,\n generate,\n compile,\n report,\n build,\n};\n\ncommands[command](config);\n"],"mappings":";;;;;AA+BA,SAAS,cAAc,QAAmB;CACxC,MAAM,UAAU,OAAO,WAAW,QAAQ,KAAK;CAC/C,MAAM,SAAS,OAAO,UAAU,KAAK,KAAK,SAAS,QAAQ;AAQ3D,QAAO;EAAE;EAAS;EAAQ,cANxB,OAAO,gBAAgB,KAAK,KAAK,QAAQ,oBAAoB;EAMvB,YALrB,KAAK,WAAW,OAAO,WAAW,GACjD,OAAO,aACP,KAAK,KAAK,SAAS,OAAO,WAAW;EAGW,iBAF5B,OAAO,mBAAmB;EAEmB;;AAGvE,SAAS,UAAU,QAAoC;CACrD,MAAM,EAAE,SAAS,YAAY,oBAAoB,cAAc,OAAO;AAEtE,QAAO,QAAQ;EACb,OAAO,OAAO;EACd;EACA;EACA,eAAe,OAAO;EACtB;EACD,CAAC;;;;;AAMJ,SAAS,IAAI,KAAa,OAAuB;AAC/C,QAAO,MAAM,IAAI,OAAO,KAAK,IAAI,GAAG,QAAQ,IAAI,OAAO,CAAC;;;;;AAM1D,SAAS,WACP,SACA,MACM;CACN,MAAM,YAAY,QAAQ,KAAK,GAAG,MAChC,KAAK,IAAI,EAAE,QAAQ,GAAG,KAAK,KAAK,OAAO,EAAE,MAAM,IAAI,OAAO,CAAC,CAC5D;CA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,IAAI,GAAG;AACf,SAAQ,IAAI,WAAW;AACvB,SAAQ,IAAI,qEAAqE;;AAGnF,SAAS,WAAW,YAA+B;CACjD,MAAM,WAAW,KAAK,QAAQ,WAAW;AACzC,KAAI,CAAC,GAAG,WAAW,SAAS,EAAE;AAC5B,UAAQ,MAAM,0BAA0B,WAAW;AACnD,UAAQ,KAAK,EAAE;;CAGjB,MAAM,MAAM,GAAG,aAAa,UAAU,QAAQ;AAC9C,QAAO,KAAK,MAAM,IAAI;;AAGxB,SAAS,UAAU,MAA0D;CAC3E,MAAM,OAAO,KAAK,MAAM,EAAE;CAC1B,IAAI;CACJ,IAAI,aAAa;AAEjB,MAAK,IAAI,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK;EACpC,MAAM,MAAM,KAAK;AACjB,MAAI,QAAQ,cAAc,IAAI,IAAI,KAAK,OACrC,cAAa,KAAK,EAAE;WACX,QAAQ,YAAY,QAAQ,MAAM;AAC3C,eAAY;AACZ,WAAQ,KAAK,EAAE;aACN,CAAC,WAAW,SAAS,SAAS,IAAe,CACtD,WAAU;OACL;AACL,WAAQ,MAAM,qBAAqB,MAAM;AACzC,eAAY;AACZ,WAAQ,KAAK,EAAE;;;AAInB,KAAI,CAAC,SAAS;AACZ,cAAY;AACZ,UAAQ,KAAK,EAAE;;AAGjB,QAAO;EAAW;EAAU;EAAY;;AAG1C,IAAM,EAAE,SAAS,eAAe,UAAU,QAAQ,KAAK;AACvD,IAAM,SAAS,WAAW,WAAW;CAEuB;CAC1D;CACA;CACA;CACA;CACA;CACD,EAEQ,SAAS,OAAO"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../src/cli/commands.ts","../../src/cli/index.ts"],"sourcesContent":["import path from 'node:path';\nimport { walkAll } from '../extractor/walker';\nimport { generateBundles } from '../extractor/bundle-generator';\nimport { writeTypes } from '../extractor/type-generator';\nimport { generateReports } from '../extractor/reports';\nimport { compileAll } from '../extractor/compiler';\nimport type { ProjectAnalysis } from '../extractor/walker-types';\nimport type { DictionaryConfig } from '../core/types';\nimport { flattenLocaleKeys } from '../extractor/reports';\n\nexport interface CliConfig {\n /** Glob patterns for page entry points. */\n pages: string[];\n /** Locales directory (relative to rootDir). */\n localesDir: string;\n /** All supported locale codes. */\n locales: string[];\n /** Default locale. */\n defaultLocale: string;\n /** Root directory. Defaults to process.cwd(). */\n rootDir?: string;\n /** Output directory for generated bundles. Defaults to '.i18n'. */\n outDir?: string;\n /** Output path for generated types. Defaults to '.i18n/i18n.d.ts'. */\n typesOutPath?: string;\n /** Extraction scope. Defaults to 'global'. */\n extractionScope?: 'global' | 'scoped';\n /** Optional dictionary configurations for compiled mode. */\n dictionaries?: Record<string, DictionaryConfig>;\n}\n\nfunction resolveConfig(config: CliConfig) {\n const rootDir = config.rootDir ?? process.cwd();\n const outDir = config.outDir ?? path.join(rootDir, '.i18n');\n const typesOutPath =\n config.typesOutPath ?? path.join(outDir, 'i18n-generated.ts');\n const localesDir = path.isAbsolute(config.localesDir)\n ? config.localesDir\n : path.join(rootDir, config.localesDir);\n const extractionScope = config.extractionScope ?? 'global';\n\n return { rootDir, outDir, typesOutPath, localesDir, extractionScope } as const;\n}\n\nfunction runWalker(config: CliConfig): ProjectAnalysis {\n const { rootDir, localesDir, extractionScope } = resolveConfig(config);\n\n return walkAll({\n pages: config.pages,\n rootDir,\n localesDir,\n defaultLocale: config.defaultLocale,\n extractionScope,\n });\n}\n\nfunction collectScopeNames(analysis: ProjectAnalysis): string[] {\n return [...new Set(analysis.routes.flatMap((route) => route.scopes))].sort();\n}\n\n/**\n * Pad a string to the given width.\n */\nfunction pad(str: string, width: number): string {\n return str + ' '.repeat(Math.max(0, width - str.length));\n}\n\n/**\n * Print a simple ASCII table to stdout.\n */\nfunction printTable(\n headers: string[],\n rows: string[][],\n): void {\n const colWidths = headers.map((h, i) =>\n Math.max(h.length, ...rows.map((r) => (r[i] ?? '').length)),\n );\n\n const sep =\n '\\u250c' +\n colWidths.map((w) => '\\u2500'.repeat(w + 2)).join('\\u252c') +\n '\\u2510';\n const mid =\n '\\u251c' +\n colWidths.map((w) => '\\u2500'.repeat(w + 2)).join('\\u253c') +\n '\\u2524';\n const bot =\n '\\u2514' +\n colWidths.map((w) => '\\u2500'.repeat(w + 2)).join('\\u2534') +\n '\\u2518';\n\n const formatRow = (cells: string[]) =>\n '\\u2502' +\n cells.map((c, i) => ' ' + pad(c, colWidths[i]) + ' ').join('\\u2502') +\n '\\u2502';\n\n console.log(sep);\n console.log(formatRow(headers));\n console.log(mid);\n for (const row of rows) {\n console.log(formatRow(row));\n }\n console.log(bot);\n}\n\n/**\n * Run the walker and print a summary table to stdout.\n * Returns the ProjectAnalysis for programmatic use.\n */\nexport function analyze(config: CliConfig): ProjectAnalysis {\n const { localesDir } = resolveConfig(config);\n const analysis = runWalker(config);\n\n const availableKeys = flattenLocaleKeys(localesDir, config.defaultLocale);\n const totalAvailable = Array.from(availableKeys.values()).reduce(\n (sum, keys) => sum + keys.length,\n 0,\n );\n\n const rows = analysis.routes.map((route) => {\n const usedCount = route.keys.filter((k) => !k.dynamic).length;\n return [\n route.routeId,\n String(usedCount),\n String(totalAvailable),\n String(totalAvailable - usedCount),\n ];\n });\n\n printTable(['Route', 'Used Keys', 'Available', 'Pruned'], rows);\n\n console.log(\n `\\n${analysis.routes.length} route(s), ${analysis.allKeys.length} unique key(s), ${analysis.availableNamespaces.length} namespace(s)`,\n );\n\n return analysis;\n}\n\n/**\n * Run the walker, then generate bundles and types.\n * Prints what was generated to stdout.\n */\nexport function generate(config: CliConfig): void {\n const { outDir, typesOutPath, localesDir } = resolveConfig(config);\n const analysis = runWalker(config);\n\n const bundles = generateBundles(analysis, {\n localesDir,\n locales: config.locales,\n outDir,\n });\n\n writeTypes(localesDir, config.defaultLocale, typesOutPath, collectScopeNames(analysis));\n\n console.log(`Generated ${bundles.length} bundle(s):`);\n for (const b of bundles) {\n console.log(` ${b.locale}/${b.name} — ${b.keyCount} keys (${b.prunedCount} pruned)`);\n }\n console.log(`Types written to ${typesOutPath}`);\n}\n\n/**\n * Run the walker, then generate diagnostic reports.\n * Prints summary to stdout.\n */\nexport function report(config: CliConfig): void {\n const { outDir, localesDir } = resolveConfig(config);\n const analysis = runWalker(config);\n\n generateReports(analysis, localesDir, config.defaultLocale, outDir, config.dictionaries);\n\n console.log(`Reports written to ${outDir}:`);\n console.log(' manifest.json');\n console.log(' missing.json');\n console.log(' unused.json');\n console.log(' stats.json');\n}\n\n/**\n * Run the walker, then compile pre-resolved flat Map modules.\n * Prints a summary to stdout.\n */\nexport function compile(config: CliConfig): void {\n const { outDir, localesDir } = resolveConfig(config);\n const analysis = runWalker(config);\n const compiledOutDir = path.join(outDir, 'compiled');\n\n compileAll(analysis, {\n localesDir,\n locales: config.locales,\n defaultLocale: config.defaultLocale,\n outDir: compiledOutDir,\n dictionaries: config.dictionaries,\n });\n\n // Count generated modules: one per route per locale, plus dictionary modules\n const routeModules = analysis.routes.length * config.locales.length;\n const dictModules =\n config.dictionaries && Object.keys(config.dictionaries).length > 0\n ? config.locales.length\n : 0;\n const total = routeModules + dictModules + 1; // +1 for manifest\n\n console.log(`Compiled ${total} module(s) to ${compiledOutDir}`);\n}\n\n/**\n * Run analyze + generate + compile + report all at once.\n */\nexport function build(config: CliConfig): void {\n const { outDir, typesOutPath, localesDir } = resolveConfig(config);\n const analysis = runWalker(config);\n\n // Analyze: print table\n const availableKeys = flattenLocaleKeys(localesDir, config.defaultLocale);\n const totalAvailable = Array.from(availableKeys.values()).reduce(\n (sum, keys) => sum + keys.length,\n 0,\n );\n\n const rows = analysis.routes.map((route) => {\n const usedCount = route.keys.filter((k) => !k.dynamic).length;\n return [\n route.routeId,\n String(usedCount),\n String(totalAvailable),\n String(totalAvailable - usedCount),\n ];\n });\n\n printTable(['Route', 'Used Keys', 'Available', 'Pruned'], rows);\n\n // Generate bundles + types\n const bundles = generateBundles(analysis, {\n localesDir,\n locales: config.locales,\n outDir,\n });\n\n writeTypes(localesDir, config.defaultLocale, typesOutPath, collectScopeNames(analysis));\n\n console.log(`\\nGenerated ${bundles.length} bundle(s)`);\n console.log(`Types written to ${typesOutPath}`);\n\n // Compile\n const compiledOutDir = path.join(outDir, 'compiled');\n compileAll(analysis, {\n localesDir,\n locales: config.locales,\n defaultLocale: config.defaultLocale,\n outDir: compiledOutDir,\n dictionaries: config.dictionaries,\n });\n console.log(`Compiled modules written to ${compiledOutDir}`);\n\n // Reports\n generateReports(analysis, localesDir, config.defaultLocale, outDir, config.dictionaries);\n\n console.log(`Reports written to ${outDir}`);\n console.log(\n `\\nDone. ${analysis.routes.length} route(s), ${analysis.allKeys.length} unique key(s).`,\n );\n}\n","#!/usr/bin/env node\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport { analyze, generate, compile, report, build } from './commands';\nimport type { CliConfig } from './commands';\n\nconst COMMANDS = ['analyze', 'generate', 'compile', 'report', 'build'] as const;\ntype Command = (typeof COMMANDS)[number];\n\nfunction printUsage(): void {\n console.log('Usage: vite-bundled-i18n <command> [--config <path>]');\n console.log('');\n console.log('Commands:');\n console.log(' analyze — Walk imports and print a summary of key usage per route');\n console.log(' generate — Generate tree-shaken bundles and TypeScript types');\n console.log(' report — Generate diagnostic reports (manifest, missing, unused, stats)');\n console.log(' compile — Compile pre-resolved flat Map modules for production');\n console.log(' build — Run analyze + generate + compile + report in one step');\n console.log('');\n console.log('Options:');\n console.log(' --config <path> Path to config file (default: i18n.config.json)');\n}\n\nfunction loadConfig(configPath: string): CliConfig {\n const resolved = path.resolve(configPath);\n if (!fs.existsSync(resolved)) {\n console.error(`Config file not found: ${resolved}`);\n process.exit(1);\n }\n\n const raw = fs.readFileSync(resolved, 'utf-8');\n return JSON.parse(raw) as CliConfig;\n}\n\nfunction parseArgs(argv: string[]): { command: Command; configPath: string } {\n const args = argv.slice(2);\n let command: Command | undefined;\n let configPath = 'i18n.config.json';\n\n for (let i = 0; i < args.length; i++) {\n const arg = args[i];\n if (arg === '--config' && i + 1 < args.length) {\n configPath = args[++i];\n } else if (arg === '--help' || arg === '-h') {\n printUsage();\n process.exit(0);\n } else if (!command && COMMANDS.includes(arg as Command)) {\n command = arg as Command;\n } else {\n console.error(`Unknown argument: ${arg}`);\n printUsage();\n process.exit(1);\n }\n }\n\n if (!command) {\n printUsage();\n process.exit(1);\n }\n\n return { command: command!, configPath };\n}\n\nconst { command, configPath } = parseArgs(process.argv);\nconst config = loadConfig(configPath);\n\nconst commands: Record<Command, (cfg: CliConfig) => void> = {\n analyze,\n generate,\n compile,\n report,\n build,\n};\n\ncommands[command](config);\n"],"mappings":";;;;;AA+BA,SAAS,cAAc,QAAmB;CACxC,MAAM,UAAU,OAAO,WAAW,QAAQ,KAAK;CAC/C,MAAM,SAAS,OAAO,UAAU,KAAK,KAAK,SAAS,QAAQ;AAQ3D,QAAO;EAAE;EAAS;EAAQ,cANxB,OAAO,gBAAgB,KAAK,KAAK,QAAQ,oBAAoB;EAMvB,YALrB,KAAK,WAAW,OAAO,WAAW,GACjD,OAAO,aACP,KAAK,KAAK,SAAS,OAAO,WAAW;EAGW,iBAF5B,OAAO,mBAAmB;EAEmB;;AAGvE,SAAS,UAAU,QAAoC;CACrD,MAAM,EAAE,SAAS,YAAY,oBAAoB,cAAc,OAAO;AAEtE,QAAO,QAAQ;EACb,OAAO,OAAO;EACd;EACA;EACA,eAAe,OAAO;EACtB;EACD,CAAC;;AAGJ,SAAS,kBAAkB,UAAqC;AAC9D,QAAO,CAAC,GAAG,IAAI,IAAI,SAAS,OAAO,SAAS,UAAU,MAAM,OAAO,CAAC,CAAC,CAAC,MAAM;;;;;AAM9E,SAAS,IAAI,KAAa,OAAuB;AAC/C,QAAO,MAAM,IAAI,OAAO,KAAK,IAAI,GAAG,QAAQ,IAAI,OAAO,CAAC;;;;;AAM1D,SAAS,WACP,SACA,MACM;CACN,MAAM,YAAY,QAAQ,KAAK,GAAG,MAChC,KAAK,IAAI,EAAE,QAAQ,GAAG,KAAK,KAAK,OAAO,EAAE,MAAM,IAAI,OAAO,CAAC,CAC5D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