vite-bundled-i18n 0.5.0 → 0.6.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 (51) hide show
  1. package/README.md +27 -1
  2. package/dist/cli/commands.d.ts +11 -0
  3. package/dist/cli/index.js +43 -4
  4. package/dist/cli/index.js.map +1 -1
  5. package/dist/context-B66VMNFr.js +14 -0
  6. package/dist/context-B66VMNFr.js.map +1 -0
  7. package/dist/core/config.d.ts +34 -0
  8. package/dist/core/i18n-generated-shim.d.ts +18 -0
  9. package/dist/core/i18n-generated-shim.js +23 -0
  10. package/dist/core/i18n-generated-shim.js.map +1 -0
  11. package/dist/core/scope-map-client.d.ts +79 -0
  12. package/dist/core/services/readiness-gate.d.ts +57 -0
  13. package/dist/core/types.d.ts +42 -2
  14. package/dist/{data-Yv_f3OCA.js → data-DtpMCpiZ.js} +85 -7
  15. package/dist/data-DtpMCpiZ.js.map +1 -0
  16. package/dist/extractor/bundle-generator.d.ts +4 -2
  17. package/dist/extractor/dynamic-keys.d.ts +41 -0
  18. package/dist/extractor/scope-registration.d.ts +50 -0
  19. package/dist/extractor/type-generator.d.ts +29 -2
  20. package/dist/extractor/walker-types.d.ts +6 -0
  21. package/dist/{getTranslations-BdfteEhG.js → getTranslations-htem-Z8C.js} +9 -1
  22. package/dist/getTranslations-htem-Z8C.js.map +1 -0
  23. package/dist/index.d.ts +4 -0
  24. package/dist/index.js +70 -5
  25. package/dist/index.js.map +1 -0
  26. package/dist/{mountDevtools-CtiMC5PM.js → mountDevtools-DgjYMAiI.js} +25 -6
  27. package/dist/mountDevtools-DgjYMAiI.js.map +1 -0
  28. package/dist/plugin/buildPlugin.d.ts +59 -0
  29. package/dist/plugin.js +166 -116
  30. package/dist/plugin.js.map +1 -1
  31. package/dist/react/GateBoundary.d.ts +45 -0
  32. package/dist/react/useGate.d.ts +20 -0
  33. package/dist/react.d.ts +3 -0
  34. package/dist/react.js +67 -15
  35. package/dist/react.js.map +1 -1
  36. package/dist/{compiler-DFE3gpoU.js → scope-registration-ACWKuj8f.js} +295 -4
  37. package/dist/scope-registration-ACWKuj8f.js.map +1 -0
  38. package/dist/{server-C0yDN0XT.js → server-D_J3294k.js} +3 -3
  39. package/dist/{server-C0yDN0XT.js.map → server-D_J3294k.js.map} +1 -1
  40. package/dist/server.js +3 -3
  41. package/dist/testing.js +73 -0
  42. package/dist/testing.js.map +1 -0
  43. package/dist/vanilla.js +4 -4
  44. package/dist/vue.d.ts +19 -0
  45. package/dist/vue.js +47 -6
  46. package/dist/vue.js.map +1 -1
  47. package/package.json +7 -2
  48. package/dist/compiler-DFE3gpoU.js.map +0 -1
  49. package/dist/data-Yv_f3OCA.js.map +0 -1
  50. package/dist/getTranslations-BdfteEhG.js.map +0 -1
  51. package/dist/mountDevtools-CtiMC5PM.js.map +0 -1
