vite-bundled-i18n 0.3.1 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/README.md +4 -1
  2. package/dist/cli/commands.d.ts +7 -0
  3. package/dist/cli/index.js +11 -6
  4. package/dist/cli/index.js.map +1 -1
  5. package/dist/{compiler-B8vL51ge.js → compiler-CMOyCfBe.js} +72 -23
  6. package/dist/compiler-CMOyCfBe.js.map +1 -0
  7. package/dist/core/config.d.ts +39 -0
  8. package/dist/core/services/key-tracker.d.ts +18 -1
  9. package/dist/core/types.d.ts +30 -0
  10. package/dist/{data-BQSxm6Hf.js → data-Yv_f3OCA.js} +53 -14
  11. package/dist/data-Yv_f3OCA.js.map +1 -0
  12. package/dist/devtools/panels/footprint.d.ts +1 -1
  13. package/dist/extractor/bundle-generator.d.ts +7 -0
  14. package/dist/extractor/compiler.d.ts +7 -0
  15. package/dist/extractor/patterns.d.ts +4 -1
  16. package/dist/extractor/scope-bundles.d.ts +18 -1
  17. package/dist/extractor/types.d.ts +2 -0
  18. package/dist/extractor/walker-types.d.ts +2 -0
  19. package/dist/extractor/walker.d.ts +1 -0
  20. package/dist/index.js +3 -3
  21. package/dist/{mountDevtools-C42c9yW2.js → mountDevtools-CtiMC5PM.js} +30 -8
  22. package/dist/mountDevtools-CtiMC5PM.js.map +1 -0
  23. package/dist/plugin.js +92 -10
  24. package/dist/plugin.js.map +1 -1
  25. package/dist/react.js +2 -1
  26. package/dist/react.js.map +1 -1
  27. package/dist/{server-q6lgW4Dd.js → server-C0yDN0XT.js} +2 -2
  28. package/dist/{server-q6lgW4Dd.js.map → server-C0yDN0XT.js.map} +1 -1
  29. package/dist/server.js +2 -2
  30. package/dist/vanilla.js +7 -4
  31. package/dist/vanilla.js.map +1 -1
  32. package/dist/vue.js +3 -2
  33. package/dist/vue.js.map +1 -1
  34. package/package.json +1 -1
  35. package/dist/compiler-B8vL51ge.js.map +0 -1
  36. package/dist/data-BQSxm6Hf.js.map +0 -1
  37. package/dist/mountDevtools-C42c9yW2.js.map +0 -1
package/README.md CHANGED
@@ -1,4 +1,4 @@
1
- # vite-bundled-i18n
1
+ npm # vite-bundled-i18n
2
2
 
3
3
  Make translations behave like code: split, scoped, and bundled per route.
4
4
 
@@ -31,6 +31,7 @@ Layout.tsx ──→ Dictionary rules ──→ __i18n/en/_dict/glob
31
31
  ## Features
32
32
 
33
33
  - **Scope bundles** — each route loads only its own translations, one HTTP request
34
+ - **Cross-namespace packing** (opt-in) — inline a route's cross-namespace keys (tree-shaken) into its scope bundle, so 1–3 foreign keys don't force a whole dictionary to load globally
34
35
  - **Dictionary ownership** — named dictionaries claim keys by pattern (`include`/`exclude`/`priority`)
35
36
  - **Progressive autocomplete** — generated types let the IDE suggest one key segment at a time
36
37
  - **Placeholder validation** — `t('cart.total', { amount: 9.99 })` is type-checked against `{{amount}}` in the JSON
@@ -231,6 +232,8 @@ Traditional i18n ships every translation key to every page. `vite-bundled-i18n`
231
232
 
232
233
  4. **Dictionary bundles are not tree-shaken** — they include all keys matching the `include`/`exclude` patterns. Dictionaries are the "always available" layer for shared UI (nav, actions, validation). Tree-shaking only applies to scope bundles.
233
234
 
235
+ 5. **Cross-namespace packing** (opt-in via `bundling.crossNamespacePacking: true`) — when a route references a handful of keys from a foreign namespace (e.g. `giftcards.show` uses `vendors.compact.name` once), those keys are tree-shaken and inlined into the scope bundle. One HTTP request covers everything the route needs. Keys already owned by a dictionary are skipped so the global layer isn't duplicated. Dev middleware mirrors the behavior by serving cross-namespace extras alongside each scope request, so dev and production resolve keys identically. See [API docs](./docs/api.md#bundlingcrossnamespacepacking) for the emitted shape.
236
+
234
237
  ### What you get
235
238
 
