vite-bundled-i18n 0.2.12 → 0.2.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/cli/index.js +3 -4
- package/dist/cli/index.js.map +1 -1
- package/dist/core/i18n-generated.d.ts +231 -0
- package/dist/core/types.d.ts +20 -36
- package/dist/plugin.js +5 -7
- package/dist/plugin.js.map +1 -1
- package/dist/{walker-B1niFoyW.js → walker-9pKaJgmJ.js} +13 -38
- package/dist/walker-9pKaJgmJ.js.map +1 -0
- package/package.json +1 -1
- package/dist/walker-B1niFoyW.js.map +0 -1
package/README.md
CHANGED
|
@@ -70,7 +70,7 @@ export default defineConfig({
|
|
|
70
70
|
locales: ['en', 'bg'],
|
|
71
71
|
defaultLocale: 'en',
|
|
72
72
|
generatedOutDir: '.i18n',
|
|
73
|
-
//
|
|
73
|
+
// types are generated to src/core/i18n-generated.ts by default
|
|
74
74
|
}),
|
|
75
75
|
],
|
|
76
76
|
})
|
package/dist/cli/index.js
CHANGED
|
@@ -1,15 +1,14 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { a as writeTypes, i as generateReports, n as compileAll, r as flattenLocaleKeys, s as generateBundles, t as walkAll } from "../walker-
|
|
2
|
+
import { a as writeTypes, i as generateReports, n as compileAll, r as flattenLocaleKeys, s as generateBundles, t as walkAll } from "../walker-9pKaJgmJ.js";
|
|
3
3
|
import fs from "node:fs";
|
|
4
4
|
import path from "node:path";
|
|
5
5
|
//#region src/cli/commands.ts
|
|
6
6
|
function resolveConfig(config) {
|
|
7
7
|
const rootDir = config.rootDir ?? process.cwd();
|
|
8
|
-
const outDir = config.outDir ?? path.join(rootDir, ".i18n");
|
|
9
8
|
return {
|
|
10
9
|
rootDir,
|
|
11
|
-
outDir,
|
|
12
|
-
typesOutPath: config.typesOutPath ?? path.join(
|
|
10
|
+
outDir: config.outDir ?? path.join(rootDir, ".i18n"),
|
|
11
|
+
typesOutPath: config.typesOutPath ?? path.join(rootDir, "src", "core", "i18n-generated.ts"),
|
|
13
12
|
localesDir: path.isAbsolute(config.localesDir) ? config.localesDir : path.join(rootDir, config.localesDir),
|
|
14
13
|
extractionScope: config.extractionScope ?? "global"
|
|
15
14
|
};
|
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}\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.d.ts');\n const localesDir = path.isAbsolute(config.localesDir)\n ? config.localesDir\n : path.join(rootDir, config.localesDir);\n const extractionScope = config.extractionScope ?? 'global';\n\n return { rootDir, outDir, typesOutPath, localesDir, extractionScope } as const;\n}\n\nfunction runWalker(config: CliConfig): ProjectAnalysis {\n const { rootDir, localesDir, extractionScope } = resolveConfig(config);\n\n return walkAll({\n pages: config.pages,\n rootDir,\n localesDir,\n defaultLocale: config.defaultLocale,\n extractionScope,\n });\n}\n\n/**\n * Pad a string to the given width.\n */\nfunction pad(str: string, width: number): string {\n return str + ' '.repeat(Math.max(0, width - str.length));\n}\n\n/**\n * Print a simple ASCII table to stdout.\n */\nfunction printTable(\n headers: string[],\n rows: string[][],\n): void {\n const colWidths = headers.map((h, i) =>\n Math.max(h.length, ...rows.map((r) => (r[i] ?? '').length)),\n );\n\n const sep =\n '\\u250c' +\n colWidths.map((w) => '\\u2500'.repeat(w + 2)).join('\\u252c') +\n '\\u2510';\n const mid =\n '\\u251c' +\n colWidths.map((w) => '\\u2500'.repeat(w + 2)).join('\\u253c') +\n '\\u2524';\n const bot =\n '\\u2514' +\n colWidths.map((w) => '\\u2500'.repeat(w + 2)).join('\\u2534') +\n '\\u2518';\n\n const formatRow = (cells: string[]) =>\n '\\u2502' +\n cells.map((c, i) => ' ' + pad(c, colWidths[i]) + ' ').join('\\u2502') +\n '\\u2502';\n\n console.log(sep);\n console.log(formatRow(headers));\n console.log(mid);\n for (const row of rows) {\n console.log(formatRow(row));\n }\n console.log(bot);\n}\n\n/**\n * Run the walker and print a summary table to stdout.\n * Returns the ProjectAnalysis for programmatic use.\n */\nexport function analyze(config: CliConfig): ProjectAnalysis {\n const { localesDir } = resolveConfig(config);\n const analysis = runWalker(config);\n\n const availableKeys = flattenLocaleKeys(localesDir, config.defaultLocale);\n const totalAvailable = Array.from(availableKeys.values()).reduce(\n (sum, keys) => sum + keys.length,\n 0,\n );\n\n const rows = analysis.routes.map((route) => {\n const usedCount = route.keys.filter((k) => !k.dynamic).length;\n return [\n route.routeId,\n String(usedCount),\n String(totalAvailable),\n String(totalAvailable - usedCount),\n ];\n });\n\n printTable(['Route', 'Used Keys', 'Available', 'Pruned'], rows);\n\n console.log(\n `\\n${analysis.routes.length} route(s), ${analysis.allKeys.length} unique key(s), ${analysis.availableNamespaces.length} namespace(s)`,\n );\n\n return analysis;\n}\n\n/**\n * Run the walker, then generate bundles and types.\n * Prints what was generated to stdout.\n */\nexport function generate(config: CliConfig): void {\n const { outDir, typesOutPath, localesDir } = resolveConfig(config);\n const analysis = runWalker(config);\n\n const bundles = generateBundles(analysis, {\n localesDir,\n locales: config.locales,\n outDir,\n });\n\n writeTypes(localesDir, config.defaultLocale, typesOutPath);\n\n console.log(`Generated ${bundles.length} bundle(s):`);\n for (const b of bundles) {\n console.log(` ${b.locale}/${b.name} — ${b.keyCount} keys (${b.prunedCount} pruned)`);\n }\n console.log(`Types written to ${typesOutPath}`);\n}\n\n/**\n * Run the walker, then generate diagnostic reports.\n * Prints summary to stdout.\n */\nexport function report(config: CliConfig): void {\n const { outDir, localesDir } = resolveConfig(config);\n const analysis = runWalker(config);\n\n generateReports(analysis, localesDir, config.defaultLocale, outDir, config.dictionaries);\n\n console.log(`Reports written to ${outDir}:`);\n console.log(' manifest.json');\n console.log(' missing.json');\n console.log(' unused.json');\n console.log(' stats.json');\n}\n\n/**\n * Run the walker, then compile pre-resolved flat Map modules.\n * Prints a summary to stdout.\n */\nexport function compile(config: CliConfig): void {\n const { outDir, localesDir } = resolveConfig(config);\n const analysis = runWalker(config);\n const compiledOutDir = path.join(outDir, 'compiled');\n\n compileAll(analysis, {\n localesDir,\n locales: config.locales,\n defaultLocale: config.defaultLocale,\n outDir: compiledOutDir,\n dictionaries: config.dictionaries,\n });\n\n // Count generated modules: one per route per locale, plus dictionary modules\n const routeModules = analysis.routes.length * config.locales.length;\n const dictModules =\n config.dictionaries && Object.keys(config.dictionaries).length > 0\n ? config.locales.length\n : 0;\n const total = routeModules + dictModules + 1; // +1 for manifest\n\n console.log(`Compiled ${total} module(s) to ${compiledOutDir}`);\n}\n\n/**\n * Run analyze + generate + compile + report all at once.\n */\nexport function build(config: CliConfig): void {\n const { outDir, typesOutPath, localesDir } = resolveConfig(config);\n const analysis = runWalker(config);\n\n // Analyze: print table\n const availableKeys = flattenLocaleKeys(localesDir, config.defaultLocale);\n const totalAvailable = Array.from(availableKeys.values()).reduce(\n (sum, keys) => sum + keys.length,\n 0,\n );\n\n const rows = analysis.routes.map((route) => {\n const usedCount = route.keys.filter((k) => !k.dynamic).length;\n return [\n route.routeId,\n String(usedCount),\n String(totalAvailable),\n String(totalAvailable - usedCount),\n ];\n });\n\n printTable(['Route', 'Used Keys', 'Available', 'Pruned'], rows);\n\n // Generate bundles + types\n const bundles = generateBundles(analysis, {\n localesDir,\n locales: config.locales,\n outDir,\n });\n\n writeTypes(localesDir, config.defaultLocale, typesOutPath);\n\n console.log(`\\nGenerated ${bundles.length} bundle(s)`);\n console.log(`Types written to ${typesOutPath}`);\n\n // Compile\n const compiledOutDir = path.join(outDir, 'compiled');\n compileAll(analysis, {\n localesDir,\n locales: config.locales,\n defaultLocale: config.defaultLocale,\n outDir: compiledOutDir,\n dictionaries: config.dictionaries,\n });\n console.log(`Compiled modules written to ${compiledOutDir}`);\n\n // Reports\n generateReports(analysis, localesDir, config.defaultLocale, outDir, config.dictionaries);\n\n console.log(`Reports written to ${outDir}`);\n console.log(\n `\\nDone. ${analysis.routes.length} route(s), ${analysis.allKeys.length} unique key(s).`,\n );\n}\n","#!/usr/bin/env node\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport { analyze, generate, compile, report, build } from './commands';\nimport type { CliConfig } from './commands';\n\nconst COMMANDS = ['analyze', 'generate', 'compile', 'report', 'build'] as const;\ntype Command = (typeof COMMANDS)[number];\n\nfunction printUsage(): void {\n console.log('Usage: vite-bundled-i18n <command> [--config <path>]');\n console.log('');\n console.log('Commands:');\n console.log(' analyze — Walk imports and print a summary of key usage per route');\n console.log(' generate — Generate tree-shaken bundles and TypeScript types');\n console.log(' report — Generate diagnostic reports (manifest, missing, unused, stats)');\n console.log(' compile — Compile pre-resolved flat Map modules for production');\n console.log(' build — Run analyze + generate + compile + report in one step');\n console.log('');\n console.log('Options:');\n console.log(' --config <path> Path to config file (default: i18n.config.json)');\n}\n\nfunction loadConfig(configPath: string): CliConfig {\n const resolved = path.resolve(configPath);\n if (!fs.existsSync(resolved)) {\n console.error(`Config file not found: ${resolved}`);\n process.exit(1);\n }\n\n const raw = fs.readFileSync(resolved, 'utf-8');\n return JSON.parse(raw) as CliConfig;\n}\n\nfunction parseArgs(argv: string[]): { command: Command; configPath: string } {\n const args = argv.slice(2);\n let command: Command | undefined;\n let configPath = 'i18n.config.json';\n\n for (let i = 0; i < args.length; i++) {\n const arg = args[i];\n if (arg === '--config' && i + 1 < args.length) {\n configPath = args[++i];\n } else if (arg === '--help' || arg === '-h') {\n printUsage();\n process.exit(0);\n } else if (!command && COMMANDS.includes(arg as Command)) {\n command = arg as Command;\n } else {\n console.error(`Unknown argument: ${arg}`);\n printUsage();\n process.exit(1);\n }\n }\n\n if (!command) {\n printUsage();\n process.exit(1);\n }\n\n return { command: command!, configPath };\n}\n\nconst { command, configPath } = parseArgs(process.argv);\nconst config = loadConfig(configPath);\n\nconst commands: Record<Command, (cfg: CliConfig) => void> = {\n analyze,\n generate,\n compile,\n report,\n build,\n};\n\ncommands[command](config);\n"],"mappings":";;;;;AA+BA,SAAS,cAAc,QAAmB;CACxC,MAAM,UAAU,OAAO,WAAW,QAAQ,KAAK;CAC/C,MAAM,SAAS,OAAO,UAAU,KAAK,KAAK,SAAS,QAAQ;AAQ3D,QAAO;EAAE;EAAS;EAAQ,cANxB,OAAO,gBAAgB,KAAK,KAAK,QAAQ,YAAY;EAMf,YALrB,KAAK,WAAW,OAAO,WAAW,GACjD,OAAO,aACP,KAAK,KAAK,SAAS,OAAO,WAAW;EAGW,iBAF5B,OAAO,mBAAmB;EAEmB;;AAGvE,SAAS,UAAU,QAAoC;CACrD,MAAM,EAAE,SAAS,YAAY,oBAAoB,cAAc,OAAO;AAEtE,QAAO,QAAQ;EACb,OAAO,OAAO;EACd;EACA;EACA,eAAe,OAAO;EACtB;EACD,CAAC;;;;;AAMJ,SAAS,IAAI,KAAa,OAAuB;AAC/C,QA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"file":"index.js","names":[],"sources":["../../src/cli/commands.ts","../../src/cli/index.ts"],"sourcesContent":["import path from 'node:path';\nimport { walkAll } from '../extractor/walker';\nimport { generateBundles } from '../extractor/bundle-generator';\nimport { writeTypes } from '../extractor/type-generator';\nimport { generateReports } from '../extractor/reports';\nimport { compileAll } from '../extractor/compiler';\nimport type { ProjectAnalysis } from '../extractor/walker-types';\nimport type { DictionaryConfig } from '../core/types';\nimport { flattenLocaleKeys } from '../extractor/reports';\n\nexport interface CliConfig {\n /** Glob patterns for page entry points. */\n pages: string[];\n /** Locales directory (relative to rootDir). */\n localesDir: string;\n /** All supported locale codes. */\n locales: string[];\n /** Default locale. */\n defaultLocale: string;\n /** Root directory. Defaults to process.cwd(). */\n rootDir?: string;\n /** Output directory for generated bundles. Defaults to '.i18n'. */\n outDir?: string;\n /** Output path for generated types. Defaults to '.i18n/i18n.d.ts'. */\n typesOutPath?: string;\n /** Extraction scope. Defaults to 'global'. */\n extractionScope?: 'global' | 'scoped';\n /** Optional dictionary configurations for compiled mode. */\n dictionaries?: Record<string, DictionaryConfig>;\n}\n\nfunction resolveConfig(config: CliConfig) {\n const rootDir = config.rootDir ?? process.cwd();\n const outDir = config.outDir ?? path.join(rootDir, '.i18n');\n const typesOutPath =\n config.typesOutPath ?? path.join(rootDir, 'src', 'core', 'i18n-generated.ts');\n const localesDir = path.isAbsolute(config.localesDir)\n ? config.localesDir\n : path.join(rootDir, config.localesDir);\n const extractionScope = config.extractionScope ?? 'global';\n\n return { rootDir, outDir, typesOutPath, localesDir, extractionScope } as const;\n}\n\nfunction runWalker(config: CliConfig): ProjectAnalysis {\n const { rootDir, localesDir, extractionScope } = resolveConfig(config);\n\n return walkAll({\n pages: config.pages,\n rootDir,\n localesDir,\n defaultLocale: config.defaultLocale,\n extractionScope,\n });\n}\n\n/**\n * Pad a string to the given width.\n */\nfunction pad(str: string, width: number): string {\n return str + ' '.repeat(Math.max(0, width - str.length));\n}\n\n/**\n * Print a simple ASCII table to stdout.\n */\nfunction printTable(\n headers: string[],\n rows: string[][],\n): void {\n const colWidths = headers.map((h, i) =>\n Math.max(h.length, ...rows.map((r) => (r[i] ?? '').length)),\n );\n\n const sep =\n '\\u250c' +\n colWidths.map((w) => '\\u2500'.repeat(w + 2)).join('\\u252c') +\n '\\u2510';\n const mid =\n '\\u251c' +\n colWidths.map((w) => '\\u2500'.repeat(w + 2)).join('\\u253c') +\n '\\u2524';\n const bot =\n '\\u2514' +\n colWidths.map((w) => '\\u2500'.repeat(w + 2)).join('\\u2534') +\n '\\u2518';\n\n const formatRow = (cells: string[]) =>\n '\\u2502' +\n cells.map((c, i) => ' ' + pad(c, colWidths[i]) + ' ').join('\\u2502') +\n '\\u2502';\n\n console.log(sep);\n console.log(formatRow(headers));\n console.log(mid);\n for (const row of rows) {\n console.log(formatRow(row));\n }\n console.log(bot);\n}\n\n/**\n * Run the walker and print a summary table to stdout.\n * Returns the ProjectAnalysis for programmatic use.\n */\nexport function analyze(config: CliConfig): ProjectAnalysis {\n const { localesDir } = resolveConfig(config);\n const analysis = runWalker(config);\n\n const availableKeys = flattenLocaleKeys(localesDir, config.defaultLocale);\n const totalAvailable = Array.from(availableKeys.values()).reduce(\n (sum, keys) => sum + keys.length,\n 0,\n );\n\n const rows = analysis.routes.map((route) => {\n const usedCount = route.keys.filter((k) => !k.dynamic).length;\n return [\n route.routeId,\n String(usedCount),\n String(totalAvailable),\n String(totalAvailable - usedCount),\n ];\n });\n\n printTable(['Route', 'Used Keys', 'Available', 'Pruned'], rows);\n\n console.log(\n `\\n${analysis.routes.length} route(s), ${analysis.allKeys.length} unique key(s), ${analysis.availableNamespaces.length} namespace(s)`,\n );\n\n return analysis;\n}\n\n/**\n * Run the walker, then generate bundles and types.\n * Prints what was generated to stdout.\n */\nexport function generate(config: CliConfig): void {\n const { outDir, typesOutPath, localesDir } = resolveConfig(config);\n const analysis = runWalker(config);\n\n const bundles = generateBundles(analysis, {\n localesDir,\n locales: config.locales,\n outDir,\n });\n\n writeTypes(localesDir, config.defaultLocale, typesOutPath);\n\n console.log(`Generated ${bundles.length} bundle(s):`);\n for (const b of bundles) {\n console.log(` ${b.locale}/${b.name} — ${b.keyCount} keys (${b.prunedCount} pruned)`);\n }\n console.log(`Types written to ${typesOutPath}`);\n}\n\n/**\n * Run the walker, then generate diagnostic reports.\n * Prints summary to stdout.\n */\nexport function report(config: CliConfig): void {\n const { outDir, localesDir } = resolveConfig(config);\n const analysis = runWalker(config);\n\n generateReports(analysis, localesDir, config.defaultLocale, outDir, config.dictionaries);\n\n console.log(`Reports written to ${outDir}:`);\n console.log(' manifest.json');\n console.log(' missing.json');\n console.log(' unused.json');\n console.log(' stats.json');\n}\n\n/**\n * Run the walker, then compile pre-resolved flat Map modules.\n * Prints a summary to stdout.\n */\nexport function compile(config: CliConfig): void {\n const { outDir, localesDir } = resolveConfig(config);\n const analysis = runWalker(config);\n const compiledOutDir = path.join(outDir, 'compiled');\n\n compileAll(analysis, {\n localesDir,\n locales: config.locales,\n defaultLocale: config.defaultLocale,\n outDir: compiledOutDir,\n dictionaries: config.dictionaries,\n });\n\n // Count generated modules: one per route per locale, plus dictionary modules\n const routeModules = analysis.routes.length * config.locales.length;\n const dictModules =\n config.dictionaries && Object.keys(config.dictionaries).length > 0\n ? config.locales.length\n : 0;\n const total = routeModules + dictModules + 1; // +1 for manifest\n\n console.log(`Compiled ${total} module(s) to ${compiledOutDir}`);\n}\n\n/**\n * Run analyze + generate + compile + report all at once.\n */\nexport function build(config: CliConfig): void {\n const { outDir, typesOutPath, localesDir } = resolveConfig(config);\n const analysis = runWalker(config);\n\n // Analyze: print table\n const availableKeys = flattenLocaleKeys(localesDir, config.defaultLocale);\n const totalAvailable = Array.from(availableKeys.values()).reduce(\n (sum, keys) => sum + keys.length,\n 0,\n );\n\n const rows = analysis.routes.map((route) => {\n const usedCount = route.keys.filter((k) => !k.dynamic).length;\n return [\n route.routeId,\n String(usedCount),\n String(totalAvailable),\n String(totalAvailable - usedCount),\n ];\n });\n\n printTable(['Route', 'Used Keys', 'Available', 'Pruned'], rows);\n\n // Generate bundles + types\n const bundles = generateBundles(analysis, {\n localesDir,\n locales: config.locales,\n outDir,\n });\n\n writeTypes(localesDir, config.defaultLocale, typesOutPath);\n\n console.log(`\\nGenerated ${bundles.length} bundle(s)`);\n console.log(`Types written to ${typesOutPath}`);\n\n // Compile\n const compiledOutDir = path.join(outDir, 'compiled');\n compileAll(analysis, {\n localesDir,\n locales: config.locales,\n defaultLocale: config.defaultLocale,\n outDir: compiledOutDir,\n dictionaries: config.dictionaries,\n });\n console.log(`Compiled modules written to ${compiledOutDir}`);\n\n // Reports\n generateReports(analysis, localesDir, config.defaultLocale, outDir, config.dictionaries);\n\n console.log(`Reports written to ${outDir}`);\n console.log(\n `\\nDone. ${analysis.routes.length} route(s), ${analysis.allKeys.length} unique key(s).`,\n );\n}\n","#!/usr/bin/env node\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport { analyze, generate, compile, report, build } from './commands';\nimport type { CliConfig } from './commands';\n\nconst COMMANDS = ['analyze', 'generate', 'compile', 'report', 'build'] as const;\ntype Command = (typeof COMMANDS)[number];\n\nfunction printUsage(): void {\n console.log('Usage: vite-bundled-i18n <command> [--config <path>]');\n console.log('');\n console.log('Commands:');\n console.log(' analyze — Walk imports and print a summary of key usage per route');\n console.log(' generate — Generate tree-shaken bundles and TypeScript types');\n console.log(' report — Generate diagnostic reports (manifest, missing, unused, stats)');\n console.log(' compile — Compile pre-resolved flat Map modules for production');\n console.log(' build — Run analyze + generate + compile + report in one step');\n console.log('');\n console.log('Options:');\n console.log(' --config <path> Path to config file (default: i18n.config.json)');\n}\n\nfunction loadConfig(configPath: string): CliConfig {\n const resolved = path.resolve(configPath);\n if (!fs.existsSync(resolved)) {\n console.error(`Config file not found: ${resolved}`);\n process.exit(1);\n }\n\n const raw = fs.readFileSync(resolved, 'utf-8');\n return JSON.parse(raw) as CliConfig;\n}\n\nfunction parseArgs(argv: string[]): { command: Command; configPath: string } {\n const args = argv.slice(2);\n let command: Command | undefined;\n let configPath = 'i18n.config.json';\n\n for (let i = 0; i < args.length; i++) {\n const arg = args[i];\n if (arg === '--config' && i + 1 < args.length) {\n configPath = args[++i];\n } else if (arg === '--help' || arg === '-h') {\n printUsage();\n process.exit(0);\n } else if (!command && COMMANDS.includes(arg as Command)) {\n command = arg as Command;\n } else {\n console.error(`Unknown argument: ${arg}`);\n printUsage();\n process.exit(1);\n }\n }\n\n if (!command) {\n printUsage();\n process.exit(1);\n }\n\n return { command: command!, configPath };\n}\n\nconst { command, configPath } = parseArgs(process.argv);\nconst config = loadConfig(configPath);\n\nconst commands: Record<Command, (cfg: CliConfig) => void> = {\n analyze,\n generate,\n compile,\n report,\n build,\n};\n\ncommands[command](config);\n"],"mappings":";;;;;AA+BA,SAAS,cAAc,QAAmB;CACxC,MAAM,UAAU,OAAO,WAAW,QAAQ,KAAK;AAS/C,QAAO;EAAE;EAAS,QARH,OAAO,UAAU,KAAK,KAAK,SAAS,QAAQ;EAQjC,cANxB,OAAO,gBAAgB,KAAK,KAAK,SAAS,OAAO,QAAQ,oBAAoB;EAMvC,YALrB,KAAK,WAAW,OAAO,WAAW,GACjD,OAAO,aACP,KAAK,KAAK,SAAS,OAAO,WAAW;EAGW,iBAF5B,OAAO,mBAAmB;EAEmB;;AAGvE,SAAS,UAAU,QAAoC;CACrD,MAAM,EAAE,SAAS,YAAY,oBAAoB,cAAc,OAAO;AAEtE,QAAO,QAAQ;EACb,OAAO,OAAO;EACd;EACA;EACA,eAAe,OAAO;EACtB;EACD,CAAC;;;;;AAMJ,SAAS,IAAI,KAAa,OAAuB;AAC/C,QAAO,MAAM,IAAI,OAAO,KAAK,IAAI,GAAG,QAAQ,IAAI,OAAO,CAAC;;;;;AAM1D,SAAS,WACP,SACA,MACM;CACN,MAAM,YAAY,QAAQ,KAAK,GAAG,MAChC,KAAK,IAAI,EAAE,QAAQ,GAAG,KAAK,KAAK,OAAO,EAAE,MAAM,IAAI,OAAO,CAAC,CAC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,SAAQ,IAAI,GAAG;AACf,SAAQ,IAAI,WAAW;AACvB,SAAQ,IAAI,qEAAqE;;AAGnF,SAAS,WAAW,YAA+B;CACjD,MAAM,WAAW,KAAK,QAAQ,WAAW;AACzC,KAAI,CAAC,GAAG,WAAW,SAAS,EAAE;AAC5B,UAAQ,MAAM,0BAA0B,WAAW;AACnD,UAAQ,KAAK,EAAE;;CAGjB,MAAM,MAAM,GAAG,aAAa,UAAU,QAAQ;AAC9C,QAAO,KAAK,MAAM,IAAI;;AAGxB,SAAS,UAAU,MAA0D;CAC3E,MAAM,OAAO,KAAK,MAAM,EAAE;CAC1B,IAAI;CACJ,IAAI,aAAa;AAEjB,MAAK,IAAI,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK;EACpC,MAAM,MAAM,KAAK;AACjB,MAAI,QAAQ,cAAc,IAAI,IAAI,KAAK,OACrC,cAAa,KAAK,EAAE;WACX,QAAQ,YAAY,QAAQ,MAAM;AAC3C,eAAY;AACZ,WAAQ,KAAK,EAAE;aACN,CAAC,WAAW,SAAS,SAAS,IAAe,CACtD,WAAU;OACL;AACL,WAAQ,MAAM,qBAAqB,MAAM;AACzC,eAAY;AACZ,WAAQ,KAAK,EAAE;;;AAInB,KAAI,CAAC,SAAS;AACZ,cAAY;AACZ,UAAQ,KAAK,EAAE;;AAGjB,QAAO;EAAW;EAAU;EAAY;;AAG1C,IAAM,EAAE,SAAS,eAAe,UAAU,QAAQ,KAAK;AACvD,IAAM,SAAS,WAAW,WAAW;CAEuB;CAC1D;CACA;CACA;CACA;CACA;CACD,EAEQ,SAAS,OAAO"}
|
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
type TranslationValue = string | number | boolean | bigint | null | undefined;
|
|
2
|
+
export interface I18nNestedKeys {
|
|
3
|
+
'account': {
|
|
4
|
+
'addresses': {
|
|
5
|
+
'addNew': true;
|
|
6
|
+
'default': true;
|
|
7
|
+
'heading': true;
|
|
8
|
+
'setDefault': true;
|
|
9
|
+
};
|
|
10
|
+
'orders': {
|
|
11
|
+
'empty': true;
|
|
12
|
+
'heading': true;
|
|
13
|
+
'orderNumber': true;
|
|
14
|
+
'placedOn': true;
|
|
15
|
+
'reorder': true;
|
|
16
|
+
'status': {
|
|
17
|
+
'cancelled': true;
|
|
18
|
+
'delivered': true;
|
|
19
|
+
'pending': true;
|
|
20
|
+
'processing': true;
|
|
21
|
+
'shipped': true;
|
|
22
|
+
};
|
|
23
|
+
'trackOrder': true;
|
|
24
|
+
};
|
|
25
|
+
'profile': {
|
|
26
|
+
'changePassword': true;
|
|
27
|
+
'confirmPassword': true;
|
|
28
|
+
'currentPassword': true;
|
|
29
|
+
'email': true;
|
|
30
|
+
'heading': true;
|
|
31
|
+
'name': true;
|
|
32
|
+
'newPassword': true;
|
|
33
|
+
'personalInfo': true;
|
|
34
|
+
'phone': true;
|
|
35
|
+
'updated': true;
|
|
36
|
+
};
|
|
37
|
+
};
|
|
38
|
+
'actions': {
|
|
39
|
+
'addToCart': true;
|
|
40
|
+
'applyFilter': true;
|
|
41
|
+
'checkout': true;
|
|
42
|
+
'clearFilters': true;
|
|
43
|
+
'create': true;
|
|
44
|
+
'delete': true;
|
|
45
|
+
'edit': true;
|
|
46
|
+
'register': true;
|
|
47
|
+
'removeFromCart': true;
|
|
48
|
+
'save': true;
|
|
49
|
+
'signIn': true;
|
|
50
|
+
'signOut': true;
|
|
51
|
+
'sortBy': true;
|
|
52
|
+
'submit': true;
|
|
53
|
+
'update': true;
|
|
54
|
+
'viewDetails': true;
|
|
55
|
+
};
|
|
56
|
+
'cart': {
|
|
57
|
+
'empty': true;
|
|
58
|
+
'emptyAction': true;
|
|
59
|
+
'item': {
|
|
60
|
+
'moveToWishlist': true;
|
|
61
|
+
'priceEach': true;
|
|
62
|
+
'quantity': true;
|
|
63
|
+
'remove': true;
|
|
64
|
+
};
|
|
65
|
+
'promoCode': {
|
|
66
|
+
'applied': true;
|
|
67
|
+
'apply': true;
|
|
68
|
+
'invalid': true;
|
|
69
|
+
'label': true;
|
|
70
|
+
'placeholder': true;
|
|
71
|
+
};
|
|
72
|
+
'summary': {
|
|
73
|
+
'estimatedDelivery': true;
|
|
74
|
+
'freeShipping': true;
|
|
75
|
+
'shipping': true;
|
|
76
|
+
'subtotal': true;
|
|
77
|
+
'tax': true;
|
|
78
|
+
'total': true;
|
|
79
|
+
};
|
|
80
|
+
'title': true;
|
|
81
|
+
};
|
|
82
|
+
'global': {
|
|
83
|
+
'appName': true;
|
|
84
|
+
'footer': {
|
|
85
|
+
'contact': true;
|
|
86
|
+
'madeWith': true;
|
|
87
|
+
'privacy': true;
|
|
88
|
+
'terms': true;
|
|
89
|
+
'version': true;
|
|
90
|
+
};
|
|
91
|
+
'meta': {
|
|
92
|
+
'description': true;
|
|
93
|
+
'title': true;
|
|
94
|
+
};
|
|
95
|
+
'nav': {
|
|
96
|
+
'about': true;
|
|
97
|
+
'account': true;
|
|
98
|
+
'cart': true;
|
|
99
|
+
'home': true;
|
|
100
|
+
'products': true;
|
|
101
|
+
};
|
|
102
|
+
'tagline': true;
|
|
103
|
+
};
|
|
104
|
+
'products': {
|
|
105
|
+
'index': {
|
|
106
|
+
'empty': true;
|
|
107
|
+
'filters': {
|
|
108
|
+
'category': true;
|
|
109
|
+
'featured': true;
|
|
110
|
+
'inStock': true;
|
|
111
|
+
'priceRange': true;
|
|
112
|
+
};
|
|
113
|
+
'heading': true;
|
|
114
|
+
'sort': {
|
|
115
|
+
'newest': true;
|
|
116
|
+
'popular': true;
|
|
117
|
+
'priceAsc': true;
|
|
118
|
+
'priceDesc': true;
|
|
119
|
+
};
|
|
120
|
+
'subheading': true;
|
|
121
|
+
};
|
|
122
|
+
'reviews': {
|
|
123
|
+
'averageRating': true;
|
|
124
|
+
'heading': true;
|
|
125
|
+
'helpful': true;
|
|
126
|
+
'noReviews': true;
|
|
127
|
+
'reported': true;
|
|
128
|
+
'reviewCount': true;
|
|
129
|
+
'writeReview': true;
|
|
130
|
+
};
|
|
131
|
+
'show': {
|
|
132
|
+
'availability': {
|
|
133
|
+
'backorder': true;
|
|
134
|
+
'inStock': true;
|
|
135
|
+
'outOfStock': true;
|
|
136
|
+
};
|
|
137
|
+
'description': true;
|
|
138
|
+
'discount': true;
|
|
139
|
+
'originalPrice': true;
|
|
140
|
+
'price': true;
|
|
141
|
+
'relatedProducts': true;
|
|
142
|
+
'sku': true;
|
|
143
|
+
'tabs': {
|
|
144
|
+
'description': true;
|
|
145
|
+
'reviews': true;
|
|
146
|
+
'specifications': true;
|
|
147
|
+
};
|
|
148
|
+
'title': true;
|
|
149
|
+
};
|
|
150
|
+
};
|
|
151
|
+
'shared': {
|
|
152
|
+
'backToHome': true;
|
|
153
|
+
'cancel': true;
|
|
154
|
+
'close': true;
|
|
155
|
+
'confirm': true;
|
|
156
|
+
'copyright': true;
|
|
157
|
+
'error': true;
|
|
158
|
+
'loading': true;
|
|
159
|
+
'next': true;
|
|
160
|
+
'no': true;
|
|
161
|
+
'noResults': true;
|
|
162
|
+
'ok': true;
|
|
163
|
+
'previous': true;
|
|
164
|
+
'retry': true;
|
|
165
|
+
'search': true;
|
|
166
|
+
'yes': true;
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
export interface I18nParamsMap {
|
|
170
|
+
'account.orders.orderNumber': {
|
|
171
|
+
number: TranslationValue;
|
|
172
|
+
};
|
|
173
|
+
'account.orders.placedOn': {
|
|
174
|
+
date: TranslationValue;
|
|
175
|
+
};
|
|
176
|
+
'actions.sortBy': {
|
|
177
|
+
field: TranslationValue;
|
|
178
|
+
};
|
|
179
|
+
'cart.summary.estimatedDelivery': {
|
|
180
|
+
date: TranslationValue;
|
|
181
|
+
};
|
|
182
|
+
'cart.item.quantity': {
|
|
183
|
+
count: TranslationValue;
|
|
184
|
+
};
|
|
185
|
+
'cart.item.priceEach': {
|
|
186
|
+
amount: TranslationValue;
|
|
187
|
+
};
|
|
188
|
+
'cart.promoCode.applied': {
|
|
189
|
+
code: TranslationValue;
|
|
190
|
+
discount: TranslationValue;
|
|
191
|
+
};
|
|
192
|
+
'global.footer.madeWith': {
|
|
193
|
+
framework: TranslationValue;
|
|
194
|
+
};
|
|
195
|
+
'global.footer.version': {
|
|
196
|
+
version: TranslationValue;
|
|
197
|
+
};
|
|
198
|
+
'global.meta.title': {
|
|
199
|
+
page: TranslationValue;
|
|
200
|
+
};
|
|
201
|
+
'products.index.subheading': {
|
|
202
|
+
count: TranslationValue;
|
|
203
|
+
};
|
|
204
|
+
'products.show.price': {
|
|
205
|
+
amount: TranslationValue;
|
|
206
|
+
};
|
|
207
|
+
'products.show.originalPrice': {
|
|
208
|
+
amount: TranslationValue;
|
|
209
|
+
};
|
|
210
|
+
'products.show.discount': {
|
|
211
|
+
percent: TranslationValue;
|
|
212
|
+
};
|
|
213
|
+
'products.show.sku': {
|
|
214
|
+
code: TranslationValue;
|
|
215
|
+
};
|
|
216
|
+
'products.show.availability.inStock': {
|
|
217
|
+
count: TranslationValue;
|
|
218
|
+
};
|
|
219
|
+
'products.show.tabs.reviews': {
|
|
220
|
+
count: TranslationValue;
|
|
221
|
+
};
|
|
222
|
+
'products.reviews.averageRating': {
|
|
223
|
+
rating: TranslationValue;
|
|
224
|
+
};
|
|
225
|
+
'products.reviews.reviewCount': {
|
|
226
|
+
count: TranslationValue;
|
|
227
|
+
};
|
|
228
|
+
}
|
|
229
|
+
export interface I18nScopeMap {
|
|
230
|
+
}
|
|
231
|
+
export {};
|
package/dist/core/types.d.ts
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import type { CompiledManifestModule } from './compiled-runtime';
|
|
2
|
+
import type { I18nNestedKeys, I18nParamsMap, I18nScopeMap } from './i18n-generated';
|
|
3
|
+
export type { I18nNestedKeys, I18nParamsMap, I18nScopeMap, };
|
|
2
4
|
/**
|
|
3
5
|
* Recursive type representing nested translation JSON.
|
|
4
6
|
* Leaf values are strings (the translated text).
|
|
@@ -39,27 +41,6 @@ export type NestedTranslations = {
|
|
|
39
41
|
*/
|
|
40
42
|
export interface I18nKeyMap {
|
|
41
43
|
}
|
|
42
|
-
/**
|
|
43
|
-
* Augmentable interface mapping fully qualified translation keys to their
|
|
44
|
-
* placeholder parameter objects. Generated alongside {@link I18nKeyMap}.
|
|
45
|
-
*
|
|
46
|
-
* Keys with no placeholders should map to `{}`.
|
|
47
|
-
*/
|
|
48
|
-
export interface I18nParamsMap {
|
|
49
|
-
}
|
|
50
|
-
/**
|
|
51
|
-
* Augmentable interface for nested key structure.
|
|
52
|
-
* Enables progressive autocomplete: typing `t('feedback.` suggests
|
|
53
|
-
* `pages`, `actions`, etc. as next segments.
|
|
54
|
-
*/
|
|
55
|
-
export interface I18nNestedKeys {
|
|
56
|
-
}
|
|
57
|
-
/**
|
|
58
|
-
* Augmentable interface for valid scope identifiers.
|
|
59
|
-
* When populated by the type generator, constrains `useI18n(scope)` to valid scopes.
|
|
60
|
-
*/
|
|
61
|
-
export interface I18nScopeMap {
|
|
62
|
-
}
|
|
63
44
|
/**
|
|
64
45
|
* Resolves to the union of registered scope identifiers when `I18nScopeMap`
|
|
65
46
|
* has entries, or falls back to `string` when it's empty.
|
|
@@ -96,22 +77,20 @@ export type Primitive = string | number | boolean | bigint | null | undefined;
|
|
|
96
77
|
* before generated types exist.
|
|
97
78
|
*/
|
|
98
79
|
export type ParamsOf<K extends TranslationKey> = K extends keyof I18nParamsMap ? I18nParamsMap[K] : Record<string, Primitive>;
|
|
99
|
-
type TranslateArgs<K extends TranslationKey> = K extends keyof I18nParamsMap ? keyof I18nParamsMap[K] extends never ? [fallback?: string] : [params: I18nParamsMap[K], fallback?: string] : [fallback?: string] | [params: Record<string, unknown>, fallback?: string];
|
|
100
80
|
/**
|
|
101
|
-
* Translation function
|
|
102
|
-
*
|
|
103
|
-
* Supports two calling conventions:
|
|
104
|
-
* - `t(key, fallback?)` — when no interpolation is needed
|
|
105
|
-
* - `t(key, params, fallback?)` — when interpolation parameters are needed
|
|
81
|
+
* Translation function.
|
|
106
82
|
*
|
|
107
|
-
*
|
|
108
|
-
*
|
|
83
|
+
* - `t(key)` or `t(key, fallback)` — for keys without placeholders
|
|
84
|
+
* - `t(key, params)` or `t(key, params, fallback)` — for keys with `{{placeholders}}`
|
|
109
85
|
*
|
|
110
|
-
*
|
|
111
|
-
* parameter is constrained to valid translation keys with full autocomplete.
|
|
112
|
-
* Without generated types, it accepts any `string`.
|
|
86
|
+
* Params are type-checked per key: `t('cart.total', { amount: 9 })` enforces `{ amount }`.
|
|
113
87
|
*/
|
|
114
|
-
export type TFunction =
|
|
88
|
+
export type TFunction = {
|
|
89
|
+
<K extends keyof I18nParamsMap>(key: K, params: I18nParamsMap[K]): string;
|
|
90
|
+
<K extends keyof I18nParamsMap>(key: K, params: I18nParamsMap[K], fallback: string): string;
|
|
91
|
+
(key: TranslationKey): string;
|
|
92
|
+
(key: TranslationKey, fallback: string): string;
|
|
93
|
+
};
|
|
115
94
|
/**
|
|
116
95
|
* Translation function for scoped/namespace-relative keys.
|
|
117
96
|
* Accepts any string since scoped keys are relative to the namespace
|
|
@@ -130,7 +109,10 @@ export type ScopedTFunction = {
|
|
|
130
109
|
* Unlike {@link TFunction}, this function does not accept fallback strings
|
|
131
110
|
* and does not degrade to key-as-value.
|
|
132
111
|
*/
|
|
133
|
-
export type TryTFunction =
|
|
112
|
+
export type TryTFunction = {
|
|
113
|
+
<K extends keyof I18nParamsMap>(key: K, params: I18nParamsMap[K]): string | undefined;
|
|
114
|
+
(key: TranslationKey): string | undefined;
|
|
115
|
+
};
|
|
134
116
|
/**
|
|
135
117
|
* Namespace-relative version of {@link TryTFunction}.
|
|
136
118
|
*/
|
|
@@ -143,7 +125,10 @@ export type ScopedTryTFunction = {
|
|
|
143
125
|
*
|
|
144
126
|
* Like {@link TryTFunction}, this function does not accept fallback strings.
|
|
145
127
|
*/
|
|
146
|
-
export type RequireTFunction =
|
|
128
|
+
export type RequireTFunction = {
|
|
129
|
+
<K extends keyof I18nParamsMap>(key: K, params: I18nParamsMap[K]): string;
|
|
130
|
+
(key: TranslationKey): string;
|
|
131
|
+
};
|
|
147
132
|
/**
|
|
148
133
|
* Namespace-relative version of {@link RequireTFunction}.
|
|
149
134
|
*/
|
|
@@ -449,4 +434,3 @@ export interface UseI18nResult {
|
|
|
449
434
|
/** The currently active locale code. */
|
|
450
435
|
locale: string;
|
|
451
436
|
}
|
|
452
|
-
export {};
|
package/dist/plugin.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as writeTypes, c as pruneNamespace, i as generateReports, l as keyMatchesPattern, n as compileAll, o as flattenKeys, s as generateBundles, t as walkAll, u as normalizeDictionaries } from "./walker-
|
|
1
|
+
import { a as writeTypes, c as pruneNamespace, i as generateReports, l as keyMatchesPattern, n as compileAll, o as flattenKeys, s as generateBundles, t as walkAll, u as normalizeDictionaries } from "./walker-9pKaJgmJ.js";
|
|
2
2
|
import fs from "node:fs";
|
|
3
3
|
import path from "node:path";
|
|
4
4
|
//#region src/plugin/devPlugin.ts
|
|
@@ -66,7 +66,7 @@ function i18nDevPlugin(config, options) {
|
|
|
66
66
|
configureServer(server) {
|
|
67
67
|
const localesPath = path.join(projectRoot, config.localesDir);
|
|
68
68
|
const defaultLocale = options?.defaultLocale ?? "en";
|
|
69
|
-
const typesOutPath = options?.typesOutPath ? path.resolve(projectRoot, options.typesOutPath) : path.join(projectRoot, "
|
|
69
|
+
const typesOutPath = options?.typesOutPath ? path.resolve(projectRoot, options.typesOutPath) : path.join(projectRoot, "src", "core", "i18n-generated.ts");
|
|
70
70
|
function regenerateTypes() {
|
|
71
71
|
try {
|
|
72
72
|
writeTypes(localesPath, defaultLocale, typesOutPath);
|
|
@@ -112,12 +112,10 @@ function i18nDevPlugin(config, options) {
|
|
|
112
112
|
//#region src/plugin/buildPlugin.ts
|
|
113
113
|
function resolveBuildPaths(options) {
|
|
114
114
|
const { rootDir, viteOutDir, sharedConfig, buildConfig } = options;
|
|
115
|
-
const localesDir = path.isAbsolute(sharedConfig.localesDir) ? sharedConfig.localesDir : path.join(rootDir, sharedConfig.localesDir);
|
|
116
|
-
const generatedOutDir = buildConfig.generatedOutDir ? path.resolve(rootDir, buildConfig.generatedOutDir) : path.join(rootDir, ".i18n");
|
|
117
115
|
return {
|
|
118
|
-
localesDir,
|
|
119
|
-
generatedOutDir,
|
|
120
|
-
typesOutPath: buildConfig.typesOutPath ? path.resolve(rootDir, buildConfig.typesOutPath) : path.join(
|
|
116
|
+
localesDir: path.isAbsolute(sharedConfig.localesDir) ? sharedConfig.localesDir : path.join(rootDir, sharedConfig.localesDir),
|
|
117
|
+
generatedOutDir: buildConfig.generatedOutDir ? path.resolve(rootDir, buildConfig.generatedOutDir) : path.join(rootDir, ".i18n"),
|
|
118
|
+
typesOutPath: buildConfig.typesOutPath ? path.resolve(rootDir, buildConfig.typesOutPath) : path.join(rootDir, "src", "core", "i18n-generated.ts"),
|
|
121
119
|
assetsOutDir: path.join(viteOutDir, buildConfig.assetsDir ?? "__i18n"),
|
|
122
120
|
extractionScope: buildConfig.extractionScope ?? "global"
|
|
123
121
|
};
|
package/dist/plugin.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"plugin.js","names":[],"sources":["../src/plugin/devPlugin.ts","../src/plugin/buildPlugin.ts","../src/plugin.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\nimport type { Plugin } from 'vite';\nimport { flattenKeys, pruneNamespace } from '../extractor/bundle-generator';\nimport { keyMatchesPattern, normalizeDictionaries } from '../extractor/dictionary-ownership';\nimport { writeTypes } from '../extractor/type-generator';\nimport type { I18nSharedConfig } from '../core/config';\n\n/**\n * Configuration for the i18n dev plugin.\n */\nexport type I18nDevPluginConfig = I18nSharedConfig;\n\n/**\n * Vite dev plugin that serves combined translation bundles.\n *\n * Instead of the browser making N separate HTTP requests for N namespace\n * files, this plugin intercepts requests to `/__i18n/` and serves all\n * requested namespaces combined into a single JSON response.\n *\n * Three types of bundles:\n *\n * **Named dictionary bundle** (`/__i18n/{locale}/_dict/{name}.json`):\n * Loads only the namespaces belonging to a specific named dictionary.\n * Each dictionary is loaded independently with its own priority.\n *\n * **Scope bundle** (`/__i18n/{locale}/{scope}.json`):\n * Loads the namespace inferred from the scope's first segment. For example,\n * `/__i18n/en/products.show.json` reads `locales/en/products.json` and\n * returns `{ \"products\": { ... } }`.\n *\n * In production (Group 2+), the Vite build plugin will generate these bundles\n * statically with tree-shaking. This dev plugin is the runtime equivalent —\n * same URL pattern, no tree-shaking, but demonstrates the loading strategy.\n *\n * @param config - Plugin configuration\n * @returns A Vite plugin\n *\n * @example\n * ```ts\n * // vite.config.ts\n * import { i18nDevPlugin } from './src/plugin/devPlugin';\n *\n * export default defineConfig({\n * plugins: [\n * react(),\n * i18nDevPlugin({\n * localesDir: 'locales',\n * dictionaries: {\n * global: { keys: ['shared', 'global', 'actions'] },\n * admin: { keys: ['admin'] },\n * },\n * }),\n * ],\n * });\n * ```\n */\nexport interface I18nDevPluginOptions {\n assetsDir?: string;\n /** Default locale for type generation. Required for dev-time autocomplete. */\n defaultLocale?: string;\n /** Path to write generated types. Defaults to `.i18n/i18n.d.ts`. */\n typesOutPath?: string;\n}\n\nexport function i18nDevPlugin(config: I18nDevPluginConfig, options?: I18nDevPluginOptions): Plugin {\n let projectRoot = '';\n const assetsPrefix = `/${options?.assetsDir ?? '__i18n'}/`;\n\n /**\n * Reads a namespace JSON file from the locales directory.\n * Returns the parsed JSON, or undefined if the file doesn't exist.\n */\n function readNamespaceFile(\n locale: string,\n namespace: string,\n ): Record<string, unknown> | undefined {\n const filePath = path.join(\n projectRoot,\n config.localesDir,\n locale,\n `${namespace}.json`,\n );\n\n try {\n const content = fs.readFileSync(filePath, 'utf-8');\n return JSON.parse(content);\n } catch {\n return undefined;\n }\n }\n\n /**\n * Builds a named dictionary bundle — only the namespaces belonging\n * to a specific dictionary, keyed by namespace name.\n */\n function buildDictionaryBundle(\n locale: string,\n dictName: string,\n ): Record<string, unknown> {\n const rule = normalizeDictionaries(config.dictionaries).find((entry) => entry.name === dictName);\n if (!rule) return {};\n\n const localeDir = path.join(projectRoot, config.localesDir, locale);\n let files: string[] = [];\n try {\n files = fs.readdirSync(localeDir).filter((file) => file.endsWith('.json'));\n } catch {\n return {};\n }\n\n const bundle: Record<string, unknown> = {};\n for (const file of files) {\n const ns = file.slice(0, -'.json'.length);\n const data = readNamespaceFile(locale, ns);\n if (!data) continue;\n\n const matchedSubKeys = flattenKeys(data)\n .filter((subKey) => rule.include.some((pattern) => keyMatchesPattern(`${ns}.${subKey}`, pattern)));\n if (matchedSubKeys.length === 0) continue;\n\n bundle[ns] = pruneNamespace(data, matchedSubKeys);\n }\n return bundle;\n }\n\n /**\n * Builds a scope bundle — reads the namespace file(s) inferred from\n * the scope and returns them keyed by namespace name.\n *\n * The first segment of the scope is the namespace:\n * 'products.show' → reads products.json → { products: { ... } }\n */\n function buildScopeBundle(\n locale: string,\n scope: string,\n ): Record<string, unknown> {\n const namespace = scope.indexOf('.') === -1\n ? scope\n : scope.slice(0, scope.indexOf('.'));\n\n const bundle: Record<string, unknown> = {};\n const data = readNamespaceFile(locale, namespace);\n if (data) {\n bundle[namespace] = data;\n }\n return bundle;\n }\n\n return {\n name: 'vite-bundled-i18n-dev',\n apply: 'serve',\n configResolved(resolvedConfig) {\n projectRoot = resolvedConfig.root;\n },\n configureServer(server) {\n const localesPath = path.join(projectRoot, config.localesDir);\n const defaultLocale = options?.defaultLocale ?? 'en';\n const typesOutPath = options?.typesOutPath\n ? path.resolve(projectRoot, options.typesOutPath)\n : path.join(projectRoot, '.i18n', 'i18n.d.ts');\n\n // Generate types on server start for dev-time autocomplete\n function regenerateTypes() {\n try {\n writeTypes(localesPath, defaultLocale, typesOutPath);\n } catch {\n // Silently skip if locales dir doesn't exist yet\n }\n }\n\n regenerateTypes();\n\n // Watch locale files: regenerate types + reload page\n server.watcher.add(localesPath);\n\n server.watcher.on('change', (filePath) => {\n if (filePath.startsWith(localesPath) && filePath.endsWith('.json')) {\n regenerateTypes();\n server.ws.send({ type: 'full-reload' });\n }\n });\n\n server.middlewares.use((req, res, next) => {\n if (!req.url?.startsWith(assetsPrefix)) {\n return next();\n }\n\n const relativePath = req.url.slice(assetsPrefix.length);\n\n // Named dictionary: {locale}/_dict/{name}.json\n const dictMatch = relativePath.match(\n /^([^/]+)\\/_dict\\/([^/]+)\\.json$/,\n );\n if (dictMatch) {\n const [, locale, dictName] = dictMatch;\n const bundle = buildDictionaryBundle(locale, dictName);\n const json = JSON.stringify(bundle);\n res.setHeader('Content-Type', 'application/json');\n res.setHeader('Cache-Control', 'no-cache');\n res.end(json);\n return;\n }\n\n // Scope bundle: {locale}/{scope}.json\n const scopeMatch = relativePath.match(\n /^([^/]+)\\/(.+)\\.json$/,\n );\n if (scopeMatch) {\n const [, locale, scope] = scopeMatch;\n const bundle = buildScopeBundle(locale, scope);\n const json = JSON.stringify(bundle);\n res.setHeader('Content-Type', 'application/json');\n res.setHeader('Cache-Control', 'no-cache');\n res.end(json);\n return;\n }\n\n next();\n });\n },\n };\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport type { Plugin, ResolvedConfig } from 'vite';\nimport type { I18nSharedConfig } from '../core/config';\nimport { writeTypes } from '../extractor/type-generator';\nimport { generateReports } from '../extractor/reports';\nimport { generateBundles } from '../extractor/bundle-generator';\nimport { compileAll } from '../extractor/compiler';\nimport { walkAll } from '../extractor/walker';\n\nexport interface I18nBuildPluginConfig {\n /** Glob patterns for route/page entry points. */\n pages: string[];\n /** All supported locale codes. */\n locales: string[];\n /** Default locale used for fallback resolution. */\n defaultLocale: string;\n /** Where to write internal artifacts like reports and compiled modules. */\n generatedOutDir?: string;\n /** Where to write generated type declarations. */\n typesOutPath?: string;\n /** Extraction scope for the walker. */\n extractionScope?: 'global' | 'scoped';\n /** Public asset directory emitted into the Vite build output. */\n assetsDir?: string;\n /** Disable writing generated types during `vite build`. */\n emitTypes?: boolean;\n /** Disable writing reports during `vite build`. */\n emitReports?: boolean;\n /** Disable writing compiled modules during `vite build`. */\n emitCompiled?: boolean;\n}\n\nexport interface EmitI18nBuildArtifactsOptions {\n rootDir: string;\n viteOutDir: string;\n sharedConfig: I18nSharedConfig;\n buildConfig: I18nBuildPluginConfig;\n}\n\nexport interface EmitI18nBuildArtifactsResult {\n assetBundles: number;\n assetsOutDir: string;\n generatedOutDir: string;\n compiledOutDir?: string;\n typesOutPath?: string;\n warnings: string[];\n}\n\nfunction resolveBuildPaths(options: EmitI18nBuildArtifactsOptions) {\n const { rootDir, viteOutDir, sharedConfig, buildConfig } = options;\n\n const localesDir = path.isAbsolute(sharedConfig.localesDir)\n ? sharedConfig.localesDir\n : path.join(rootDir, sharedConfig.localesDir);\n const generatedOutDir = buildConfig.generatedOutDir\n ? path.resolve(rootDir, buildConfig.generatedOutDir)\n : path.join(rootDir, '.i18n');\n const typesOutPath = buildConfig.typesOutPath\n ? path.resolve(rootDir, buildConfig.typesOutPath)\n : path.join(generatedOutDir, 'i18n.d.ts');\n const assetsOutDir = path.join(viteOutDir, buildConfig.assetsDir ?? '__i18n');\n const extractionScope = buildConfig.extractionScope ?? 'global';\n\n return {\n localesDir,\n generatedOutDir,\n typesOutPath,\n assetsOutDir,\n extractionScope,\n };\n}\n\nfunction joinPublicPath(base: string, relativePath: string): string {\n const normalizedBase = base.endsWith('/') ? base : `${base}/`;\n const normalizedRelative = relativePath.replace(/^\\/+/, '');\n return `${normalizedBase}${normalizedRelative}`;\n}\n\nexport function emitI18nBuildArtifacts(\n options: EmitI18nBuildArtifactsOptions,\n): EmitI18nBuildArtifactsResult {\n const { rootDir, sharedConfig, buildConfig } = options;\n const {\n localesDir,\n generatedOutDir,\n typesOutPath,\n assetsOutDir,\n extractionScope,\n } = resolveBuildPaths(options);\n\n const analysis = walkAll({\n pages: buildConfig.pages,\n rootDir,\n localesDir,\n defaultLocale: buildConfig.defaultLocale,\n extractionScope,\n });\n\n const bundles = generateBundles(analysis, {\n localesDir,\n locales: buildConfig.locales,\n outDir: assetsOutDir,\n dictionaries: sharedConfig.dictionaries,\n });\n\n if (buildConfig.emitTypes !== false) {\n const scopeNames = analysis.routes.map(r => r.routeId);\n writeTypes(localesDir, buildConfig.defaultLocale, typesOutPath, scopeNames);\n }\n\n let compiledOutDir: string | undefined;\n if (buildConfig.emitCompiled !== false) {\n compiledOutDir = path.join(assetsOutDir, 'compiled');\n compileAll(analysis, {\n localesDir,\n locales: buildConfig.locales,\n defaultLocale: buildConfig.defaultLocale,\n outDir: compiledOutDir,\n dictionaries: sharedConfig.dictionaries,\n });\n }\n\n if (buildConfig.emitReports !== false) {\n generateReports(\n analysis,\n localesDir,\n buildConfig.defaultLocale,\n generatedOutDir,\n sharedConfig.dictionaries,\n );\n }\n\n const warnings: string[] = [];\n\n // Count extracted keys vs bundled keys\n const totalExtractedKeys = analysis.allKeys.filter(k => !k.dynamic).length;\n const totalBundledKeys = bundles.reduce((sum, b) => sum + b.keyCount, 0);\n\n if (totalExtractedKeys > 0 && totalBundledKeys === 0) {\n const localeCheckDir = path.join(localesDir, buildConfig.defaultLocale);\n let foundFiles: string[] = [];\n try {\n foundFiles = fs.readdirSync(localeCheckDir).filter(f => f.endsWith('.json'));\n } catch { /* dir doesn't exist */ }\n\n const hint = foundFiles.length === 0\n ? `No JSON files found in ${localeCheckDir}`\n : `Found ${foundFiles.length} file(s) but 0 keys matched`;\n\n warnings.push(\n `vite-bundled-i18n: 0 of ${totalExtractedKeys} extracted keys found in translation files.\\n` +\n ` Expected structure: ${localesDir}/{locale}/{namespace}.json\\n` +\n ` ${hint}\\n` +\n ` Hint: Subdirectories are not supported. Each namespace must be a single flat JSON file.`\n );\n }\n\n return {\n assetBundles: bundles.length,\n assetsOutDir,\n generatedOutDir,\n compiledOutDir,\n typesOutPath: buildConfig.emitTypes === false ? undefined : typesOutPath,\n warnings,\n };\n}\n\nexport function i18nBuildPlugin(\n sharedConfig: I18nSharedConfig,\n buildConfig: I18nBuildPluginConfig,\n): Plugin {\n let resolvedConfig: ResolvedConfig | undefined;\n const assetsDir = buildConfig.assetsDir ?? '__i18n';\n\n return {\n name: 'vite-bundled-i18n-build',\n apply: 'build',\n // enforce: 'post' ensures config() runs AFTER other plugins (e.g. Laravel's\n // Vite plugin) that set `base` in their own config() hooks.\n enforce: 'post',\n config(config) {\n const base = config.base ?? '/';\n const i18nBase = joinPublicPath(base, assetsDir).replace(/\\/$/, '');\n const manifestUrl = joinPublicPath(base, `${assetsDir}/compiled/manifest.js`);\n return {\n define: {\n __VITE_I18N_COMPILED_MANIFEST__: JSON.stringify(manifestUrl),\n __VITE_I18N_BASE__: JSON.stringify(i18nBase),\n },\n };\n },\n configResolved(config) {\n resolvedConfig = config;\n },\n closeBundle() {\n if (!resolvedConfig) return;\n\n const result = emitI18nBuildArtifacts({\n rootDir: resolvedConfig.root,\n viteOutDir: path.resolve(resolvedConfig.root, resolvedConfig.build.outDir),\n sharedConfig,\n buildConfig,\n });\n\n for (const warning of result.warnings) {\n resolvedConfig.logger.warn(warning);\n }\n\n resolvedConfig.logger.info(\n `vite-bundled-i18n: emitted ${result.assetBundles} i18n asset bundle(s) to ${path.relative(resolvedConfig.root, result.assetsOutDir)}`,\n );\n if (result.compiledOutDir) {\n resolvedConfig.logger.info(\n `vite-bundled-i18n: compiled runtime modules written to ${path.relative(resolvedConfig.root, result.compiledOutDir)}`,\n );\n }\n if (result.typesOutPath) {\n resolvedConfig.logger.info(\n `vite-bundled-i18n: types written to ${path.relative(resolvedConfig.root, result.typesOutPath)}`,\n );\n }\n },\n };\n}\n","/**\n * Vite plugin entry point for vite-bundled-i18n.\n *\n * `i18nPlugin()` unifies:\n * - dev-time bundle serving via `/__i18n/...`\n * - build-time generation of static `/__i18n/...` assets, reports, types, and compiled modules\n */\nimport type { PluginOption } from 'vite';\nimport type { I18nSharedConfig } from './core/config';\nimport { i18nDevPlugin } from './plugin/devPlugin';\nimport {\n emitI18nBuildArtifacts,\n i18nBuildPlugin,\n} from './plugin/buildPlugin';\nimport type {\n I18nBuildPluginConfig,\n} from './plugin/buildPlugin';\n\nexport type {\n I18nDevPluginConfig,\n} from './plugin/devPlugin';\nexport type {\n EmitI18nBuildArtifactsOptions,\n EmitI18nBuildArtifactsResult,\n I18nBuildPluginConfig,\n} from './plugin/buildPlugin';\n\nexport {\n emitI18nBuildArtifacts,\n i18nBuildPlugin,\n i18nDevPlugin,\n};\n\nexport function i18nPlugin(\n sharedConfig: I18nSharedConfig,\n buildConfig?: I18nBuildPluginConfig,\n): PluginOption[] {\n const plugins: PluginOption[] = [\n i18nDevPlugin(sharedConfig, {\n assetsDir: buildConfig?.assetsDir,\n defaultLocale: buildConfig?.defaultLocale,\n typesOutPath: buildConfig?.typesOutPath,\n }),\n ];\n\n if (buildConfig) {\n plugins.push(i18nBuildPlugin(sharedConfig, buildConfig));\n }\n\n return plugins;\n}\n"],"mappings":";;;;AAiEA,SAAgB,cAAc,QAA6B,SAAwC;CACjG,IAAI,cAAc;CAClB,MAAM,eAAe,IAAI,SAAS,aAAa,SAAS;;;;;CAMxD,SAAS,kBACP,QACA,WACqC;EACrC,MAAM,WAAW,KAAK,KACpB,aACA,OAAO,YACP,QACA,GAAG,UAAU,OACd;AAED,MAAI;GACF,MAAM,UAAU,GAAG,aAAa,UAAU,QAAQ;AAClD,UAAO,KAAK,MAAM,QAAQ;UACpB;AACN;;;;;;;CAQJ,SAAS,sBACP,QACA,UACyB;EACzB,MAAM,OAAO,sBAAsB,OAAO,aAAa,CAAC,MAAM,UAAU,MAAM,SAAS,SAAS;AAChG,MAAI,CAAC,KAAM,QAAO,EAAE;EAEpB,MAAM,YAAY,KAAK,KAAK,aAAa,OAAO,YAAY,OAAO;EACnE,IAAI,QAAkB,EAAE;AACxB,MAAI;AACF,WAAQ,GAAG,YAAY,UAAU,CAAC,QAAQ,SAAS,KAAK,SAAS,QAAQ,CAAC;UACpE;AACN,UAAO,EAAE;;EAGX,MAAM,SAAkC,EAAE;AAC1C,OAAK,MAAM,QAAQ,OAAO;GACxB,MAAM,KAAK,KAAK,MAAM,GAAG,GAAgB;GACzC,M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../src/plugin/buildPlugin.ts","../src/plugin.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\nimport type { Plugin } from 'vite';\nimport { flattenKeys, pruneNamespace } from '../extractor/bundle-generator';\nimport { keyMatchesPattern, normalizeDictionaries } from '../extractor/dictionary-ownership';\nimport { writeTypes } from '../extractor/type-generator';\nimport type { I18nSharedConfig } from '../core/config';\n\n/**\n * Configuration for the i18n dev plugin.\n */\nexport type I18nDevPluginConfig = I18nSharedConfig;\n\n/**\n * Vite dev plugin that serves combined translation bundles.\n *\n * Instead of the browser making N separate HTTP requests for N namespace\n * files, this plugin intercepts requests to `/__i18n/` and serves all\n * requested namespaces combined into a single JSON response.\n *\n * Three types of bundles:\n *\n * **Named dictionary bundle** (`/__i18n/{locale}/_dict/{name}.json`):\n * Loads only the namespaces belonging to a specific named dictionary.\n * Each dictionary is loaded independently with its own priority.\n *\n * **Scope bundle** (`/__i18n/{locale}/{scope}.json`):\n * Loads the namespace inferred from the scope's first segment. For example,\n * `/__i18n/en/products.show.json` reads `locales/en/products.json` and\n * returns `{ \"products\": { ... } }`.\n *\n * In production (Group 2+), the Vite build plugin will generate these bundles\n * statically with tree-shaking. This dev plugin is the runtime equivalent —\n * same URL pattern, no tree-shaking, but demonstrates the loading strategy.\n *\n * @param config - Plugin configuration\n * @returns A Vite plugin\n *\n * @example\n * ```ts\n * // vite.config.ts\n * import { i18nDevPlugin } from './src/plugin/devPlugin';\n *\n * export default defineConfig({\n * plugins: [\n * react(),\n * i18nDevPlugin({\n * localesDir: 'locales',\n * dictionaries: {\n * global: { keys: ['shared', 'global', 'actions'] },\n * admin: { keys: ['admin'] },\n * },\n * }),\n * ],\n * });\n * ```\n */\nexport interface I18nDevPluginOptions {\n assetsDir?: string;\n /** Default locale for type generation. Required for dev-time autocomplete. */\n defaultLocale?: string;\n /** Path to write generated types. Defaults to `.i18n/i18n.d.ts`. */\n typesOutPath?: string;\n}\n\nexport function i18nDevPlugin(config: I18nDevPluginConfig, options?: I18nDevPluginOptions): Plugin {\n let projectRoot = '';\n const assetsPrefix = `/${options?.assetsDir ?? '__i18n'}/`;\n\n /**\n * Reads a namespace JSON file from the locales directory.\n * Returns the parsed JSON, or undefined if the file doesn't exist.\n */\n function readNamespaceFile(\n locale: string,\n namespace: string,\n ): Record<string, unknown> | undefined {\n const filePath = path.join(\n projectRoot,\n config.localesDir,\n locale,\n `${namespace}.json`,\n );\n\n try {\n const content = fs.readFileSync(filePath, 'utf-8');\n return JSON.parse(content);\n } catch {\n return undefined;\n }\n }\n\n /**\n * Builds a named dictionary bundle — only the namespaces belonging\n * to a specific dictionary, keyed by namespace name.\n */\n function buildDictionaryBundle(\n locale: string,\n dictName: string,\n ): Record<string, unknown> {\n const rule = normalizeDictionaries(config.dictionaries).find((entry) => entry.name === dictName);\n if (!rule) return {};\n\n const localeDir = path.join(projectRoot, config.localesDir, locale);\n let files: string[] = [];\n try {\n files = fs.readdirSync(localeDir).filter((file) => file.endsWith('.json'));\n } catch {\n return {};\n }\n\n const bundle: Record<string, unknown> = {};\n for (const file of files) {\n const ns = file.slice(0, -'.json'.length);\n const data = readNamespaceFile(locale, ns);\n if (!data) continue;\n\n const matchedSubKeys = flattenKeys(data)\n .filter((subKey) => rule.include.some((pattern) => keyMatchesPattern(`${ns}.${subKey}`, pattern)));\n if (matchedSubKeys.length === 0) continue;\n\n bundle[ns] = pruneNamespace(data, matchedSubKeys);\n }\n return bundle;\n }\n\n /**\n * Builds a scope bundle — reads the namespace file(s) inferred from\n * the scope and returns them keyed by namespace name.\n *\n * The first segment of the scope is the namespace:\n * 'products.show' → reads products.json → { products: { ... } }\n */\n function buildScopeBundle(\n locale: string,\n scope: string,\n ): Record<string, unknown> {\n const namespace = scope.indexOf('.') === -1\n ? scope\n : scope.slice(0, scope.indexOf('.'));\n\n const bundle: Record<string, unknown> = {};\n const data = readNamespaceFile(locale, namespace);\n if (data) {\n bundle[namespace] = data;\n }\n return bundle;\n }\n\n return {\n name: 'vite-bundled-i18n-dev',\n apply: 'serve',\n configResolved(resolvedConfig) {\n projectRoot = resolvedConfig.root;\n },\n configureServer(server) {\n const localesPath = path.join(projectRoot, config.localesDir);\n const defaultLocale = options?.defaultLocale ?? 'en';\n const typesOutPath = options?.typesOutPath\n ? path.resolve(projectRoot, options.typesOutPath)\n : path.join(projectRoot, 'src', 'core', 'i18n-generated.ts');\n\n // Generate types on server start for dev-time autocomplete\n function regenerateTypes() {\n try {\n writeTypes(localesPath, defaultLocale, typesOutPath);\n } catch {\n // Silently skip if locales dir doesn't exist yet\n }\n }\n\n regenerateTypes();\n\n // Watch locale files: regenerate types + reload page\n server.watcher.add(localesPath);\n\n server.watcher.on('change', (filePath) => {\n if (filePath.startsWith(localesPath) && filePath.endsWith('.json')) {\n regenerateTypes();\n server.ws.send({ type: 'full-reload' });\n }\n });\n\n server.middlewares.use((req, res, next) => {\n if (!req.url?.startsWith(assetsPrefix)) {\n return next();\n }\n\n const relativePath = req.url.slice(assetsPrefix.length);\n\n // Named dictionary: {locale}/_dict/{name}.json\n const dictMatch = relativePath.match(\n /^([^/]+)\\/_dict\\/([^/]+)\\.json$/,\n );\n if (dictMatch) {\n const [, locale, dictName] = dictMatch;\n const bundle = buildDictionaryBundle(locale, dictName);\n const json = JSON.stringify(bundle);\n res.setHeader('Content-Type', 'application/json');\n res.setHeader('Cache-Control', 'no-cache');\n res.end(json);\n return;\n }\n\n // Scope bundle: {locale}/{scope}.json\n const scopeMatch = relativePath.match(\n /^([^/]+)\\/(.+)\\.json$/,\n );\n if (scopeMatch) {\n const [, locale, scope] = scopeMatch;\n const bundle = buildScopeBundle(locale, scope);\n const json = JSON.stringify(bundle);\n res.setHeader('Content-Type', 'application/json');\n res.setHeader('Cache-Control', 'no-cache');\n res.end(json);\n return;\n }\n\n next();\n });\n },\n };\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport type { Plugin, ResolvedConfig } from 'vite';\nimport type { I18nSharedConfig } from '../core/config';\nimport { writeTypes } from '../extractor/type-generator';\nimport { generateReports } from '../extractor/reports';\nimport { generateBundles } from '../extractor/bundle-generator';\nimport { compileAll } from '../extractor/compiler';\nimport { walkAll } from '../extractor/walker';\n\nexport interface I18nBuildPluginConfig {\n /** Glob patterns for route/page entry points. */\n pages: string[];\n /** All supported locale codes. */\n locales: string[];\n /** Default locale used for fallback resolution. */\n defaultLocale: string;\n /** Where to write internal artifacts like reports and compiled modules. */\n generatedOutDir?: string;\n /** Where to write generated type declarations. */\n typesOutPath?: string;\n /** Extraction scope for the walker. */\n extractionScope?: 'global' | 'scoped';\n /** Public asset directory emitted into the Vite build output. */\n assetsDir?: string;\n /** Disable writing generated types during `vite build`. */\n emitTypes?: boolean;\n /** Disable writing reports during `vite build`. */\n emitReports?: boolean;\n /** Disable writing compiled modules during `vite build`. */\n emitCompiled?: boolean;\n}\n\nexport interface EmitI18nBuildArtifactsOptions {\n rootDir: string;\n viteOutDir: string;\n sharedConfig: I18nSharedConfig;\n buildConfig: I18nBuildPluginConfig;\n}\n\nexport interface EmitI18nBuildArtifactsResult {\n assetBundles: number;\n assetsOutDir: string;\n generatedOutDir: string;\n compiledOutDir?: string;\n typesOutPath?: string;\n warnings: string[];\n}\n\nfunction resolveBuildPaths(options: EmitI18nBuildArtifactsOptions) {\n const { rootDir, viteOutDir, sharedConfig, buildConfig } = options;\n\n const localesDir = path.isAbsolute(sharedConfig.localesDir)\n ? sharedConfig.localesDir\n : path.join(rootDir, sharedConfig.localesDir);\n const generatedOutDir = buildConfig.generatedOutDir\n ? path.resolve(rootDir, buildConfig.generatedOutDir)\n : path.join(rootDir, '.i18n');\n const typesOutPath = buildConfig.typesOutPath\n ? path.resolve(rootDir, buildConfig.typesOutPath)\n : path.join(rootDir, 'src', 'core', 'i18n-generated.ts');\n const assetsOutDir = path.join(viteOutDir, buildConfig.assetsDir ?? '__i18n');\n const extractionScope = buildConfig.extractionScope ?? 'global';\n\n return {\n localesDir,\n generatedOutDir,\n typesOutPath,\n assetsOutDir,\n extractionScope,\n };\n}\n\nfunction joinPublicPath(base: string, relativePath: string): string {\n const normalizedBase = base.endsWith('/') ? base : `${base}/`;\n const normalizedRelative = relativePath.replace(/^\\/+/, '');\n return `${normalizedBase}${normalizedRelative}`;\n}\n\nexport function emitI18nBuildArtifacts(\n options: EmitI18nBuildArtifactsOptions,\n): EmitI18nBuildArtifactsResult {\n const { rootDir, sharedConfig, buildConfig } = options;\n const {\n localesDir,\n generatedOutDir,\n typesOutPath,\n assetsOutDir,\n extractionScope,\n } = resolveBuildPaths(options);\n\n const analysis = walkAll({\n pages: buildConfig.pages,\n rootDir,\n localesDir,\n defaultLocale: buildConfig.defaultLocale,\n extractionScope,\n });\n\n const bundles = generateBundles(analysis, {\n localesDir,\n locales: buildConfig.locales,\n outDir: assetsOutDir,\n dictionaries: sharedConfig.dictionaries,\n });\n\n if (buildConfig.emitTypes !== false) {\n const scopeNames = analysis.routes.map(r => r.routeId);\n writeTypes(localesDir, buildConfig.defaultLocale, typesOutPath, scopeNames);\n }\n\n let compiledOutDir: string | undefined;\n if (buildConfig.emitCompiled !== false) {\n compiledOutDir = path.join(assetsOutDir, 'compiled');\n compileAll(analysis, {\n localesDir,\n locales: buildConfig.locales,\n defaultLocale: buildConfig.defaultLocale,\n outDir: compiledOutDir,\n dictionaries: sharedConfig.dictionaries,\n });\n }\n\n if (buildConfig.emitReports !== false) {\n generateReports(\n analysis,\n localesDir,\n buildConfig.defaultLocale,\n generatedOutDir,\n sharedConfig.dictionaries,\n );\n }\n\n const warnings: string[] = [];\n\n // Count extracted keys vs bundled keys\n const totalExtractedKeys = analysis.allKeys.filter(k => !k.dynamic).length;\n const totalBundledKeys = bundles.reduce((sum, b) => sum + b.keyCount, 0);\n\n if (totalExtractedKeys > 0 && totalBundledKeys === 0) {\n const localeCheckDir = path.join(localesDir, buildConfig.defaultLocale);\n let foundFiles: string[] = [];\n try {\n foundFiles = fs.readdirSync(localeCheckDir).filter(f => f.endsWith('.json'));\n } catch { /* dir doesn't exist */ }\n\n const hint = foundFiles.length === 0\n ? `No JSON files found in ${localeCheckDir}`\n : `Found ${foundFiles.length} file(s) but 0 keys matched`;\n\n warnings.push(\n `vite-bundled-i18n: 0 of ${totalExtractedKeys} extracted keys found in translation files.\\n` +\n ` Expected structure: ${localesDir}/{locale}/{namespace}.json\\n` +\n ` ${hint}\\n` +\n ` Hint: Subdirectories are not supported. Each namespace must be a single flat JSON file.`\n );\n }\n\n return {\n assetBundles: bundles.length,\n assetsOutDir,\n generatedOutDir,\n compiledOutDir,\n typesOutPath: buildConfig.emitTypes === false ? undefined : typesOutPath,\n warnings,\n };\n}\n\nexport function i18nBuildPlugin(\n sharedConfig: I18nSharedConfig,\n buildConfig: I18nBuildPluginConfig,\n): Plugin {\n let resolvedConfig: ResolvedConfig | undefined;\n const assetsDir = buildConfig.assetsDir ?? '__i18n';\n\n return {\n name: 'vite-bundled-i18n-build',\n apply: 'build',\n // enforce: 'post' ensures config() runs AFTER other plugins (e.g. Laravel's\n // Vite plugin) that set `base` in their own config() hooks.\n enforce: 'post',\n config(config) {\n const base = config.base ?? '/';\n const i18nBase = joinPublicPath(base, assetsDir).replace(/\\/$/, '');\n const manifestUrl = joinPublicPath(base, `${assetsDir}/compiled/manifest.js`);\n return {\n define: {\n __VITE_I18N_COMPILED_MANIFEST__: JSON.stringify(manifestUrl),\n __VITE_I18N_BASE__: JSON.stringify(i18nBase),\n },\n };\n },\n configResolved(config) {\n resolvedConfig = config;\n },\n closeBundle() {\n if (!resolvedConfig) return;\n\n const result = emitI18nBuildArtifacts({\n rootDir: resolvedConfig.root,\n viteOutDir: path.resolve(resolvedConfig.root, resolvedConfig.build.outDir),\n sharedConfig,\n buildConfig,\n });\n\n for (const warning of result.warnings) {\n resolvedConfig.logger.warn(warning);\n }\n\n resolvedConfig.logger.info(\n `vite-bundled-i18n: emitted ${result.assetBundles} i18n asset bundle(s) to ${path.relative(resolvedConfig.root, result.assetsOutDir)}`,\n );\n if (result.compiledOutDir) {\n resolvedConfig.logger.info(\n `vite-bundled-i18n: compiled runtime modules written to ${path.relative(resolvedConfig.root, result.compiledOutDir)}`,\n );\n }\n if (result.typesOutPath) {\n resolvedConfig.logger.info(\n `vite-bundled-i18n: types written to ${path.relative(resolvedConfig.root, result.typesOutPath)}`,\n );\n }\n },\n };\n}\n","/**\n * Vite plugin entry point for vite-bundled-i18n.\n *\n * `i18nPlugin()` unifies:\n * - dev-time bundle serving via `/__i18n/...`\n * - build-time generation of static `/__i18n/...` assets, reports, types, and compiled modules\n */\nimport type { PluginOption } from 'vite';\nimport type { I18nSharedConfig } from './core/config';\nimport { i18nDevPlugin } from './plugin/devPlugin';\nimport {\n emitI18nBuildArtifacts,\n i18nBuildPlugin,\n} from './plugin/buildPlugin';\nimport type {\n I18nBuildPluginConfig,\n} from './plugin/buildPlugin';\n\nexport type {\n I18nDevPluginConfig,\n} from './plugin/devPlugin';\nexport type {\n EmitI18nBuildArtifactsOptions,\n EmitI18nBuildArtifactsResult,\n I18nBuildPluginConfig,\n} from './plugin/buildPlugin';\n\nexport {\n emitI18nBuildArtifacts,\n i18nBuildPlugin,\n i18nDevPlugin,\n};\n\nexport function i18nPlugin(\n sharedConfig: I18nSharedConfig,\n buildConfig?: I18nBuildPluginConfig,\n): PluginOption[] {\n const plugins: PluginOption[] = [\n i18nDevPlugin(sharedConfig, {\n assetsDir: buildConfig?.assetsDir,\n defaultLocale: buildConfig?.defaultLocale,\n typesOutPath: buildConfig?.typesOutPath,\n }),\n ];\n\n if (buildConfig) {\n plugins.push(i18nBuildPlugin(sharedConfig, buildConfig));\n }\n\n return plugins;\n}\n"],"mappings":";;;;AAiEA,SAAgB,cAAc,QAA6B,SAAwC;CACjG,IAAI,cAAc;CAClB,MAAM,eAAe,IAAI,SAAS,aAAa,SAAS;;;;;CAMxD,SAAS,kBACP,QACA,WACqC;EACrC,MAAM,WAAW,KAAK,KACpB,aACA,OAAO,YACP,QACA,GAAG,UAAU,OACd;AAED,MAAI;GACF,MAAM,UAAU,GAAG,aAAa,U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S,eAAe,MAAM,OAAO,aAAa,GACrI;AACD,OAAI,OAAO,eACT,gBAAe,OAAO,KACpB,0DAA0D,KAAK,SAAS,eAAe,MAAM,OAAO,eAAe,GACpH;AAEH,OAAI,OAAO,aACT,gBAAe,OAAO,KACpB,uCAAuC,KAAK,SAAS,eAAe,MAAM,OAAO,aAAa,GAC/F;;EAGN;;;;AC9LH,SAAgB,WACd,cACA,aACgB;CAChB,MAAM,UAA0B,CAC9B,cAAc,cAAc;EAC1B,WAAW,aAAa;EACxB,eAAe,aAAa;EAC5B,cAAc,aAAa;EAC5B,CAAC,CACH;AAED,KAAI,YACF,SAAQ,KAAK,gBAAgB,cAAc,YAAY,CAAC;AAG1D,QAAO"}
|
|
@@ -377,14 +377,13 @@ function generateTypes(localesDir, defaultLocale, scopes) {
|
|
|
377
377
|
const leafValues = data !== null && typeof data === "object" && !Array.isArray(data) ? flattenToLeafValues(data) : /* @__PURE__ */ new Map();
|
|
378
378
|
for (const [keyPath, value] of leafValues) paramsMap.set(`${namespace}.${keyPath}`, extractPlaceholders(value));
|
|
379
379
|
}
|
|
380
|
-
const namespaces = [...namespaceMap.keys()];
|
|
381
380
|
const allQualifiedKeys = [];
|
|
382
381
|
for (const [ns, paths] of namespaceMap) for (const p of paths) allQualifiedKeys.push(`${ns}.${p}`);
|
|
383
382
|
let paramsMapEntries;
|
|
384
383
|
const keysWithParams = allQualifiedKeys.filter((k) => (paramsMap.get(k) ?? []).length > 0);
|
|
385
384
|
if (keysWithParams.length === 0) paramsMapEntries = " // No parameterized keys found";
|
|
386
385
|
else paramsMapEntries = keysWithParams.map((k) => {
|
|
387
|
-
return ` '${k}': ${`{ ${paramsMap.get(k).map((name) => `${name}:
|
|
386
|
+
return ` '${k}': ${`{ ${paramsMap.get(k).map((name) => `${name}: TranslationValue`).join("; ")} }`};`;
|
|
388
387
|
}).join("\n");
|
|
389
388
|
let nestedKeysBlock;
|
|
390
389
|
if (allQualifiedKeys.length === 0) nestedKeysBlock = " interface I18nNestedKeys {}";
|
|
@@ -392,48 +391,24 @@ function generateTypes(localesDir, defaultLocale, scopes) {
|
|
|
392
391
|
let scopeMapEntries;
|
|
393
392
|
if (!scopes || scopes.length === 0) scopeMapEntries = " // No scopes found";
|
|
394
393
|
else scopeMapEntries = scopes.sort().map((s) => ` '${s}': true;`).join("\n");
|
|
395
|
-
const augmentation = [
|
|
396
|
-
`declare module 'vite-bundled-i18n' {`,
|
|
397
|
-
nestedKeysBlock,
|
|
398
|
-
``,
|
|
399
|
-
` interface I18nParamsMap {`,
|
|
400
|
-
paramsMapEntries,
|
|
401
|
-
` }`,
|
|
402
|
-
``,
|
|
403
|
-
` interface I18nScopeMap {`,
|
|
404
|
-
scopeMapEntries,
|
|
405
|
-
` }`,
|
|
406
|
-
`}`
|
|
407
|
-
].join("\n");
|
|
408
|
-
let namespaceType;
|
|
409
|
-
if (namespaces.length === 0) namespaceType = "export type Namespace = never;";
|
|
410
|
-
else namespaceType = `export type Namespace = ${namespaces.map((n) => `'${n}'`).join(" | ")};`;
|
|
411
|
-
let namespaceKeyPathsType;
|
|
412
|
-
if (namespaces.length === 0) namespaceKeyPathsType = "export type NamespaceKeyPaths<T extends Namespace> = never;";
|
|
413
|
-
else namespaceKeyPathsType = `export type NamespaceKeyPaths<T extends Namespace> =\n${namespaces.map((ns) => {
|
|
414
|
-
const paths = namespaceMap.get(ns);
|
|
415
|
-
return ` T extends '${ns}' ? ${paths.length === 0 ? "never" : paths.map((p) => `'${p}'`).join(" | ")} :`;
|
|
416
|
-
}).join("\n")}\n never;`;
|
|
417
394
|
return [
|
|
418
395
|
"// Auto-generated by vite-bundled-i18n — do not edit.",
|
|
419
396
|
"// Regenerated on: npm run dev (auto), npm run build, npm run i18n -- generate",
|
|
420
397
|
"//",
|
|
421
|
-
"//
|
|
422
|
-
"// translation keys, placeholder params, and valid scopes. It enables:",
|
|
423
|
-
"// - Progressive autocomplete: t('feedback.' → pages, actions, ...)",
|
|
424
|
-
"// - Placeholder validation: t('cart.total', { amount }) is type-checked",
|
|
425
|
-
"// - Scope validation: useI18n('feedbak.index') → compile error (typo)",
|
|
426
|
-
"//",
|
|
427
|
-
"// If your tsconfig doesn't include this file's directory, add it:",
|
|
428
|
-
"// \"include\": [\"src\", \".i18n\"]",
|
|
398
|
+
"// Add \".i18n\" to your tsconfig include: { \"include\": [\"src\", \".i18n\"] }",
|
|
429
399
|
"",
|
|
430
|
-
|
|
400
|
+
"type TranslationValue = string | number | boolean | bigint | null | undefined;",
|
|
431
401
|
"",
|
|
432
|
-
"
|
|
433
|
-
|
|
402
|
+
"// Direct exports — used by the package to populate types",
|
|
403
|
+
`export ${nestedKeysBlock.replace(" interface ", "interface ")}`,
|
|
434
404
|
"",
|
|
435
|
-
|
|
436
|
-
|
|
405
|
+
`export interface I18nParamsMap {`,
|
|
406
|
+
paramsMapEntries,
|
|
407
|
+
`}`,
|
|
408
|
+
"",
|
|
409
|
+
`export interface I18nScopeMap {`,
|
|
410
|
+
scopeMapEntries,
|
|
411
|
+
`}`,
|
|
437
412
|
""
|
|
438
413
|
].join("\n");
|
|
439
414
|
}
|
|
@@ -1375,4 +1350,4 @@ function walkAll(options) {
|
|
|
1375
1350
|
//#endregion
|
|
1376
1351
|
export { writeTypes as a, pruneNamespace as c, generateReports as i, keyMatchesPattern as l, compileAll as n, flattenKeys as o, flattenLocaleKeys as r, generateBundles as s, walkAll as t, normalizeDictionaries as u };
|
|
1377
1352
|
|
|
1378
|
-
//# sourceMappingURL=walker-
|
|
1353
|
+
//# sourceMappingURL=walker-9pKaJgmJ.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"walker-9pKaJgmJ.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/compiler.ts","../src/extractor/ast-utils.ts","../src/extractor/patterns.ts","../src/extractor/extract.ts","../src/extractor/walker.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: Set<string>;\n routeIds: Set<string>;\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\nexport function buildScopePlans(\n analysis: ProjectAnalysis,\n availableKeys: Iterable<string>,\n): ScopeBundlePlan[] {\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 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 if (keyNamespace(key) !== namespace) continue;\n\n if (!key.dynamic) {\n plan.keys.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 plan.keys.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\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 } = 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)) {\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 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 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\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 } = 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());\n for (const plan of scopePlans) {\n const usedKeys = new Set(\n [...plan.keys].filter((key) => !ownership.keyOwner.has(key)),\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","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 */\nfunction isOurPackage(specifier: string): boolean {\n return (\n PACKAGE_NAMES.has(specifier) ||\n specifier.includes('/core/t') ||\n specifier.includes('/react/useI18n')\n );\n}\n\n/**\n * Checks if a module specifier is one that exports `useI18n`.\n */\nfunction isUseI18nPackage(specifier: string): boolean {\n return (\n specifier === 'vite-bundled-i18n/react' ||\n specifier === 'vite-i18n-manager/react' ||\n specifier.includes('/react/useI18n')\n );\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)) 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)) {\n useI18nNames.add(localName);\n }\n\n if (importedName === 'i18nKey' && isOurPackage(specifier)) {\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 */\nexport function extractScopes(sourceFile: ts.SourceFile): 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)) 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);\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' },\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 });\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 }),\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"],"mappings":";;;;;AAkBA,SAAgB,6BAA6B,MAAkC;AAE7E,QAAO,CAAC,IADU,KAAK,QAAQ,EAAE,EAAE,KAAK,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|
"private": false,
|
|
4
|
-
"version": "0.2.
|
|
4
|
+
"version": "0.2.13",
|
|
5
5
|
"description": "Route-aware i18n for Vite apps with typed keys, scope bundles, dictionary ownership, and compiled production output.",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"types": "./dist/index.d.ts",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"walker-B1niFoyW.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/compiler.ts","../src/extractor/ast-utils.ts","../src/extractor/patterns.ts","../src/extractor/extract.ts","../src/extractor/walker.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: Set<string>;\n routeIds: Set<string>;\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\nexport function buildScopePlans(\n analysis: ProjectAnalysis,\n availableKeys: Iterable<string>,\n): ScopeBundlePlan[] {\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 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 if (keyNamespace(key) !== namespace) continue;\n\n if (!key.dynamic) {\n plan.keys.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 plan.keys.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\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 } = 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)) {\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 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 const namespaces = [...namespaceMap.keys()];\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}: Primitive`).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 augmentation ----\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 const augmentation = [\n `declare module 'vite-bundled-i18n' {`,\n nestedKeysBlock,\n ``,\n ` interface I18nParamsMap {`,\n paramsMapEntries,\n ` }`,\n ``,\n ` interface I18nScopeMap {`,\n scopeMapEntries,\n ` }`,\n `}`,\n ].join('\\n');\n\n // ---- Namespace ------------------------------------------------------------\n let namespaceType: string;\n if (namespaces.length === 0) {\n namespaceType = 'export type Namespace = never;';\n } else {\n namespaceType = `export type Namespace = ${namespaces.map((n) => `'${n}'`).join(' | ')};`;\n }\n\n // ---- NamespaceKeyPaths<T> -------------------------------------------------\n let namespaceKeyPathsType: string;\n if (namespaces.length === 0) {\n namespaceKeyPathsType =\n 'export type NamespaceKeyPaths<T extends Namespace> = never;';\n } else {\n const conditions = namespaces\n .map((ns) => {\n const paths = namespaceMap.get(ns)!;\n const union =\n paths.length === 0\n ? 'never'\n : paths.map((p) => `'${p}'`).join(' | ');\n return ` T extends '${ns}' ? ${union} :`;\n })\n .join('\\n');\n namespaceKeyPathsType =\n `export type NamespaceKeyPaths<T extends Namespace> =\\n${conditions}\\n never;`;\n }\n\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 '// This file augments the vite-bundled-i18n package types with your project\\'s',\n '// translation keys, placeholder params, and valid scopes. It enables:',\n '// - Progressive autocomplete: t(\\'feedback.\\' → pages, actions, ...)',\n '// - Placeholder validation: t(\\'cart.total\\', { amount }) is type-checked',\n '// - Scope validation: useI18n(\\'feedbak.index\\') → compile error (typo)',\n '//',\n '// If your tsconfig doesn\\'t include this file\\'s directory, add it:',\n '// \"include\": [\"src\", \".i18n\"]',\n '',\n augmentation,\n '',\n '/** Union of all namespace names. */',\n namespaceType,\n '',\n '/** Key paths within a specific namespace (without the namespace prefix). */',\n namespaceKeyPathsType,\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 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\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 } = 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());\n for (const plan of scopePlans) {\n const usedKeys = new Set(\n [...plan.keys].filter((key) => !ownership.keyOwner.has(key)),\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","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 */\nfunction isOurPackage(specifier: string): boolean {\n return (\n PACKAGE_NAMES.has(specifier) ||\n specifier.includes('/core/t') ||\n specifier.includes('/react/useI18n')\n );\n}\n\n/**\n * Checks if a module specifier is one that exports `useI18n`.\n */\nfunction isUseI18nPackage(specifier: string): boolean {\n return (\n specifier === 'vite-bundled-i18n/react' ||\n specifier === 'vite-i18n-manager/react' ||\n specifier.includes('/react/useI18n')\n );\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)) 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)) {\n useI18nNames.add(localName);\n }\n\n if (importedName === 'i18nKey' && isOurPackage(specifier)) {\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 */\nexport function extractScopes(sourceFile: ts.SourceFile): 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)) 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);\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' },\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 });\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 }),\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"],"mappings":";;;;;AAkBA,SAAgB,6BAA6B,MAAkC;AAE7E,QAAO,CAAC,IADU,KAAK,QAAQ,EAAE,EAAE,KAAK,QAAQ,GAAG,IAAI,IAAI,EACt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