package/README.md CHANGED
@@ -165,6 +165,31 @@ function ProductsPage() {
165
165
 
166
166
  **`useI18n(scope)`** triggers a single HTTP request to load the scope bundle. Dictionaries are always available. Previously visited scopes are instant (cached). Missing-key warnings are automatically suppressed while a scope is loading — no need to guard every `useMemo`.
167
167
 
168
+ **`useI18n()` without a scope** returns a translator bound to the current cache — whatever's already loaded (dictionaries + any scope the parent or sibling components registered). Use this in child components below a page that has already declared its scope, or in layout components that only read dictionary keys.
169
+
170
+ ```tsx
171
+ // Pattern A — page registers its own scope
172
+ function ProductsPage() {
173
+ const { t } = useI18n('products.show') // loads products.show bundle
174
+ return <section><Header /><Details /></section>
175
+ }
176
+
177
+ // Pattern B — page composes children; each child declares its own scope
178
+ function AdminPage() {
179
+ return <><Sidebar /><MainContent /></> // no scope at the page level
180
+ }
181
+ function Sidebar() {
182
+ const { t } = useI18n('sidebar.admin') // child registers
183
+ return <nav>{t('sidebar.admin.heading')}</nav>
184
+ }
185
+ function MainContent() {
186
+ const { t } = useI18n() // reads whatever's loaded
187
+ return <main>{t('sidebar.admin.welcome')}</main>
188
+ }
189
+ ```
190
+
191
+ Both patterns feed the same `PAGE_SCOPE_MAP` — the walker aggregates scopes across the full route tree, so routers using the [integration pattern](#router-integration) preload correctly either way.
192
+
168
193
  **`I18nBoundary`** handles scope loading without early returns:
169
194
 
170
195
  ```tsx
@@ -428,6 +453,7 @@ cache: {
428
453
  | `vite-bundled-i18n/server` | `initServerI18n` (SSR) |
429
454
  | `vite-bundled-i18n/plugin` | Vite plugin (`i18nPlugin`) |
430
455
  | `vite-bundled-i18n/generated` | Generated types + `PAGE_SCOPE_MAP` / `I18nPageIdentifier` |
456
+ | `vite-bundled-i18n/testing` | `createTestI18n`, `I18nTestProvider`, `createI18nTestPlugin` |
431
457
 
432
458
  ## Documentation
433
459
 
@@ -437,7 +463,7 @@ cache: {
437
463
 
438
464
  ## Releases
439
465
 
440
- Current release: **v0.5.0** — persistent extraction cache, framework-neutral page scope map, typed `PAGE_SCOPE_MAP`, `loadScope` concurrency guarantees.
466
+ Current release: **v0.6.0** — framework-agnostic readiness gate (`i18n.gate`, `<GateBoundary>`, `useGate()`), runtime `createScopeMapClient()`, `t.dynamic()` escape hatch, `bundling.dynamicKeys` + `strictScopeRegistration`, `vite-bundled-i18n/testing` subpackage. Breaking: `loadScope` now auto-registers with the gate by default — opt out via `{ trackReadiness: false }`.
441
467
 
442
468
  Version history lives in the [git log](https://github.com/nicolasvlachos/vite-bundled-i18n/commits/main) — each release is a `feat: v{version}` commit with a summary of the changes.
443
469
 
@@ -26,6 +26,17 @@ export interface CliConfig {
26
26
  * See `I18nSharedConfig.bundling.crossNamespacePacking`.
27
27
  */
28
28
  crossNamespacePacking?: boolean;
29
+ /**
30
+ * Runtime-computed keys to treat as always-extracted. Matches
31
+ * `I18nSharedConfig.bundling.dynamicKeys`. CLI-side JSON config only,
32
+ * since function-based identifiers aren't serializable.
33
+ */
34
+ dynamicKeys?: readonly string[];
35
+ /**
36
+ * Severity for the "page registers no scope" audit. Matches
37
+ * `I18nSharedConfig.bundling.strictScopeRegistration`.
38
+ */
39
+ strictScopeRegistration?: 'off' | 'warn' | 'error';
29
40
  /**
30
41
  * Extraction cache control. `false` disables, an object configures the
31
42
  * backing directory and persistence. Env vars (`VITE_I18N_NO_CACHE`,
package/dist/cli/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { a as createExtractionCache, d as generateReports, h as generateBundles, i as computeConfigHash, l as flattenLocaleKeys, n as PLUGIN_VERSION, p as writeTypes, r as resolveCacheConfig, s as walkAll, t as compileAll } from "../compiler-DFE3gpoU.js";
2
+ import { _ as writeRuntimeConst, a as PLUGIN_VERSION, b as generateBundles, c as createExtractionCache, f as flattenLocaleKeys, g as runtimePathFromTypesPath, i as buildScopeMap, m as generateReports, n as compileAll, o as resolveCacheConfig, r as applyDynamicKeys, s as computeConfigHash, t as checkScopeRegistration, u as walkAll, v as writeTypes } from "../scope-registration-ACWKuj8f.js";
3
3
  import fs from "node:fs";
4
4
  import path from "node:path";
5
5
  //#region src/cli/commands.ts
@@ -43,7 +43,7 @@ function persistCache(config, cache, rootDir) {
43
43
  }
44
44
  function runWalker(config, cache) {
45
45
  const { rootDir, localesDir, extractionScope } = resolveConfig(config);
46
- return walkAll({
46
+ const analysis = walkAll({
47
47
  pages: config.pages,
48
48
  rootDir,
49
49
  localesDir,
@@ -52,11 +52,50 @@ function runWalker(config, cache) {
52
52
  hookSources: config.hookSources,
53
53
  cache
54
54
  });
55
+ if (config.dynamicKeys && config.dynamicKeys.length > 0) {
56
+ const report = applyDynamicKeys(analysis, {
57
+ dynamicKeys: config.dynamicKeys,
58
+ dictionaries: config.dictionaries,
59
+ crossNamespacePacking: config.crossNamespacePacking
60
+ });
61
+ for (const orphan of report.orphans) console.warn(`[vite-bundled-i18n] dynamicKeys entry "${orphan}" matches no route and no dictionary — it won't ship anywhere.`);
62
+ }
63
+ const strictMode = config.strictScopeRegistration ?? "warn";
64
+ if (strictMode !== "off") {
65
+ const report = checkScopeRegistration(analysis, {
66
+ rootDir,
67
+ mode: strictMode
68
+ });
69
+ if (report.violations.length > 0) {
70
+ if (strictMode === "error") throw new Error("vite-bundled-i18n: scope registration failures (strictScopeRegistration: 'error'):\n\n" + report.messages.join("\n\n"));
71
+ for (const message of report.messages) console.warn(message);
72
+ }
73
+ }
74
+ return analysis;
55
75
  }
56
76
  function collectScopeNames(analysis) {
57
77
  return [...new Set(analysis.routes.flatMap((route) => route.scopes))].sort();
58
78
  }
59
79
  /**
80
+ * Emit both the typed `.ts` (for TSC/IDE) and runtime `.js` (for Vite
81
+ * resolve.alias) generated files. Called by every CLI command that
82
+ * previously only wrote the `.ts` file — keeps CLI output aligned with
83
+ * the Vite plugin's `emitGeneratedArtifacts` so there's no drift.
84
+ */
85
+ function emitGeneratedPair(analysis, config, localesDir, rootDir, typesOutPath) {
86
+ const scopeNames = collectScopeNames(analysis);
87
+ const scopeMap = buildScopeMap(analysis, {
88
+ rootDir,
89
+ defaultLocale: config.defaultLocale,
90
+ dictionaries: config.dictionaries
91
+ });
92
+ const pageScopeMap = {};
93
+ for (const [id, entry] of Object.entries(scopeMap.pages)) pageScopeMap[id] = entry.scopes;
94
+ const hasPageMap = Object.keys(pageScopeMap).length > 0;
95
+ writeTypes(localesDir, config.defaultLocale, typesOutPath, scopeNames, hasPageMap ? pageScopeMap : void 0);
96
+ writeRuntimeConst(runtimePathFromTypesPath(typesOutPath), hasPageMap ? pageScopeMap : void 0);
97
+ }
98
+ /**
60
99
  * Pad a string to the given width.
61
100
  */