236
239
  ```
@@ -19,6 +19,13 @@ export interface CliConfig {
19
19
  extractionScope?: 'global' | 'scoped';
20
20
  /** Optional dictionary configurations for compiled mode. */
21
21
  dictionaries?: Record<string, DictionaryConfig>;
22
+ /** Additional module specifiers that export `useI18n`. */
23
+ hookSources?: string[];
24
+ /**
25
+ * Inline cross-namespace keys (tree-shaken) into each scope bundle.
26
+ * See `I18nSharedConfig.bundling.crossNamespacePacking`.
27
+ */
28
+ crossNamespacePacking?: boolean;
22
29
  }
23
30
  /**
24
31
  * Run the walker and print a summary table to stdout.
package/dist/cli/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { a as generateReports, l as generateBundles, n as walkAll, r as flattenLocaleKeys, s as writeTypes, t as compileAll } from "../compiler-B8vL51ge.js";
2
+ import { a as generateReports, l as generateBundles, n as walkAll, r as flattenLocaleKeys, s as writeTypes, t as compileAll } from "../compiler-CMOyCfBe.js";
3
3
  import fs from "node:fs";
4
4
  import path from "node:path";
5
5
  //#region src/cli/commands.ts
@@ -21,7 +21,8 @@ function runWalker(config) {
21
21
  rootDir,
22
22
  localesDir,
23
23
  defaultLocale: config.defaultLocale,
24
- extractionScope
24
+ extractionScope,
25
+ hookSources: config.hookSources
25
26
  });
26
27
  }
27
28
  function collectScopeNames(analysis) {
@@ -84,7 +85,8 @@ function generate(config) {
84
85
  const bundles = generateBundles(analysis, {
85
86
  localesDir,
86
87
  locales: config.locales,
87
- outDir
88
+ outDir,
89
+ crossNamespacePacking: config.crossNamespacePacking
88
90
  });
89
91
  writeTypes(localesDir, config.defaultLocale, typesOutPath, collectScopeNames(analysis));
90
92
  console.log(`Generated ${bundles.length} bundle(s):`);
@@ -117,7 +119,8 @@ function compile(config) {
117
119
  locales: config.locales,
118
120
  defaultLocale: config.defaultLocale,
119
121
  outDir: compiledOutDir,
120
- dictionaries: config.dictionaries
122
+ dictionaries: config.dictionaries,
123
+ crossNamespacePacking: config.crossNamespacePacking
121
124
  });
122
125
  const total = analysis.routes.length * config.locales.length + (config.dictionaries && Object.keys(config.dictionaries).length > 0 ? config.locales.length : 0) + 1;
123
126
  console.log(`Compiled ${total} module(s) to ${compiledOutDir}`);
@@ -147,7 +150,8 @@ function build(config) {
147
150
  const bundles = generateBundles(analysis, {
148
151
  localesDir,
149
152
  locales: config.locales,
150
- outDir
153
+ outDir,
154
+ crossNamespacePacking: config.crossNamespacePacking
151
155
  });
152
156
  writeTypes(localesDir, config.defaultLocale, typesOutPath, collectScopeNames(analysis));
153
157
  console.log(`\nGenerated ${bundles.length} bundle(s)`);
@@ -158,7 +162,8 @@ function build(config) {
158
162
  locales: config.locales,
159
163
  defaultLocale: config.defaultLocale,
160
164
  outDir: compiledOutDir,
161
- dictionaries: config.dictionaries
165
+ dictionaries: config.dictionaries,
166
+ crossNamespacePacking: config.crossNamespacePacking
162
167
  });
163
168
  console.log(`Compiled modules written to ${compiledOutDir}`);
164
169
  generateReports(analysis, localesDir, config.defaultLocale, outDir, config.dictionaries);
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../src/cli/commands.ts","../../src/cli/index.ts"],"sourcesContent":["import path from 'node:path';\nimport { walkAll } from '../extractor/walker';\nimport { generateBundles } from '../extractor/bundle-generator';\nimport { writeTypes } from '../extractor/type-generator';\nimport { generateReports } from '../extractor/reports';\nimport { compileAll } from '../extractor/compiler';\nimport type { ProjectAnalysis } from '../extractor/walker-types';\nimport type { DictionaryConfig } from '../core/types';\nimport { flattenLocaleKeys } from '../extractor/reports';\n\nexport interface CliConfig {\n /** Glob patterns for page entry points. */\n pages: string[];\n /** Locales directory (relative to rootDir). */\n localesDir: string;\n /** All supported locale codes. */\n locales: string[];\n /** Default locale. */\n defaultLocale: string;\n /** Root directory. Defaults to process.cwd(). */\n rootDir?: string;\n /** Output directory for generated bundles. Defaults to '.i18n'. */\n outDir?: string;\n /** Output path for generated types. Defaults to '.i18n/i18n.d.ts'. */\n typesOutPath?: string;\n /** Extraction scope. Defaults to 'global'. */\n extractionScope?: 'global' | 'scoped';\n /** Optional dictionary configurations for compiled mode. */\n dictionaries?: Record<string, DictionaryConfig>;\n}\n\nfunction resolveConfig(config: CliConfig) {\n const rootDir = config.rootDir ?? process.cwd();\n const outDir = config.outDir ?? path.join(rootDir, '.i18n');\n const typesOutPath =\n config.typesOutPath ?? path.join(outDir, 'i18n-generated.ts');\n const localesDir = path.isAbsolute(config.localesDir)\n ? config.localesDir\n : path.join(rootDir, config.localesDir);\n const extractionScope = config.extractionScope ?? 'global';\n\n return { rootDir, outDir, typesOutPath, localesDir, extractionScope } as const;\n}\n\nfunction runWalker(config: CliConfig): ProjectAnalysis {\n const { rootDir, localesDir, extractionScope } = resolveConfig(config);\n\n return walkAll({\n pages: config.pages,\n rootDir,\n localesDir,\n defaultLocale: config.defaultLocale,\n extractionScope,\n });\n}\n\nfunction collectScopeNames(analysis: ProjectAnalysis): string[] {\n return [...new Set(analysis.routes.flatMap((route) => route.scopes))].sort();\n}\n\n/**\n * Pad a string to the given width.\n */\nfunction pad(str: string, width: number): string {\n return str + ' '.repeat(Math.max(0, width - str.length));\n}\n\n/**\n * Print a simple ASCII table to stdout.\n */\nfunction printTable(\n headers: string[],\n rows: string[][],\n): void {\n const colWidths = headers.map((h, i) =>\n Math.max(h.length, ...rows.map((r) => (r[i] ?? '').length)),\n );\n\n const sep =\n '\\u250c' +\n colWidths.map((w) => '\\u2500'.repeat(w + 2)).join('\\u252c') +\n '\\u2510';\n const mid =\n '\\u251c' +\n colWidths.map((w) => '\\u2500'.repeat(w + 2)).join('\\u253c') +\n '\\u2524';\n const bot =\n '\\u2514' +\n colWidths.map((w) => '\\u2500'.repeat(w + 2)).join('\\u2534') +\n '\\u2518';\n\n const formatRow = (cells: string[]) =>\n '\\u2502' +\n cells.map((c, i) => ' ' + pad(c, colWidths[i]) + ' ').join('\\u2502') +\n '\\u2502';\n\n console.log(sep);\n console.log(formatRow(headers));\n console.log(mid);\n for (const row of rows) {\n console.log(formatRow(row));\n }\n console.log(bot);\n}\n\n/**\n * Run the walker and print a summary table to stdout.\n * Returns the ProjectAnalysis for programmatic use.\n */\nexport function analyze(config: CliConfig): ProjectAnalysis {\n const { localesDir } = resolveConfig(config);\n const analysis = runWalker(config);\n\n const availableKeys = flattenLocaleKeys(localesDir, config.defaultLocale);\n const totalAvailable = Array.from(availableKeys.values()).reduce(\n (sum, keys) => sum + keys.length,\n 0,\n );\n\n const rows = analysis.routes.map((route) => {\n const usedCount = route.keys.filter((k) => !k.dynamic).length;\n return [\n route.routeId,\n String(usedCount),\n String(totalAvailable),\n String(totalAvailable - usedCount),\n ];\n });\n\n printTable(['Route', 'Used Keys', 'Available', 'Pruned'], rows);\n\n console.log(\n `\\n${analysis.routes.length} route(s), ${analysis.allKeys.length} unique key(s), ${analysis.availableNamespaces.length} namespace(s)`,\n );\n\n return analysis;\n}\n\n/**\n * Run the walker, then generate bundles and types.\n * Prints what was generated to stdout.\n */\nexport function generate(config: CliConfig): void {\n const { outDir, typesOutPath, localesDir } = resolveConfig(config);\n const analysis = runWalker(config);\n\n const bundles = generateBundles(analysis, {\n localesDir,\n locales: config.locales,\n outDir,\n });\n\n writeTypes(localesDir, config.defaultLocale, typesOutPath, collectScopeNames(analysis));\n\n console.log(`Generated ${bundles.length} bundle(s):`);\n for (const b of bundles) {\n console.log(` ${b.locale}/${b.name} — ${b.keyCount} keys (${b.prunedCount} pruned)`);\n }\n console.log(`Types written to ${typesOutPath}`);\n}\n\n/**\n * Run the walker, then generate diagnostic reports.\n * Prints summary to stdout.\n */\nexport function report(config: CliConfig): void {\n const { outDir, localesDir } = resolveConfig(config);\n const analysis = runWalker(config);\n\n generateReports(analysis, localesDir, config.defaultLocale, outDir, config.dictionaries);\n\n console.log(`Reports written to ${outDir}:`);\n console.log(' manifest.json');\n console.log(' missing.json');\n console.log(' unused.json');\n console.log(' stats.json');\n}\n\n/**\n * Run the walker, then compile pre-resolved flat Map modules.\n * Prints a summary to stdout.\n */\nexport function compile(config: CliConfig): void {\n const { outDir, localesDir } = resolveConfig(config);\n const analysis = runWalker(config);\n const compiledOutDir = path.join(outDir, 'compiled');\n\n compileAll(analysis, {\n localesDir,\n locales: config.locales,\n defaultLocale: config.defaultLocale,\n outDir: compiledOutDir,\n dictionaries: config.dictionaries,\n });\n\n // Count generated modules: one per route per locale, plus dictionary modules\n const routeModules = analysis.routes.length * config.locales.length;\n const dictModules =\n config.dictionaries && Object.keys(config.dictionaries).length > 0\n ? config.locales.length\n : 0;\n const total = routeModules + dictModules + 1; // +1 for manifest\n\n console.log(`Compiled ${total} module(s) to ${compiledOutDir}`);\n}\n\n/**\n * Run analyze + generate + compile + report all at once.\n */\nexport function build(config: CliConfig): void {\n const { outDir, typesOutPath, localesDir } = resolveConfig(config);\n const analysis = runWalker(config);\n\n // Analyze: print table\n const availableKeys = flattenLocaleKeys(localesDir, config.defaultLocale);\n const totalAvailable = Array.from(availableKeys.values()).reduce(\n (sum, keys) => sum + keys.length,\n 0,\n );\n\n const rows = analysis.routes.map((route) => {\n const usedCount = route.keys.filter((k) => !k.dynamic).length;\n return [\n route.routeId,\n String(usedCount),\n String(totalAvailable),\n String(totalAvailable - usedCount),\n ];\n });\n\n printTable(['Route', 'Used Keys', 'Available', 'Pruned'], rows);\n\n // Generate bundles + types\n const bundles = generateBundles(analysis, {\n localesDir,\n locales: config.locales,\n outDir,\n });\n\n writeTypes(localesDir, config.defaultLocale, typesOutPath, collectScopeNames(analysis));\n\n console.log(`\\nGenerated ${bundles.length} bundle(s)`);\n console.log(`Types written to ${typesOutPath}`);\n\n // Compile\n const compiledOutDir = path.join(outDir, 'compiled');\n compileAll(analysis, {\n localesDir,\n locales: config.locales,\n defaultLocale: config.defaultLocale,\n outDir: compiledOutDir,\n dictionaries: config.dictionaries,\n });\n console.log(`Compiled modules written to ${compiledOutDir}`);\n\n // Reports\n generateReports(analysis, localesDir, config.defaultLocale, outDir, config.dictionaries);\n\n console.log(`Reports written to ${outDir}`);\n console.log(\n `\\nDone. ${analysis.routes.length} route(s), ${analysis.allKeys.length} unique key(s).`,\n );\n}\n","#!/usr/bin/env node\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport { analyze, generate, compile, report, build } from './commands';\nimport type { CliConfig } from './commands';\n\nconst COMMANDS = ['analyze', 'generate', 'compile', 'report', 'build'] as const;\ntype Command = (typeof COMMANDS)[number];\n\nfunction printUsage(): void {\n console.log('Usage: vite-bundled-i18n <command> [--config <path>]');\n console.log('');\n console.log('Commands:');\n console.log(' analyze — Walk imports and print a summary of key usage per route');\n console.log(' generate — Generate tree-shaken bundles and TypeScript types');\n console.log(' report — Generate diagnostic reports (manifest, missing, unused, stats)');\n console.log(' compile — Compile pre-resolved flat Map modules for production');\n console.log(' build — Run analyze + generate + compile + report in one step');\n console.log('');\n console.log('Options:');\n console.log(' --config <path> Path to config file (default: i18n.config.json)');\n}\n\nfunction loadConfig(configPath: string): CliConfig {\n const resolved = path.resolve(configPath);\n if (!fs.existsSync(resolved)) {\n console.error(`Config file not found: ${resolved}`);\n process.exit(1);\n }\n\n const raw = fs.readFileSync(resolved, 'utf-8');\n return JSON.parse(raw) as CliConfig;\n}\n\nfunction parseArgs(argv: string[]): { command: Command; configPath: string } {\n const args = argv.slice(2);\n let command: Command | undefined;\n let configPath = 'i18n.config.json';\n\n for (let i = 0; i < args.length; i++) {\n const arg = args[i];\n if (arg === '--config' && i + 1 < args.length) {\n configPath = args[++i];\n } else if (arg === '--help' || arg === '-h') {\n printUsage();\n process.exit(0);\n } else if (!command && COMMANDS.includes(arg as Command)) {\n command = arg as Command;\n } else {\n console.error(`Unknown argument: ${arg}`);\n printUsage();\n process.exit(1);\n }\n }\n\n if (!command) {\n printUsage();\n process.exit(1);\n }\n\n return { command: command!, configPath };\n}\n\nconst { command, configPath } = parseArgs(process.argv);\nconst config = loadConfig(configPath);\n\nconst commands: Record<Command, (cfg: CliConfig) => void> = {\n analyze,\n generate,\n compile,\n report,\n build,\n};\n\ncommands[command](config);\n"],"mappings":";;;;;AA+BA,SAAS,cAAc,QAAmB;CACxC,MAAM,UAAU,OAAO,WAAW,QAAQ,KAAK;CAC/C,MAAM,SAAS,OAAO,UAAU,KAAK,KAAK,SAAS,QAAQ;AAQ3D,QAAO;EAAE;EAAS;EAAQ,cANxB,OAAO,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,KAAK;EACpC,MAAM,MAAM,KAAK;AACjB,MAAI,QAAQ,cAAc,IAAI,IAAI,KAAK,OACrC,cAAa,KAAK,EAAE;WACX,QAAQ,YAAY,QAAQ,MAAM;AAC3C,eAAY;AACZ,WAAQ,KAAK,EAAE;aACN,CAAC,WAAW,SAAS,SAAS,IAAe,CACtD,WAAU;OACL;AACL,WAAQ,MAAM,qBAAqB,MAAM;AACzC,eAAY;AACZ,WAAQ,KAAK,EAAE;;;AAInB,KAAI,CAAC,SAAS;AACZ,cAAY;AACZ,UAAQ,KAAK,EAAE;;AAGjB,QAAO;EAAW;EAAU;EAAY;;AAG1C,IAAM,EAAE,SAAS,eAAe,UAAU,QAAQ,KAAK;AACvD,IAAM,SAAS,WAAW,WAAW;CAEuB;CAC1D;CACA;CACA;CACA;CACA;CACD,EAEQ,SAAS,OAAO"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../src/cli/commands.ts","../../src/cli/index.ts"],"sourcesContent":["import path from 'node:path';\nimport { walkAll } from '../extractor/walker';\nimport { generateBundles } from '../extractor/bundle-generator';\nimport { writeTypes } from '../extractor/type-generator';\nimport { generateReports } from '../extractor/reports';\nimport { compileAll } from '../extractor/compiler';\nimport type { ProjectAnalysis } from '../extractor/walker-types';\nimport type { DictionaryConfig } from '../core/types';\nimport { flattenLocaleKeys } from '../extractor/reports';\n\nexport interface CliConfig {\n /** Glob patterns for page entry points. */\n pages: string[];\n /** Locales directory (relative to rootDir). */\n localesDir: string;\n /** All supported locale codes. */\n locales: string[];\n /** Default locale. */\n defaultLocale: string;\n /** Root directory. Defaults to process.cwd(). */\n rootDir?: string;\n /** Output directory for generated bundles. Defaults to '.i18n'. */\n outDir?: string;\n /** Output path for generated types. Defaults to '.i18n/i18n.d.ts'. */\n typesOutPath?: string;\n /** Extraction scope. Defaults to 'global'. */\n extractionScope?: 'global' | 'scoped';\n /** Optional dictionary configurations for compiled mode. */\n dictionaries?: Record<string, DictionaryConfig>;\n /** Additional module specifiers that export `useI18n`. */\n hookSources?: string[];\n /**\n * Inline cross-namespace keys (tree-shaken) into each scope bundle.\n * See `I18nSharedConfig.bundling.crossNamespacePacking`.\n */\n crossNamespacePacking?: boolean;\n}\n\nfunction resolveConfig(config: CliConfig) {\n const rootDir = config.rootDir ?? process.cwd();\n const outDir = config.outDir ?? path.join(rootDir, '.i18n');\n const typesOutPath =\n config.typesOutPath ?? path.join(outDir, 'i18n-generated.ts');\n const localesDir = path.isAbsolute(config.localesDir)\n ? config.localesDir\n : path.join(rootDir, config.localesDir);\n const extractionScope = config.extractionScope ?? 'global';\n\n return { rootDir, outDir, typesOutPath, localesDir, extractionScope } as const;\n}\n\nfunction runWalker(config: CliConfig): ProjectAnalysis {\n const { rootDir, localesDir, extractionScope } = resolveConfig(config);\n\n return walkAll({\n pages: config.pages,\n rootDir,\n localesDir,\n defaultLocale: config.defaultLocale,\n extractionScope,\n hookSources: config.hookSources,\n });\n}\n\nfunction collectScopeNames(analysis: ProjectAnalysis): string[] {\n return [...new Set(analysis.routes.flatMap((route) => route.scopes))].sort();\n}\n\n/**\n * Pad a string to the given width.\n */\nfunction pad(str: string, width: number): string {\n return str + ' '.repeat(Math.max(0, width - str.length));\n}\n\n/**\n * Print a simple ASCII table to stdout.\n */\nfunction printTable(\n headers: string[],\n rows: string[][],\n): void {\n const colWidths = headers.map((h, i) =>\n Math.max(h.length, ...rows.map((r) => (r[i] ?? '').length)),\n );\n\n const sep =\n '\\u250c' +\n colWidths.map((w) => '\\u2500'.repeat(w + 2)).join('\\u252c') +\n '\\u2510';\n const mid =\n '\\u251c' +\n colWidths.map((w) => '\\u2500'.repeat(w + 2)).join('\\u253c') +\n '\\u2524';\n const bot =\n '\\u2514' +\n colWidths.map((w) => '\\u2500'.repeat(w + 2)).join('\\u2534') +\n '\\u2518';\n\n const formatRow = (cells: string[]) =>\n '\\u2502' +\n cells.map((c, i) => ' ' + pad(c, colWidths[i]) + ' ').join('\\u2502') +\n '\\u2502';\n\n console.log(sep);\n console.log(formatRow(headers));\n console.log(mid);\n for (const row of rows) {\n console.log(formatRow(row));\n }\n console.log(bot);\n}\n\n/**\n * Run the walker and print a summary table to stdout.\n * Returns the ProjectAnalysis for programmatic use.\n */\nexport function analyze(config: CliConfig): ProjectAnalysis {\n const { localesDir } = resolveConfig(config);\n const analysis = runWalker(config);\n\n const availableKeys = flattenLocaleKeys(localesDir, config.defaultLocale);\n const totalAvailable = Array.from(availableKeys.values()).reduce(\n (sum, keys) => sum + keys.length,\n 0,\n );\n\n const rows = analysis.routes.map((route) => {\n const usedCount = route.keys.filter((k) => !k.dynamic).length;\n return [\n route.routeId,\n String(usedCount),\n String(totalAvailable),\n String(totalAvailable - usedCount),\n ];\n });\n\n printTable(['Route', 'Used Keys', 'Available', 'Pruned'], rows);\n\n console.log(\n `\\n${analysis.routes.length} route(s), ${analysis.allKeys.length} unique key(s), ${analysis.availableNamespaces.length} namespace(s)`,\n );\n\n return analysis;\n}\n\n/**\n * Run the walker, then generate bundles and types.\n * Prints what was generated to stdout.\n */\nexport function generate(config: CliConfig): void {\n const { outDir, typesOutPath, localesDir } = resolveConfig(config);\n const analysis = runWalker(config);\n\n const bundles = generateBundles(analysis, {\n localesDir,\n locales: config.locales,\n outDir,\n crossNamespacePacking: config.crossNamespacePacking,\n });\n\n writeTypes(localesDir, config.defaultLocale, typesOutPath, collectScopeNames(analysis));\n\n console.log(`Generated ${bundles.length} bundle(s):`);\n for (const b of bundles) {\n console.log(` ${b.locale}/${b.name} — ${b.keyCount} keys (${b.prunedCount} pruned)`);\n }\n console.log(`Types written to ${typesOutPath}`);\n}\n\n/**\n * Run the walker, then generate diagnostic reports.\n * Prints summary to stdout.\n */\nexport function report(config: CliConfig): void {\n const { outDir, localesDir } = resolveConfig(config);\n const analysis = runWalker(config);\n\n generateReports(analysis, localesDir, config.defaultLocale, outDir, config.dictionaries);\n\n console.log(`Reports written to ${outDir}:`);\n console.log(' manifest.json');\n console.log(' missing.json');\n console.log(' unused.json');\n console.log(' stats.json');\n}\n\n/**\n * Run the walker, then compile pre-resolved flat Map modules.\n * Prints a summary to stdout.\n */\nexport function compile(config: CliConfig): void {\n const { outDir, localesDir } = resolveConfig(config);\n const analysis = runWalker(config);\n const compiledOutDir = path.join(outDir, 'compiled');\n\n compileAll(analysis, {\n localesDir,\n locales: config.locales,\n defaultLocale: config.defaultLocale,\n outDir: compiledOutDir,\n dictionaries: config.dictionaries,\n crossNamespacePacking: config.crossNamespacePacking,\n });\n\n // Count generated modules: one per route per locale, plus dictionary modules\n const routeModules = analysis.routes.length * config.locales.length;\n const dictModules =\n config.dictionaries && Object.keys(config.dictionaries).length > 0\n ? config.locales.length\n : 0;\n const total = routeModules + dictModules + 1; // +1 for manifest\n\n console.log(`Compiled ${total} module(s) to ${compiledOutDir}`);\n}\n\n/**\n * Run analyze + generate + compile + report all at once.\n */\nexport function build(config: CliConfig): void {\n const { outDir, typesOutPath, localesDir } = resolveConfig(config);\n const analysis = runWalker(config);\n\n // Analyze: print table\n const availableKeys = flattenLocaleKeys(localesDir, config.defaultLocale);\n const totalAvailable = Array.from(availableKeys.values()).reduce(\n (sum, keys) => sum + keys.length,\n 0,\n );\n\n const rows = analysis.routes.map((route) => {\n const usedCount = route.keys.filter((k) => !k.dynamic).length;\n return [\n route.routeId,\n String(usedCount),\n String(totalAvailable),\n String(totalAvailable - usedCount),\n ];\n });\n\n printTable(['Route', 'Used Keys', 'Available', 'Pruned'], rows);\n\n // Generate bundles + types\n const bundles = generateBundles(analysis, {\n localesDir,\n locales: config.locales,\n outDir,\n crossNamespacePacking: config.crossNamespacePacking,\n });\n\n writeTypes(localesDir, config.defaultLocale, typesOutPath, collectScopeNames(analysis));\n\n console.log(`\\nGenerated ${bundles.length} bundle(s)`);\n console.log(`Types written to ${typesOutPath}`);\n\n // Compile\n const compiledOutDir = path.join(outDir, 'compiled');\n compileAll(analysis, {\n localesDir,\n locales: config.locales,\n defaultLocale: config.defaultLocale,\n outDir: compiledOutDir,\n dictionaries: config.dictionaries,\n crossNamespacePacking: config.crossNamespacePacking,\n });\n console.log(`Compiled modules written to ${compiledOutDir}`);\n\n // Reports\n generateReports(analysis, localesDir, config.defaultLocale, outDir, config.dictionaries);\n\n console.log(`Reports written to ${outDir}`);\n console.log(\n `\\nDone. ${analysis.routes.length} route(s), ${analysis.allKeys.length} unique key(s).`,\n );\n}\n","#!/usr/bin/env node\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport { analyze, generate, compile, report, build } from './commands';\nimport type { CliConfig } from './commands';\n\nconst COMMANDS = ['analyze', 'generate', 'compile', 'report', 'build'] as const;\ntype Command = (typeof COMMANDS)[number];\n\nfunction printUsage(): void {\n console.log('Usage: vite-bundled-i18n <command> [--config <path>]');\n console.log('');\n console.log('Commands:');\n console.log(' analyze — Walk imports and print a summary of key usage per route');\n console.log(' generate — Generate tree-shaken bundles and TypeScript types');\n console.log(' report — Generate diagnostic reports (manifest, missing, unused, stats)');\n console.log(' compile — Compile pre-resolved flat Map modules for production');\n console.log(' build — Run analyze + generate + compile + report in one step');\n console.log('');\n console.log('Options:');\n console.log(' --config <path> Path to config file (default: i18n.config.json)');\n}\n\nfunction loadConfig(configPath: string): CliConfig {\n const resolved = path.resolve(configPath);\n if (!fs.existsSync(resolved)) {\n console.error(`Config file not found: ${resolved}`);\n process.exit(1);\n }\n\n const raw = fs.readFileSync(resolved, 'utf-8');\n return JSON.parse(raw) as CliConfig;\n}\n\nfunction parseArgs(argv: string[]): { command: Command; configPath: string } {\n const args = argv.slice(2);\n let command: Command | undefined;\n let configPath = 'i18n.config.json';\n\n for (let i = 0; i < args.length; i++) {\n const arg = args[i];\n if (arg === '--config' && i + 1 < args.length) {\n configPath = args[++i];\n } else if (arg === '--help' || arg === '-h') {\n printUsage();\n process.exit(0);\n } else if (!command && COMMANDS.includes(arg as Command)) {\n command = arg as Command;\n } else {\n console.error(`Unknown argument: ${arg}`);\n printUsage();\n process.exit(1);\n }\n }\n\n if (!command) {\n printUsage();\n process.exit(1);\n }\n\n return { command: command!, configPath };\n}\n\nconst { command, configPath } = parseArgs(process.argv);\nconst config = loadConfig(configPath);\n\nconst commands: Record<Command, (cfg: CliConfig) => void> = {\n analyze,\n generate,\n compile,\n report,\n build,\n};\n\ncommands[command](config);\n"],"mappings":";;;;;AAsCA,SAAS,cAAc,QAAmB;CACxC,MAAM,UAAU,OAAO,WAAW,QAAQ,KAAK;CAC/C,MAAM,SAAS,OAAO,UAAU,KAAK,KAAK,SAAS,QAAQ;AAQ3D,QAAO;EAAE;EAAS;EAAQ,cANxB,OAAO,gBAAgB,KAAK,KAAK,QAAQ,oBAAoB;EAMvB,YALrB,KAAK,WAAW,OAAO,WAAW,GACjD,OAAO,aACP,KAAK,KAAK,SAAS,OAAO,WAAW;EAGW,iBAF5B,OAAO,mBAAmB;EAEmB;;AAGvE,SAAS,UAAU,QAAoC;CACrD,MAAM,EAAE,SAAS,YAAY,oBAAoB,cAAc,OAAO;AAEtE,QAAO,QAAQ;EACb,OAAO,OAAO;EACd;EACA;EACA,eAAe,OAAO;EACtB;EACA,aAAa,OAAO;EACrB,CAAC;;AAGJ,SAAS,kBAAkB,UAAqC;AAC9D,QAAO,CAAC,GAAG,IAAI,IAAI,SAAS,OAAO,SAAS,UAAU,MAAM,OAAO,CAAC,CAAC,CAAC,MAAM;;;;;AAM9E,SAAS,IAAI,KAAa,OAAuB;AAC/C,QAAO,MAAM,IAAI,OAAO,KAAK,IAAI,GAAG,QAAQ,IAAI,OAAO,CAAC;;;;;AAM1D,SAAS,WACP,SACA,MACM;CACN,MAAM,YAAY,QAAQ,KAAK,GAAG,MAChC,KAAK,IAAI,EAAE,QAAQ,GAAG,KAAK,KAAK,OAAO,EAAE,MAAM,IAAI,OAAO,CAAC,CAC5D;CAED,MAAM,MACJ,MACA,UAAU,KAAK,MAAM,IAAS,OAAO,IAAI,EAAE,CAAC,CAAC,KAAK,IAAS,GAC3D;CACF,MAAM,MACJ,MACA,UAAU,KAAK,MAAM,IAAS,OAAO,IAAI,EAAE,CAAC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f,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"}
@@ -64,7 +64,16 @@ function keyNamespace(key) {
64
64
  const dotIndex = source.indexOf(".");
65
65
  return dotIndex === -1 ? void 0 : source.slice(0, dotIndex);
66
66
  }
67
- function buildScopePlans(analysis, availableKeys) {
67
+ function getOrCreate(map, key) {
68
+ let set = map.get(key);
69
+ if (!set) {
70
+ set = /* @__PURE__ */ new Set();
71
+ map.set(key, set);
72
+ }
73
+ return set;
74
+ }
75
+ function buildScopePlans(analysis, availableKeys, options = {}) {
76
+ const { crossNamespacePacking = false } = options;
68
77
  const scopePlans = /* @__PURE__ */ new Map();
69
78
  const allAvailableKeys = [...availableKeys];
70
79
  for (const route of analysis.routes) for (const scope of route.scopes) {
@@ -75,19 +84,24 @@ function buildScopePlans(analysis, availableKeys) {
75
84
  scope,
76
85
  namespace,
77
86
  keys: /* @__PURE__ */ new Set(),
87
+ extras: /* @__PURE__ */ new Map(),
78
88
  routeIds: /* @__PURE__ */ new Set()
79
89
  };
80
90
  scopePlans.set(scope, plan);
81
91
  }
82
92
  plan.routeIds.add(route.routeId);
83
93
  for (const key of route.keys) {
84
- if (keyNamespace(key) !== namespace) continue;
94
+ const ns = keyNamespace(key);
95
+ if (!ns) continue;
96
+ const isPrimary = ns === namespace;
97
+ if (!isPrimary && !crossNamespacePacking) continue;
98
+ const bucket = isPrimary ? plan.keys : getOrCreate(plan.extras, ns);
85
99
  if (!key.dynamic) {
86
- plan.keys.add(key.key);
100
+ bucket.add(key.key);
87
101
  continue;
88
102
  }
89
103
  if (!key.staticPrefix) continue;
90
- for (const availableKey of allAvailableKeys) if (availableKey.startsWith(key.staticPrefix)) plan.keys.add(availableKey);
104
+ for (const availableKey of allAvailableKeys) if (availableKey.startsWith(key.staticPrefix)) bucket.add(availableKey);
91
105
  }
92
106
  }
93
107
  return [...scopePlans.values()].sort((a, b) => a.scope.localeCompare(b.scope));
@@ -161,14 +175,14 @@ function readNamespaceFile(localesDir, locale, namespace) {
161
175
  * Generate tree-shaken per-route translation bundles from project analysis.
162
176
  */
163
177
  function generateBundles(analysis, options) {
164
- const { localesDir, locales, outDir, dictionaries } = options;
178
+ const { localesDir, locales, outDir, dictionaries, crossNamespacePacking } = options;
165
179
  const bundles = [];
166
180
  const availableKeys = /* @__PURE__ */ new Set();
167
181
  for (const route of analysis.routes) for (const key of route.keys) if (!key.dynamic) availableKeys.add(key.key);
168
182
  const ownership = resolveDictionaryOwnership(availableKeys, dictionaries);
169
183
  const hasNamedDictionaries = ownership.rules.length > 0;
170
184
  const sharedNsSet = hasNamedDictionaries ? /* @__PURE__ */ new Set() : new Set(analysis.sharedNamespaces);
171
- for (const plan of buildScopePlans(analysis, availableKeys)) for (const locale of locales) {
185
+ for (const plan of buildScopePlans(analysis, availableKeys, { crossNamespacePacking })) for (const locale of locales) {
172
186
  const bundleData = {};
173
187
  let totalKeyCount = 0;
174
188
  let totalPrunedCount = 0;
@@ -185,6 +199,18 @@ function generateBundles(analysis, options) {
185
199
  totalKeyCount += keptCount;
186
200
  totalPrunedCount += availableCount - keptCount;
187
201
  }
202
+ if (crossNamespacePacking) for (const [extraNs, extraKeys] of plan.extras) {
203
+ const retained = [...extraKeys].filter((k) => !ownership.keyOwner.has(k));
204
+ if (retained.length === 0) continue;
205
+ if (!hasNamedDictionaries && sharedNsSet.has(extraNs)) continue;
206
+ const extraSubKeys = retained.filter((key) => key.startsWith(`${extraNs}.`)).map((key) => key.slice(extraNs.length + 1));
207
+ if (extraSubKeys.length === 0) continue;
208
+ const extraFullData = readNamespaceFile(localesDir, locale, extraNs);
209
+ if (!extraFullData) continue;
210
+ const pruned = pruneNamespace(extraFullData, [...new Set(extraSubKeys)]);
211
+ bundleData[extraNs] = pruned;
212
+ totalKeyCount += flattenKeys(pruned).length;
213
+ }
188
214
  const filePath = path.join(outDir, locale, `${plan.scope}.json`);
189
215
  fs.mkdirSync(path.dirname(filePath), { recursive: true });
190
216
  fs.writeFileSync(filePath, JSON.stringify(bundleData, null, 2));
@@ -707,15 +733,29 @@ var PACKAGE_NAMES = new Set([
707
733
  ]);
708
734
  /**
709
735
  * Package specifiers recognized as ours.
736
+ *
737
+ * @param specifier - The import module specifier to check.
738
+ * @param hookSources - Additional module specifiers configured via `extraction.hookSources`.
739
+ */
740
+ function isOurPackage(specifier, hookSources) {
741
+ return PACKAGE_NAMES.has(specifier) || specifier.includes("/core/t") || specifier.includes("/react/useI18n") || matchesHookSource(specifier, hookSources);
742
+ }
743
+ /**
744
+ * Checks if a module specifier exports `useI18n`.
745
+ *
746
+ * @param specifier - The import module specifier to check.
747
+ * @param hookSources - Additional module specifiers configured via `extraction.hookSources`.
710
748
  */
711
- function isOurPackage(specifier) {
712
- return PACKAGE_NAMES.has(specifier) || specifier.includes("/core/t") || specifier.includes("/react/useI18n");
749
+ function isUseI18nPackage(specifier, hookSources) {
750
+ return specifier === "vite-bundled-i18n/react" || specifier === "vite-i18n-manager/react" || specifier.includes("/react/useI18n") || matchesHookSource(specifier, hookSources);
713
751
  }
714
752
  /**
715
- * Checks if a module specifier is one that exports `useI18n`.
753
+ * Checks if a specifier matches any configured hook source.
754
+ * Uses exact match or endsWith to handle path alias resolution.
716
755
  */
717
- function isUseI18nPackage(specifier) {
718
- return specifier === "vite-bundled-i18n/react" || specifier === "vite-i18n-manager/react" || specifier.includes("/react/useI18n");
756
+ function matchesHookSource(specifier, hookSources) {
757
+ if (!hookSources || hookSources.length === 0) return false;
758
+ return hookSources.some((source) => specifier === source || specifier.endsWith(source));
719
759
  }
720
760
  /**
721
761
  * Checks if a module specifier is one that exports the global `t`.
@@ -756,7 +796,7 @@ function findTranslationCalls(sourceFile, options) {
756
796
  if (!ts.isImportDeclaration(node)) return;
757
797
  if (!ts.isStringLiteral(node.moduleSpecifier)) return;
758
798
  const specifier = node.moduleSpecifier.text;
759
- if (!isOurPackage(specifier)) return;
799
+ if (!isOurPackage(specifier, options.hookSources)) return;
760
800
  const clause = node.importClause;
761
801
  if (!clause) return;
762
802
  const bindings = clause.namedBindings;
@@ -767,8 +807,8 @@ function findTranslationCalls(sourceFile, options) {
767
807
  if (importedName === "t" && isGlobalTPackage(specifier)) {
768
808
  if (options.scope !== "scoped") trackedNames.set(localName, "global");
769
809
  }
770
- if (importedName === "useI18n" && isUseI18nPackage(specifier)) useI18nNames.add(localName);
771
- if (importedName === "i18nKey" && isOurPackage(specifier)) i18nKeyNames.add(localName);
810
+ if (importedName === "useI18n" && isUseI18nPackage(specifier, options.hookSources)) useI18nNames.add(localName);
811
+ if (importedName === "i18nKey" && isOurPackage(specifier, options.hookSources)) i18nKeyNames.add(localName);
772
812
  }
773
813
  });
774
814
  ts.forEachChild(sourceFile, (node) => {
@@ -929,15 +969,18 @@ function findTranslationCalls(sourceFile, options) {
929
969
  }
930
970
  /**
931
971
  * Extracts scope strings from all useI18n() calls in a source file.
972
+ *
973
+ * @param sourceFile - The parsed TypeScript source file.
974
+ * @param hookSources - Additional module specifiers that export `useI18n`.
932
975
  */
933
- function extractScopes(sourceFile) {
976
+ function extractScopes(sourceFile, hookSources) {
934
977
  const scopes = [];
935
978
  const useI18nNames = /* @__PURE__ */ new Set();
936
979
  ts.forEachChild(sourceFile, (node) => {
937
980
  if (!ts.isImportDeclaration(node)) return;
938
981
  if (!ts.isStringLiteral(node.moduleSpecifier)) return;
939
982
  const specifier = node.moduleSpecifier.text;
940
- if (!isUseI18nPackage(specifier)) return;
983
+ if (!isUseI18nPackage(specifier, hookSources)) return;
941
984
  const clause = node.importClause;
942
985
  if (!clause) return;
943
986
  const bindings = clause.namedBindings;
@@ -999,7 +1042,7 @@ function extractKeys(source, options) {
999
1042
  };
1000
1043
  }
1001
1044
  const keys = findTranslationCalls(sourceFile, opts);
1002
- const scopes = extractScopes(sourceFile);
1045
+ const scopes = extractScopes(sourceFile, opts.hookSources);
1003
1046
  const imports = collectImports(sourceFile);
1004
1047
  return {
1005
1048
  filePath: opts.filePath,
@@ -1138,7 +1181,8 @@ function walkRoute(entryPoint, options) {
1138
1181
  allFiles.push(resolved);
1139
1182
  const result = extractKeys(source, {
1140
1183
  scope: options.extractionScope,
1141
- filePath: resolved
1184
+ filePath: resolved,
1185
+ hookSources: options.hookSources
1142
1186
  });
1143
1187
  for (const key of result.keys) if (!seenKeys.has(key.key)) {
1144
1188
  seenKeys.add(key.key);
@@ -1171,7 +1215,8 @@ function walkAll(options) {
1171
1215
  absolute: true
1172
1216
  }).map((entry) => walkRoute(entry, {
1173
1217
  rootDir,
1174
- extractionScope
1218
+ extractionScope,
1219
+ hookSources: options.hookSources
1175
1220
  }));
1176
1221
  const availableNamespaces = discoverNamespaces(path.isAbsolute(options.localesDir) ? options.localesDir : path.join(rootDir, options.localesDir), options.defaultLocale);
1177
1222
  const allKeysMap = /* @__PURE__ */ new Map();
@@ -1320,13 +1365,17 @@ function generateManifest(scopeIds, locales, dictionaryNames) {
1320
1365
  * Orchestrates the full compilation of pre-compiled i18n modules.
1321
1366
  */
1322
1367
  function compileAll(analysis, options) {
1323
- const { localesDir, locales, defaultLocale, outDir, dictionaries } = options;
1368
+ const { localesDir, locales, defaultLocale, outDir, dictionaries, crossNamespacePacking } = options;
1324
1369
  fs.mkdirSync(outDir, { recursive: true });
1325
1370
  const defaultFullMap = buildFullLocaleMap(localesDir, defaultLocale);
1326
1371
  const ownership = resolveDictionaryOwnership(defaultFullMap.keys(), dictionaries);
1327
- const scopePlans = buildScopePlans(analysis, defaultFullMap.keys());
1372
+ const scopePlans = buildScopePlans(analysis, defaultFullMap.keys(), { crossNamespacePacking });
1328
1373
  for (const plan of scopePlans) {
1329
1374
  const usedKeys = new Set([...plan.keys].filter((key) => !ownership.keyOwner.has(key)));
1375
+ if (crossNamespacePacking) for (const extraKeys of plan.extras.values()) for (const key of extraKeys) {
1376
+ if (ownership.keyOwner.has(key)) continue;
1377
+ usedKeys.add(key);
1378
+ }
1330
1379
  for (const locale of locales) {
1331
1380
  const localeDir = path.join(outDir, locale);
1332
1381
  fs.mkdirSync(localeDir, { recursive: true });
@@ -1348,6 +1397,6 @@ function compileAll(analysis, options) {
1348
1397
  fs.writeFileSync(path.join(outDir, "manifest.js"), manifestSource);
1349
1398
  }
1350
1399
  //#endregion
1351
- export { generateReports as a, flattenKeys as c, keyMatchesPattern as d, normalizeDictionaries as f, generateDictionaryOwnershipReport as i, generateBundles as l, walkAll as n, generateTypes as o, resolveDictionaryOwnership as p, flattenLocaleKeys as r, writeTypes as s, compileAll as t, pruneNamespace as u };
1400
+ export { generateReports as a, flattenKeys as c, buildScopePlans as d, inferScopeNamespace as f, resolveDictionaryOwnership as h, generateDictionaryOwnershipReport as i, generateBundles as l, normalizeDictionaries as m, walkAll as n, generateTypes as o, keyMatchesPattern as p, flattenLocaleKeys as r, writeTypes as s, compileAll as t, pruneNamespace as u };
1352
1401
 
1353
- //# sourceMappingURL=compiler-B8vL51ge.js.map
1402
+ //# sourceMappingURL=compiler-CMOyCfBe.js.map