vite-bundled-i18n 0.2.11 → 0.2.13

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 CHANGED
@@ -1,6 +1,6 @@
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. Production builds emit static, scope-matched bundles.
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.
4
4
 
5
5
  ```bash
6
6
  npm i vite-bundled-i18n
@@ -11,12 +11,14 @@ Requires Node `>=20` and Vite. React, Vue, and vanilla adapters are included —
11
11
  ## Features
12
12
 
13
13
  - **Scope bundles** — translations grouped by route (`products.index`) and loaded on demand
14
- - **Dictionary ownership** — named dictionaries claim keys by pattern with explicit priority
15
- - **Type generation** — TypeScript types for every key and placeholder, generated from source
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`, ...)
16
+ - **Placeholder validation** — `t('cart.total', { amount: 9.99 })` is type-checked against `{{amount}}` in the JSON
16
17
  - **Compiled production output** — Vite plugin emits `__i18n/` assets as static JSON or compiled modules
17
18
  - **Multi-framework** — React, Vue, and vanilla JS share a single core
18
19
  - **SSR** — server-side rendering with automatic client hydration
19
- - **AST extraction** — finds translation keys in source without execution
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
20
22
 
21
23
  ## Setup
22
24
 
@@ -31,6 +33,7 @@ export const i18nConfig = defineI18nConfig({
31
33
  dictionaries: {
32
34
  global: {
33
35
  include: ['shared.*', 'global.*', 'actions.*'],
36
+ exclude: ['shared.validation.*'], // optional — carve out large sub-namespaces
34
37
  priority: 1,
35
38
  pinned: true,
36
39
  },
@@ -67,12 +70,14 @@ export default defineConfig({
67
70
  locales: ['en', 'bg'],
68
71
  defaultLocale: 'en',
69
72
  generatedOutDir: '.i18n',
70
- typesOutPath: 'src/i18n-types.d.ts',
73
+ // types are generated to src/core/i18n-generated.ts by default
71
74
  }),
72
75
  ],
73
76
  })
74
77
  ```
75
78
 
79
+ Types are generated automatically on `npm run dev` (on server start and when locale files change) and during `npm run build`. No manual step needed.
80
+
76
81
  ### React
77
82
 
78
83
  ```tsx