62
101
  function pad(str, width) {
@@ -120,7 +159,7 @@ function generate(config) {
120
159
  outDir,
121
160
  crossNamespacePacking: config.crossNamespacePacking
122
161
  });
123
- writeTypes(localesDir, config.defaultLocale, typesOutPath, collectScopeNames(analysis));
162
+ emitGeneratedPair(analysis, config, localesDir, rootDir, typesOutPath);
124
163
  console.log(`Generated ${bundles.length} bundle(s):`);
125
164
  for (const b of bundles) console.log(` ${b.locale}/${b.name} — ${b.keyCount} keys (${b.prunedCount} pruned)`);
126
165
  console.log(`Types written to ${typesOutPath}`);
@@ -192,7 +231,7 @@ function build(config) {
192
231
  outDir,
193
232
  crossNamespacePacking: config.crossNamespacePacking
194
233
  });
195
- writeTypes(localesDir, config.defaultLocale, typesOutPath, collectScopeNames(analysis));
234
+ emitGeneratedPair(analysis, config, localesDir, rootDir, typesOutPath);
196
235
  console.log(`\nGenerated ${bundles.length} bundle(s)`);
197
236
  console.log(`Types written to ${typesOutPath}`);
198
237
  const compiledOutDir = path.join(outDir, "compiled");
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../src/cli/commands.ts","../../src/cli/index.ts"],"sourcesContent":["import fs from 'node:fs';\nimport 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';\nimport {\n createExtractionCache,\n computeConfigHash,\n type ExtractionCache,\n} from '../extractor/extraction-cache';\nimport { resolveCacheConfig } from '../extractor/cache-config';\nimport { PLUGIN_VERSION } from '../plugin/version';\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 * Extraction cache control. `false` disables, an object configures the\n * backing directory and persistence. Env vars (`VITE_I18N_NO_CACHE`,\n * `VITE_I18N_CLEAR_CACHE`, `VITE_I18N_CACHE_DEBUG`) always take\n * precedence. See `resolveCacheConfig`.\n */\n cache?: boolean | {\n enabled?: boolean;\n dir?: string;\n persist?: boolean;\n };\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 buildCliCache(config: CliConfig, rootDir: string): ExtractionCache | undefined {\n const cacheSettings = resolveCacheConfig(config.cache, { rootDir });\n if (!cacheSettings.enabled) return undefined;\n\n if (cacheSettings.clearBeforeStart) {\n try {\n fs.rmSync(cacheSettings.dir, { recursive: true, force: true });\n } catch {\n // Non-fatal — fall through to a fresh cache.\n }\n }\n\n return createExtractionCache({\n dir: cacheSettings.dir,\n pluginVersion: PLUGIN_VERSION,\n configHash: computeConfigHash({\n pages: config.pages,\n defaultLocale: config.defaultLocale,\n extractionScope: config.extractionScope ?? 'global',\n hookSources: config.hookSources,\n dictionaries: config.dictionaries,\n crossNamespacePacking: config.crossNamespacePacking,\n }),\n debug: cacheSettings.debug,\n });\n}\n\nfunction persistCache(config: CliConfig, cache: ExtractionCache | undefined, rootDir: string): void {\n if (!cache) return;\n const cacheSettings = resolveCacheConfig(config.cache, { rootDir });\n if (cacheSettings.persist) {\n cache.persistToDisk();\n }\n}\n\nfunction runWalker(config: CliConfig, cache?: ExtractionCache): 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 cache,\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 { rootDir, localesDir } = resolveConfig(config);\n const cache = buildCliCache(config, rootDir);\n const analysis = runWalker(config, cache);\n persistCache(config, cache, rootDir);\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 { rootDir, outDir, typesOutPath, localesDir } = resolveConfig(config);\n const cache = buildCliCache(config, rootDir);\n const analysis = runWalker(config, cache);\n persistCache(config, cache, rootDir);\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 { rootDir, outDir, localesDir } = resolveConfig(config);\n const cache = buildCliCache(config, rootDir);\n const analysis = runWalker(config, cache);\n persistCache(config, cache, rootDir);\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 { rootDir, outDir, localesDir } = resolveConfig(config);\n const cache = buildCliCache(config, rootDir);\n const analysis = runWalker(config, cache);\n persistCache(config, cache, rootDir);\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 { rootDir, outDir, typesOutPath, localesDir } = resolveConfig(config);\n const cache = buildCliCache(config, rootDir);\n const analysis = runWalker(config, cache);\n persistCache(config, cache, rootDir);\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> [options]');\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 console.log(' --no-cache Disable the extraction cache for this run');\n console.log(' --clear-cache Clear the extraction cache before running');\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\ninterface ParsedArgs {\n command: Command;\n configPath: string;\n noCache: boolean;\n clearCache: boolean;\n}\n\nfunction parseArgs(argv: string[]): ParsedArgs {\n const args = argv.slice(2);\n let command: Command | undefined;\n let configPath = 'i18n.config.json';\n let noCache = false;\n let clearCache = false;\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 === '--no-cache') {\n noCache = true;\n } else if (arg === '--clear-cache') {\n clearCache = true;\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, noCache, clearCache };\n}\n\nconst { command, configPath, noCache, clearCache } = parseArgs(process.argv);\nconst config = loadConfig(configPath);\n\n// CLI flags merge into the config's `cache` field so downstream resolution\n// sees them. Env vars still take the final word via resolveCacheConfig.\nif (noCache) {\n config.cache = false;\n}\nif (clearCache) {\n // Resolve-time handling: a CLI-driven clear is honored even when config\n // doesn't opt into the cache object form. We signal via an env var so\n // the central resolver is the single source of truth.\n process.env.VITE_I18N_CLEAR_CACHE = '1';\n}\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":";;;;;AAyDA,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,cAAc,QAAmB,SAA8C;CACtF,MAAM,gBAAgB,mBAAmB,OAAO,OAAO,EAAE,SAAS,CAAC;AACnE,KAAI,CAAC,cAAc,QAAS,QAAO,KAAA;AAEnC,KAAI,cAAc,iBAChB,KAAI;AACF,KAAG,OAAO,cAAc,KAAK;GAAE,WAAW;GAAM,OAAO;GAAM,CAAC;SACxD;AAKV,QAAO,sBAAsB;EAC3B,KAAK,cAAc;EACnB,eAAe;EACf,YAAY,kBAAkB;GAC5B,OAAO,OAAO;GACd,eAAe,OAAO;GACtB,iBAAiB,OAAO,mBAAmB;GAC3C,aAAa,OAAO;GACpB,cAAc,OAAO;GACrB,uBAAuB,OAAO;GAC/B,CAAC;EACF,OAAO,cAAc;EACtB,CAAC;;AAGJ,SAAS,aAAa,QAAmB,OAAoC,SAAuB;AAClG,KAAI,CAA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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 fs from 'node:fs';\nimport path from 'node:path';\nimport { walkAll } from '../extractor/walker';\nimport { generateBundles } from '../extractor/bundle-generator';\nimport { writeTypes, writeRuntimeConst, runtimePathFromTypesPath } 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';\nimport {\n createExtractionCache,\n computeConfigHash,\n type ExtractionCache,\n} from '../extractor/extraction-cache';\nimport { resolveCacheConfig } from '../extractor/cache-config';\nimport { PLUGIN_VERSION } from '../plugin/version';\nimport { buildScopeMap } from '../extractor/scope-map';\nimport { applyDynamicKeys } from '../extractor/dynamic-keys';\nimport { checkScopeRegistration } from '../extractor/scope-registration';\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 * Runtime-computed keys to treat as always-extracted. Matches\n * `I18nSharedConfig.bundling.dynamicKeys`. CLI-side JSON config only,\n * since function-based identifiers aren't serializable.\n */\n dynamicKeys?: readonly string[];\n /**\n * Severity for the \"page registers no scope\" audit. Matches\n * `I18nSharedConfig.bundling.strictScopeRegistration`.\n */\n strictScopeRegistration?: 'off' | 'warn' | 'error';\n /**\n * Extraction cache control. `false` disables, an object configures the\n * backing directory and persistence. Env vars (`VITE_I18N_NO_CACHE`,\n * `VITE_I18N_CLEAR_CACHE`, `VITE_I18N_CACHE_DEBUG`) always take\n * precedence. See `resolveCacheConfig`.\n */\n cache?: boolean | {\n enabled?: boolean;\n dir?: string;\n persist?: boolean;\n };\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 buildCliCache(config: CliConfig, rootDir: string): ExtractionCache | undefined {\n const cacheSettings = resolveCacheConfig(config.cache, { rootDir });\n if (!cacheSettings.enabled) return undefined;\n\n if (cacheSettings.clearBeforeStart) {\n try {\n fs.rmSync(cacheSettings.dir, { recursive: true, force: true });\n } catch {\n // Non-fatal — fall through to a fresh cache.\n }\n }\n\n return createExtractionCache({\n dir: cacheSettings.dir,\n pluginVersion: PLUGIN_VERSION,\n configHash: computeConfigHash({\n pages: config.pages,\n defaultLocale: config.defaultLocale,\n extractionScope: config.extractionScope ?? 'global',\n hookSources: config.hookSources,\n dictionaries: config.dictionaries,\n crossNamespacePacking: config.crossNamespacePacking,\n }),\n debug: cacheSettings.debug,\n });\n}\n\nfunction persistCache(config: CliConfig, cache: ExtractionCache | undefined, rootDir: string): void {\n if (!cache) return;\n const cacheSettings = resolveCacheConfig(config.cache, { rootDir });\n if (cacheSettings.persist) {\n cache.persistToDisk();\n }\n}\n\nfunction runWalker(config: CliConfig, cache?: ExtractionCache): ProjectAnalysis {\n const { rootDir, localesDir, extractionScope } = resolveConfig(config);\n\n const analysis = walkAll({\n pages: config.pages,\n rootDir,\n localesDir,\n defaultLocale: config.defaultLocale,\n extractionScope,\n hookSources: config.hookSources,\n cache,\n });\n\n // Mirror the build plugin: apply declared dynamic keys and audit scope\n // registration so CLI-generated artifacts match `vite build` exactly.\n // Shared primitive, same semantics, no drift.\n if (config.dynamicKeys && config.dynamicKeys.length > 0) {\n const report = applyDynamicKeys(analysis, {\n dynamicKeys: config.dynamicKeys,\n dictionaries: config.dictionaries,\n crossNamespacePacking: config.crossNamespacePacking,\n });\n for (const orphan of report.orphans) {\n console.warn(\n `[vite-bundled-i18n] dynamicKeys entry \"${orphan}\" matches no route ` +\n `and no dictionary — it won't ship anywhere.`,\n );\n }\n }\n\n const strictMode = config.strictScopeRegistration ?? 'warn';\n if (strictMode !== 'off') {\n const report = checkScopeRegistration(analysis, { rootDir, mode: strictMode });\n if (report.violations.length > 0) {\n if (strictMode === 'error') {\n throw new Error(\n 'vite-bundled-i18n: scope registration failures (strictScopeRegistration: \\'error\\'):\\n\\n' +\n report.messages.join('\\n\\n'),\n );\n }\n for (const message of report.messages) console.warn(message);\n }\n }\n\n return analysis;\n}\n\nfunction collectScopeNames(analysis: ProjectAnalysis): string[] {\n return [...new Set(analysis.routes.flatMap((route) => route.scopes))].sort();\n}\n\n/**\n * Emit both the typed `.ts` (for TSC/IDE) and runtime `.js` (for Vite\n * resolve.alias) generated files. Called by every CLI command that\n * previously only wrote the `.ts` file — keeps CLI output aligned with\n * the Vite plugin's `emitGeneratedArtifacts` so there's no drift.\n */\nfunction emitGeneratedPair(\n analysis: ProjectAnalysis,\n config: CliConfig,\n localesDir: string,\n rootDir: string,\n typesOutPath: string,\n): void {\n const scopeNames = collectScopeNames(analysis);\n const scopeMap = buildScopeMap(analysis, {\n rootDir,\n defaultLocale: config.defaultLocale,\n dictionaries: config.dictionaries,\n });\n const pageScopeMap: Record<string, readonly string[]> = {};\n for (const [id, entry] of Object.entries(scopeMap.pages)) {\n pageScopeMap[id] = entry.scopes;\n }\n const hasPageMap = Object.keys(pageScopeMap).length > 0;\n writeTypes(\n localesDir,\n config.defaultLocale,\n typesOutPath,\n scopeNames,\n hasPageMap ? pageScopeMap : undefined,\n );\n writeRuntimeConst(\n runtimePathFromTypesPath(typesOutPath),\n hasPageMap ? pageScopeMap : undefined,\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 { rootDir, localesDir } = resolveConfig(config);\n const cache = buildCliCache(config, rootDir);\n const analysis = runWalker(config, cache);\n persistCache(config, cache, rootDir);\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 { rootDir, outDir, typesOutPath, localesDir } = resolveConfig(config);\n const cache = buildCliCache(config, rootDir);\n const analysis = runWalker(config, cache);\n persistCache(config, cache, rootDir);\n\n const bundles = generateBundles(analysis, {\n localesDir,\n locales: config.locales,\n outDir,\n crossNamespacePacking: config.crossNamespacePacking,\n });\n\n emitGeneratedPair(analysis, config, localesDir, rootDir, 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 { rootDir, outDir, localesDir } = resolveConfig(config);\n const cache = buildCliCache(config, rootDir);\n const analysis = runWalker(config, cache);\n persistCache(config, cache, rootDir);\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 { rootDir, outDir, localesDir } = resolveConfig(config);\n const cache = buildCliCache(config, rootDir);\n const analysis = runWalker(config, cache);\n persistCache(config, cache, rootDir);\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 { rootDir, outDir, typesOutPath, localesDir } = resolveConfig(config);\n const cache = buildCliCache(config, rootDir);\n const analysis = runWalker(config, cache);\n persistCache(config, cache, rootDir);\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 emitGeneratedPair(analysis, config, localesDir, rootDir, 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 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> [options]');\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 console.log(' --no-cache Disable the extraction cache for this run');\n console.log(' --clear-cache Clear the extraction cache before running');\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\ninterface ParsedArgs {\n command: Command;\n configPath: string;\n noCache: boolean;\n clearCache: boolean;\n}\n\nfunction parseArgs(argv: string[]): ParsedArgs {\n const args = argv.slice(2);\n let command: Command | undefined;\n let configPath = 'i18n.config.json';\n let noCache = false;\n let clearCache = false;\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 === '--no-cache') {\n noCache = true;\n } else if (arg === '--clear-cache') {\n clearCache = true;\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, noCache, clearCache };\n}\n\nconst { command, configPath, noCache, clearCache } = parseArgs(process.argv);\nconst config = loadConfig(configPath);\n\n// CLI flags merge into the config's `cache` field so downstream resolution\n// sees them. Env vars still take the final word via resolveCacheConfig.\nif (noCache) {\n config.cache = false;\n}\nif (clearCache) {\n // Resolve-time handling: a CLI-driven clear is honored even when config\n // doesn't opt into the cache object form. We signal via an env var so\n // the central resolver is the single source of truth.\n process.env.VITE_I18N_CLEAR_CACHE = '1';\n}\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":";;;;;AAuEA,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,cAAc,QAAmB,SAA8C;CACtF,MAAM,gBAAgB,mBAAmB,OAAO,OAAO,EAAE,SAAS,CAAC;AACnE,KAAI,CAAC,cAAc,QAAS,QAAO,KAAA;AAEnC,KAAI,cAAc,iBAChB,KAAI;AACF,KAAG,OAAO,cAAc,KAAK;GAAE,WAAW;GAAM,OAAO;GAAM,CAAC;SACxD;AAKV,QAAO,sBAAsB;EAC3B,KAAK,cAAc;EACnB,eAAe;EACf,YAAY,kBAAkB;GAC5B,OAAO,OAAO;GACd,eAAe,OAAO;GACtB,iBAAiB,OAAO,mBAAmB;GAC3C,aAAa,OAAO;GACpB,cAAc,OAAO;GACrB,uB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DAA+D;;AAG7E,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;;AAUxB,SAAS,UAAU,MAA4B;CAC7C,MAAM,OAAO,KAAK,MAAM,EAAE;CAC1B,IAAI;CACJ,IAAI,aAAa;CACjB,IAAI,UAAU;CACd,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,aACjB,WAAU;WACD,QAAQ,gBACjB,cAAa;WACJ,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;EAAS;EAAY;;AAG/D,IAAM,EAAE,SAAS,YAAY,SAAS,eAAe,UAAU,QAAQ,KAAK;AAC5E,IAAM,SAAS,WAAW,WAAW;AAIrC,IAAI,QACF,QAAO,QAAQ;AAEjB,IAAI,WAIF,SAAQ,IAAI,wBAAwB;CAGsB;CAC1D;CACA;CACA;CACA;CACA;CACD,EAEQ,SAAS,OAAO"}
@@ -0,0 +1,14 @@
1
+ import { createContext } from "react";
2
+ //#region src/react/context.ts
3
+ /**
4
+ * React context for the i18n instance.
5
+ *
6
+ * Provided by `I18nProvider`, consumed by `useI18n`.
7
+ * The default value is `null` — using `useI18n` outside of a provider
8
+ * will throw a descriptive error.
9
+ */
10
+ var I18nContext = createContext(null);
11
+ //#endregion
12
+ export { I18nContext as t };
13
+
14
+ //# sourceMappingURL=context-B66VMNFr.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"context-B66VMNFr.js","names":[],"sources":["../src/react/context.ts"],"sourcesContent":["import { createContext } from 'react';\nimport type { I18nInstance } from '../core/types';\n\n/**\n * Context value passed from I18nProvider to consumers.\n * Includes the i18n instance and a version counter that increments\n * whenever the store is updated (dictionaries loaded, locale changed).\n * The version forces useMemo in useI18n to re-create the t function.\n */\nexport interface I18nContextValue {\n instance: I18nInstance;\n version: number;\n dictsReady: boolean;\n}\n\n/**\n * React context for the i18n instance.\n *\n * Provided by `I18nProvider`, consumed by `useI18n`.\n * The default value is `null` — using `useI18n` outside of a provider\n * will throw a descriptive error.\n */\nexport const I18nContext = createContext<I18nContextValue | null>(null);\n"],"mappings":";;;;;;;;;AAsBA,IAAa,cAAc,cAAuC,KAAK"}
@@ -56,6 +56,40 @@ export interface I18nSharedConfig {
56
56
  * @default false
57
57
  */
58
58
  crossNamespacePacking?: boolean;
59
+ /**
60
+ * After extraction, verify that every file matching the `pages` glob
61
+ * declares at least one `useI18n('<literal>')` scope. Files without
62
+ * a registered scope don't contribute to any scope bundle — their
63
+ * translation keys only work if covered by a dictionary, which is
64
+ * almost always a mistake.
65
+ *
66
+ * - `'off'` — no check
67
+ * - `'warn'` (default) — log a warning per offender via Vite's logger
68
+ * - `'error'` — throw during the build; fails CI
69
+ */
70
+ strictScopeRegistration?: 'off' | 'warn' | 'error';
71
+ /**
72
+ * Fully qualified keys the extractor can't see from static `t()` calls —
73
+ * e.g. keys built from variables (`t.dynamic(\`status.\${state}\`)`) or
74
+ * keys resolved at runtime via a map.
75
+ *
76
+ * Each listed key is added to every route whose scope's primary
77
+ * namespace (or packed cross-ns extras namespace) matches the key's
78
+ * namespace. Dictionary-owned keys are skipped — dictionaries already
79
+ * guarantee global availability.
80
+ *
81
+ * Keys whose namespace matches no route and isn't dictionary-owned
82
+ * emit a build warning. A "dangling" dynamic key silently bloats
83
+ * nothing; flagging it forces the user to correct the config.
84
+ *
85
+ * @example
86
+ * ```ts
87
+ * bundling: {
88
+ * dynamicKeys: ['status.active', 'status.pending', 'status.failed'],
89
+ * }
90
+ * ```
91
+ */
92
+ dynamicKeys?: readonly string[];
59
93
  };
