vite-bundled-i18n 0.3.2 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -1
- package/dist/cli/commands.d.ts +5 -0
- package/dist/cli/index.js +9 -5
- package/dist/cli/index.js.map +1 -1
- package/dist/{compiler-76bzcfdD.js → compiler-CMOyCfBe.js} +40 -10
- package/dist/compiler-CMOyCfBe.js.map +1 -0
- package/dist/core/config.d.ts +23 -0
- package/dist/core/services/key-tracker.d.ts +18 -1
- package/dist/core/types.d.ts +30 -0
- package/dist/{data-BQSxm6Hf.js → data-Yv_f3OCA.js} +53 -14
- package/dist/data-Yv_f3OCA.js.map +1 -0
- package/dist/devtools/panels/footprint.d.ts +1 -1
- package/dist/extractor/bundle-generator.d.ts +7 -0
- package/dist/extractor/compiler.d.ts +7 -0
- package/dist/extractor/scope-bundles.d.ts +18 -1
- package/dist/index.js +3 -3
- package/dist/{mountDevtools-C42c9yW2.js → mountDevtools-CtiMC5PM.js} +30 -8
- package/dist/mountDevtools-CtiMC5PM.js.map +1 -0
- package/dist/plugin.js +88 -8
- package/dist/plugin.js.map +1 -1
- package/dist/react.js +2 -1
- package/dist/react.js.map +1 -1
- package/dist/{server-q6lgW4Dd.js → server-C0yDN0XT.js} +2 -2
- package/dist/{server-q6lgW4Dd.js.map → server-C0yDN0XT.js.map} +1 -1
- package/dist/server.js +2 -2
- package/dist/vanilla.js +7 -4
- package/dist/vanilla.js.map +1 -1
- package/dist/vue.js +3 -2
- package/dist/vue.js.map +1 -1
- package/package.json +1 -1
- package/dist/compiler-76bzcfdD.js.map +0 -1
- package/dist/data-BQSxm6Hf.js.map +0 -1
- package/dist/mountDevtools-C42c9yW2.js.map +0 -1
package/README.md
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
# vite-bundled-i18n
|
|
1
|
+
npm # vite-bundled-i18n
|
|
2
2
|
|
|
3
3
|
Make translations behave like code: split, scoped, and bundled per route.
|
|
4
4
|
|
|
@@ -31,6 +31,7 @@ Layout.tsx ──→ Dictionary rules ──→ __i18n/en/_dict/glob
|
|
|
31
31
|
## Features
|
|
32
32
|
|
|
33
33
|
- **Scope bundles** — each route loads only its own translations, one HTTP request
|
|
34
|
+
- **Cross-namespace packing** (opt-in) — inline a route's cross-namespace keys (tree-shaken) into its scope bundle, so 1–3 foreign keys don't force a whole dictionary to load globally
|
|
34
35
|
- **Dictionary ownership** — named dictionaries claim keys by pattern (`include`/`exclude`/`priority`)
|
|
35
36
|
- **Progressive autocomplete** — generated types let the IDE suggest one key segment at a time
|
|
36
37
|
- **Placeholder validation** — `t('cart.total', { amount: 9.99 })` is type-checked against `{{amount}}` in the JSON
|
|
@@ -231,6 +232,8 @@ Traditional i18n ships every translation key to every page. `vite-bundled-i18n`
|
|
|
231
232
|
|
|
232
233
|
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
|
|
|
235
|
+
5. **Cross-namespace packing** (opt-in via `bundling.crossNamespacePacking: true`) — when a route references a handful of keys from a foreign namespace (e.g. `giftcards.show` uses `vendors.compact.name` once), those keys are tree-shaken and inlined into the scope bundle. One HTTP request covers everything the route needs. Keys already owned by a dictionary are skipped so the global layer isn't duplicated. Dev middleware mirrors the behavior by serving cross-namespace extras alongside each scope request, so dev and production resolve keys identically. See [API docs](./docs/api.md#bundlingcrossnamespacepacking) for the emitted shape.
|
|
236
|
+
|
|
234
237
|
### What you get
|
|
235
238
|
|
|
236
239
|
```
|
package/dist/cli/commands.d.ts
CHANGED
|
@@ -21,6 +21,11 @@ export interface CliConfig {
|
|
|
21
21
|
dictionaries?: Record<string, DictionaryConfig>;
|
|
22
22
|
/** Additional module specifiers that export `useI18n`. */
|
|
23
23
|
hookSources?: string[];
|
|
24
|
+
/**
|
|
25
|
+
* Inline cross-namespace keys (tree-shaken) into each scope bundle.
|
|
26
|
+
* See `I18nSharedConfig.bundling.crossNamespacePacking`.
|
|
27
|
+
*/
|
|
28
|
+
crossNamespacePacking?: boolean;
|
|
24
29
|
}
|
|
25
30
|
/**
|
|
26
31
|
* Run the walker and print a summary table to stdout.
|
package/dist/cli/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { a as generateReports, l as generateBundles, n as walkAll, r as flattenLocaleKeys, s as writeTypes, t as compileAll } from "../compiler-
|
|
2
|
+
import { a as generateReports, l as generateBundles, n as walkAll, r as flattenLocaleKeys, s as writeTypes, t as compileAll } from "../compiler-CMOyCfBe.js";
|
|
3
3
|
import fs from "node:fs";
|
|
4
4
|
import path from "node:path";
|
|
5
5
|
//#region src/cli/commands.ts
|
|
@@ -85,7 +85,8 @@ function generate(config) {
|
|
|
85
85
|
const bundles = generateBundles(analysis, {
|
|
86
86
|
localesDir,
|
|
87
87
|
locales: config.locales,
|
|
88
|
-
outDir
|
|
88
|
+
outDir,
|
|
89
|
+
crossNamespacePacking: config.crossNamespacePacking
|
|
89
90
|
});
|
|
90
91
|
writeTypes(localesDir, config.defaultLocale, typesOutPath, collectScopeNames(analysis));
|
|
91
92
|
console.log(`Generated ${bundles.length} bundle(s):`);
|
|
@@ -118,7 +119,8 @@ function compile(config) {
|
|
|
118
119
|
locales: config.locales,
|
|
119
120
|
defaultLocale: config.defaultLocale,
|
|
120
121
|
outDir: compiledOutDir,
|
|
121
|
-
dictionaries: config.dictionaries
|
|
122
|
+
dictionaries: config.dictionaries,
|
|
123
|
+
crossNamespacePacking: config.crossNamespacePacking
|
|
122
124
|
});
|
|
123
125
|
const total = analysis.routes.length * config.locales.length + (config.dictionaries && Object.keys(config.dictionaries).length > 0 ? config.locales.length : 0) + 1;
|
|
124
126
|
console.log(`Compiled ${total} module(s) to ${compiledOutDir}`);
|
|
@@ -148,7 +150,8 @@ function build(config) {
|
|
|
148
150
|
const bundles = generateBundles(analysis, {
|
|
149
151
|
localesDir,
|
|
150
152
|
locales: config.locales,
|
|
151
|
-
outDir
|
|
153
|
+
outDir,
|
|
154
|
+
crossNamespacePacking: config.crossNamespacePacking
|
|
152
155
|
});
|
|
153
156
|
writeTypes(localesDir, config.defaultLocale, typesOutPath, collectScopeNames(analysis));
|
|
154
157
|
console.log(`\nGenerated ${bundles.length} bundle(s)`);
|
|
@@ -159,7 +162,8 @@ function build(config) {
|
|
|
159
162
|
locales: config.locales,
|
|
160
163
|
defaultLocale: config.defaultLocale,
|
|
161
164
|
outDir: compiledOutDir,
|
|
162
|
-
dictionaries: config.dictionaries
|
|
165
|
+
dictionaries: config.dictionaries,
|
|
166
|
+
crossNamespacePacking: config.crossNamespacePacking
|
|
163
167
|
});
|
|
164
168
|
console.log(`Compiled modules written to ${compiledOutDir}`);
|
|
165
169
|
generateReports(analysis, localesDir, config.defaultLocale, outDir, config.dictionaries);
|
package/dist/cli/index.js.map
CHANGED
|
@@ -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 /** Additional module specifiers that export `useI18n`. */\n hookSources?: string[];\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 hookSources: config.hookSources,\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\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,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 /** Additional module specifiers that export `useI18n`. */\n hookSources?: string[];\n /**\n * Inline cross-namespace keys (tree-shaken) into each scope bundle.\n * See `I18nSharedConfig.bundling.crossNamespacePacking`.\n */\n crossNamespacePacking?: boolean;\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 hookSources: config.hookSources,\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 crossNamespacePacking: config.crossNamespacePacking,\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 crossNamespacePacking: config.crossNamespacePacking,\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 crossNamespacePacking: config.crossNamespacePacking,\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 crossNamespacePacking: config.crossNamespacePacking,\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":";;;;;AAsCA,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;EACA,aAAa,OAAO;EACrB,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,GA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
|
64
64
|
const dotIndex = source.indexOf(".");
|
|
65
65
|
return dotIndex === -1 ? void 0 : source.slice(0, dotIndex);
|
|
66
66
|
}
|
|
67
|
-
function
|
|
67
|
+
function getOrCreate(map, key) {
|
|
68
|
+
let set = map.get(key);
|
|
69
|
+
if (!set) {
|
|
70
|
+
set = /* @__PURE__ */ new Set();
|
|
71
|
+
map.set(key, set);
|
|
72
|
+
}
|
|
73
|
+
return set;
|
|
74
|
+
}
|
|
75
|
+
function buildScopePlans(analysis, availableKeys, options = {}) {
|
|
76
|
+
const { crossNamespacePacking = false } = options;
|
|
68
77
|
const scopePlans = /* @__PURE__ */ new Map();
|
|
69
78
|
const allAvailableKeys = [...availableKeys];
|
|
70
79
|
for (const route of analysis.routes) for (const scope of route.scopes) {
|
|
@@ -75,19 +84,24 @@ function buildScopePlans(analysis, availableKeys) {
|
|
|
75
84
|
scope,
|
|
76
85
|
namespace,
|
|
77
86
|
keys: /* @__PURE__ */ new Set(),
|
|
87
|
+
extras: /* @__PURE__ */ new Map(),
|
|
78
88
|
routeIds: /* @__PURE__ */ new Set()
|
|
79
89
|
};
|
|
80
90
|
scopePlans.set(scope, plan);
|
|
81
91
|
}
|
|
82
92
|
plan.routeIds.add(route.routeId);
|
|
83
93
|
for (const key of route.keys) {
|
|
84
|
-
|
|
94
|
+
const ns = keyNamespace(key);
|
|
95
|
+
if (!ns) continue;
|
|
96
|
+
const isPrimary = ns === namespace;
|
|
97
|
+
if (!isPrimary && !crossNamespacePacking) continue;
|
|
98
|
+
const bucket = isPrimary ? plan.keys : getOrCreate(plan.extras, ns);
|
|
85
99
|
if (!key.dynamic) {
|
|
86
|
-
|
|
100
|
+
bucket.add(key.key);
|
|
87
101
|
continue;
|
|
88
102
|
}
|
|
89
103
|
if (!key.staticPrefix) continue;
|
|
90
|
-
for (const availableKey of allAvailableKeys) if (availableKey.startsWith(key.staticPrefix))
|
|
104
|
+
for (const availableKey of allAvailableKeys) if (availableKey.startsWith(key.staticPrefix)) bucket.add(availableKey);
|
|
91
105
|
}
|
|
92
106
|
}
|
|
93
107
|
return [...scopePlans.values()].sort((a, b) => a.scope.localeCompare(b.scope));
|
|
@@ -161,14 +175,14 @@ function readNamespaceFile(localesDir, locale, namespace) {
|
|
|
161
175
|
* Generate tree-shaken per-route translation bundles from project analysis.
|
|
162
176
|
*/
|
|
163
177
|
function generateBundles(analysis, options) {
|
|
164
|
-
const { localesDir, locales, outDir, dictionaries } = options;
|
|
178
|
+
const { localesDir, locales, outDir, dictionaries, crossNamespacePacking } = options;
|
|
165
179
|
const bundles = [];
|
|
166
180
|
const availableKeys = /* @__PURE__ */ new Set();
|
|
167
181
|
for (const route of analysis.routes) for (const key of route.keys) if (!key.dynamic) availableKeys.add(key.key);
|
|
168
182
|
const ownership = resolveDictionaryOwnership(availableKeys, dictionaries);
|
|
169
183
|
const hasNamedDictionaries = ownership.rules.length > 0;
|
|
170
184
|
const sharedNsSet = hasNamedDictionaries ? /* @__PURE__ */ new Set() : new Set(analysis.sharedNamespaces);
|
|
171
|
-
for (const plan of buildScopePlans(analysis, availableKeys)) for (const locale of locales) {
|
|
185
|
+
for (const plan of buildScopePlans(analysis, availableKeys, { crossNamespacePacking })) for (const locale of locales) {
|
|
172
186
|
const bundleData = {};
|
|
173
187
|
let totalKeyCount = 0;
|
|
174
188
|
let totalPrunedCount = 0;
|
|
@@ -185,6 +199,18 @@ function generateBundles(analysis, options) {
|
|
|
185
199
|
totalKeyCount += keptCount;
|
|
186
200
|
totalPrunedCount += availableCount - keptCount;
|
|
187
201
|
}
|
|
202
|
+
if (crossNamespacePacking) for (const [extraNs, extraKeys] of plan.extras) {
|
|
203
|
+
const retained = [...extraKeys].filter((k) => !ownership.keyOwner.has(k));
|
|
204
|
+
if (retained.length === 0) continue;
|
|
205
|
+
if (!hasNamedDictionaries && sharedNsSet.has(extraNs)) continue;
|
|
206
|
+
const extraSubKeys = retained.filter((key) => key.startsWith(`${extraNs}.`)).map((key) => key.slice(extraNs.length + 1));
|
|
207
|
+
if (extraSubKeys.length === 0) continue;
|
|
208
|
+
const extraFullData = readNamespaceFile(localesDir, locale, extraNs);
|
|
209
|
+
if (!extraFullData) continue;
|
|
210
|
+
const pruned = pruneNamespace(extraFullData, [...new Set(extraSubKeys)]);
|
|
211
|
+
bundleData[extraNs] = pruned;
|
|
212
|
+
totalKeyCount += flattenKeys(pruned).length;
|
|
213
|
+
}
|
|
188
214
|
const filePath = path.join(outDir, locale, `${plan.scope}.json`);
|
|
189
215
|
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
|
190
216
|
fs.writeFileSync(filePath, JSON.stringify(bundleData, null, 2));
|
|
@@ -1339,13 +1365,17 @@ function generateManifest(scopeIds, locales, dictionaryNames) {
|
|
|
1339
1365
|
* Orchestrates the full compilation of pre-compiled i18n modules.
|
|
1340
1366
|
*/
|
|
1341
1367
|
function compileAll(analysis, options) {
|
|
1342
|
-
const { localesDir, locales, defaultLocale, outDir, dictionaries } = options;
|
|
1368
|
+
const { localesDir, locales, defaultLocale, outDir, dictionaries, crossNamespacePacking } = options;
|
|
1343
1369
|
fs.mkdirSync(outDir, { recursive: true });
|
|
1344
1370
|
const defaultFullMap = buildFullLocaleMap(localesDir, defaultLocale);
|
|
1345
1371
|
const ownership = resolveDictionaryOwnership(defaultFullMap.keys(), dictionaries);
|
|
1346
|
-
const scopePlans = buildScopePlans(analysis, defaultFullMap.keys());
|
|
1372
|
+
const scopePlans = buildScopePlans(analysis, defaultFullMap.keys(), { crossNamespacePacking });
|
|
1347
1373
|
for (const plan of scopePlans) {
|
|
1348
1374
|
const usedKeys = new Set([...plan.keys].filter((key) => !ownership.keyOwner.has(key)));
|
|
1375
|
+
if (crossNamespacePacking) for (const extraKeys of plan.extras.values()) for (const key of extraKeys) {
|
|
1376
|
+
if (ownership.keyOwner.has(key)) continue;
|
|
1377
|
+
usedKeys.add(key);
|
|
1378
|
+
}
|
|
1349
1379
|
for (const locale of locales) {
|
|
1350
1380
|
const localeDir = path.join(outDir, locale);
|
|
1351
1381
|
fs.mkdirSync(localeDir, { recursive: true });
|
|
@@ -1367,6 +1397,6 @@ function compileAll(analysis, options) {
|
|
|
1367
1397
|
fs.writeFileSync(path.join(outDir, "manifest.js"), manifestSource);
|
|
1368
1398
|
}
|
|
1369
1399
|
//#endregion
|
|
1370
|
-
export { generateReports as a, flattenKeys as c,
|
|
1400
|
+
export { generateReports as a, flattenKeys as c, buildScopePlans as d, inferScopeNamespace as f, resolveDictionaryOwnership as h, generateDictionaryOwnershipReport as i, generateBundles as l, normalizeDictionaries as m, walkAll as n, generateTypes as o, keyMatchesPattern as p, flattenLocaleKeys as r, writeTypes as s, compileAll as t, pruneNamespace as u };
|
|
1371
1401
|
|
|
1372
|
-
//# sourceMappingURL=compiler-
|
|
1402
|
+
//# sourceMappingURL=compiler-CMOyCfBe.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"compiler-CMOyCfBe.js","names":[],"sources":["../src/extractor/dictionary-ownership.ts","../src/extractor/scope-bundles.ts","../src/extractor/bundle-generator.ts","../src/extractor/type-generator.ts","../src/extractor/reports.ts","../src/extractor/ast-utils.ts","../src/extractor/patterns.ts","../src/extractor/extract.ts","../src/extractor/walker.ts","../src/extractor/compiler.ts"],"sourcesContent":["import type { DictionaryConfig } from '../core/types';\n\nexport interface NormalizedDictionaryRule {\n name: string;\n include: string[];\n exclude: string[];\n priority: number;\n pinned: boolean;\n order: number;\n}\n\nexport interface DictionaryOwnership {\n rules: NormalizedDictionaryRule[];\n keyOwner: Map<string, string>;\n dictionaryKeys: Map<string, Set<string>>;\n dictionaryNamespaces: Set<string>;\n}\n\nexport function getDictionaryIncludePatterns(dict: DictionaryConfig): string[] {\n const fromKeys = (dict.keys ?? []).map((key) => `${key}.*`);\n return [...fromKeys, ...(dict.include ?? [])];\n}\n\nexport function normalizeDictionaries(\n dictionaries?: Record<string, DictionaryConfig>,\n): NormalizedDictionaryRule[] {\n if (!dictionaries) return [];\n\n return Object.entries(dictionaries)\n .map(([name, dict], order) => ({\n name,\n include: getDictionaryIncludePatterns(dict),\n exclude: dict.exclude ?? [],\n priority: dict.priority ?? 0,\n pinned: dict.pinned ?? false,\n order,\n }))\n .filter((rule) => rule.include.length > 0)\n .sort((a, b) => b.priority - a.priority || a.order - b.order);\n}\n\nexport function keyMatchesPattern(key: string, pattern: string): boolean {\n if (pattern.includes('.')) {\n if (pattern.endsWith('*')) {\n const prefix = pattern.slice(0, -1);\n return key.startsWith(prefix);\n }\n return key === pattern;\n }\n\n const namespace = key.split('.')[0];\n if (pattern.endsWith('*')) {\n return namespace.startsWith(pattern.slice(0, -1));\n }\n return namespace === pattern;\n}\n\nexport function resolveDictionaryOwnership(\n availableKeys: Iterable<string>,\n dictionaries?: Record<string, DictionaryConfig>,\n): DictionaryOwnership {\n const rules = normalizeDictionaries(dictionaries);\n const keyOwner = new Map<string, string>();\n const dictionaryKeys = new Map<string, Set<string>>();\n const dictionaryNamespaces = new Set<string>();\n\n for (const rule of rules) {\n dictionaryKeys.set(rule.name, new Set());\n }\n\n for (const key of availableKeys) {\n for (const rule of rules) {\n const included = rule.include.some((pattern) => keyMatchesPattern(key, pattern));\n const excluded = rule.exclude.some((pattern) => keyMatchesPattern(key, pattern));\n if (included && !excluded) {\n keyOwner.set(key, rule.name);\n dictionaryKeys.get(rule.name)!.add(key);\n const namespace = key.split('.')[0];\n if (namespace) {\n dictionaryNamespaces.add(namespace);\n }\n break;\n }\n }\n }\n\n return {\n rules,\n keyOwner,\n dictionaryKeys,\n dictionaryNamespaces,\n };\n}\n","import type { ProjectAnalysis } from './walker-types';\nimport type { ExtractedKey } from './types';\n\nexport interface ScopeBundlePlan {\n scope: string;\n namespace: string;\n /** Keys from the scope's own (primary) namespace. */\n keys: Set<string>;\n /**\n * Cross-namespace keys referenced on this route, keyed by namespace.\n *\n * Populated only when `buildScopePlans` is called with\n * `crossNamespacePacking: true`. Empty otherwise.\n */\n extras: Map<string, Set<string>>;\n routeIds: Set<string>;\n}\n\nexport interface BuildScopePlansOptions {\n /**\n * Collect cross-namespace keys into {@link ScopeBundlePlan.extras} so the\n * emit phase can inline them into each scope bundle.\n *\n * @default false\n */\n crossNamespacePacking?: boolean;\n}\n\nexport function inferScopeNamespace(scope: string): string {\n return scope.includes('.') ? scope.slice(0, scope.indexOf('.')) : scope;\n}\n\nfunction keyNamespace(key: ExtractedKey): string | undefined {\n const source = key.dynamic && key.staticPrefix ? key.staticPrefix : key.key;\n if (!source) return undefined;\n const dotIndex = source.indexOf('.');\n return dotIndex === -1 ? undefined : source.slice(0, dotIndex);\n}\n\nfunction getOrCreate<K, V>(map: Map<K, Set<V>>, key: K): Set<V> {\n let set = map.get(key);\n if (!set) {\n set = new Set<V>();\n map.set(key, set);\n }\n return set;\n}\n\nexport function buildScopePlans(\n analysis: ProjectAnalysis,\n availableKeys: Iterable<string>,\n options: BuildScopePlansOptions = {},\n): ScopeBundlePlan[] {\n const { crossNamespacePacking = false } = options;\n const scopePlans = new Map<string, ScopeBundlePlan>();\n const allAvailableKeys = [...availableKeys];\n\n for (const route of analysis.routes) {\n for (const scope of route.scopes) {\n const namespace = inferScopeNamespace(scope);\n let plan = scopePlans.get(scope);\n if (!plan) {\n plan = {\n scope,\n namespace,\n keys: new Set<string>(),\n extras: new Map<string, Set<string>>(),\n routeIds: new Set<string>(),\n };\n scopePlans.set(scope, plan);\n }\n\n plan.routeIds.add(route.routeId);\n\n for (const key of route.keys) {\n const ns = keyNamespace(key);\n if (!ns) continue;\n\n const isPrimary = ns === namespace;\n if (!isPrimary && !crossNamespacePacking) continue;\n\n const bucket = isPrimary ? plan.keys : getOrCreate(plan.extras, ns);\n\n if (!key.dynamic) {\n bucket.add(key.key);\n continue;\n }\n\n if (!key.staticPrefix) continue;\n for (const availableKey of allAvailableKeys) {\n if (availableKey.startsWith(key.staticPrefix)) {\n bucket.add(availableKey);\n }\n }\n }\n }\n }\n\n return [...scopePlans.values()].sort((a, b) => a.scope.localeCompare(b.scope));\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport type { ProjectAnalysis } from './walker-types';\nimport type { DictionaryConfig } from '../core/types';\nimport { resolveDictionaryOwnership, keyMatchesPattern } from './dictionary-ownership';\nimport { buildScopePlans } from './scope-bundles';\n\n/**\n * Options for the bundle generator.\n */\nexport interface BundleGeneratorOptions {\n /** Path to locales directory (absolute). */\n localesDir: string;\n /** Locales to generate bundles for. */\n locales: string[];\n /** Output directory for generated bundles (absolute). */\n outDir: string;\n /** Optional named dictionary configurations. */\n dictionaries?: Record<string, DictionaryConfig>;\n /**\n * Inline cross-namespace keys (tree-shaken) into each scope bundle.\n * See `I18nSharedConfig.bundling.crossNamespacePacking`.\n *\n * @default false\n */\n crossNamespacePacking?: boolean;\n}\n\n/**\n * Metadata about a generated bundle file.\n */\nexport interface GeneratedBundle {\n /** The route ID or dictionary name this bundle is for. */\n name: string;\n /** The locale this bundle is for. */\n locale: string;\n /** The output file path. */\n filePath: string;\n /** Number of keys in this bundle. */\n keyCount: number;\n /** Number of keys pruned (available but not used). */\n prunedCount: number;\n}\n\n/**\n * Flatten a nested object into dot-separated key paths.\n */\nexport function flattenKeys(data: object, prefix?: string): string[] {\n const keys: string[] = [];\n for (const [k, v] of Object.entries(data)) {\n const fullKey = prefix ? `${prefix}.${k}` : k;\n if (v !== null && typeof v === 'object' && !Array.isArray(v)) {\n keys.push(...flattenKeys(v as object, fullKey));\n } else {\n keys.push(fullKey);\n }\n }\n return keys;\n}\n\n/**\n * Set a value at a dot-separated path in a nested object, creating\n * intermediate objects as needed.\n */\nfunction setNestedValue(obj: Record<string, unknown>, keyPath: string, value: unknown): void {\n const parts = keyPath.split('.');\n let current: Record<string, unknown> = obj;\n for (let i = 0; i < parts.length - 1; i++) {\n const part = parts[i];\n if (!(part in current) || typeof current[part] !== 'object' || current[part] === null) {\n current[part] = {};\n }\n current = current[part] as Record<string, unknown>;\n }\n current[parts[parts.length - 1]] = value;\n}\n\n/**\n * Get a value at a dot-separated path in a nested object.\n * Returns undefined if the path does not exist.\n */\nfunction getNestedValue(obj: Record<string, unknown>, keyPath: string): unknown {\n const parts = keyPath.split('.');\n let current: unknown = obj;\n for (const part of parts) {\n if (current === null || typeof current !== 'object') return undefined;\n current = (current as Record<string, unknown>)[part];\n }\n return current;\n}\n\n/**\n * Prune a namespace JSON object to only include the specified key paths.\n *\n * For keys that point to a subtree (object), the entire subtree is included.\n * This supports dynamic keys with a static prefix — the full subtree under\n * the prefix is preserved.\n */\nexport function pruneNamespace(\n fullData: object,\n usedKeyPaths: string[],\n): object {\n const result: Record<string, unknown> = {};\n for (const keyPath of usedKeyPaths) {\n const value = getNestedValue(fullData as Record<string, unknown>, keyPath);\n if (value !== undefined) {\n setNestedValue(result, keyPath, value);\n }\n }\n return result;\n}\n\n/**\n * Read a namespace JSON file for a given locale.\n */\nfunction readNamespaceFile(\n localesDir: string,\n locale: string,\n namespace: string,\n): Record<string, unknown> | null {\n const filePath = path.join(localesDir, locale, `${namespace}.json`);\n if (!fs.existsSync(filePath)) return null;\n const content = fs.readFileSync(filePath, 'utf-8');\n return JSON.parse(content) as Record<string, unknown>;\n}\n\n/**\n * Generate tree-shaken per-route translation bundles from project analysis.\n */\nexport function generateBundles(\n analysis: ProjectAnalysis,\n options: BundleGeneratorOptions,\n): GeneratedBundle[] {\n const { localesDir, locales, outDir, dictionaries, crossNamespacePacking } = options;\n const bundles: GeneratedBundle[] = [];\n\n const availableKeys = new Set<string>();\n for (const route of analysis.routes) {\n for (const key of route.keys) {\n if (!key.dynamic) {\n availableKeys.add(key.key);\n }\n }\n }\n const ownership = resolveDictionaryOwnership(availableKeys, dictionaries);\n const hasNamedDictionaries = ownership.rules.length > 0;\n const sharedNsSet = hasNamedDictionaries ? new Set<string>() : new Set(analysis.sharedNamespaces);\n\n // Generate per-scope bundles keyed by scope string, matching runtime URLs.\n for (const plan of buildScopePlans(analysis, availableKeys, { crossNamespacePacking })) {\n for (const locale of locales) {\n const bundleData: Record<string, unknown> = {};\n let totalKeyCount = 0;\n let totalPrunedCount = 0;\n const scopeKeys = [...plan.keys].filter((key) => {\n if (ownership.keyOwner.has(key)) return false;\n return !(!hasNamedDictionaries && sharedNsSet.has(plan.namespace));\n });\n const subKeys = scopeKeys\n .filter((key) => key.startsWith(`${plan.namespace}.`))\n .map((key) => key.slice(plan.namespace.length + 1));\n const fullData = readNamespaceFile(localesDir, locale, plan.namespace);\n if (fullData && subKeys.length > 0) {\n const pruned = pruneNamespace(fullData, [...new Set(subKeys)]);\n bundleData[plan.namespace] = pruned;\n\n const availableCount = flattenKeys(fullData).length;\n const keptCount = flattenKeys(pruned).length;\n totalKeyCount += keptCount;\n totalPrunedCount += availableCount - keptCount;\n }\n\n // Cross-namespace extras: tree-shake per foreign namespace and inline.\n if (crossNamespacePacking) {\n for (const [extraNs, extraKeys] of plan.extras) {\n // Skip namespaces fully covered by a dictionary — don't duplicate\n // the always-available layer into every scope bundle.\n const retained = [...extraKeys].filter((k) => !ownership.keyOwner.has(k));\n if (retained.length === 0) continue;\n if (!hasNamedDictionaries && sharedNsSet.has(extraNs)) continue;\n\n const extraSubKeys = retained\n .filter((key) => key.startsWith(`${extraNs}.`))\n .map((key) => key.slice(extraNs.length + 1));\n if (extraSubKeys.length === 0) continue;\n\n const extraFullData = readNamespaceFile(localesDir, locale, extraNs);\n if (!extraFullData) continue;\n\n const pruned = pruneNamespace(extraFullData, [...new Set(extraSubKeys)]);\n bundleData[extraNs] = pruned;\n totalKeyCount += flattenKeys(pruned).length;\n }\n }\n\n const filePath = path.join(outDir, locale, `${plan.scope}.json`);\n fs.mkdirSync(path.dirname(filePath), { recursive: true });\n fs.writeFileSync(filePath, JSON.stringify(bundleData, null, 2));\n\n bundles.push({\n name: plan.scope,\n locale,\n filePath,\n keyCount: totalKeyCount,\n prunedCount: totalPrunedCount,\n });\n }\n }\n\n if (hasNamedDictionaries) {\n for (const rule of ownership.rules) {\n // Dictionary bundles include ALL keys from matching namespaces — no tree-shaking.\n // Dictionaries are the \"preload everything I need\" layer.\n // Only scope bundles are pruned to extracted keys.\n const matchedNamespaces = new Set<string>();\n\n // Find all namespaces that match this dictionary's include patterns (minus exclude)\n const localeDir = path.join(localesDir, locales[0]);\n let nsFiles: string[] = [];\n try {\n nsFiles = fs.readdirSync(localeDir).filter(f => f.endsWith('.json'));\n } catch { /* dir may not exist */ }\n\n for (const file of nsFiles) {\n const ns = file.slice(0, -'.json'.length);\n // Check if any key in this namespace would match the include patterns\n if (rule.include.some(pattern => keyMatchesPattern(`${ns}.x`, pattern) || keyMatchesPattern(`${ns}.`, pattern) || pattern === `${ns}.*` || pattern.startsWith(`${ns}.`) || (pattern.endsWith('*') && ns.startsWith(pattern.slice(0, -1))))) {\n matchedNamespaces.add(ns);\n }\n }\n\n // Also check from the ownership map (covers exact key patterns)\n const ownedKeys = ownership.dictionaryKeys.get(rule.name) ?? new Set<string>();\n for (const key of ownedKeys) {\n const ns = key.split('.')[0];\n if (ns) matchedNamespaces.add(ns);\n }\n\n for (const locale of locales) {\n const bundleData: Record<string, unknown> = {};\n let totalKeyCount = 0;\n\n for (const ns of matchedNamespaces) {\n const fullData = readNamespaceFile(localesDir, locale, ns);\n if (!fullData) continue;\n\n // Include ALL keys from the namespace that match include and don't match exclude\n const allKeys = flattenKeys(fullData);\n const includedKeys = allKeys.filter(subKey => {\n const fullKey = `${ns}.${subKey}`;\n const included = rule.include.some(pattern => keyMatchesPattern(fullKey, pattern));\n const excluded = rule.exclude.length > 0 &&\n rule.exclude.some(pattern => keyMatchesPattern(fullKey, pattern));\n return included && !excluded;\n });\n\n if (includedKeys.length === 0) continue;\n\n const pruned = pruneNamespace(fullData, includedKeys);\n bundleData[ns] = pruned;\n totalKeyCount += flattenKeys(pruned).length;\n }\n\n const filePath = path.join(outDir, locale, '_dict', `${rule.name}.json`);\n fs.mkdirSync(path.dirname(filePath), { recursive: true });\n fs.writeFileSync(filePath, JSON.stringify(bundleData, null, 2));\n\n bundles.push({\n name: `_dict/${rule.name}`,\n locale,\n filePath,\n keyCount: totalKeyCount,\n prunedCount: 0,\n });\n }\n }\n\n return bundles;\n }\n\n // Legacy shared-namespace dictionary bundles\n for (const sharedNs of analysis.sharedNamespaces) {\n // Collect ALL keys used across ALL routes for this namespace\n const allSubKeys = new Set<string>();\n for (const route of analysis.routes) {\n for (const key of route.keys) {\n const dotIndex = key.key.indexOf('.');\n if (dotIndex === -1) continue;\n const ns = key.key.substring(0, dotIndex);\n if (ns === sharedNs) {\n const subKey = key.dynamic && key.staticPrefix\n ? key.staticPrefix.substring(dotIndex + 1)\n : key.key.substring(dotIndex + 1);\n allSubKeys.add(subKey);\n }\n }\n }\n\n for (const locale of locales) {\n const fullData = readNamespaceFile(localesDir, locale, sharedNs);\n if (!fullData) continue;\n\n const uniqueSubKeys = [...allSubKeys];\n const pruned = pruneNamespace(fullData, uniqueSubKeys);\n\n const filePath = path.join(outDir, locale, '_dict', `${sharedNs}.json`);\n fs.mkdirSync(path.dirname(filePath), { recursive: true });\n fs.writeFileSync(filePath, JSON.stringify(pruned, null, 2));\n\n const availableCount = flattenKeys(fullData).length;\n const keptCount = flattenKeys(pruned).length;\n\n bundles.push({\n name: `_dict/${sharedNs}`,\n locale,\n filePath,\n keyCount: keptCount,\n prunedCount: availableCount - keptCount,\n });\n }\n }\n\n return bundles;\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\n\nconst PLACEHOLDER_PATTERN = /\\{\\{\\s*(\\w+)\\s*\\}\\}/g;\n\n/**\n * Recursively flattens a nested object to dot-separated leaf key paths.\n *\n * @example\n * flattenToKeyPaths({ show: { title: 'X' }, ok: 'Z' })\n * // → ['show.title', 'ok']\n */\nexport function flattenToKeyPaths(data: object, prefix?: string): string[] {\n const result: string[] = [];\n\n for (const [key, value] of Object.entries(data)) {\n const fullKey = prefix !== undefined ? `${prefix}.${key}` : key;\n if (value !== null && typeof value === 'object' && !Array.isArray(value)) {\n result.push(...flattenToKeyPaths(value as object, fullKey));\n } else {\n result.push(fullKey);\n }\n }\n\n return result;\n}\n\n/**\n * Recursively flattens a nested object to a map of dot-separated leaf key paths\n * to their string values.\n */\nexport function flattenToLeafValues(\n data: object,\n prefix?: string,\n): Map<string, string> {\n const result = new Map<string, string>();\n\n for (const [key, value] of Object.entries(data)) {\n const fullKey = prefix !== undefined ? `${prefix}.${key}` : key;\n if (typeof value === 'string') {\n result.set(fullKey, value);\n } else if (value !== null && typeof value === 'object' && !Array.isArray(value)) {\n for (const [nestedKey, nestedValue] of flattenToLeafValues(value as object, fullKey)) {\n result.set(nestedKey, nestedValue);\n }\n }\n }\n\n return result;\n}\n\n/**\n * Extracts placeholder names from a translation string.\n */\nexport function extractPlaceholders(text: string): string[] {\n const names = new Set<string>();\n for (const match of text.matchAll(PLACEHOLDER_PATTERN)) {\n if (match[1]) {\n names.add(match[1]);\n }\n }\n return [...names];\n}\n\n/**\n * Builds nested TypeScript interface content from flat dot-separated keys.\n * Each leaf becomes `true`, each branch becomes a nested object.\n */\nfunction buildNestedInterface(keys: string[]): string {\n // Build tree structure\n type TreeNode = { [segment: string]: TreeNode | true };\n const tree: TreeNode = {};\n\n for (const key of keys) {\n const parts = key.split('.');\n let current: TreeNode = tree;\n for (let i = 0; i < parts.length; i++) {\n const part = parts[i];\n if (i === parts.length - 1) {\n current[part] = true;\n } else {\n if (current[part] === true || current[part] === undefined) {\n current[part] = {};\n }\n current = current[part] as TreeNode;\n }\n }\n }\n\n // Serialize to TypeScript\n function serialize(node: TreeNode | true, indent: number): string {\n if (node === true) return 'true';\n const pad = ' '.repeat(indent);\n const entries = Object.entries(node).sort(([a], [b]) => a.localeCompare(b));\n const lines = entries.map(([key, value]) => {\n const serialized = serialize(value, indent + 1);\n if (serialized === 'true') {\n return `${pad}'${key}': true;`;\n }\n return `${pad}'${key}': {\\n${serialized}\\n${pad}};`;\n });\n return lines.join('\\n');\n }\n\n return serialize(tree, 2);\n}\n\n/**\n * Reads all `.json` files in `{localesDir}/{defaultLocale}/`, flattens each to\n * key paths, and returns a TypeScript declaration string that:\n *\n * 1. Augments the `vite-bundled-i18n` module to populate `I18nKeyMap` — this\n * wires autocomplete directly into `t()`, `useI18n().t`, and `hasKey()`.\n * 2. Exports `TranslationKey`, `Namespace`, and `NamespaceKeyPaths<T>` for\n * direct use in application code.\n *\n * When this file is present in the project, `t('shar...')` autocompletes to\n * `t('shared.ok')`. Without it, `t()` accepts any string.\n */\nexport function generateTypes(localesDir: string, defaultLocale: string, scopes?: string[]): string {\n const localeDir = path.join(localesDir, defaultLocale);\n\n let entries: string[];\n try {\n entries = fs.readdirSync(localeDir);\n } catch {\n entries = [];\n }\n\n const jsonFiles = entries.filter((f) => f.endsWith('.json')).sort();\n\n /** Map from namespace name → flat key paths (without namespace prefix) */\n const namespaceMap = new Map<string, string[]>();\n /** Map from fully qualified key → placeholder names */\n const paramsMap = new Map<string, string[]>();\n\n for (const file of jsonFiles) {\n const namespace = file.slice(0, -'.json'.length);\n const raw = fs.readFileSync(path.join(localeDir, file), 'utf-8');\n const data: unknown = JSON.parse(raw);\n const keyPaths =\n data !== null && typeof data === 'object' && !Array.isArray(data)\n ? flattenToKeyPaths(data as object)\n : [];\n namespaceMap.set(namespace, keyPaths);\n\n const leafValues =\n data !== null && typeof data === 'object' && !Array.isArray(data)\n ? flattenToLeafValues(data as object)\n : new Map<string, string>();\n for (const [keyPath, value] of leafValues) {\n paramsMap.set(`${namespace}.${keyPath}`, extractPlaceholders(value));\n }\n }\n\n // Collect all fully qualified keys\n const allQualifiedKeys: string[] = [];\n for (const [ns, paths] of namespaceMap) {\n for (const p of paths) {\n allQualifiedKeys.push(`${ns}.${p}`);\n }\n }\n\n // ---- I18nParamsMap (only keys with placeholders — skip empty {}) -----------\n let paramsMapEntries: string;\n const keysWithParams = allQualifiedKeys.filter(k => (paramsMap.get(k) ?? []).length > 0);\n if (keysWithParams.length === 0) {\n paramsMapEntries = ' // No parameterized keys found';\n } else {\n paramsMapEntries = keysWithParams\n .map((k) => {\n const placeholders = paramsMap.get(k)!;\n const shape = `{ ${placeholders.map((name) => `${name}: TranslationValue`).join('; ')} }`;\n return ` '${k}': ${shape};`;\n })\n .join('\\n');\n }\n\n // ---- I18nNestedKeys (progressive autocomplete) ----------------------------\n let nestedKeysBlock: string;\n if (allQualifiedKeys.length === 0) {\n nestedKeysBlock = ' interface I18nNestedKeys {}';\n } else {\n const nestedBody = buildNestedInterface(allQualifiedKeys);\n nestedKeysBlock = ` interface I18nNestedKeys {\\n${nestedBody}\\n }`;\n }\n\n // ---- I18nScopeMap ----\n let scopeMapEntries: string;\n if (!scopes || scopes.length === 0) {\n scopeMapEntries = ' // No scopes found';\n } else {\n scopeMapEntries = scopes\n .sort()\n .map((s) => ` '${s}': true;`)\n .join('\\n');\n }\n\n // Direct exports — the generated file is imported by src/core/types.ts.\n // No module augmentation. This works for both npm consumers and local dev.\n return [\n '// Auto-generated by vite-bundled-i18n — do not edit.',\n '// Regenerated on: npm run dev (auto), npm run build, npm run i18n -- generate',\n '//',\n '// Add \".i18n\" to your tsconfig include: { \"include\": [\"src\", \".i18n\"] }',\n '',\n 'type TranslationValue = string | number | boolean | bigint | null | undefined;',\n '',\n '// Direct exports — used by the package to populate types',\n `export ${nestedKeysBlock.replace(' interface ', 'interface ')}`,\n '',\n `export interface I18nParamsMap {`,\n paramsMapEntries,\n `}`,\n '',\n `export interface I18nScopeMap {`,\n scopeMapEntries,\n `}`,\n '',\n ].join('\\n');\n}\n\n/**\n * Calls {@link generateTypes} and writes the result to `outPath`.\n */\nexport function writeTypes(\n localesDir: string,\n defaultLocale: string,\n outPath: string,\n scopes?: string[],\n): void {\n const content = generateTypes(localesDir, defaultLocale, scopes);\n fs.mkdirSync(path.dirname(outPath), { recursive: true });\n fs.writeFileSync(outPath, content, 'utf-8');\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport type { ProjectAnalysis } from './walker-types';\nimport { flattenKeys } from './bundle-generator';\nimport type { DictionaryConfig } from '../core/types';\nimport {\n keyMatchesPattern,\n normalizeDictionaries,\n resolveDictionaryOwnership,\n} from './dictionary-ownership';\n\n/**\n * Read all namespace JSON files for the default locale and return a map of\n * namespace → flattened dot-path key arrays.\n */\nexport function flattenLocaleKeys(\n localesDir: string,\n defaultLocale: string,\n): Map<string, string[]> {\n const result = new Map<string, string[]>();\n const localeDir = path.join(localesDir, defaultLocale);\n\n if (!fs.existsSync(localeDir)) return result;\n\n const entries = fs.readdirSync(localeDir);\n for (const entry of entries) {\n if (!entry.endsWith('.json')) continue;\n const namespace = entry.slice(0, -5);\n const filePath = path.join(localeDir, entry);\n try {\n const data = JSON.parse(fs.readFileSync(filePath, 'utf-8')) as object;\n result.set(namespace, flattenKeys(data));\n } catch {\n // skip malformed files\n }\n }\n\n return result;\n}\n\n/**\n * Generate the manifest report: mapping of routeId → { scopes, keys, files }.\n */\nexport function generateManifest(\n analysis: ProjectAnalysis,\n): Record<string, object> {\n const manifest: Record<string, object> = {};\n\n for (const route of analysis.routes) {\n manifest[route.routeId] = {\n scopes: route.scopes,\n keys: route.keys.map((k) => k.key),\n files: route.files,\n };\n }\n\n return manifest;\n}\n\n/**\n * A single missing-key entry.\n */\nexport interface MissingKeyEntry {\n key: string;\n usedIn: string[];\n line: number;\n}\n\n/**\n * Generate the missing-keys report: keys used in code that don't exist in\n * translation files.\n */\nexport function generateMissing(\n analysis: ProjectAnalysis,\n availableKeys: Map<string, string[]>,\n): { summary?: { total: number; hint: string }; keys: MissingKeyEntry[] } {\n const missing: MissingKeyEntry[] = [];\n\n for (const key of analysis.allKeys) {\n // Skip dynamic keys — they can't be checked statically.\n if (key.dynamic) continue;\n\n const dotIndex = key.key.indexOf('.');\n if (dotIndex === -1) continue;\n\n const namespace = key.key.substring(0, dotIndex);\n const subKey = key.key.substring(dotIndex + 1);\n\n const namespacePaths = availableKeys.get(namespace);\n if (!namespacePaths || !namespacePaths.includes(subKey)) {\n // Collect all files where this key appears across routes.\n const usedIn: string[] = [];\n for (const route of analysis.routes) {\n for (const rk of route.keys) {\n if (rk.key === key.key && rk.line === key.line) {\n for (const file of route.files) {\n if (!usedIn.includes(file)) {\n usedIn.push(file);\n }\n }\n }\n }\n }\n\n missing.push({ key: key.key, usedIn, line: key.line });\n }\n }\n\n if (missing.length > 50) {\n return {\n summary: {\n total: missing.length,\n hint: 'If most keys are missing, verify localesDir structure: {locale}/{namespace}.json',\n },\n keys: missing,\n };\n }\n\n return { keys: missing };\n}\n\n/**\n * A single unused-key entry.\n */\nexport interface UnusedKeyEntry {\n key: string;\n namespace: string;\n}\n\n/**\n * Generate the unused-keys report: keys in translation files that no route\n * uses.\n */\nexport function generateUnused(\n analysis: ProjectAnalysis,\n availableKeys: Map<string, string[]>,\n): { keys: UnusedKeyEntry[] } {\n const unused: UnusedKeyEntry[] = [];\n\n // Build a set of all fully-qualified keys used across all routes.\n const usedKeys = new Set<string>(analysis.allKeys.map((k) => k.key));\n\n for (const [namespace, keyPaths] of availableKeys) {\n for (const keyPath of keyPaths) {\n const fullKey = `${namespace}.${keyPath}`;\n if (!usedKeys.has(fullKey)) {\n unused.push({ key: fullKey, namespace });\n }\n }\n }\n\n return { keys: unused };\n}\n\n/**\n * Per-route statistics entry.\n */\nexport interface RouteStats {\n routeId: string;\n usedKeys: number;\n availableKeys: number;\n prunedKeys: number;\n}\n\n/**\n * A key that is used by more than one route and whose namespace is not in a\n * dictionary, making it a candidate for extraction.\n */\nexport interface DictionaryCandidate {\n key: string;\n namespace: string;\n usedByRoutes: string[];\n routeCount: number;\n}\n\n/**\n * Per-namespace usage summary.\n */\nexport interface NamespaceUsageEntry {\n namespace: string;\n routeCount: number;\n totalRoutes: number;\n percentage: number;\n inDictionary: boolean;\n}\n\n/**\n * Full overlap analysis result.\n */\nexport interface OverlapAnalysis {\n candidates: DictionaryCandidate[];\n namespaceUsage: NamespaceUsageEntry[];\n}\n\nexport interface DictionaryOwnershipRuleReport {\n name: string;\n priority: number;\n include: string[];\n ownedKeys: string[];\n}\n\nexport interface DictionaryCollisionReport {\n key: string;\n owner: string;\n matchedDictionaries: string[];\n}\n\nexport interface DictionaryOwnershipReport {\n rules: DictionaryOwnershipRuleReport[];\n collisions: DictionaryCollisionReport[];\n unownedKeys: string[];\n}\n\n/**\n * Analyse key and namespace overlap across routes. Keys used by more than one\n * route whose namespace is NOT already a dictionary namespace are returned as\n * candidates. The namespace-level summary describes what fraction of routes\n * use each namespace.\n */\nexport function generateOverlapAnalysis(\n analysis: ProjectAnalysis,\n dictionaryNamespaces?: Set<string>,\n): OverlapAnalysis {\n const dictNs = dictionaryNamespaces ?? new Set<string>();\n const totalRoutes = analysis.routes.length;\n\n // 1. Map each fully-qualified key → set of routeIds that use it.\n const keyToRoutes = new Map<string, Set<string>>();\n for (const route of analysis.routes) {\n for (const k of route.keys) {\n if (k.dynamic) continue;\n if (!keyToRoutes.has(k.key)) {\n keyToRoutes.set(k.key, new Set());\n }\n keyToRoutes.get(k.key)!.add(route.routeId);\n }\n }\n\n // 2. Build candidates: keys used by >1 route whose namespace is not a\n // dictionary namespace.\n const candidates: DictionaryCandidate[] = [];\n for (const [key, routes] of keyToRoutes) {\n if (routes.size <= 1) continue;\n const dotIndex = key.indexOf('.');\n if (dotIndex === -1) continue;\n const namespace = key.substring(0, dotIndex);\n if (dictNs.has(namespace)) continue;\n const usedByRoutes = Array.from(routes);\n candidates.push({ key, namespace, usedByRoutes, routeCount: usedByRoutes.length });\n }\n\n // Sort for stable output: descending routeCount then alphabetical key.\n candidates.sort((a, b) => b.routeCount - a.routeCount || a.key.localeCompare(b.key));\n\n // 3. Namespace-level analysis: for each namespace, count distinct routes.\n const namespaceToRoutes = new Map<string, Set<string>>();\n for (const route of analysis.routes) {\n for (const k of route.keys) {\n if (k.dynamic) continue;\n const dotIndex = k.key.indexOf('.');\n if (dotIndex === -1) continue;\n const namespace = k.key.substring(0, dotIndex);\n if (!namespaceToRoutes.has(namespace)) {\n namespaceToRoutes.set(namespace, new Set());\n }\n namespaceToRoutes.get(namespace)!.add(route.routeId);\n }\n }\n\n const namespaceUsage: NamespaceUsageEntry[] = [];\n for (const [namespace, routes] of namespaceToRoutes) {\n const routeCount = routes.size;\n const percentage =\n totalRoutes === 0 ? 0 : Math.round((routeCount / totalRoutes) * 100);\n namespaceUsage.push({\n namespace,\n routeCount,\n totalRoutes,\n percentage,\n inDictionary: dictNs.has(namespace),\n });\n }\n\n // Sort descending by routeCount then alphabetically.\n namespaceUsage.sort(\n (a, b) => b.routeCount - a.routeCount || a.namespace.localeCompare(b.namespace),\n );\n\n return { candidates, namespaceUsage };\n}\n\n/**\n * Generate the stats report: summary counts.\n */\nexport function generateStats(\n analysis: ProjectAnalysis,\n availableKeys: Map<string, string[]>,\n): object {\n const totalKeysInFiles = Array.from(availableKeys.values()).reduce(\n (sum, paths) => sum + paths.length,\n 0,\n );\n\n const missingResult = generateMissing(analysis, availableKeys);\n const unusedResult = generateUnused(analysis, availableKeys);\n\n const perRoute: RouteStats[] = analysis.routes.map((route) => ({\n routeId: route.routeId,\n usedKeys: route.keys.filter((k) => !k.dynamic).length,\n availableKeys: totalKeysInFiles,\n prunedKeys: totalKeysInFiles - route.keys.filter((k) => !k.dynamic).length,\n }));\n\n const overlapResult = generateOverlapAnalysis(analysis);\n const sharedKeysCount = new Set(\n overlapResult.candidates.map((c) => c.key),\n ).size;\n const dictionaryCandidates = Array.from(\n new Set(overlapResult.candidates.map((c) => c.namespace)),\n );\n\n return {\n totalKeysInCode: analysis.allKeys.length,\n totalKeysInFiles,\n usedKeys: analysis.allKeys.length,\n missingKeys: missingResult.keys.length,\n unusedKeys: unusedResult.keys.length,\n routes: analysis.routes.length,\n namespaces: analysis.availableNamespaces.length,\n sharedNamespaces: analysis.sharedNamespaces,\n sharedKeysCount,\n dictionaryCandidates,\n perRoute,\n };\n}\n\nexport function generateDictionaryOwnershipReport(\n availableKeys: Map<string, string[]>,\n dictionaries?: Record<string, DictionaryConfig>,\n): DictionaryOwnershipReport {\n const rules = normalizeDictionaries(dictionaries);\n const allKeys = [...availableKeys.entries()].flatMap(([namespace, keys]) =>\n keys.map((key) => `${namespace}.${key}`),\n );\n const ownership = resolveDictionaryOwnership(allKeys, dictionaries);\n\n const collisions: DictionaryCollisionReport[] = [];\n for (const key of allKeys) {\n const matched = rules\n .filter((rule) => rule.include.some((pattern) => keyMatchesPattern(key, pattern)))\n .map((rule) => rule.name);\n if (matched.length > 1) {\n collisions.push({\n key,\n owner: ownership.keyOwner.get(key) ?? matched[0],\n matchedDictionaries: matched,\n });\n }\n }\n\n return {\n rules: rules.map((rule) => ({\n name: rule.name,\n priority: rule.priority,\n include: rule.include,\n ownedKeys: [...(ownership.dictionaryKeys.get(rule.name) ?? new Set())].sort(),\n })),\n collisions: collisions.sort((a, b) => a.key.localeCompare(b.key)),\n unownedKeys: allKeys.filter((key) => !ownership.keyOwner.has(key)).sort(),\n };\n}\n\n/**\n * Orchestrate report generation: flatten locale keys, generate all four\n * reports, and write them as JSON files to outDir.\n */\nexport function generateReports(\n analysis: ProjectAnalysis,\n localesDir: string,\n defaultLocale: string,\n outDir: string,\n dictionaries?: Record<string, DictionaryConfig>,\n): void {\n const availableKeys = flattenLocaleKeys(localesDir, defaultLocale);\n\n const manifest = generateManifest(analysis);\n const missing = generateMissing(analysis, availableKeys);\n const unused = generateUnused(analysis, availableKeys);\n const stats = generateStats(analysis, availableKeys);\n const overlap = generateOverlapAnalysis(analysis);\n const ownership = generateDictionaryOwnershipReport(availableKeys, dictionaries);\n\n fs.mkdirSync(outDir, { recursive: true });\n\n fs.writeFileSync(\n path.join(outDir, 'manifest.json'),\n JSON.stringify(manifest, null, 2),\n );\n fs.writeFileSync(\n path.join(outDir, 'missing.json'),\n JSON.stringify(missing, null, 2),\n );\n fs.writeFileSync(\n path.join(outDir, 'unused.json'),\n JSON.stringify(unused, null, 2),\n );\n fs.writeFileSync(\n path.join(outDir, 'stats.json'),\n JSON.stringify(stats, null, 2),\n );\n fs.writeFileSync(\n path.join(outDir, 'overlap.json'),\n JSON.stringify(overlap, null, 2),\n );\n fs.writeFileSync(\n path.join(outDir, 'ownership.json'),\n JSON.stringify(ownership, null, 2),\n );\n}\n","import ts from 'typescript';\n\n/**\n * Extracts a string value from a node if it's a string literal or\n * a no-substitution template literal. Returns undefined for anything else.\n */\nexport function getStringValue(node: ts.Expression): string | undefined {\n if (ts.isStringLiteral(node)) {\n return node.text;\n }\n if (ts.isNoSubstitutionTemplateLiteral(node)) {\n return node.text;\n }\n return undefined;\n}\n\n/**\n * Extracts the longest static prefix from an expression.\n *\n * For string literals, returns the full string.\n * For template literals, returns the head text (before the first expression), trimmed of trailing dots.\n * For binary `+` expressions, recursively extracts from the left side.\n * For anything else, returns undefined.\n */\nexport function getStaticPrefix(node: ts.Expression): string | undefined {\n if (ts.isStringLiteral(node)) {\n const text = node.text;\n return text.endsWith('.') ? text.slice(0, -1) : text || undefined;\n }\n\n if (ts.isNoSubstitutionTemplateLiteral(node)) {\n const text = node.text;\n return text.endsWith('.') ? text.slice(0, -1) : text || undefined;\n }\n\n if (ts.isTemplateExpression(node)) {\n const head = node.head.text;\n return head.endsWith('.') ? head.slice(0, -1) : head || undefined;\n }\n\n if (ts.isBinaryExpression(node) && node.operatorToken.kind === ts.SyntaxKind.PlusToken) {\n return getStaticPrefix(node.left);\n }\n\n return undefined;\n}\n\n/**\n * Collects all non-type-only import and export-from specifiers from a source file.\n */\nexport function collectImports(sourceFile: ts.SourceFile): string[] {\n const imports: string[] = [];\n\n ts.forEachChild(sourceFile, (node) => {\n if (ts.isImportDeclaration(node)) {\n if (node.importClause?.isTypeOnly) return;\n if (ts.isStringLiteral(node.moduleSpecifier)) {\n imports.push(node.moduleSpecifier.text);\n }\n }\n\n if (ts.isExportDeclaration(node) && node.moduleSpecifier) {\n if (node.isTypeOnly) return;\n if (ts.isStringLiteral(node.moduleSpecifier)) {\n imports.push(node.moduleSpecifier.text);\n }\n }\n });\n\n return imports;\n}\n","import ts from 'typescript';\nimport { getStringValue, getStaticPrefix } from './ast-utils';\nimport type { ExtractionOptions, ExtractedKey } from './types';\n\nconst DEFAULT_KEY_FIELDS = ['labelKey', 'titleKey', 'translationKey'];\n\n/** Function names recognized as translation calls even when not traced to useI18n(). */\nconst TRANSLATION_CALLEE_NAMES = new Set(['t', 'get']);\n\nfunction getKeyFields(options: ExtractionOptions): Set<string> {\n if (!options.keyFields || options.keyFields.length === 0) {\n return new Set(DEFAULT_KEY_FIELDS);\n }\n return new Set([...DEFAULT_KEY_FIELDS, ...options.keyFields]);\n}\nconst PACKAGE_NAMES = new Set([\n 'vite-bundled-i18n',\n 'vite-bundled-i18n/react',\n 'vite-i18n-manager',\n 'vite-i18n-manager/react',\n]);\n\n/**\n * Package specifiers recognized as ours.\n *\n * @param specifier - The import module specifier to check.\n * @param hookSources - Additional module specifiers configured via `extraction.hookSources`.\n */\nfunction isOurPackage(specifier: string, hookSources?: string[]): boolean {\n return (\n PACKAGE_NAMES.has(specifier) ||\n specifier.includes('/core/t') ||\n specifier.includes('/react/useI18n') ||\n matchesHookSource(specifier, hookSources)\n );\n}\n\n/**\n * Checks if a module specifier exports `useI18n`.\n *\n * @param specifier - The import module specifier to check.\n * @param hookSources - Additional module specifiers configured via `extraction.hookSources`.\n */\nfunction isUseI18nPackage(specifier: string, hookSources?: string[]): boolean {\n return (\n specifier === 'vite-bundled-i18n/react' ||\n specifier === 'vite-i18n-manager/react' ||\n specifier.includes('/react/useI18n') ||\n matchesHookSource(specifier, hookSources)\n );\n}\n\n/**\n * Checks if a specifier matches any configured hook source.\n * Uses exact match or endsWith to handle path alias resolution.\n */\nfunction matchesHookSource(specifier: string, hookSources?: string[]): boolean {\n if (!hookSources || hookSources.length === 0) return false;\n return hookSources.some(source => specifier === source || specifier.endsWith(source));\n}\n\n/**\n * Checks if a module specifier is one that exports the global `t`.\n */\nfunction isGlobalTPackage(specifier: string): boolean {\n return (\n specifier === 'vite-bundled-i18n' ||\n specifier === 'vite-i18n-manager' ||\n specifier.includes('/core/t')\n );\n}\n\n/**\n * Extract the fallback string from a t() call's arguments.\n * - t(key, fallback) where fallback is a string literal\n * - t(key, params, fallback) where params is an object literal and fallback is a string literal\n */\nfunction extractFallback(args: ts.NodeArray<ts.Expression>): string | undefined {\n if (args.length >= 2) {\n const second = args[1];\n // t(key, fallbackString)\n const secondStr = getStringValue(second);\n if (secondStr !== undefined) {\n return secondStr;\n }\n // t(key, paramsObject, fallbackString)\n if (args.length >= 3 && ts.isObjectLiteralExpression(second)) {\n const third = args[2];\n const thirdStr = getStringValue(third);\n if (thirdStr !== undefined) {\n return thirdStr;\n }\n }\n }\n return undefined;\n}\n\n/**\n * Finds all t() translation calls in a source file.\n */\nexport function findTranslationCalls(\n sourceFile: ts.SourceFile,\n options: ExtractionOptions,\n): ExtractedKey[] {\n const results: ExtractedKey[] = [];\n const seenStaticFieldKeys = new Set<string>();\n\n // Track which local identifiers map to our global `t`\n // key = local name, value = 'global' | 'useI18n'\n const trackedNames = new Map<string, 'global' | 'useI18n'>();\n\n // Set of local names bound to our `useI18n` import\n const useI18nNames = new Set<string>();\n const i18nKeyNames = new Set<string>();\n const literalConstants = new Map<string, string>();\n /** Tracks `as const` objects and string enums: varName → (propName → stringValue) */\n const constObjectMaps = new Map<string, Map<string, string>>();\n\n // Pass 1: Walk imports\n ts.forEachChild(sourceFile, (node) => {\n if (!ts.isImportDeclaration(node)) return;\n if (!ts.isStringLiteral(node.moduleSpecifier)) return;\n const specifier = node.moduleSpecifier.text;\n if (!isOurPackage(specifier, options.hookSources)) return;\n\n const clause = node.importClause;\n if (!clause) return;\n const bindings = clause.namedBindings;\n if (!bindings || !ts.isNamedImports(bindings)) return;\n\n for (const element of bindings.elements) {\n const importedName = (element.propertyName ?? element.name).text;\n const localName = element.name.text;\n\n if (importedName === 't' && isGlobalTPackage(specifier)) {\n if (options.scope !== 'scoped') {\n trackedNames.set(localName, 'global');\n }\n }\n\n if (importedName === 'useI18n' && isUseI18nPackage(specifier, options.hookSources)) {\n useI18nNames.add(localName);\n }\n\n if (importedName === 'i18nKey' && isOurPackage(specifier, options.hookSources)) {\n i18nKeyNames.add(localName);\n }\n }\n });\n\n // Pass 1b: Collect `as const` objects and string enums\n ts.forEachChild(sourceFile, (node) => {\n // as const objects: const X = { ... } as const\n if (ts.isVariableStatement(node)) {\n for (const decl of node.declarationList.declarations) {\n if (!ts.isIdentifier(decl.name) || !decl.initializer) continue;\n if (!ts.isAsExpression(decl.initializer)) continue;\n const init = decl.initializer.expression;\n if (!ts.isObjectLiteralExpression(init)) continue;\n\n const entries = new Map<string, string>();\n for (const prop of init.properties) {\n if (!ts.isPropertyAssignment(prop)) continue;\n const propName = ts.isIdentifier(prop.name)\n ? prop.name.text\n : ts.isStringLiteral(prop.name)\n ? prop.name.text\n : undefined;\n if (!propName) continue;\n const value = getStringValue(prop.initializer);\n if (value !== undefined) {\n entries.set(propName, value);\n }\n }\n if (entries.size > 0) {\n constObjectMaps.set(decl.name.text, entries);\n }\n }\n }\n\n // String enums\n if (ts.isEnumDeclaration(node) && ts.isIdentifier(node.name)) {\n const entries = new Map<string, string>();\n for (const member of node.members) {\n const memberName = ts.isIdentifier(member.name)\n ? member.name.text\n : ts.isStringLiteral(member.name)\n ? member.name.text\n : undefined;\n if (!memberName || !member.initializer) continue;\n const value = getStringValue(member.initializer);\n if (value !== undefined) {\n entries.set(memberName, value);\n }\n }\n if (entries.size > 0) {\n constObjectMaps.set(node.name.text, entries);\n }\n }\n });\n\n // Pass 2: Walk entire AST to find useI18n destructuring and t() calls\n const keyFields = getKeyFields(options);\n function visit(node: ts.Node): void {\n if (\n ts.isVariableDeclaration(node) &&\n ts.isIdentifier(node.name) &&\n node.initializer &&\n getStringValue(node.initializer) !== undefined\n ) {\n literalConstants.set(node.name.text, getStringValue(node.initializer)!);\n }\n\n // Look for: const { t } = useI18n(...) or const { t: alias } = useI18n(...)\n if (\n ts.isVariableDeclaration(node) &&\n node.initializer &&\n ts.isCallExpression(node.initializer) &&\n ts.isIdentifier(node.initializer.expression) &&\n useI18nNames.has(node.initializer.expression.text) &&\n node.name &&\n ts.isObjectBindingPattern(node.name)\n ) {\n for (const element of node.name.elements) {\n if (!ts.isIdentifier(element.name)) continue;\n const propName = element.propertyName\n ? ts.isIdentifier(element.propertyName)\n ? element.propertyName.text\n : undefined\n : element.name.text;\n\n if (propName === 't') {\n const localName = element.name.text;\n trackedNames.set(localName, 'useI18n');\n }\n }\n }\n\n // Look for calls to tracked identifiers\n if (\n ts.isCallExpression(node) &&\n ts.isIdentifier(node.expression) &&\n trackedNames.has(node.expression.text)\n ) {\n const args = node.arguments;\n if (args.length === 0) {\n ts.forEachChild(node, visit);\n return;\n }\n\n const keyArg = args[0];\n let staticKey = getStringValue(keyArg)\n ?? (ts.isIdentifier(keyArg) ? literalConstants.get(keyArg.text) : undefined);\n\n // Const object / enum property access: KEYS.active\n if (staticKey === undefined && ts.isPropertyAccessExpression(keyArg) && ts.isIdentifier(keyArg.expression)) {\n const objMap = constObjectMaps.get(keyArg.expression.text);\n if (objMap) {\n const value = objMap.get(keyArg.name.text);\n if (value !== undefined) {\n staticKey = value;\n }\n }\n }\n\n const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());\n\n // Const object / enum element access with dynamic index: KEYS[status]\n if (staticKey === undefined && ts.isElementAccessExpression(keyArg) && ts.isIdentifier(keyArg.expression)) {\n const objMap = constObjectMaps.get(keyArg.expression.text);\n if (objMap) {\n for (const value of objMap.values()) {\n results.push({\n key: value,\n dynamic: false,\n line: line + 1,\n column: character,\n });\n }\n ts.forEachChild(node, visit);\n return;\n }\n }\n\n if (staticKey !== undefined) {\n // Static key\n results.push({\n key: staticKey,\n fallback: extractFallback(args),\n dynamic: false,\n line: line + 1,\n column: character,\n });\n } else {\n // Dynamic key\n const prefix = getStaticPrefix(keyArg);\n results.push({\n key: prefix ? `${prefix}.*` : '*',\n dynamic: true,\n staticPrefix: prefix || undefined,\n line: line + 1,\n column: character,\n });\n }\n }\n\n if (\n ts.isCallExpression(node) &&\n ts.isIdentifier(node.expression) &&\n i18nKeyNames.has(node.expression.text) &&\n node.arguments.length > 0\n ) {\n const keyArg = node.arguments[0];\n let staticKey = getStringValue(keyArg)\n ?? (ts.isIdentifier(keyArg) ? literalConstants.get(keyArg.text) : undefined);\n\n // Const object / enum property access: KEYS.active\n if (staticKey === undefined && ts.isPropertyAccessExpression(keyArg) && ts.isIdentifier(keyArg.expression)) {\n const objMap = constObjectMaps.get(keyArg.expression.text);\n if (objMap) {\n const value = objMap.get(keyArg.name.text);\n if (value !== undefined) {\n staticKey = value;\n }\n }\n }\n\n const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());\n\n // Const object / enum element access with dynamic index: KEYS[status]\n if (staticKey === undefined && ts.isElementAccessExpression(keyArg) && ts.isIdentifier(keyArg.expression)) {\n const objMap = constObjectMaps.get(keyArg.expression.text);\n if (objMap) {\n for (const value of objMap.values()) {\n results.push({\n key: value,\n dynamic: false,\n line: line + 1,\n column: character,\n });\n }\n ts.forEachChild(node, visit);\n return;\n }\n }\n\n if (staticKey !== undefined) {\n results.push({\n key: staticKey,\n dynamic: false,\n line: line + 1,\n column: character,\n });\n } else {\n const prefix = getStaticPrefix(keyArg);\n results.push({\n key: prefix ? `${prefix}.*` : '*',\n dynamic: true,\n staticPrefix: prefix || undefined,\n line: line + 1,\n column: character,\n });\n }\n }\n\n // Catch t() / get() calls from untracked sources (e.g., t passed as argument to helpers).\n // Only fires in global extraction mode — scoped mode only tracks traced identifiers.\n if (\n options.scope !== 'scoped' &&\n ts.isCallExpression(node) &&\n ts.isIdentifier(node.expression) &&\n !trackedNames.has(node.expression.text) &&\n !i18nKeyNames.has(node.expression.text) &&\n TRANSLATION_CALLEE_NAMES.has(node.expression.text) &&\n node.arguments.length > 0\n ) {\n const keyArg = node.arguments[0];\n const staticKey = getStringValue(keyArg)\n ?? (ts.isIdentifier(keyArg) ? literalConstants.get(keyArg.text) : undefined);\n // Only extract if it looks like a dotted translation key (has at least one dot)\n if (staticKey !== undefined && staticKey.includes('.')) {\n const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());\n results.push({\n key: staticKey,\n dynamic: false,\n line: line + 1,\n column: character,\n });\n }\n }\n\n if (\n ts.isPropertyAssignment(node) &&\n ((ts.isIdentifier(node.name) && keyFields.has(node.name.text))\n || (ts.isStringLiteral(node.name) && keyFields.has(node.name.text)))\n ) {\n const staticKey = getStringValue(node.initializer)\n ?? (ts.isIdentifier(node.initializer) ? literalConstants.get(node.initializer.text) : undefined);\n if (staticKey !== undefined && !seenStaticFieldKeys.has(staticKey)) {\n const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());\n seenStaticFieldKeys.add(staticKey);\n results.push({\n key: staticKey,\n dynamic: false,\n line: line + 1,\n column: character,\n });\n }\n }\n\n ts.forEachChild(node, visit);\n }\n\n visit(sourceFile);\n return results;\n}\n\n/**\n * Extracts scope strings from all useI18n() calls in a source file.\n *\n * @param sourceFile - The parsed TypeScript source file.\n * @param hookSources - Additional module specifiers that export `useI18n`.\n */\nexport function extractScopes(sourceFile: ts.SourceFile, hookSources?: string[]): string[] {\n const scopes: string[] = [];\n\n // First check that useI18n is actually imported from our package\n const useI18nNames = new Set<string>();\n\n ts.forEachChild(sourceFile, (node) => {\n if (!ts.isImportDeclaration(node)) return;\n if (!ts.isStringLiteral(node.moduleSpecifier)) return;\n const specifier = node.moduleSpecifier.text;\n if (!isUseI18nPackage(specifier, hookSources)) return;\n\n const clause = node.importClause;\n if (!clause) return;\n const bindings = clause.namedBindings;\n if (!bindings || !ts.isNamedImports(bindings)) return;\n\n for (const element of bindings.elements) {\n const importedName = (element.propertyName ?? element.name).text;\n const localName = element.name.text;\n if (importedName === 'useI18n') {\n useI18nNames.add(localName);\n }\n }\n });\n\n function visit(node: ts.Node): void {\n if (\n ts.isCallExpression(node) &&\n ts.isIdentifier(node.expression) &&\n useI18nNames.has(node.expression.text) &&\n node.arguments.length > 0\n ) {\n const scopeArg = node.arguments[0];\n const scopeStr = getStringValue(scopeArg);\n if (scopeStr !== undefined) {\n scopes.push(scopeStr);\n }\n }\n\n ts.forEachChild(node, visit);\n }\n\n visit(sourceFile);\n return scopes;\n}\n","import ts from 'typescript';\nimport { collectImports } from './ast-utils';\nimport { findTranslationCalls, extractScopes } from './patterns';\nimport type { ExtractionOptions, ExtractionResult } from './types';\n\nconst DEFAULT_OPTIONS: ExtractionOptions = {\n scope: 'global',\n filePath: '',\n};\n\n/**\n * Extracts translation keys, scopes, and imports from a TypeScript/TSX source string.\n *\n * Parses the source with the TypeScript compiler, walks the AST to find\n * `t()` and `useI18n()` patterns, and returns structured extraction data.\n *\n * @param source - The TypeScript/TSX source code to analyze\n * @param options - Extraction options (scope mode, file path for metadata)\n * @returns The extraction result with keys, scopes, and imports\n */\nexport function extractKeys(\n source: string,\n options?: Partial<ExtractionOptions>,\n): ExtractionResult {\n const opts: ExtractionOptions = { ...DEFAULT_OPTIONS, ...options };\n\n if (!source.trim()) {\n return { filePath: opts.filePath, scopes: [], keys: [], imports: [] };\n }\n\n let sourceFile: ts.SourceFile;\n try {\n sourceFile = ts.createSourceFile(\n opts.filePath || 'source.tsx',\n source,\n ts.ScriptTarget.Latest,\n true,\n ts.ScriptKind.TSX,\n );\n } catch {\n console.warn('vite-bundled-i18n: Failed to parse ' + opts.filePath);\n return { filePath: opts.filePath, scopes: [], keys: [], imports: [] };\n }\n\n const keys = findTranslationCalls(sourceFile, opts);\n const scopes = extractScopes(sourceFile, opts.hookSources);\n const imports = collectImports(sourceFile);\n\n return {\n filePath: opts.filePath,\n scopes,\n keys,\n imports,\n };\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport { globSync } from 'tinyglobby';\nimport ts from 'typescript';\nimport { extractKeys } from './extract';\nimport type { ExtractedKey } from './types';\nimport type {\n WalkerOptions,\n RouteAnalysis,\n ProjectAnalysis,\n} from './walker-types';\n\nconst RESOLVE_EXTENSIONS = ['.tsx', '.ts', '.jsx', '.js'];\nconst INDEX_EXTENSIONS = ['/index.tsx', '/index.ts'];\nconst tsconfigPathCache = new Map<string, { baseUrl?: string; paths?: Record<string, string[]> }>();\n\nfunction tryResolveBase(base: string): string | undefined {\n for (const ext of RESOLVE_EXTENSIONS) {\n const candidate = base + ext;\n if (fs.existsSync(candidate)) {\n return candidate;\n }\n }\n\n for (const indexSuffix of INDEX_EXTENSIONS) {\n const candidate = base + indexSuffix;\n if (fs.existsSync(candidate)) {\n return candidate;\n }\n }\n\n return undefined;\n}\n\nfunction readTsconfigPaths(rootDir: string): { baseUrl?: string; paths?: Record<string, string[]> } {\n const cached = tsconfigPathCache.get(rootDir);\n if (cached) return cached;\n\n for (const fileName of ['tsconfig.app.json', 'tsconfig.json']) {\n const fullPath = path.join(rootDir, fileName);\n if (!fs.existsSync(fullPath)) continue;\n\n try {\n const configFile = ts.readConfigFile(fullPath, ts.sys.readFile);\n if (configFile.error) continue;\n const parsed = ts.parseJsonConfigFileContent(configFile.config, ts.sys, rootDir);\n const result = {\n baseUrl: parsed.options.baseUrl,\n paths: parsed.options.paths,\n };\n tsconfigPathCache.set(rootDir, result);\n return result;\n } catch {\n // Ignore malformed tsconfig and continue with default resolution.\n }\n }\n\n const empty = {};\n tsconfigPathCache.set(rootDir, empty);\n return empty;\n}\n\nfunction resolveAliasImport(\n specifier: string,\n rootDir: string,\n): string | undefined {\n const { baseUrl, paths } = readTsconfigPaths(rootDir);\n if (!baseUrl || !paths) return undefined;\n\n for (const [pattern, targets] of Object.entries(paths)) {\n const wildcardIndex = pattern.indexOf('*');\n\n if (wildcardIndex === -1) {\n if (specifier !== pattern) continue;\n for (const target of targets) {\n const candidate = tryResolveBase(path.resolve(baseUrl, target));\n if (candidate) return candidate;\n }\n continue;\n }\n\n const prefix = pattern.slice(0, wildcardIndex);\n const suffix = pattern.slice(wildcardIndex + 1);\n if (!specifier.startsWith(prefix) || !specifier.endsWith(suffix)) {\n continue;\n }\n\n const matched = specifier.slice(prefix.length, specifier.length - suffix.length);\n for (const target of targets) {\n const resolvedTarget = target.replace('*', matched);\n const candidate = tryResolveBase(path.resolve(baseUrl, resolvedTarget));\n if (candidate) return candidate;\n }\n }\n\n return undefined;\n}\n\n/**\n * Resolves a relative import specifier to an absolute file path.\n *\n * Only handles relative imports (starting with `.` or `..`).\n * Returns undefined for package/bare imports or if no file is found.\n */\nexport function resolveImport(\n specifier: string,\n fromFile: string,\n rootDir?: string,\n): string | undefined {\n if (specifier.startsWith('.')) {\n const base = path.resolve(path.dirname(fromFile), specifier);\n return tryResolveBase(base);\n }\n\n if (rootDir) {\n return resolveAliasImport(specifier, rootDir);\n }\n\n return undefined;\n}\n\n/**\n * Derives a route identifier from the entry point file path.\n *\n * Strips the rootDir prefix and `src/pages/` prefix, then removes the extension.\n * Falls back to stripping just the rootDir prefix if `src/pages/` is not present.\n */\nexport function deriveRouteId(entryPoint: string, rootDir: string): string {\n let rel = path.relative(rootDir, entryPoint);\n\n const pagesPrefix = path.join('src', 'pages') + path.sep;\n if (rel.startsWith(pagesPrefix)) {\n rel = rel.slice(pagesPrefix.length);\n }\n\n // Strip extension\n const ext = path.extname(rel);\n if (ext) {\n rel = rel.slice(0, -ext.length);\n }\n\n return rel;\n}\n\n/**\n * Discovers namespace names from locale JSON files.\n *\n * Reads `{localesDir}/{defaultLocale}/` and returns sorted `.json`\n * filenames without their extension.\n */\nexport function discoverNamespaces(\n localesDir: string,\n defaultLocale: string,\n): string[] {\n const dir = path.join(localesDir, defaultLocale);\n\n try {\n const entries = fs.readdirSync(dir);\n return entries\n .filter((f) => f.endsWith('.json'))\n .map((f) => f.slice(0, -5))\n .sort();\n } catch {\n return [];\n }\n}\n\n/**\n * Walks a single route's import graph starting from the entry point.\n *\n * Reads each file, extracts translation keys and import specifiers,\n * then recursively follows relative imports. Handles circular imports\n * via a visited set and deduplicates keys by key string.\n */\nexport function walkRoute(\n entryPoint: string,\n options: { rootDir: string; extractionScope: 'global' | 'scoped'; hookSources?: string[] },\n): RouteAnalysis {\n const visited = new Set<string>();\n const allKeys: ExtractedKey[] = [];\n const allScopes: string[] = [];\n const allFiles: string[] = [];\n const seenKeys = new Set<string>();\n\n function visit(filePath: string): void {\n const resolved = path.resolve(filePath);\n if (visited.has(resolved)) {\n return;\n }\n visited.add(resolved);\n\n let source: string;\n try {\n source = fs.readFileSync(resolved, 'utf-8');\n } catch {\n return;\n }\n\n allFiles.push(resolved);\n\n const result = extractKeys(source, {\n scope: options.extractionScope,\n filePath: resolved,\n hookSources: options.hookSources,\n });\n\n for (const key of result.keys) {\n if (!seenKeys.has(key.key)) {\n seenKeys.add(key.key);\n allKeys.push(key);\n }\n }\n\n for (const scope of result.scopes) {\n if (!allScopes.includes(scope)) {\n allScopes.push(scope);\n }\n }\n\n for (const imp of result.imports) {\n const importPath = resolveImport(imp, resolved, options.rootDir);\n if (importPath) {\n visit(importPath);\n }\n }\n }\n\n visit(entryPoint);\n\n return {\n entryPoint: path.resolve(entryPoint),\n routeId: deriveRouteId(path.resolve(entryPoint), options.rootDir),\n scopes: allScopes,\n keys: allKeys,\n files: allFiles,\n };\n}\n\n/**\n * Walks the entire project: finds page entry points, analyzes each route,\n * discovers namespaces, and computes shared namespace candidates.\n */\nexport function walkAll(options: WalkerOptions): ProjectAnalysis {\n const rootDir = options.rootDir ?? process.cwd();\n const extractionScope = options.extractionScope ?? 'global';\n\n // Find page entry points\n const entryFiles = globSync(options.pages, { cwd: rootDir, absolute: true });\n\n // Walk each route\n const routes = entryFiles.map((entry) =>\n walkRoute(entry, { rootDir, extractionScope, hookSources: options.hookSources }),\n );\n\n // Discover namespaces\n const localesPath = path.isAbsolute(options.localesDir)\n ? options.localesDir\n : path.join(rootDir, options.localesDir);\n const availableNamespaces = discoverNamespaces(\n localesPath,\n options.defaultLocale,\n );\n\n // Deduplicate all keys across routes\n const allKeysMap = new Map<string, ExtractedKey>();\n for (const route of routes) {\n for (const key of route.keys) {\n if (!allKeysMap.has(key.key)) {\n allKeysMap.set(key.key, key);\n }\n }\n }\n const allKeys = Array.from(allKeysMap.values());\n\n // Compute shared namespaces (used by >50% of routes)\n const sharedNamespaces: string[] = [];\n if (routes.length > 0) {\n const nsCounts = new Map<string, number>();\n for (const route of routes) {\n const routeNamespaces = new Set<string>();\n for (const key of route.keys) {\n const ns = key.key.split('.')[0];\n if (ns) {\n routeNamespaces.add(ns);\n }\n }\n for (const ns of routeNamespaces) {\n nsCounts.set(ns, (nsCounts.get(ns) ?? 0) + 1);\n }\n }\n\n const threshold = routes.length / 2;\n for (const [ns, count] of nsCounts) {\n if (count > threshold) {\n sharedNamespaces.push(ns);\n }\n }\n sharedNamespaces.sort();\n }\n\n return {\n routes,\n availableNamespaces,\n allKeys,\n sharedNamespaces,\n };\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport type { ProjectAnalysis } from './walker-types';\nimport type { DictionaryConfig } from '../core/types';\nimport { resolveDictionaryOwnership } from './dictionary-ownership';\nimport { buildScopePlans } from './scope-bundles';\n\n/**\n * Options for the module compiler.\n */\nexport interface CompilerOptions {\n /** Absolute path to the locales directory. */\n localesDir: string;\n /** List of locale codes to compile. */\n locales: string[];\n /** Default locale code used for fallback resolution. */\n defaultLocale: string;\n /** Output directory for compiled modules. */\n outDir: string;\n /** Optional dictionary configurations. */\n dictionaries?: Record<string, DictionaryConfig>;\n /**\n * Inline cross-namespace keys (tree-shaken) into each scope module.\n * See `I18nSharedConfig.bundling.crossNamespacePacking`.\n *\n * @default false\n */\n crossNamespacePacking?: boolean;\n}\n\n/**\n * Escapes backslashes and single quotes for use in JS string literals.\n */\nfunction escapeValue(value: string): string {\n return value.replace(/\\\\/g, '\\\\\\\\').replace(/'/g, \"\\\\'\");\n}\n\n/**\n * Flattens a nested translation object into a flat Map with fully qualified keys.\n *\n * @param namespace - The namespace prefix (e.g., 'products')\n * @param data - The nested translation object\n * @param prefix - Internal prefix for recursion\n * @returns A Map of fully qualified keys to string values\n */\nexport function flattenNamespace(\n namespace: string,\n data: Record<string, unknown>,\n prefix?: string,\n): Map<string, string> {\n const result = new Map<string, string>();\n const currentPrefix = prefix ? `${prefix}.` : `${namespace}.`;\n\n for (const [key, value] of Object.entries(data)) {\n const fullKey = `${currentPrefix}${key}`;\n if (typeof value === 'string') {\n result.set(fullKey, value);\n } else if (typeof value === 'object' && value !== null) {\n const nested = flattenNamespace(\n namespace,\n value as Record<string, unknown>,\n fullKey,\n );\n for (const [k, v] of nested) {\n result.set(k, v);\n }\n }\n }\n\n return result;\n}\n\n/**\n * Creates a new map with all keys from primary, plus any missing keys filled from fallback.\n */\nexport function preResolveFallbacks(\n primary: Map<string, string>,\n fallback: Map<string, string>,\n): Map<string, string> {\n const result = new Map(primary);\n for (const [key, value] of fallback) {\n if (!result.has(key)) {\n result.set(key, value);\n }\n }\n return result;\n}\n\n/**\n * Generates a JavaScript module exporting a flat Map of translation entries.\n */\nexport function generateCompiledModule(entries: Map<string, string>): string {\n const lines: string[] = [];\n lines.push('// Auto-generated by vite-bundled-i18n. Do not edit.');\n lines.push('const m = new Map([');\n for (const [key, value] of entries) {\n lines.push(` ['${escapeValue(key)}','${escapeValue(value)}'],`);\n }\n lines.push(']);');\n lines.push('export default m;');\n lines.push('');\n return lines.join('\\n');\n}\n\n/**\n * Reads namespace JSON files for a locale and returns a combined flattened Map.\n */\nfunction buildLocaleMap(\n localesDir: string,\n locale: string,\n namespaces: string[],\n): Map<string, string> {\n const combined = new Map<string, string>();\n for (const ns of namespaces) {\n const filePath = path.join(localesDir, locale, `${ns}.json`);\n if (!fs.existsSync(filePath)) continue;\n const data = JSON.parse(\n fs.readFileSync(filePath, 'utf-8'),\n ) as Record<string, unknown>;\n const flat = flattenNamespace(ns, data);\n for (const [k, v] of flat) {\n combined.set(k, v);\n }\n }\n return combined;\n}\n\n/**\n * Reads ALL namespace JSON files for a locale directory.\n */\nfunction buildFullLocaleMap(\n localesDir: string,\n locale: string,\n): Map<string, string> {\n const localeDir = path.join(localesDir, locale);\n if (!fs.existsSync(localeDir)) return new Map();\n const files = fs.readdirSync(localeDir).filter((f) => f.endsWith('.json'));\n const namespaces = files.map((f) => f.replace(/\\.json$/, ''));\n return buildLocaleMap(localesDir, locale, namespaces);\n}\n\n/**\n * Filters a map to only include entries whose keys are in the given set.\n */\nfunction filterMap(\n map: Map<string, string>,\n keys: Set<string>,\n): Map<string, string> {\n const result = new Map<string, string>();\n for (const [k, v] of map) {\n if (keys.has(k)) {\n result.set(k, v);\n }\n }\n return result;\n}\n\n/**\n * Generates a dictionary module for a locale by reading all dictionary namespace files,\n * flattening them, and pre-resolving fallbacks against the default locale.\n */\nexport function generateDictionaryModule(\n localesDir: string,\n locale: string,\n defaultLocale: string,\n dictionaries: Record<string, DictionaryConfig>,\n dictionaryName: string,\n): string {\n const fullAvailable = buildFullLocaleMap(localesDir, defaultLocale);\n const ownership = resolveDictionaryOwnership(fullAvailable.keys(), dictionaries);\n const ownedKeys = ownership.dictionaryKeys.get(dictionaryName) ?? new Set<string>();\n\n const localeMap = filterMap(buildFullLocaleMap(localesDir, locale), ownedKeys);\n\n if (locale !== defaultLocale) {\n const defaultMap = filterMap(buildFullLocaleMap(localesDir, defaultLocale), ownedKeys);\n const resolved = preResolveFallbacks(localeMap, defaultMap);\n return generateCompiledModule(resolved);\n }\n\n return generateCompiledModule(localeMap);\n}\n\n/**\n * Generates a manifest module with dynamic import mappings for routes and dictionaries.\n */\nexport function generateManifest(\n scopeIds: string[],\n locales: string[],\n dictionaryNames: string[],\n): string {\n const lines: string[] = [];\n lines.push('// Auto-generated by vite-bundled-i18n. Do not edit.');\n lines.push('export const scopes = {');\n for (const scopeId of scopeIds) {\n lines.push(` '${escapeValue(scopeId)}': {`);\n for (const locale of locales) {\n lines.push(\n ` '${escapeValue(locale)}': () => import('./${locale}/${scopeId}.js'),`,\n );\n }\n lines.push(' },');\n }\n lines.push('};');\n lines.push('');\n\n lines.push('export const routes = scopes;');\n lines.push('');\n\n if (dictionaryNames.length > 0) {\n lines.push('export const dictionaries = {');\n for (const name of dictionaryNames) {\n lines.push(` '${escapeValue(name)}': {`);\n for (const locale of locales) {\n lines.push(\n ` '${escapeValue(locale)}': () => import('./${locale}/_dict/${name}.js'),`,\n );\n }\n lines.push(' },');\n }\n lines.push('};');\n lines.push('');\n }\n\n return lines.join('\\n');\n}\n\n/**\n * Orchestrates the full compilation of pre-compiled i18n modules.\n */\nexport function compileAll(\n analysis: ProjectAnalysis,\n options: CompilerOptions,\n): void {\n const { localesDir, locales, defaultLocale, outDir, dictionaries, crossNamespacePacking } = options;\n\n fs.mkdirSync(outDir, { recursive: true });\n\n // Build the default locale full map for fallback resolution\n const defaultFullMap = buildFullLocaleMap(localesDir, defaultLocale);\n\n // Determine which namespaces the routes reference\n const ownership = resolveDictionaryOwnership(defaultFullMap.keys(), dictionaries);\n\n // For each scope + locale: collect used keys, filter, resolve fallbacks, write\n const scopePlans = buildScopePlans(analysis, defaultFullMap.keys(), { crossNamespacePacking });\n for (const plan of scopePlans) {\n const usedKeys = new Set(\n [...plan.keys].filter((key) => !ownership.keyOwner.has(key)),\n );\n if (crossNamespacePacking) {\n for (const extraKeys of plan.extras.values()) {\n for (const key of extraKeys) {\n if (ownership.keyOwner.has(key)) continue;\n usedKeys.add(key);\n }\n }\n }\n for (const locale of locales) {\n const localeDir = path.join(outDir, locale);\n fs.mkdirSync(localeDir, { recursive: true });\n\n const localeMap = buildFullLocaleMap(localesDir, locale);\n const filtered = filterMap(localeMap, usedKeys);\n\n const resolved =\n locale !== defaultLocale\n ? preResolveFallbacks(filtered, filterMap(defaultFullMap, usedKeys))\n : filtered;\n\n const moduleSource = generateCompiledModule(resolved);\n fs.writeFileSync(\n path.join(localeDir, `${plan.scope}.js`),\n moduleSource,\n );\n }\n }\n\n // For each locale: generate per-dictionary modules\n if (dictionaries && Object.keys(dictionaries).length > 0) {\n for (const locale of locales) {\n const localeDir = path.join(outDir, locale);\n const dictDir = path.join(localeDir, '_dict');\n fs.mkdirSync(dictDir, { recursive: true });\n\n for (const dictionaryName of Object.keys(dictionaries)) {\n const dictModule = generateDictionaryModule(\n localesDir,\n locale,\n defaultLocale,\n dictionaries,\n dictionaryName,\n );\n fs.writeFileSync(path.join(dictDir, `${dictionaryName}.js`), dictModule);\n }\n }\n }\n\n // Generate manifest\n const scopeIds = scopePlans.map((plan) => plan.scope);\n const dictionaryNames = dictionaries ? Object.keys(dictionaries) : [];\n const manifestSource = generateManifest(scopeIds, locales, dictionaryNames);\n fs.writeFileSync(path.join(outDir, 'manifest.js'), manifestSource);\n}\n"],"mappings":";;;;;AAkBA,SAAgB,6BAA6B,MAAkC;AAE7E,QAAO,CAAC,IADU,KAAK,QAAQ,EAAE,EAAE,KAAK,QAAQ,GAAG,IAAI,IAAI,EACtC,GAAI,KAAK,WAAW,EAAE,CAAE;;AAG/C,SAAgB,sBACd,cAC4B;AAC5B,KAAI,CAAC,aAAc,QAAO,EAAE;AAE5B,QAAO,OAAO,QAAQ,aAAa,CAChC,KAAK,CAAC,MAAM,OAAO,WAAW;EAC7B;EACA,SAAS,6BAA6B,KAAK;EAC3C,SAAS,KAAK,WAAW,EAAE;EAC3B,UAAU,KAAK,YAAY;EAC3B,QAAQ,KAAK,UAAU;EACvB;EACD,EAAE,CACF,QAAQ,SAAS,KAAK,QAAQ,SAAS,EAAE,CACzC,MAAM,GAAG,MAAM,EAAE,WAAW,EAAE,YAAY,EAAE,QAAQ,EAAE,MAAM;;AAGjE,SAAgB,kBAAkB,KAAa,SAA0B;AACvE,KAAI,QAAQ,SAAS,IAAI,EAAE;AACzB,MAAI,QAAQ,SAAS,IAAI,EAAE;GACzB,MAAM,SAAS,QAAQ,MAAM,GAAG,GAAG;AACnC,UAAO,IAAI,WAAW,OAAO;;AAE/B,SAAO,QAAQ;;CAGjB,MAAM,YAAY,IAAI,MAAM,IAAI,CAAC;AACjC,KAAI,QAAQ,SAAS,IAAI,CACvB,QAAO,UAAU,WAAW,QAAQ,MAAM,GAAG,GAAG,CAAC;AAEnD,QAAO,cAAc;;AAGvB,SAAgB,2BACd,eACA,cACqB;CACrB,MAAM,QAAQ,sBAAsB,aAAa;CACjD,MAAM,2BAAW,IAAI,KAAqB;CAC1C,MAAM,iCAAiB,IAAI,KAA0B;CACrD,MAAM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,UAAU,SAAS;EAC5B,MAAM,YAAY,KAAK,KAAK,QAAQ,OAAO;EAC3C,MAAM,UAAU,KAAK,KAAK,WAAW,QAAQ;AAC7C,KAAG,UAAU,SAAS,EAAE,WAAW,MAAM,CAAC;AAE1C,OAAK,MAAM,kBAAkB,OAAO,KAAK,aAAa,EAAE;GACtD,MAAM,aAAa,yBACjB,YACA,QACA,eACA,cACA,eACD;AACD,MAAG,cAAc,KAAK,KAAK,SAAS,GAAG,eAAe,KAAK,EAAE,WAAW;;;CAQ9E,MAAM,iBAAiB,iBAFN,WAAW,KAAK,SAAS,KAAK,MAAM,EAEH,SAD1B,eAAe,OAAO,KAAK,aAAa,GAAG,EAAE,CACM;AAC3E,IAAG,cAAc,KAAK,KAAK,QAAQ,cAAc,EAAE,eAAe"}
|
package/dist/core/config.d.ts
CHANGED
|
@@ -34,6 +34,29 @@ export interface I18nSharedConfig {
|
|
|
34
34
|
*/
|
|
35
35
|
hookSources?: string[];
|
|
36
36
|
};
|
|
37
|
+
/** Bundling behavior for scope/dictionary emission. */
|
|
38
|
+
bundling?: {
|
|
39
|
+
/**
|
|
40
|
+
* Inline cross-namespace keys into each scope bundle.
|
|
41
|
+
*
|
|
42
|
+
* By default, a scope bundle contains only the keys that belong to the
|
|
43
|
+
* scope's own namespace (e.g. `products.show` → `products.*` only). Keys
|
|
44
|
+
* referenced on the route from other namespaces are expected to be
|
|
45
|
+
* covered by a dictionary.
|
|
46
|
+
*
|
|
47
|
+
* When enabled, the extractor collects cross-namespace keys referenced
|
|
48
|
+
* on each route, tree-shakes them down to just the used subset, and
|
|
49
|
+
* inlines them into the same scope bundle. Keys that are already owned
|
|
50
|
+
* by a dictionary are skipped (no point duplicating the always-available
|
|
51
|
+
* layer into per-page bundles).
|
|
52
|
+
*
|
|
53
|
+
* This trades a slightly larger per-scope payload for zero extra HTTP
|
|
54
|
+
* requests and zero ceremony around shared cross-module components.
|
|
55
|
+
*
|
|
56
|
+
* @default false
|
|
57
|
+
*/
|
|
58
|
+
crossNamespacePacking?: boolean;
|
|
59
|
+
};
|
|
37
60
|
}
|
|
38
61
|
/**
|
|
39
62
|
* Defines the shared i18n configuration.
|
|
@@ -9,7 +9,8 @@ type WarnFn = (message: string) => void;
|
|
|
9
9
|
*/
|
|
10
10
|
export interface KeyTracker {
|
|
11
11
|
/**
|
|
12
|
-
* Record a single key lookup.
|
|
12
|
+
* Record a single key lookup. Entries are tagged with the current epoch
|
|
13
|
+
* so devtools can filter stale entries after a locale change or reset.
|
|
13
14
|
*
|
|
14
15
|
* @param key - Fully qualified translation key.
|
|
15
16
|
* @param namespace - Namespace extracted from the key.
|
|
@@ -24,6 +25,22 @@ export interface KeyTracker {
|
|
|
24
25
|
* @returns A mutable reference to the internal entries array.
|
|
25
26
|
*/
|
|
26
27
|
getKeyUsage(): KeyUsageEntry[];
|
|
28
|
+
/**
|
|
29
|
+
* Return the current epoch. Devtools compare each entry's `epoch` field
|
|
30
|
+
* against this value to drop stale rows from previous routes/locales.
|
|
31
|
+
*/
|
|
32
|
+
getEpoch(): number;
|
|
33
|
+
/**
|
|
34
|
+
* Bump the epoch without clearing entries. Call this on locale change
|
|
35
|
+
* or namespace unload — old entries stay in memory (for "all keys ever
|
|
36
|
+
* used" views) but the devtools panel filters them out.
|
|
37
|
+
*/
|
|
38
|
+
bumpEpoch(): void;
|
|
39
|
+
/**
|
|
40
|
+
* Clear all entries and bump the epoch. Call from HMR hooks and explicit
|
|
41
|
+
* host-app reset paths.
|
|
42
|
+
*/
|
|
43
|
+
reset(): void;
|
|
27
44
|
/**
|
|
28
45
|
* Emit a console warning for a missing key, deduplicating by key string.
|
|
29
46
|
*
|