@@ -93,8 +98,8 @@ createRoot(document.getElementById('root')!).render(
93
98
  import { useI18n } from 'vite-bundled-i18n/react'
94
99
 
95
100
  export function ProductsPage() {
96
- // t and translations.get are interchangeable — t is a shorthand alias.
97
- // Both accept a key, optional placeholders, and an optional fallback string.
101
+ // t() has full autocomplete — type 't('products.' and the IDE suggests the next segment.
102
+ // Placeholders are type-checked: t('cart.total', { amount }) enforces { amount: Primitive }.
98
103
  const { t, translations, ready } = useI18n('products.index')
99
104
 
100
105
  if (!ready) return <div>{t('shared.loading', 'Loading...')}</div>
@@ -108,6 +113,16 @@ export function ProductsPage() {
108
113
  }
109
114
  ```
110
115
 
116
+ Use `I18nBoundary` to avoid rules-of-hooks violations from early returns:
117
+
118
+ ```tsx
119
+ import { I18nBoundary } from 'vite-bundled-i18n/react'
120
+
121
+ <I18nBoundary scope="products.index" fallback={<Spinner />}>
122
+ <ProductsPage />
123
+ </I18nBoundary>
124
+ ```
125
+
111
126
  ### Vue
112
127
 
113
128
  ```ts
@@ -134,12 +149,20 @@ translations.has('actions.save')
134
149
  translations.namespace('global').get('nav.home')
135
150
  ```
136
151
 
152
+ ### Locale Switching
153
+
154
+ ```ts
155
+ await i18n.changeLocale('bg')
156
+ ```
157
+
158
+ All React/Vue consumers re-render automatically.
159
+
137
160
  ### Package Entries
138
161
 
139
162
  | Entry | Purpose |
140
163
  |-------|---------|
141
164
  | `vite-bundled-i18n` | Core runtime and configuration |
142
- | `vite-bundled-i18n/react` | React adapter (`I18nProvider`, `useI18n`) |
165
+ | `vite-bundled-i18n/react` | React adapter (`I18nProvider`, `useI18n`, `I18nBoundary`) |
143
166
  | `vite-bundled-i18n/vue` | Vue adapter (`createI18nPlugin`, `useI18n`) |
144
167
  | `vite-bundled-i18n/vanilla` | Framework-agnostic `getTranslations` |
145
168
  | `vite-bundled-i18n/server` | SSR utilities (`initServerI18n`) |
@@ -147,12 +170,13 @@ translations.namespace('global').get('nav.home')
147
170
 
148
171
  ## Dictionaries
149
172
 
150
- Dictionaries define key ownership — which translation keys belong to which bundle:
173
+ Dictionaries define key ownership — which namespaces are preloaded and available globally:
151
174
 
152
175
  ```ts
153
176
  dictionaries: {
154
177
  global: {
155
178
  include: ['shared.*', 'global.*', 'actions.*'],
179
+ exclude: ['shared.validation.*'], // carve out sub-namespaces you don't need client-side
156
180
  priority: 1,
157
181
  pinned: true,
158
182
  },
@@ -164,8 +188,29 @@ dictionaries: {
164
188
  ```
165
189
 
166
190
  - `include` accepts exact keys, namespace wildcards, and prefix patterns
167
- - Higher priority dictionaries claim keys first; lower priority dictionaries exclude already-owned keys
191
+ - `exclude` removes matching keys from the dictionary (applied after `include`)
192
+ - Higher priority dictionaries claim keys first; lower priority dictionaries skip already-owned keys
168
193
  - Pinned dictionaries remain in memory and are never evicted
194
+ - Dictionary bundles include ALL keys from matching namespaces — no tree-shaking. Scope bundles are the per-page optimization layer.
195
+
196
+ ## Custom URL Resolution
197
+
198
+ For non-standard deployments (custom API routes, CDN, single endpoint), use `resolveUrl`:
199
+
200
+ ```ts
201
+ const i18n = createI18n({
202
+ ...i18nConfig,
203
+ locale: 'en',
204
+ defaultLocale: 'en',
205
+ supportedLocales: ['en', 'bg'],
206
+ resolveUrl: (locale, type, name) => {
207
+ // type: 'dictionary' | 'scope' | 'namespace' | 'manifest'
208
+ return `/api/translations/${locale}/${type}/${name}`
209
+ },
210
+ })
211
+ ```
212
+
213
+ When not set, the runtime uses the build-injected base path from Vite's `base` config automatically.
169
214
 
170
215
  ## Data Files
171
216
 
@@ -180,7 +225,7 @@ export const nav = defineI18nData([
180
225
  ])
181
226
  ```
182
227
 
183
- The AST extractor recognizes these helpers and includes referenced keys in scope analysis.
228
+ 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.
184
229
 
185
230
  ## Server-Side Rendering
186
231
 
@@ -205,7 +250,7 @@ __i18n/compiled/manifest.js
205
250
  __i18n/compiled/{locale}/...
206
251
  ```
207
252
 
208
- The runtime resolves these assets automatically in production — no additional configuration required.
253
+ 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.
209
254
 
210
255
  ## Fetch Options
211
256
 
@@ -218,7 +263,7 @@ createI18n({
218
263
  })
219
264
  ```
220
265
 
221
- Accepts a static `RequestInit` object, a sync function, or an async function for dynamic auth tokens.
266
+ 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.
222
267
 
223
268
  ## Cache
224
269
 
@@ -13,7 +13,7 @@ export interface CliConfig {
13
13
  rootDir?: string;
14
14
  /** Output directory for generated bundles. Defaults to '.i18n'. */
15
15
  outDir?: string;
16
- /** Output path for generated types. Defaults to 'src/i18n-types.d.ts'. */
16
+ /** Output path for generated types. Defaults to '.i18n/i18n.d.ts'. */
17
17
  typesOutPath?: string;
18
18
  /** Extraction scope. Defaults to 'global'. */
19
19
  extractionScope?: 'global' | 'scoped';
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-Kj7M4oN5.js";
2
+ import { a as writeTypes, i as generateReports, n as compileAll, r as flattenLocaleKeys, s as generateBundles, t as walkAll } from "../walker-9pKaJgmJ.js";
3
3
  import fs from "node:fs";
4
4
  import path from "node:path";
5
5
  //#region src/cli/commands.ts
@@ -8,7 +8,7 @@ function resolveConfig(config) {
8
8
  return {
9
9
  rootDir,
10
10
  outDir: config.outDir ?? path.join(rootDir, ".i18n"),
11
- typesOutPath: config.typesOutPath ?? path.join(rootDir, "src", "i18n-types.d.ts"),
11
+ typesOutPath: config.typesOutPath ?? path.join(rootDir, "src", "core", "i18n-generated.ts"),
12
12
  localesDir: path.isAbsolute(config.localesDir) ? config.localesDir : path.join(rootDir, config.localesDir),
13
13
  extractionScope: config.extractionScope ?? "global"
14
14
  };
@@ -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 'src/i18n-types.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(rootDir, 'src', 'i18n-types.d.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;AAS/C,QAAO;EAAE;EAAS,QARH,OAAO,UAAU,KAAK,KAAK,SAAS,QAAQ;EAQjC,cANxB,OAAO,gBAAgB,KAAK,KAAK,SAAS,OAAO,kBAAkB;EAM7B,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,OAA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,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(rootDir, 'src', 'core', '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;AAS/C,QAAO;EAAE;EAAS,QARH,OAAO,UAAU,KAAK,KAAK,SAAS,QAAQ;EAQjC,cANxB,OAAO,gBAAgB,KAAK,KAAK,SAAS,OAAO,QAAQ,oBAAoB;EAMvC,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;CAC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
6
+ 'default': true;
7
+ 'heading': true;
8
+ 'setDefault': true;
9
+ };
10
+ 'orders': {
11
+ 'empty': true;
12
+ 'heading': true;
13
+ 'orderNumber': true;
14
+ 'placedOn': true;
15
+ 'reorder': true;
16
+ 'status': {
17
+ 'cancelled': true;
18
+ 'delivered': true;
19
+ 'pending': true;
20
+ 'processing': true;
21
+ 'shipped': true;
22
+ };
23
+ 'trackOrder': true;
24
+ };
25
+ 'profile': {
26
+ 'changePassword': true;
27
+ 'confirmPassword': true;
28
+ 'currentPassword': true;
29
+ 'email': true;
30
+ 'heading': true;
31
+ 'name': true;
32
+ 'newPassword': true;
33
+ 'personalInfo': true;
34
+ 'phone': true;
35
+ 'updated': true;
36
+ };
37
+ };
38
+ 'actions': {
39
+ 'addToCart': true;
40
+ 'applyFilter': true;
41
+ 'checkout': true;
42
+ 'clearFilters': true;
43
+ 'create': true;
44
+ 'delete': true;
45
+ 'edit': true;
46
+ 'register': true;
47
+ 'removeFromCart': true;
48
+ 'save': true;
49
+ 'signIn': true;
50
+ 'signOut': true;
51
+ 'sortBy': true;
52
+ 'submit': true;
53
+ 'update': true;
54
+ 'viewDetails': true;
55
+ };
56
+ 'cart': {
57
+ 'empty': true;
58
+ 'emptyAction': true;
59
+ 'item': {
60
+ 'moveToWishlist': true;
61
+ 'priceEach': true;
62
+ 'quantity': true;
63
+ 'remove': true;
64
+ };
65
+ 'promoCode': {
66
+ 'applied': true;
67
+ 'apply': true;
68
+ 'invalid': true;
69
+ 'label': true;
70
+ 'placeholder': true;
71
+ };
72
+ 'summary': {
73
+ 'estimatedDelivery': true;
74
+ 'freeShipping': true;
75
+ 'shipping': true;
76
+ 'subtotal': true;
77
+ 'tax': true;
78
+ 'total': true;
79
+ };
80
+ 'title': true;
81
+ };
82
+ 'global': {
83
+ 'appName': true;
84
+ 'footer': {
85
+ 'contact': true;
86
+ 'madeWith': true;
87
+ 'privacy': true;
88
+ 'terms': true;
89
+ 'version': true;
90
+ };
91
+ 'meta': {
92
+ 'description': true;
93
+ 'title': true;
94
+ };
95
+ 'nav': {
96
+ 'about': true;
97
+ 'account': true;
98
+ 'cart': true;
99
+ 'home': true;
100
+ 'products': true;
101
+ };
102
+ 'tagline': true;
103
+ };
104
+ 'products': {
105
+ 'index': {
106
+ 'empty': true;
107
+ 'filters': {
108
+ 'category': true;
109
+ 'featured': true;
110
+ 'inStock': true;
111
+ 'priceRange': true;
112
+ };
113
+ 'heading': true;
114
+ 'sort': {
115
+ 'newest': true;
116
+ 'popular': true;
117
+ 'priceAsc': true;
118
+ 'priceDesc': true;
119
+ };
120
+ 'subheading': true;
121
+ };
122
+ 'reviews': {
123
+ 'averageRating': true;
124
+ 'heading': true;
125
+ 'helpful': true;
126
+ 'noReviews': true;
127
+ 'reported': true;
128
+ 'reviewCount': true;
129
+ 'writeReview': true;
130
+ };
131
+ 'show': {
132
+ 'availability': {
133
+ 'backorder': true;
134
+ 'inStock': true;
135
+ 'outOfStock': true;
136
+ };
137
+ 'description': true;
138
+ 'discount': true;
139
+ 'originalPrice': true;
140
+ 'price': true;
141
+ 'relatedProducts': true;
142
+ 'sku': true;
143
+ 'tabs': {
144
+ 'description': true;
145
+ 'reviews': true;
146
+ 'specifications': true;
147
+ };
148
+ 'title': true;
149
+ };
150
+ };
151
+ 'shared': {
152
+ 'backToHome': true;
153
+ 'cancel': true;
154
+ 'close': true;
155
+ 'confirm': true;
156
+ 'copyright': true;
157
+ 'error': true;
158
+ 'loading': true;
159
+ 'next': true;
160
+ 'no': true;
161
+ 'noResults': true;
162
+ 'ok': true;
163
+ 'previous': true;
164
+ 'retry': true;
165
+ 'search': true;
166
+ 'yes': true;
167
+ };
168
+ }
169
+ export interface I18nParamsMap {
170
+ 'account.orders.orderNumber': {
171
+ number: TranslationValue;
172
+ };
173
+ 'account.orders.placedOn': {
174
+ date: TranslationValue;
175
+ };
176
+ 'actions.sortBy': {
177
+ field: TranslationValue;
178
+ };
179
+ 'cart.summary.estimatedDelivery': {
180
+ date: TranslationValue;
181
+ };
182
+ 'cart.item.quantity': {
183
+ count: TranslationValue;
184
+ };
185
+ 'cart.item.priceEach': {
186
+ amount: TranslationValue;
187
+ };
188
+ 'cart.promoCode.applied': {
189
+ code: TranslationValue;
190
+ discount: TranslationValue;
191
+ };
192
+ 'global.footer.madeWith': {
193
+ framework: TranslationValue;
194
+ };
195
+ 'global.footer.version': {
196
+ version: TranslationValue;
197
+ };
198
+ 'global.meta.title': {
199
+ page: TranslationValue;
200
+ };
201
+ 'products.index.subheading': {
202
+ count: TranslationValue;
203
+ };
204
+ 'products.show.price': {
205
+ amount: TranslationValue;
206
+ };
207
+ 'products.show.originalPrice': {
208
+ amount: TranslationValue;
209
+ };
210
+ 'products.show.discount': {
211
+ percent: TranslationValue;
212
+ };
213
+ 'products.show.sku': {
214
+ code: TranslationValue;
215
+ };
216
+ 'products.show.availability.inStock': {
217
+ count: TranslationValue;
218
+ };
219
+ 'products.show.tabs.reviews': {
220
+ count: TranslationValue;
221
+ };
222
+ 'products.reviews.averageRating': {
223
+ rating: TranslationValue;
224
+ };
225
+ 'products.reviews.reviewCount': {
226
+ count: TranslationValue;
227
+ };
228
+ }
229
+ export interface I18nScopeMap {
230
+ }
231
+ export {};
@@ -1,4 +1,6 @@
1
1
  import type { CompiledManifestModule } from './compiled-runtime';
2
+ import type { I18nNestedKeys, I18nParamsMap, I18nScopeMap } from './i18n-generated';
3
+ export type { I18nNestedKeys, I18nParamsMap, I18nScopeMap, };
2
4
  /**
3
5
  * Recursive type representing nested translation JSON.
4
6
  * Leaf values are strings (the translated text).
@@ -28,48 +30,42 @@ export type NestedTranslations = {
28
30
  * @example
29
31
  * ```ts
30
32
  * // Generated by: npm run i18n -- generate
31
- * // src/i18n-types.d.ts
33
+ * // .i18n/i18n.d.ts
32
34
  * declare module 'vite-bundled-i18n' {
33
- * interface I18nKeyMap {
34
- * 'shared.ok': true;
35
- * 'products.show.title': true;
35
+ * interface I18nNestedKeys {
36
+ * shared: { ok: true };
37
+ * products: { show: { title: true } };
36
38
  * }
37
39
  * }
38
40
  * ```
39
41
  */
40
42
  export interface I18nKeyMap {
41
43
  }
42
- /**
43
- * Augmentable interface mapping fully qualified translation keys to their
44
- * placeholder parameter objects. Generated alongside {@link I18nKeyMap}.
45
- *
46
- * Keys with no placeholders should map to `{}`.
47
- */
48
- export interface I18nParamsMap {
49
- }
50
- /**
51
- * Augmentable interface for nested key structure.
52
- * Enables progressive autocomplete: typing `t('feedback.` suggests
53
- * `pages`, `actions`, etc. as next segments.
54
- */
55
- export interface I18nNestedKeys {
56
- }
57
- /**
58
- * Augmentable interface for valid scope identifiers.
59
- * When populated by the type generator, constrains `useI18n(scope)` to valid scopes.
60
- */
61
- export interface I18nScopeMap {
62
- }
63
44
  /**
64
45
  * Resolves to the union of registered scope identifiers when `I18nScopeMap`
65
46
  * has entries, or falls back to `string` when it's empty.
66
47
  */
67
48
  export type ValidScope = keyof I18nScopeMap extends never ? string : keyof I18nScopeMap & string;
68
49
  /**
69
- * Resolves to the union of registered translation keys when `I18nKeyMap`
70
- * has entries, or falls back to `string` when it's empty (no generated types).
50
+ * Recursive dot-path expansion for nested key tree interfaces.
51
+ * Converts `{ a: { b: true; c: { d: true } } }` to `'a.b' | 'a.c.d'`.
52
+ *
53
+ * Used to derive `TranslationKey` from `I18nNestedKeys` — this gives
54
+ * progressive autocomplete in the IDE (one level at a time) instead of
55
+ * dumping 2000+ flat strings into the completion list.
56
+ */
57
+ export type DotPath<T, Prefix extends string = ''> = {
58
+ [K in keyof T & string]: T[K] extends Record<string, unknown> ? DotPath<T[K], `${Prefix}${K}.`> : `${Prefix}${K}`;
59
+ }[keyof T & string];
60
+ /**
61
+ * Resolves to the union of registered translation keys.
62
+ *
63
+ * When `I18nNestedKeys` is populated (by the type generator), derives
64
+ * keys from the nested tree via `DotPath` — this gives progressive
65
+ * autocomplete in the IDE (one segment at a time). Falls back to
66
+ * `string` when no types are generated.
71
67
  */
72
- export type TranslationKey = keyof I18nKeyMap extends never ? string : keyof I18nKeyMap & string;
68
+ export type TranslationKey = keyof I18nNestedKeys extends never ? string : DotPath<I18nNestedKeys>;
73
69
  /**
74
70
  * Primitive value types accepted for interpolation placeholders.
75
71
  */
@@ -81,22 +77,20 @@ export type Primitive = string | number | boolean | bigint | null | undefined;
81
77
  * before generated types exist.
82
78
  */
83
79
  export type ParamsOf<K extends TranslationKey> = K extends keyof I18nParamsMap ? I18nParamsMap[K] : Record<string, Primitive>;
84
- type TranslateArgs<K extends TranslationKey> = K extends keyof I18nParamsMap ? keyof I18nParamsMap[K] extends never ? [fallback?: string] : [params: I18nParamsMap[K], fallback?: string] : [fallback?: string] | [params: Record<string, unknown>, fallback?: string];
85
80
  /**
86
- * Translation function with overloaded signatures.
81
+ * Translation function.
87
82
  *
88
- * Supports two calling conventions:
89
- * - `t(key, fallback?)` — when no interpolation is needed
90
- * - `t(key, params, fallback?)` — when interpolation parameters are needed
83
+ * - `t(key)` or `t(key, fallback)` — for keys without placeholders
84
+ * - `t(key, params)` or `t(key, params, fallback)` — for keys with `{{placeholders}}`
91
85
  *
92
- * Overload resolution: if the second argument is a string, it is treated as a
93
- * fallback. If it is an object, it is treated as interpolation params.
94
- *
95
- * When generated types are present (`I18nKeyMap` is populated), the `key`
96
- * parameter is constrained to valid translation keys with full autocomplete.
97
- * Without generated types, it accepts any `string`.
86
+ * Params are type-checked per key: `t('cart.total', { amount: 9 })` enforces `{ amount }`.
98
87
  */
99
- export type TFunction = <K extends TranslationKey>(key: K, ...args: TranslateArgs<K>) => string;
88
+ export type TFunction = {
89
+ <K extends keyof I18nParamsMap>(key: K, params: I18nParamsMap[K]): string;
90
+ <K extends keyof I18nParamsMap>(key: K, params: I18nParamsMap[K], fallback: string): string;
91
+ (key: TranslationKey): string;
92
+ (key: TranslationKey, fallback: string): string;
93
+ };
100
94
  /**
101
95
  * Translation function for scoped/namespace-relative keys.
102
96
  * Accepts any string since scoped keys are relative to the namespace
@@ -115,7 +109,10 @@ export type ScopedTFunction = {
115
109
  * Unlike {@link TFunction}, this function does not accept fallback strings
116
110
  * and does not degrade to key-as-value.
117
111
  */
118
- export type TryTFunction = <K extends TranslationKey>(key: K, ...args: K extends keyof I18nParamsMap ? keyof I18nParamsMap[K] extends never ? [] : [params: I18nParamsMap[K]] : [] | [params: Record<string, unknown>]) => string | undefined;
112
+ export type TryTFunction = {
113
+ <K extends keyof I18nParamsMap>(key: K, params: I18nParamsMap[K]): string | undefined;
114
+ (key: TranslationKey): string | undefined;
115
+ };
119
116
  /**
120
117
  * Namespace-relative version of {@link TryTFunction}.
121
118
  */
@@ -128,7 +125,10 @@ export type ScopedTryTFunction = {
128
125
  *
129
126
  * Like {@link TryTFunction}, this function does not accept fallback strings.
130
127
  */
131
- export type RequireTFunction = <K extends TranslationKey>(key: K, ...args: K extends keyof I18nParamsMap ? keyof I18nParamsMap[K] extends never ? [] : [params: I18nParamsMap[K]] : [] | [params: Record<string, unknown>]) => string;
128
+ export type RequireTFunction = {
129
+ <K extends keyof I18nParamsMap>(key: K, params: I18nParamsMap[K]): string;
130
+ (key: TranslationKey): string;
131
+ };
132
132
  /**
133
133
  * Namespace-relative version of {@link RequireTFunction}.
134
134
  */
@@ -434,4 +434,3 @@ export interface UseI18nResult {
434
434
  /** The currently active locale code. */
435
435
  locale: string;
436
436
  }
437
- export {};
package/dist/index.d.ts CHANGED
@@ -17,4 +17,4 @@ export { defineI18nData, i18nKey } from './core/data';
17
17
  export { t, hasKey, scopedT, setGlobalInstance, getGlobalTranslations } from './core/t';
18
18
  export { initServerI18n } from './server';
19
19
  export type { I18nSharedConfig, } from './core/config';
20
- export type { NestedTranslations, I18nConfig, I18nInstance, DictionaryConfig, CacheConfig, RuntimeCacheConfig, CacheStats, CompiledConfig, I18nKeyMap, I18nParamsMap, Primitive, ParamsOf, TranslationKey, TFunction, TryTFunction, RequireTFunction, Translations, NamespacedTranslations, ScopedTFunction, UseI18nResult, KeyUsageEntry, I18nScopeMap, ValidScope, } from './core/types';
20
+ export type { NestedTranslations, I18nConfig, I18nInstance, DictionaryConfig, CacheConfig, RuntimeCacheConfig, CacheStats, CompiledConfig, I18nKeyMap, I18nParamsMap, Primitive, ParamsOf, TranslationKey, TFunction, TryTFunction, RequireTFunction, Translations, NamespacedTranslations, ScopedTFunction, UseI18nResult, KeyUsageEntry, I18nScopeMap, I18nNestedKeys, ValidScope, DotPath, } from './core/types';
@@ -52,7 +52,7 @@ export interface I18nDevPluginOptions {
52
52
  assetsDir?: string;
53
53
  /** Default locale for type generation. Required for dev-time autocomplete. */
54
54
  defaultLocale?: string;
55
- /** Path to write generated types. Defaults to `src/i18n-types.d.ts`. */
55
+ /** Path to write generated types. Defaults to `.i18n/i18n.d.ts`. */
56
56
  typesOutPath?: string;
57
57
  }
58
58
  export declare function i18nDevPlugin(config: I18nDevPluginConfig, options?: I18nDevPluginOptions): Plugin;