60
94
  }
61
95
  /**
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Runtime shim for the `vite-bundled-i18n/generated` package export.
3
+ *
4
+ * This is a package-shipped placeholder with empty exports. It guarantees
5
+ * that `import { PAGE_SCOPE_MAP } from 'vite-bundled-i18n/generated'` always
6
+ * resolves at module-resolution time, even before the i18nPlugin has run
7
+ * for the first time.
8
+ *
9
+ * Real values come from `.i18n/i18n-generated.js` in the consumer project,
10
+ * written by the plugin's `buildStart` hook. The plugin also programmatically
11
+ * registers a Vite `resolve.alias` so that both dev and build resolve
12
+ * `vite-bundled-i18n/generated` directly to that file, bypassing this shim.
13
+ *
14
+ * Non-Vite consumers (raw Node scripts, tests that don't go through Vite)
15
+ * fall through to these empty defaults.
16
+ */
17
+ /** @type {Readonly<Record<string, readonly string[]>>} */
18
+ export declare const PAGE_SCOPE_MAP: Readonly<{}>;
@@ -0,0 +1,23 @@
1
+ //#region src/core/i18n-generated-shim.ts
2
+ /**
3
+ * Runtime shim for the `vite-bundled-i18n/generated` package export.
4
+ *
5
+ * This is a package-shipped placeholder with empty exports. It guarantees
6
+ * that `import { PAGE_SCOPE_MAP } from 'vite-bundled-i18n/generated'` always
7
+ * resolves at module-resolution time, even before the i18nPlugin has run
8
+ * for the first time.
9
+ *
10
+ * Real values come from `.i18n/i18n-generated.js` in the consumer project,
11
+ * written by the plugin's `buildStart` hook. The plugin also programmatically
12
+ * registers a Vite `resolve.alias` so that both dev and build resolve
13
+ * `vite-bundled-i18n/generated` directly to that file, bypassing this shim.
14
+ *
15
+ * Non-Vite consumers (raw Node scripts, tests that don't go through Vite)
16
+ * fall through to these empty defaults.
17
+ */
18
+ /** @type {Readonly<Record<string, readonly string[]>>} */
19
+ var PAGE_SCOPE_MAP = Object.freeze({});
20
+ //#endregion
21
+ export { PAGE_SCOPE_MAP };
22
+
23
+ //# sourceMappingURL=i18n-generated-shim.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"i18n-generated-shim.js","names":[],"sources":["../../src/core/i18n-generated-shim.ts"],"sourcesContent":["/**\n * Runtime shim for the `vite-bundled-i18n/generated` package export.\n *\n * This is a package-shipped placeholder with empty exports. It guarantees\n * that `import { PAGE_SCOPE_MAP } from 'vite-bundled-i18n/generated'` always\n * resolves at module-resolution time, even before the i18nPlugin has run\n * for the first time.\n *\n * Real values come from `.i18n/i18n-generated.js` in the consumer project,\n * written by the plugin's `buildStart` hook. The plugin also programmatically\n * registers a Vite `resolve.alias` so that both dev and build resolve\n * `vite-bundled-i18n/generated` directly to that file, bypassing this shim.\n *\n * Non-Vite consumers (raw Node scripts, tests that don't go through Vite)\n * fall through to these empty defaults.\n */\n\n/** @type {Readonly<Record<string, readonly string[]>>} */\nexport const PAGE_SCOPE_MAP = Object.freeze({});\n"],"mappings":";;;;;;;;;;;;;;;;;;AAkBA,IAAa,iBAAiB,OAAO,OAAO,EAAE,CAAC"}
@@ -0,0 +1,79 @@
1
+ /**
2
+ * Framework-agnostic runtime client for the `scope-map.json` artifact
3
+ * emitted by the Vite plugin / dev middleware.
4
+ *
5
+ * Consumers use this alongside their router's async resolve hook to
6
+ * parallelize scope loading with component resolution:
7
+ *
8
+ * ```ts
9
+ * import { createScopeMapClient } from 'vite-bundled-i18n';
10
+ * import { i18n } from './i18n';
11
+ *
12
+ * const scopeMap = createScopeMapClient();
13
+ *
14
+ * router.beforeResolve(async (to, from, next) => {
15
+ * const [scopes] = await Promise.all([
16
+ * scopeMap.get(to.name as string),
17
+ * to.meta.loadComponent?.(),
18
+ * ]);
19
+ * await Promise.all(scopes.map((s) => i18n.loadScope(i18n.getLocale(), s)));
20
+ * next();
21
+ * });
22
+ * ```
23
+ *
24
+ * The client keeps an in-memory cache. `load()` is idempotent — concurrent
25
+ * calls share a single fetch. `invalidate()` clears the cache so the next
26
+ * access re-fetches.
27
+ */
28
+ export interface ScopeMapPageEntryRuntime {
29
+ readonly scopes: readonly string[];
30
+ readonly dictionaries: readonly string[];
31
+ }
32
+ export interface ScopeMapFileRuntime {
33
+ readonly version: number;
34
+ readonly defaultLocale: string;
35
+ readonly pages: Readonly<Record<string, ScopeMapPageEntryRuntime>>;
36
+ }
37
+ export interface CreateScopeMapClientOptions {
38
+ /** Static URL override. Defaults to `/__i18n/scope-map.json`. */
39
+ url?: string;
40
+ /**
41
+ * Dynamic URL resolver. Called on every `load()` — use this when the URL
42
+ * depends on runtime state (e.g. an authenticated tenant id, a deploy
43
+ * channel). Overrides `url` when provided.
44
+ */
45
+ resolveUrl?: () => string;
46
+ /**
47
+ * Custom `fetch` implementation. Defaults to `globalThis.fetch`. Tests
48
+ * inject a mock; SSR layers inject a server-side fetch.
49
+ */
50
+ fetchImpl?: typeof fetch;
51
+ }
52
+ export interface ScopeMapClient {
53
+ /**
54
+ * Return the scope list for `pageId`. Triggers a load if the map isn't
55
+ * cached yet; subsequent calls resolve from memory. Unknown page ids
56
+ * resolve to an empty array — the caller decides whether that's an error.
57
+ */
58
+ get(pageId: string): Promise<readonly string[]>;
59
+ /**
60
+ * Synchronous lookup. Returns the scope list if the map is already loaded,
61
+ * otherwise `null`. Use this when you can tolerate a miss (e.g. in a
62
+ * render path that also calls `load()` elsewhere).
63
+ */
64
+ getSync(pageId: string): readonly string[] | null;
65
+ /**
66
+ * Fetch the scope-map once (concurrent callers share the in-flight
67
+ * promise). A second call after a successful load is a no-op.
68
+ */
69
+ load(): Promise<void>;
70
+ /** Clear the in-memory cache so the next access re-fetches. */
71
+ invalidate(): void;
72
+ /** `true` once `load()` has completed successfully. */
73
+ isLoaded(): boolean;
74
+ }
75
+ /**
76
+ * Create a new {@link ScopeMapClient}. Safe to instantiate multiple times;
77
+ * each instance keeps its own cache.
78
+ */
79
+ export declare function createScopeMapClient(options?: CreateScopeMapClientOptions): ScopeMapClient;
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Framework-agnostic readiness primitive. Keeps a refcount of outstanding
3
+ * async operations (typically {@link I18nInstance.loadScope} calls); exposes
4
+ * a boolean `ready`, a pending count, a promise gate, and a subscription
5
+ * for UI layers.
6
+ *
7
+ * The gate is the single source of truth for "is i18n idle right now?".
8
+ * React (`<GateBoundary>` / `useGate()`) and Vue (`useGate()`) adapters
9
+ * both wrap this — neither layer keeps its own counter.
10
+ *
11
+ * Contract:
12
+ * - `register()` returns a one-shot release function. Double-release is
13
+ * idempotent; no negative counts.
14
+ * - `whenReady()` resolves immediately when already ready, otherwise on
15
+ * the next transition to ready.
16
+ * - `subscribe()` fires on every pending-count change (including
17
+ * transitions through intermediate counts). Listeners receive the
18
+ * current `ready` boolean.
19
+ * - `reset()` forcibly zeroes the pending set and notifies. Stale release
20
+ * tokens from before the reset are no-ops.
21
+ */
22
+ export interface ReadinessGate {
23
+ /**
24
+ * Increment the pending count. Returns a release function that
25
+ * decrements it. Release is idempotent — safe to call more than once.
26
+ */
27
+ register(): () => void;
28
+ /**
29
+ * Resolve when the gate is (or becomes) ready. Resolves in a microtask
30
+ * when already ready; otherwise on the next transition to pendingCount=0.
31
+ */
32
+ whenReady(): Promise<void>;
33
+ /**
34
+ * Subscribe to readiness-state changes. The listener is invoked with
35
+ * the current `ready` boolean on every pending-count transition.
36
+ * Returns an unsubscribe function.
37
+ */
38
+ subscribe(listener: (ready: boolean) => void): () => void;
39
+ /** `true` when pendingCount is 0. */
40
+ readonly ready: boolean;
41
+ /** Number of outstanding registrations. */
42
+ readonly pendingCount: number;
43
+ /**
44
+ * Clear all pending registrations and force the gate into the ready
45
+ * state. Pre-existing release tokens become no-ops (they won't produce
46
+ * negative counts or spurious notifications). Subscribers are notified
47
+ * and any pending {@link whenReady} promises resolve.
48
+ *
49
+ * Intended for locale-change cleanup and test teardown.
50
+ */
51
+ reset(): void;
52
+ }
53
+ /**
54
+ * Create a new readiness gate instance. Typically instantiated once per
55
+ * `I18nInstance`.
56
+ */
57
+ export declare function createReadinessGate(): ReadinessGate;
@@ -1,4 +1,5 @@
1
1
  import type { CompiledManifestModule } from './compiled-runtime';
2
+ import type { ReadinessGate } from './services/readiness-gate';
2
3
  import type { I18nNestedKeys, I18nParamsMap, I18nScopeMap } from 'vite-bundled-i18n/generated';
3
4
  export type { I18nNestedKeys, I18nParamsMap, I18nScopeMap, };
4
5
  /**
@@ -90,6 +91,28 @@ export type TFunction = {
90
91
  (key: TranslationKey, fallback: string): string;
91
92
  (key: TranslationKey, params: Record<string, unknown>): string;
92
93
  (key: TranslationKey, params: Record<string, unknown>, fallback: string): string;
94
+ /**
95
+ * Escape hatch for runtime-computed keys. Accepts any string —
96
+ * bypasses the typed `TranslationKey` union. Use when the key is
97
+ * assembled from variables (`t.dynamic(\`status.\${state}\`)`) and
98
+ * you've already paired it with an entry in
99
+ * `bundling.dynamicKeys` (or a dictionary) so the referenced
100
+ * value actually ships to the client.
101
+ *
102
+ * Identical runtime behavior to `t(...)` — only the type contract
103
+ * differs.
104
+ */
105
+ dynamic: DynamicTFunction;
106
+ };
107
+ /**
108
+ * Loosely-typed sibling of {@link TFunction} for keys that can't be
109
+ * statically expressed. Accepts any string.
110
+ */
111
+ export type DynamicTFunction = {
112
+ (key: string): string;
113
+ (key: string, fallback: string): string;
114
+ (key: string, params: Record<string, unknown>): string;
115
+ (key: string, params: Record<string, unknown>, fallback: string): string;
93
116
  };
94
117
  /**
95
118
  * Translation function for scoped/namespace-relative keys.
@@ -101,6 +124,8 @@ export type ScopedTFunction = {
101
124
  (key: string, fallback: string): string;
102
125
  (key: string, params: Record<string, unknown>): string;
103
126
  (key: string, params: Record<string, unknown>, fallback: string): string;
127
+ /** Same loose-typed escape hatch as {@link TFunction.dynamic}. */
128
+ dynamic: DynamicTFunction;
104
129
  };
105
130
  /**
106
131
  * Translation function that returns undefined when the key is not currently
@@ -346,9 +371,17 @@ export interface I18nInstance {
346
371
  loadAllDictionaries: (locale: string) => Promise<void>;
347
372
  /**
348
373
  * Loads a page/scope bundle for a locale.
349
- * One HTTP request: `/__i18n/{locale}/{scope}.json`
374
+ * One HTTP request: `/__i18n/{locale}/{scope}.json`.
375
+ *
376
+ * **Readiness tracking:** By default the call auto-registers with
377
+ * {@link I18nInstance.gate}, which UI adapters (`<GateBoundary>`,
378
+ * `useGate()`) read from. Pass `{ trackReadiness: false }` to skip
379
+ * registration — use this only when you have an explicit orchestration
380
+ * layer that already gates rendering independently.
350
381
  */
351
- loadScope: (locale: string, scope: string) => Promise<void>;
382
+ loadScope: (locale: string, scope: string, options?: {
383
+ trackReadiness?: boolean;
384
+ }) => Promise<void>;
352
385
  /**
353
386
  * Adds resources directly to the store. Useful for testing and SSR.
354
387
  */
@@ -457,6 +490,13 @@ export interface I18nInstance {
457
490
  * called without a scope).
458
491
  */
459
492
  setActiveScope: (scope: string | undefined) => void;
493
+ /**
494
+ * Framework-agnostic readiness primitive. Every `loadScope` call
495
+ * auto-registers with this gate (opt out per-call via
496
+ * `{ trackReadiness: false }`); UI adapters subscribe for the "am I
497
+ * still loading?" state. See {@link ReadinessGate}.
498
+ */
499
+ gate: ReadinessGate;
460
500
  }
461
501
  /**
462
502
  * Records how a translation key was resolved at runtime.