vite-bundled-i18n 0.7.2 → 0.7.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +10 -0
- package/dist/{build-stamp-BvP03CCo.js → build-stamp-B_2oi0vc.js} +36 -65
- package/dist/build-stamp-B_2oi0vc.js.map +1 -0
- package/dist/cli/commands.d.ts +19 -0
- package/dist/cli/index.js +83 -4
- package/dist/cli/index.js.map +1 -1
- package/dist/core/i18n-generated.d.ts +2 -0
- package/dist/eslint.js +1 -1
- package/dist/plugin.js +1 -1
- package/docs/api.md +1032 -0
- package/docs/architecture.md +144 -0
- package/docs/getting-started.md +666 -0
- package/package.json +7 -3
- package/skills/vite-bundled-i18n/SKILL.md +60 -0
- package/skills/vite-bundled-i18n/agents/openai.yaml +4 -0
- package/skills/vite-bundled-i18n/references/api-reference.md +142 -0
- package/skills/vite-bundled-i18n/references/best-practices.md +127 -0
- package/skills/vite-bundled-i18n/references/setup.md +174 -0
- package/skills/vite-bundled-i18n/references/troubleshooting.md +132 -0
- package/dist/build-stamp-BvP03CCo.js.map +0 -1
package/README.md
CHANGED
|
@@ -546,6 +546,16 @@ If after that the key is _still_ missing, the issue is in the source — not the
|
|
|
546
546
|
|
|
547
547
|
The CLI's `clean` command accepts repeatable `--extra-path` flags for project layouts that emit assets outside `.i18n/` (e.g. `--extra-path public/__i18n --extra-path public/build/__i18n`).
|
|
548
548
|
|
|
549
|
+
### Codex skill for consumer apps
|
|
550
|
+
|
|
551
|
+
The package also ships a Codex skill with setup guidance, best practices, API notes, and troubleshooting for consumer apps. Install it into the current app with:
|
|
552
|
+
|
|
553
|
+
```bash
|
|
554
|
+
npx vite-bundled-i18n install-skill
|
|
555
|
+
```
|
|
556
|
+
|
|
557
|
+
By default this copies the skill to `.agents/skills/vite-bundled-i18n`. Use `--global` to install into `${CODEX_HOME:-~/.codex}/skills`, `--target <skills-dir>` for a custom skills directory, and `--force` to refresh an existing copy.
|
|
558
|
+
|
|
549
559
|
## ESLint plugin
|
|
550
560
|
|
|
551
561
|
`vite-bundled-i18n/eslint` ships five rules that catch the patterns the extractor cannot see — keys reached through aliases, props, member access, or runtime concatenation. Same package, optional peer dep on `eslint >= 8`, opt in via the subpath:
|
|
@@ -925,6 +925,33 @@ function findTranslationCalls(sourceFile, options) {
|
|
|
925
925
|
}
|
|
926
926
|
});
|
|
927
927
|
const keyFields = getKeyFields(options);
|
|
928
|
+
function resolveStaticKeys(keyArg) {
|
|
929
|
+
const direct = getStringValue(keyArg) ?? (ts.isIdentifier(keyArg) ? literalConstants.get(keyArg.text) : void 0);
|
|
930
|
+
if (direct !== void 0) return [direct];
|
|
931
|
+
if (ts.isPropertyAccessExpression(keyArg) && ts.isIdentifier(keyArg.expression)) {
|
|
932
|
+
const value = constObjectMaps.get(keyArg.expression.text)?.get(keyArg.name.text);
|
|
933
|
+
return value === void 0 ? void 0 : [value];
|
|
934
|
+
}
|
|
935
|
+
if (ts.isElementAccessExpression(keyArg) && ts.isIdentifier(keyArg.expression)) {
|
|
936
|
+
const objMap = constObjectMaps.get(keyArg.expression.text);
|
|
937
|
+
if (!objMap) return void 0;
|
|
938
|
+
const staticMember = keyArg.argumentExpression ? getStringValue(keyArg.argumentExpression) : void 0;
|
|
939
|
+
if (staticMember !== void 0) {
|
|
940
|
+
const value = objMap.get(staticMember);
|
|
941
|
+
return value === void 0 ? void 0 : [value];
|
|
942
|
+
}
|
|
943
|
+
return [...objMap.values()];
|
|
944
|
+
}
|
|
945
|
+
}
|
|
946
|
+
function pushStaticKeys(keys, line, character, fallback) {
|
|
947
|
+
for (const key of keys) results.push({
|
|
948
|
+
key,
|
|
949
|
+
fallback,
|
|
950
|
+
dynamic: false,
|
|
951
|
+
line: line + 1,
|
|
952
|
+
column: character
|
|
953
|
+
});
|
|
954
|
+
}
|
|
928
955
|
function visit(node) {
|
|
929
956
|
if (ts.isVariableDeclaration(node) && ts.isIdentifier(node.name) && node.initializer && getStringValue(node.initializer) !== void 0) literalConstants.set(node.name.text, getStringValue(node.initializer));
|
|
930
957
|
if (ts.isVariableDeclaration(node) && node.initializer && ts.isCallExpression(node.initializer) && ts.isIdentifier(node.initializer.expression) && useI18nNames.has(node.initializer.expression.text) && node.name && ts.isObjectBindingPattern(node.name)) for (const element of node.name.elements) {
|
|
@@ -941,35 +968,9 @@ function findTranslationCalls(sourceFile, options) {
|
|
|
941
968
|
return;
|
|
942
969
|
}
|
|
943
970
|
const keyArg = args[0];
|
|
944
|
-
|
|
945
|
-
if (staticKey === void 0 && ts.isPropertyAccessExpression(keyArg) && ts.isIdentifier(keyArg.expression)) {
|
|
946
|
-
const objMap = constObjectMaps.get(keyArg.expression.text);
|
|
947
|
-
if (objMap) {
|
|
948
|
-
const value = objMap.get(keyArg.name.text);
|
|
949
|
-
if (value !== void 0) staticKey = value;
|
|
950
|
-
}
|
|
951
|
-
}
|
|
971
|
+
const staticKeys = resolveStaticKeys(keyArg);
|
|
952
972
|
const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());
|
|
953
|
-
if (
|
|
954
|
-
const objMap = constObjectMaps.get(keyArg.expression.text);
|
|
955
|
-
if (objMap) {
|
|
956
|
-
for (const value of objMap.values()) results.push({
|
|
957
|
-
key: value,
|
|
958
|
-
dynamic: false,
|
|
959
|
-
line: line + 1,
|
|
960
|
-
column: character
|
|
961
|
-
});
|
|
962
|
-
ts.forEachChild(node, visit);
|
|
963
|
-
return;
|
|
964
|
-
}
|
|
965
|
-
}
|
|
966
|
-
if (staticKey !== void 0) results.push({
|
|
967
|
-
key: staticKey,
|
|
968
|
-
fallback: extractFallback(args),
|
|
969
|
-
dynamic: false,
|
|
970
|
-
line: line + 1,
|
|
971
|
-
column: character
|
|
972
|
-
});
|
|
973
|
+
if (staticKeys !== void 0) pushStaticKeys(staticKeys, line, character, extractFallback(args));
|
|
973
974
|
else {
|
|
974
975
|
const prefix = getStaticPrefix(keyArg);
|
|
975
976
|
results.push({
|
|
@@ -983,34 +984,9 @@ function findTranslationCalls(sourceFile, options) {
|
|
|
983
984
|
}
|
|
984
985
|
if (ts.isCallExpression(node) && ts.isIdentifier(node.expression) && i18nKeyNames.has(node.expression.text) && node.arguments.length > 0) {
|
|
985
986
|
const keyArg = node.arguments[0];
|
|
986
|
-
|
|
987
|
-
if (staticKey === void 0 && ts.isPropertyAccessExpression(keyArg) && ts.isIdentifier(keyArg.expression)) {
|
|
988
|
-
const objMap = constObjectMaps.get(keyArg.expression.text);
|
|
989
|
-
if (objMap) {
|
|
990
|
-
const value = objMap.get(keyArg.name.text);
|
|
991
|
-
if (value !== void 0) staticKey = value;
|
|
992
|
-
}
|
|
993
|
-
}
|
|
987
|
+
const staticKeys = resolveStaticKeys(keyArg);
|
|
994
988
|
const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());
|
|
995
|
-
if (
|
|
996
|
-
const objMap = constObjectMaps.get(keyArg.expression.text);
|
|
997
|
-
if (objMap) {
|
|
998
|
-
for (const value of objMap.values()) results.push({
|
|
999
|
-
key: value,
|
|
1000
|
-
dynamic: false,
|
|
1001
|
-
line: line + 1,
|
|
1002
|
-
column: character
|
|
1003
|
-
});
|
|
1004
|
-
ts.forEachChild(node, visit);
|
|
1005
|
-
return;
|
|
1006
|
-
}
|
|
1007
|
-
}
|
|
1008
|
-
if (staticKey !== void 0) results.push({
|
|
1009
|
-
key: staticKey,
|
|
1010
|
-
dynamic: false,
|
|
1011
|
-
line: line + 1,
|
|
1012
|
-
column: character
|
|
1013
|
-
});
|
|
989
|
+
if (staticKeys !== void 0) pushStaticKeys(staticKeys, line, character);
|
|
1014
990
|
else {
|
|
1015
991
|
const prefix = getStaticPrefix(keyArg);
|
|
1016
992
|
results.push({
|
|
@@ -1024,15 +1000,10 @@ function findTranslationCalls(sourceFile, options) {
|
|
|
1024
1000
|
}
|
|
1025
1001
|
if (options.scope !== "scoped" && ts.isCallExpression(node) && ts.isIdentifier(node.expression) && !trackedNames.has(node.expression.text) && !i18nKeyNames.has(node.expression.text) && TRANSLATION_CALLEE_NAMES.has(node.expression.text) && node.arguments.length > 0) {
|
|
1026
1002
|
const keyArg = node.arguments[0];
|
|
1027
|
-
const
|
|
1028
|
-
if (
|
|
1003
|
+
const staticKeys = resolveStaticKeys(keyArg);
|
|
1004
|
+
if (staticKeys !== void 0) {
|
|
1029
1005
|
const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());
|
|
1030
|
-
|
|
1031
|
-
key: staticKey,
|
|
1032
|
-
dynamic: false,
|
|
1033
|
-
line: line + 1,
|
|
1034
|
-
column: character
|
|
1035
|
-
});
|
|
1006
|
+
pushStaticKeys(staticKeys.filter((key) => key.includes(".")), line, character);
|
|
1036
1007
|
}
|
|
1037
1008
|
}
|
|
1038
1009
|
if (ts.isPropertyAssignment(node) && (ts.isIdentifier(node.name) && keyFields.has(node.name.text) || ts.isStringLiteral(node.name) && keyFields.has(node.name.text))) {
|
|
@@ -1588,7 +1559,7 @@ function resolveCacheConfig(input, context) {
|
|
|
1588
1559
|
* back to a development placeholder during tests and direct imports before
|
|
1589
1560
|
* the build step runs.
|
|
1590
1561
|
*/
|
|
1591
|
-
var PLUGIN_VERSION = "0.7.
|
|
1562
|
+
var PLUGIN_VERSION = "0.7.4";
|
|
1592
1563
|
//#endregion
|
|
1593
1564
|
//#region src/extractor/scope-map.ts
|
|
1594
1565
|
var COMPOSITE_PAGE_SUFFIXES = [
|
|
@@ -2269,4 +2240,4 @@ function formatDuration(ms) {
|
|
|
2269
2240
|
//#endregion
|
|
2270
2241
|
export { keyMatchesPattern as A, writeRuntimeConst as C, pruneNamespace as D, generateBundles as E, resolveDictionaryOwnership as M, buildScopePlans as O, runtimePathFromTypesPath as S, flattenKeys as T, extractKeys as _, runStrictExtraction as a, generateReports as b, applyDynamicKeys as c, resolveCacheConfig as d, CACHE_FILE_NAME as f, walkAll as g, resolveImport as h, assertNoStrictExtractionErrors as i, normalizeDictionaries as j, inferScopeNamespace as k, buildScopeMap as l, createExtractionCache as m, detectStaleness as n, writeStrictExtractionReport as o, computeConfigHash as p, writeBuildStamp as r, compileAll as s, computeAnalysisFingerprint as t, PLUGIN_VERSION as u, flattenLocaleKeys as v, writeTypes as w, generateTypes as x, generateDictionaryOwnershipReport as y };
|
|
2271
2242
|
|
|
2272
|
-
//# sourceMappingURL=build-stamp-
|
|
2243
|
+
//# sourceMappingURL=build-stamp-B_2oi0vc.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"build-stamp-B_2oi0vc.js","names":[],"sources":["../src/extractor/dictionary-ownership.ts","../src/extractor/scope-bundles.ts","../src/extractor/bundle-generator.ts","../src/extractor/type-generator.ts","../src/extractor/reports.ts","../src/extractor/ast-utils.ts","../src/extractor/patterns.ts","../src/extractor/extract.ts","../src/extractor/walker.ts","../src/extractor/extraction-cache.ts","../src/extractor/cache-config.ts","../src/plugin/version.ts","../src/extractor/scope-map.ts","../src/extractor/dynamic-keys.ts","../src/extractor/compiler.ts","../src/extractor/scope-registration.ts","../src/extractor/strict-extraction.ts","../src/extractor/build-stamp.ts"],"sourcesContent":["import type { DictionaryConfig } from '../core/types';\n\nexport interface NormalizedDictionaryRule {\n name: string;\n include: string[];\n exclude: string[];\n priority: number;\n pinned: boolean;\n order: number;\n}\n\nexport interface DictionaryOwnership {\n rules: NormalizedDictionaryRule[];\n keyOwner: Map<string, string>;\n dictionaryKeys: Map<string, Set<string>>;\n dictionaryNamespaces: Set<string>;\n}\n\nexport function getDictionaryIncludePatterns(dict: DictionaryConfig): string[] {\n const fromKeys = (dict.keys ?? []).map((key) => `${key}.*`);\n return [...fromKeys, ...(dict.include ?? [])];\n}\n\nexport function normalizeDictionaries(\n dictionaries?: Record<string, DictionaryConfig>,\n): NormalizedDictionaryRule[] {\n if (!dictionaries) return [];\n\n return Object.entries(dictionaries)\n .map(([name, dict], order) => ({\n name,\n include: getDictionaryIncludePatterns(dict),\n exclude: dict.exclude ?? [],\n priority: dict.priority ?? 0,\n pinned: dict.pinned ?? false,\n order,\n }))\n .filter((rule) => rule.include.length > 0)\n .sort((a, b) => b.priority - a.priority || a.order - b.order);\n}\n\nexport function keyMatchesPattern(key: string, pattern: string): boolean {\n if (pattern.includes('.')) {\n if (pattern.endsWith('*')) {\n const prefix = pattern.slice(0, -1);\n return key.startsWith(prefix);\n }\n return key === pattern;\n }\n\n const namespace = key.split('.')[0];\n if (pattern.endsWith('*')) {\n return namespace.startsWith(pattern.slice(0, -1));\n }\n return namespace === pattern;\n}\n\nexport function resolveDictionaryOwnership(\n availableKeys: Iterable<string>,\n dictionaries?: Record<string, DictionaryConfig>,\n): DictionaryOwnership {\n const rules = normalizeDictionaries(dictionaries);\n const keyOwner = new Map<string, string>();\n const dictionaryKeys = new Map<string, Set<string>>();\n const dictionaryNamespaces = new Set<string>();\n\n for (const rule of rules) {\n dictionaryKeys.set(rule.name, new Set());\n }\n\n for (const key of availableKeys) {\n for (const rule of rules) {\n const included = rule.include.some((pattern) => keyMatchesPattern(key, pattern));\n const excluded = rule.exclude.some((pattern) => keyMatchesPattern(key, pattern));\n if (included && !excluded) {\n keyOwner.set(key, rule.name);\n dictionaryKeys.get(rule.name)!.add(key);\n const namespace = key.split('.')[0];\n if (namespace) {\n dictionaryNamespaces.add(namespace);\n }\n break;\n }\n }\n }\n\n return {\n rules,\n keyOwner,\n dictionaryKeys,\n dictionaryNamespaces,\n };\n}\n","import type { ProjectAnalysis } from './walker-types';\nimport type { ExtractedKey } from './types';\n\nexport interface ScopeBundlePlan {\n scope: string;\n namespace: string;\n /** Keys from the scope's own (primary) namespace. */\n keys: Set<string>;\n /**\n * Cross-namespace keys referenced on this route, keyed by namespace.\n *\n * Populated only when `buildScopePlans` is called with\n * `crossNamespacePacking: true`. Empty otherwise.\n */\n extras: Map<string, Set<string>>;\n routeIds: Set<string>;\n}\n\nexport interface BuildScopePlansOptions {\n /**\n * Collect cross-namespace keys into {@link ScopeBundlePlan.extras} so the\n * emit phase can inline them into each scope bundle.\n *\n * @default false\n */\n crossNamespacePacking?: boolean;\n}\n\nexport function inferScopeNamespace(scope: string): string {\n return scope.includes('.') ? scope.slice(0, scope.indexOf('.')) : scope;\n}\n\nfunction keyNamespace(key: ExtractedKey): string | undefined {\n const source = key.dynamic && key.staticPrefix ? key.staticPrefix : key.key;\n if (!source) return undefined;\n const dotIndex = source.indexOf('.');\n return dotIndex === -1 ? undefined : source.slice(0, dotIndex);\n}\n\nfunction getOrCreate<K, V>(map: Map<K, Set<V>>, key: K): Set<V> {\n let set = map.get(key);\n if (!set) {\n set = new Set<V>();\n map.set(key, set);\n }\n return set;\n}\n\nexport function buildScopePlans(\n analysis: ProjectAnalysis,\n availableKeys: Iterable<string>,\n options: BuildScopePlansOptions = {},\n): ScopeBundlePlan[] {\n const { crossNamespacePacking = false } = options;\n const scopePlans = new Map<string, ScopeBundlePlan>();\n const allAvailableKeys = [...availableKeys];\n\n for (const route of analysis.routes) {\n for (const scope of route.scopes) {\n const namespace = inferScopeNamespace(scope);\n let plan = scopePlans.get(scope);\n if (!plan) {\n plan = {\n scope,\n namespace,\n keys: new Set<string>(),\n extras: new Map<string, Set<string>>(),\n routeIds: new Set<string>(),\n };\n scopePlans.set(scope, plan);\n }\n\n plan.routeIds.add(route.routeId);\n\n for (const key of route.keys) {\n const ns = keyNamespace(key);\n if (!ns) continue;\n\n const isPrimary = ns === namespace;\n if (!isPrimary && !crossNamespacePacking) continue;\n\n const bucket = isPrimary ? plan.keys : getOrCreate(plan.extras, ns);\n\n if (!key.dynamic) {\n bucket.add(key.key);\n continue;\n }\n\n if (!key.staticPrefix) continue;\n for (const availableKey of allAvailableKeys) {\n if (availableKey.startsWith(key.staticPrefix)) {\n bucket.add(availableKey);\n }\n }\n }\n }\n }\n\n return [...scopePlans.values()].sort((a, b) => a.scope.localeCompare(b.scope));\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport type { ProjectAnalysis } from './walker-types';\nimport type { DictionaryConfig } from '../core/types';\nimport { resolveDictionaryOwnership, keyMatchesPattern } from './dictionary-ownership';\nimport { buildScopePlans } from './scope-bundles';\n\n/**\n * Options for the bundle generator.\n */\nexport interface BundleGeneratorOptions {\n /** Path to locales directory (absolute). */\n localesDir: string;\n /** Locales to generate bundles for. */\n locales: string[];\n /** Output directory for generated bundles (absolute). */\n outDir: string;\n /** Optional named dictionary configurations. */\n dictionaries?: Record<string, DictionaryConfig>;\n /**\n * Inline cross-namespace keys (tree-shaken) into each scope bundle.\n * See `I18nSharedConfig.bundling.crossNamespacePacking`.\n *\n * @default false\n */\n crossNamespacePacking?: boolean;\n}\n\n/**\n * Metadata about a generated bundle file.\n */\nexport interface GeneratedBundle {\n /** The route ID or dictionary name this bundle is for. */\n name: string;\n /** The locale this bundle is for. */\n locale: string;\n /** The output file path. */\n filePath: string;\n /** Number of keys in this bundle. */\n keyCount: number;\n /** Number of keys pruned (available but not used). */\n prunedCount: number;\n}\n\n/**\n * Flatten a nested object into dot-separated key paths. Null/undefined at\n * the entry or any subtree short-circuits to an empty list — a missing\n * namespace contributes no keys, never throws.\n */\nexport function flattenKeys(data: object | null | undefined, prefix?: string): string[] {\n if (data == null) return [];\n const keys: string[] = [];\n for (const [k, v] of Object.entries(data)) {\n const fullKey = prefix ? `${prefix}.${k}` : k;\n if (v !== null && typeof v === 'object' && !Array.isArray(v)) {\n keys.push(...flattenKeys(v as object, fullKey));\n } else {\n keys.push(fullKey);\n }\n }\n return keys;\n}\n\n/**\n * Set a value at a dot-separated path in a nested object, creating\n * intermediate objects as needed.\n */\nfunction setNestedValue(obj: Record<string, unknown>, keyPath: string, value: unknown): void {\n const parts = keyPath.split('.');\n let current: Record<string, unknown> = obj;\n for (let i = 0; i < parts.length - 1; i++) {\n const part = parts[i];\n if (!(part in current) || typeof current[part] !== 'object' || current[part] === null) {\n current[part] = {};\n }\n current = current[part] as Record<string, unknown>;\n }\n current[parts[parts.length - 1]] = value;\n}\n\n/**\n * Get a value at a dot-separated path in a nested object.\n * Returns undefined if the path does not exist.\n */\nfunction getNestedValue(obj: Record<string, unknown>, keyPath: string): unknown {\n const parts = keyPath.split('.');\n let current: unknown = obj;\n for (const part of parts) {\n if (current === null || typeof current !== 'object') return undefined;\n current = (current as Record<string, unknown>)[part];\n }\n return current;\n}\n\n/**\n * Prune a namespace JSON object to only include the specified key paths.\n *\n * For keys that point to a subtree (object), the entire subtree is included.\n * This supports dynamic keys with a static prefix — the full subtree under\n * the prefix is preserved.\n */\nexport function pruneNamespace(\n fullData: object,\n usedKeyPaths: string[],\n): object {\n const result: Record<string, unknown> = {};\n for (const keyPath of usedKeyPaths) {\n const value = getNestedValue(fullData as Record<string, unknown>, keyPath);\n if (value !== undefined) {\n setNestedValue(result, keyPath, value);\n }\n }\n return result;\n}\n\n/**\n * Read a namespace JSON file for a given locale.\n */\nfunction readNamespaceFile(\n localesDir: string,\n locale: string,\n namespace: string,\n): Record<string, unknown> | null {\n const filePath = path.join(localesDir, locale, `${namespace}.json`);\n if (!fs.existsSync(filePath)) return null;\n const content = fs.readFileSync(filePath, 'utf-8');\n return JSON.parse(content) as Record<string, unknown>;\n}\n\n/**\n * Generate tree-shaken per-route translation bundles from project analysis.\n */\nexport function generateBundles(\n analysis: ProjectAnalysis,\n options: BundleGeneratorOptions,\n): GeneratedBundle[] {\n const { localesDir, locales, outDir, dictionaries, crossNamespacePacking } = options;\n const bundles: GeneratedBundle[] = [];\n\n const availableKeys = new Set<string>();\n for (const route of analysis.routes) {\n for (const key of route.keys) {\n if (!key.dynamic) {\n availableKeys.add(key.key);\n }\n }\n }\n const ownership = resolveDictionaryOwnership(availableKeys, dictionaries);\n const hasNamedDictionaries = ownership.rules.length > 0;\n const sharedNsSet = hasNamedDictionaries ? new Set<string>() : new Set(analysis.sharedNamespaces);\n\n // Generate per-scope bundles keyed by scope string, matching runtime URLs.\n for (const plan of buildScopePlans(analysis, availableKeys, { crossNamespacePacking })) {\n for (const locale of locales) {\n const bundleData: Record<string, unknown> = {};\n let totalKeyCount = 0;\n let totalPrunedCount = 0;\n const scopeKeys = [...plan.keys].filter((key) => {\n if (ownership.keyOwner.has(key)) return false;\n return !(!hasNamedDictionaries && sharedNsSet.has(plan.namespace));\n });\n const subKeys = scopeKeys\n .filter((key) => key.startsWith(`${plan.namespace}.`))\n .map((key) => key.slice(plan.namespace.length + 1));\n const fullData = readNamespaceFile(localesDir, locale, plan.namespace);\n if (fullData && subKeys.length > 0) {\n const pruned = pruneNamespace(fullData, [...new Set(subKeys)]);\n bundleData[plan.namespace] = pruned;\n\n const availableCount = flattenKeys(fullData).length;\n const keptCount = flattenKeys(pruned).length;\n totalKeyCount += keptCount;\n totalPrunedCount += availableCount - keptCount;\n }\n\n // Cross-namespace extras: tree-shake per foreign namespace and inline.\n if (crossNamespacePacking) {\n for (const [extraNs, extraKeys] of plan.extras) {\n // Skip namespaces fully covered by a dictionary — don't duplicate\n // the always-available layer into every scope bundle.\n const retained = [...extraKeys].filter((k) => !ownership.keyOwner.has(k));\n if (retained.length === 0) continue;\n if (!hasNamedDictionaries && sharedNsSet.has(extraNs)) continue;\n\n const extraSubKeys = retained\n .filter((key) => key.startsWith(`${extraNs}.`))\n .map((key) => key.slice(extraNs.length + 1));\n if (extraSubKeys.length === 0) continue;\n\n const extraFullData = readNamespaceFile(localesDir, locale, extraNs);\n if (!extraFullData) continue;\n\n const pruned = pruneNamespace(extraFullData, [...new Set(extraSubKeys)]);\n bundleData[extraNs] = pruned;\n totalKeyCount += flattenKeys(pruned).length;\n }\n }\n\n const filePath = path.join(outDir, locale, `${plan.scope}.json`);\n fs.mkdirSync(path.dirname(filePath), { recursive: true });\n fs.writeFileSync(filePath, JSON.stringify(bundleData, null, 2));\n\n bundles.push({\n name: plan.scope,\n locale,\n filePath,\n keyCount: totalKeyCount,\n prunedCount: totalPrunedCount,\n });\n }\n }\n\n if (hasNamedDictionaries) {\n for (const rule of ownership.rules) {\n // Dictionary bundles include ALL keys from matching namespaces — no tree-shaking.\n // Dictionaries are the \"preload everything I need\" layer.\n // Only scope bundles are pruned to extracted keys.\n const matchedNamespaces = new Set<string>();\n\n // Find all namespaces that match this dictionary's include patterns (minus exclude)\n const localeDir = path.join(localesDir, locales[0]);\n let nsFiles: string[] = [];\n try {\n nsFiles = fs.readdirSync(localeDir).filter(f => f.endsWith('.json'));\n } catch { /* dir may not exist */ }\n\n for (const file of nsFiles) {\n const ns = file.slice(0, -'.json'.length);\n // Check if any key in this namespace would match the include patterns\n if (rule.include.some(pattern => keyMatchesPattern(`${ns}.x`, pattern) || keyMatchesPattern(`${ns}.`, pattern) || pattern === `${ns}.*` || pattern.startsWith(`${ns}.`) || (pattern.endsWith('*') && ns.startsWith(pattern.slice(0, -1))))) {\n matchedNamespaces.add(ns);\n }\n }\n\n // Also check from the ownership map (covers exact key patterns)\n const ownedKeys = ownership.dictionaryKeys.get(rule.name) ?? new Set<string>();\n for (const key of ownedKeys) {\n const ns = key.split('.')[0];\n if (ns) matchedNamespaces.add(ns);\n }\n\n for (const locale of locales) {\n const bundleData: Record<string, unknown> = {};\n let totalKeyCount = 0;\n\n for (const ns of matchedNamespaces) {\n const fullData = readNamespaceFile(localesDir, locale, ns);\n if (!fullData) continue;\n\n // Include ALL keys from the namespace that match include and don't match exclude\n const allKeys = flattenKeys(fullData);\n const includedKeys = allKeys.filter(subKey => {\n const fullKey = `${ns}.${subKey}`;\n const included = rule.include.some(pattern => keyMatchesPattern(fullKey, pattern));\n const excluded = rule.exclude.length > 0 &&\n rule.exclude.some(pattern => keyMatchesPattern(fullKey, pattern));\n return included && !excluded;\n });\n\n if (includedKeys.length === 0) continue;\n\n const pruned = pruneNamespace(fullData, includedKeys);\n bundleData[ns] = pruned;\n totalKeyCount += flattenKeys(pruned).length;\n }\n\n const filePath = path.join(outDir, locale, '_dict', `${rule.name}.json`);\n fs.mkdirSync(path.dirname(filePath), { recursive: true });\n fs.writeFileSync(filePath, JSON.stringify(bundleData, null, 2));\n\n bundles.push({\n name: `_dict/${rule.name}`,\n locale,\n filePath,\n keyCount: totalKeyCount,\n prunedCount: 0,\n });\n }\n }\n\n return bundles;\n }\n\n // Legacy shared-namespace dictionary bundles\n for (const sharedNs of analysis.sharedNamespaces) {\n // Collect ALL keys used across ALL routes for this namespace\n const allSubKeys = new Set<string>();\n for (const route of analysis.routes) {\n for (const key of route.keys) {\n const dotIndex = key.key.indexOf('.');\n if (dotIndex === -1) continue;\n const ns = key.key.substring(0, dotIndex);\n if (ns === sharedNs) {\n const subKey = key.dynamic && key.staticPrefix\n ? key.staticPrefix.substring(dotIndex + 1)\n : key.key.substring(dotIndex + 1);\n allSubKeys.add(subKey);\n }\n }\n }\n\n for (const locale of locales) {\n const fullData = readNamespaceFile(localesDir, locale, sharedNs);\n if (!fullData) continue;\n\n const uniqueSubKeys = [...allSubKeys];\n const pruned = pruneNamespace(fullData, uniqueSubKeys);\n\n const filePath = path.join(outDir, locale, '_dict', `${sharedNs}.json`);\n fs.mkdirSync(path.dirname(filePath), { recursive: true });\n fs.writeFileSync(filePath, JSON.stringify(pruned, null, 2));\n\n const availableCount = flattenKeys(fullData).length;\n const keptCount = flattenKeys(pruned).length;\n\n bundles.push({\n name: `_dict/${sharedNs}`,\n locale,\n filePath,\n keyCount: keptCount,\n prunedCount: availableCount - keptCount,\n });\n }\n }\n\n return bundles;\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\n\nconst PLACEHOLDER_PATTERN = /\\{\\{\\s*(\\w+)\\s*\\}\\}/g;\n\n/**\n * Recursively flattens a nested object to dot-separated leaf key paths.\n *\n * @example\n * flattenToKeyPaths({ show: { title: 'X' }, ok: 'Z' })\n * // → ['show.title', 'ok']\n */\nexport function flattenToKeyPaths(data: object | null | undefined, prefix?: string): string[] {\n if (data == null) return [];\n const result: string[] = [];\n\n for (const [key, value] of Object.entries(data)) {\n const fullKey = prefix !== undefined ? `${prefix}.${key}` : key;\n if (value !== null && typeof value === 'object' && !Array.isArray(value)) {\n result.push(...flattenToKeyPaths(value as object, fullKey));\n } else {\n result.push(fullKey);\n }\n }\n\n return result;\n}\n\n/**\n * Recursively flattens a nested object to a map of dot-separated leaf key paths\n * to their string values.\n */\nexport function flattenToLeafValues(\n data: object | null | undefined,\n prefix?: string,\n): Map<string, string> {\n const result = new Map<string, string>();\n if (data == null) return result;\n\n for (const [key, value] of Object.entries(data)) {\n const fullKey = prefix !== undefined ? `${prefix}.${key}` : key;\n if (typeof value === 'string') {\n result.set(fullKey, value);\n } else if (value !== null && typeof value === 'object' && !Array.isArray(value)) {\n for (const [nestedKey, nestedValue] of flattenToLeafValues(value as object, fullKey)) {\n result.set(nestedKey, nestedValue);\n }\n }\n }\n\n return result;\n}\n\n/**\n * Extracts placeholder names from a translation string.\n */\nexport function extractPlaceholders(text: string): string[] {\n const names = new Set<string>();\n for (const match of text.matchAll(PLACEHOLDER_PATTERN)) {\n if (match[1]) {\n names.add(match[1]);\n }\n }\n return [...names];\n}\n\n/**\n * Builds nested TypeScript interface content from flat dot-separated keys.\n * Each leaf becomes `true`, each branch becomes a nested object.\n */\nfunction buildNestedInterface(keys: string[]): string {\n // Build tree structure\n type TreeNode = { [segment: string]: TreeNode | true };\n const tree: TreeNode = {};\n\n for (const key of keys) {\n const parts = key.split('.');\n let current: TreeNode = tree;\n for (let i = 0; i < parts.length; i++) {\n const part = parts[i];\n if (i === parts.length - 1) {\n current[part] = true;\n } else {\n if (current[part] === true || current[part] === undefined) {\n current[part] = {};\n }\n current = current[part] as TreeNode;\n }\n }\n }\n\n // Serialize to TypeScript\n function serialize(node: TreeNode | true, indent: number): string {\n if (node === true) return 'true';\n const pad = ' '.repeat(indent);\n const entries = Object.entries(node).sort(([a], [b]) => a.localeCompare(b));\n const lines = entries.map(([key, value]) => {\n const serialized = serialize(value, indent + 1);\n if (serialized === 'true') {\n return `${pad}'${key}': true;`;\n }\n return `${pad}'${key}': {\\n${serialized}\\n${pad}};`;\n });\n return lines.join('\\n');\n }\n\n return serialize(tree, 2);\n}\n\n/**\n * Reads all `.json` files in `{localesDir}/{defaultLocale}/`, flattens each to\n * key paths, and returns a TypeScript declaration string that:\n *\n * 1. Augments the `vite-bundled-i18n` module to populate `I18nKeyMap` — this\n * wires autocomplete directly into `t()`, `useI18n().t`, and `hasKey()`.\n * 2. Exports `TranslationKey`, `Namespace`, and `NamespaceKeyPaths<T>` for\n * direct use in application code.\n *\n * When this file is present in the project, `t('shar...')` autocompletes to\n * `t('shared.ok')`. Without it, `t()` accepts any string.\n */\nexport function generateTypes(\n localesDir: string,\n defaultLocale: string,\n scopes?: string[],\n pageScopeMap?: Record<string, readonly string[]>,\n): string {\n const localeDir = path.join(localesDir, defaultLocale);\n\n let entries: string[];\n try {\n entries = fs.readdirSync(localeDir);\n } catch {\n entries = [];\n }\n\n const jsonFiles = entries.filter((f) => f.endsWith('.json')).sort();\n\n /** Map from namespace name → flat key paths (without namespace prefix) */\n const namespaceMap = new Map<string, string[]>();\n /** Map from fully qualified key → placeholder names */\n const paramsMap = new Map<string, string[]>();\n\n for (const file of jsonFiles) {\n const namespace = file.slice(0, -'.json'.length);\n const raw = fs.readFileSync(path.join(localeDir, file), 'utf-8');\n const data: unknown = JSON.parse(raw);\n const keyPaths =\n data !== null && typeof data === 'object' && !Array.isArray(data)\n ? flattenToKeyPaths(data as object)\n : [];\n namespaceMap.set(namespace, keyPaths);\n\n const leafValues =\n data !== null && typeof data === 'object' && !Array.isArray(data)\n ? flattenToLeafValues(data as object)\n : new Map<string, string>();\n for (const [keyPath, value] of leafValues) {\n paramsMap.set(`${namespace}.${keyPath}`, extractPlaceholders(value));\n }\n }\n\n // Collect all fully qualified keys\n const allQualifiedKeys: string[] = [];\n for (const [ns, paths] of namespaceMap) {\n for (const p of paths) {\n allQualifiedKeys.push(`${ns}.${p}`);\n }\n }\n\n // ---- I18nParamsMap (only keys with placeholders — skip empty {}) -----------\n let paramsMapEntries: string;\n const keysWithParams = allQualifiedKeys.filter(k => (paramsMap.get(k) ?? []).length > 0);\n if (keysWithParams.length === 0) {\n paramsMapEntries = ' // No parameterized keys found';\n } else {\n paramsMapEntries = keysWithParams\n .map((k) => {\n const placeholders = paramsMap.get(k)!;\n const shape = `{ ${placeholders.map((name) => `${name}: TranslationValue`).join('; ')} }`;\n return ` '${k}': ${shape};`;\n })\n .join('\\n');\n }\n\n // ---- I18nNestedKeys (progressive autocomplete) ----------------------------\n let nestedKeysBlock: string;\n if (allQualifiedKeys.length === 0) {\n nestedKeysBlock = ' interface I18nNestedKeys {}';\n } else {\n const nestedBody = buildNestedInterface(allQualifiedKeys);\n nestedKeysBlock = ` interface I18nNestedKeys {\\n${nestedBody}\\n }`;\n }\n\n // ---- I18nScopeMap ----\n let scopeMapEntries: string;\n if (!scopes || scopes.length === 0) {\n scopeMapEntries = ' // No scopes found';\n } else {\n scopeMapEntries = scopes\n .sort()\n .map((s) => ` '${s}': true;`)\n .join('\\n');\n }\n\n // ---- I18nPageIdentifier + PAGE_SCOPE_MAP ----\n // Framework-agnostic \"page id → scopes\" data. Consumers read this at\n // runtime (typed) inside their router's async resolve hook and call\n // i18n.loadScope(...) in parallel with component resolution.\n let pageIdentifierDecl: string;\n let pageScopeMapDecl: string;\n const pageIds = pageScopeMap ? Object.keys(pageScopeMap).sort() : [];\n if (pageIds.length === 0) {\n pageIdentifierDecl = 'export type I18nPageIdentifier = string;';\n pageScopeMapDecl =\n 'export const PAGE_SCOPE_MAP: Readonly<Record<string, readonly string[]>> = {};';\n } else {\n pageIdentifierDecl = `export type I18nPageIdentifier = ${pageIds\n .map((id) => `'${escapeSingleQuotes(id)}'`)\n .join(' | ')};`;\n\n const entries = pageIds\n .map((id) => {\n const scopesForPage = pageScopeMap![id];\n const values = scopesForPage\n .map((s) => `'${escapeSingleQuotes(s)}'`)\n .join(', ');\n return ` '${escapeSingleQuotes(id)}': [${values}],`;\n })\n .join('\\n');\n pageScopeMapDecl = [\n 'export const PAGE_SCOPE_MAP: {',\n ' readonly [K in I18nPageIdentifier]: readonly (keyof I18nScopeMap & string)[];',\n '} = {',\n entries,\n '} as const;',\n ].join('\\n');\n }\n\n // Direct exports — the generated file is imported by src/core/types.ts.\n // No module augmentation. This works for both npm consumers and local dev.\n return [\n '// Auto-generated by vite-bundled-i18n — do not edit.',\n '// Regenerated on: npm run dev (auto), npm run build, npm run i18n -- generate',\n '//',\n '// Add \".i18n\" to your tsconfig include: { \"include\": [\"src\", \".i18n\"] }',\n '',\n 'type TranslationValue = string | number | boolean | bigint | null | undefined;',\n '',\n '// Direct exports — used by the package to populate types',\n `export ${nestedKeysBlock.replace(' interface ', 'interface ')}`,\n '',\n `export interface I18nParamsMap {`,\n paramsMapEntries,\n `}`,\n '',\n `export interface I18nScopeMap {`,\n scopeMapEntries,\n `}`,\n '',\n pageIdentifierDecl,\n '',\n pageScopeMapDecl,\n '',\n ].join('\\n');\n}\n\nfunction escapeSingleQuotes(s: string): string {\n return s.replace(/\\\\/g, '\\\\\\\\').replace(/'/g, \"\\\\'\");\n}\n\n/**\n * Calls {@link generateTypes} and writes the result to `outPath`.\n */\nexport function writeTypes(\n localesDir: string,\n defaultLocale: string,\n outPath: string,\n scopes?: string[],\n pageScopeMap?: Record<string, readonly string[]>,\n): void {\n const content = generateTypes(localesDir, defaultLocale, scopes, pageScopeMap);\n fs.mkdirSync(path.dirname(outPath), { recursive: true });\n fs.writeFileSync(outPath, content, 'utf-8');\n}\n\n/**\n * Emit a runtime-only `.js` sibling of the generated `.ts` types file.\n *\n * The types file (`.i18n/i18n-generated.ts`) is the canonical source for\n * TSC and IDE autocomplete — its `PAGE_SCOPE_MAP` const has both real\n * runtime values and a typed shape. But Vite doesn't resolve tsconfig-path\n * aliases by default, so a plain `import { PAGE_SCOPE_MAP } from\n * 'vite-bundled-i18n/generated'` needs a concrete `.js` target.\n *\n * The plugin writes this file alongside the types file and registers a\n * programmatic `resolve.alias` pointing `vite-bundled-i18n/generated` at\n * it. The published `dist/core/i18n-generated-shim.js` serves non-Vite\n * consumers as an empty-default fallback.\n */\nexport function generateRuntimeConst(\n pageScopeMap?: Record<string, readonly string[]>,\n): string {\n const ids = pageScopeMap ? Object.keys(pageScopeMap).sort() : [];\n const lines: string[] = [\n '// Auto-generated by vite-bundled-i18n — do not edit.',\n '// Runtime companion to i18n-generated.ts (types). Aliased by the',\n '// plugin at `vite-bundled-i18n/generated`.',\n '',\n ];\n\n if (ids.length === 0) {\n lines.push('export const PAGE_SCOPE_MAP = Object.freeze({});');\n } else {\n lines.push('export const PAGE_SCOPE_MAP = Object.freeze({');\n for (const id of ids) {\n const scopesForPage = pageScopeMap![id];\n const values = scopesForPage\n .map((s) => `'${escapeSingleQuotes(s)}'`)\n .join(', ');\n lines.push(` '${escapeSingleQuotes(id)}': Object.freeze([${values}]),`);\n }\n lines.push('});');\n }\n lines.push('');\n return lines.join('\\n');\n}\n\n/**\n * Write the runtime `.js` companion at the given path. Creates parent\n * directories as needed. Empty map → placeholder that resolves but exposes\n * no page entries (matches the package-shipped shim shape).\n */\nexport function writeRuntimeConst(\n outPath: string,\n pageScopeMap?: Record<string, readonly string[]>,\n): void {\n const content = generateRuntimeConst(pageScopeMap);\n fs.mkdirSync(path.dirname(outPath), { recursive: true });\n fs.writeFileSync(outPath, content, 'utf-8');\n}\n\n/**\n * Derive the runtime `.js` path from the types `.ts` path — same basename,\n * same directory, different extension. Used so the plugin and CLI always\n * keep the two in sync without extra config.\n */\nexport function runtimePathFromTypesPath(typesOutPath: string): string {\n const dir = path.dirname(typesOutPath);\n const base = path.basename(typesOutPath);\n const withoutExt = base.replace(/\\.(ts|tsx|d\\.ts)$/, '');\n return path.join(dir, `${withoutExt}.js`);\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport type { ProjectAnalysis } from './walker-types';\nimport { flattenKeys } from './bundle-generator';\nimport type { DictionaryConfig } from '../core/types';\nimport {\n keyMatchesPattern,\n normalizeDictionaries,\n resolveDictionaryOwnership,\n} from './dictionary-ownership';\n\n/**\n * Read all namespace JSON files for the default locale and return a map of\n * namespace → flattened dot-path key arrays.\n */\nexport function flattenLocaleKeys(\n localesDir: string,\n defaultLocale: string,\n): Map<string, string[]> {\n const result = new Map<string, string[]>();\n const localeDir = path.join(localesDir, defaultLocale);\n\n if (!fs.existsSync(localeDir)) return result;\n\n const entries = fs.readdirSync(localeDir);\n for (const entry of entries) {\n if (!entry.endsWith('.json')) continue;\n const namespace = entry.slice(0, -5);\n const filePath = path.join(localeDir, entry);\n try {\n const data = JSON.parse(fs.readFileSync(filePath, 'utf-8')) as object;\n result.set(namespace, flattenKeys(data));\n } catch {\n // skip malformed files\n }\n }\n\n return result;\n}\n\n/**\n * Generate the manifest report: mapping of routeId → { scopes, keys, files }.\n */\nexport function generateManifest(\n analysis: ProjectAnalysis,\n): Record<string, object> {\n const manifest: Record<string, object> = {};\n\n for (const route of analysis.routes) {\n manifest[route.routeId] = {\n scopes: route.scopes,\n keys: route.keys.map((k) => k.key),\n files: route.files,\n };\n }\n\n return manifest;\n}\n\n/**\n * A single missing-key entry.\n */\nexport interface MissingKeyEntry {\n key: string;\n usedIn: string[];\n line: number;\n}\n\n/**\n * Generate the missing-keys report: keys used in code that don't exist in\n * translation files.\n */\nexport function generateMissing(\n analysis: ProjectAnalysis,\n availableKeys: Map<string, string[]>,\n): { summary?: { total: number; hint: string }; keys: MissingKeyEntry[] } {\n const missing: MissingKeyEntry[] = [];\n\n for (const key of analysis.allKeys) {\n // Skip dynamic keys — they can't be checked statically.\n if (key.dynamic) continue;\n\n const dotIndex = key.key.indexOf('.');\n if (dotIndex === -1) continue;\n\n const namespace = key.key.substring(0, dotIndex);\n const subKey = key.key.substring(dotIndex + 1);\n\n const namespacePaths = availableKeys.get(namespace);\n if (!namespacePaths || !namespacePaths.includes(subKey)) {\n // Collect all files where this key appears across routes.\n const usedIn: string[] = [];\n for (const route of analysis.routes) {\n for (const rk of route.keys) {\n if (rk.key === key.key && rk.line === key.line) {\n for (const file of route.files) {\n if (!usedIn.includes(file)) {\n usedIn.push(file);\n }\n }\n }\n }\n }\n\n missing.push({ key: key.key, usedIn, line: key.line });\n }\n }\n\n if (missing.length > 50) {\n return {\n summary: {\n total: missing.length,\n hint: 'If most keys are missing, verify localesDir structure: {locale}/{namespace}.json',\n },\n keys: missing,\n };\n }\n\n return { keys: missing };\n}\n\n/**\n * A single unused-key entry.\n */\nexport interface UnusedKeyEntry {\n key: string;\n namespace: string;\n}\n\n/**\n * Generate the unused-keys report: keys in translation files that no route\n * uses.\n */\nexport function generateUnused(\n analysis: ProjectAnalysis,\n availableKeys: Map<string, string[]>,\n): { keys: UnusedKeyEntry[] } {\n const unused: UnusedKeyEntry[] = [];\n\n // Build a set of all fully-qualified keys used across all routes.\n const usedKeys = new Set<string>(analysis.allKeys.map((k) => k.key));\n\n for (const [namespace, keyPaths] of availableKeys) {\n for (const keyPath of keyPaths) {\n const fullKey = `${namespace}.${keyPath}`;\n if (!usedKeys.has(fullKey)) {\n unused.push({ key: fullKey, namespace });\n }\n }\n }\n\n return { keys: unused };\n}\n\n/**\n * Per-route statistics entry.\n */\nexport interface RouteStats {\n routeId: string;\n usedKeys: number;\n availableKeys: number;\n prunedKeys: number;\n}\n\n/**\n * A key that is used by more than one route and whose namespace is not in a\n * dictionary, making it a candidate for extraction.\n */\nexport interface DictionaryCandidate {\n key: string;\n namespace: string;\n usedByRoutes: string[];\n routeCount: number;\n}\n\n/**\n * Per-namespace usage summary.\n */\nexport interface NamespaceUsageEntry {\n namespace: string;\n routeCount: number;\n totalRoutes: number;\n percentage: number;\n inDictionary: boolean;\n}\n\n/**\n * Full overlap analysis result.\n */\nexport interface OverlapAnalysis {\n candidates: DictionaryCandidate[];\n namespaceUsage: NamespaceUsageEntry[];\n}\n\nexport interface DictionaryOwnershipRuleReport {\n name: string;\n priority: number;\n include: string[];\n ownedKeys: string[];\n}\n\nexport interface DictionaryCollisionReport {\n key: string;\n owner: string;\n matchedDictionaries: string[];\n}\n\nexport interface DictionaryOwnershipReport {\n rules: DictionaryOwnershipRuleReport[];\n collisions: DictionaryCollisionReport[];\n unownedKeys: string[];\n}\n\n/**\n * Analyse key and namespace overlap across routes. Keys used by more than one\n * route whose namespace is NOT already a dictionary namespace are returned as\n * candidates. The namespace-level summary describes what fraction of routes\n * use each namespace.\n */\nexport function generateOverlapAnalysis(\n analysis: ProjectAnalysis,\n dictionaryNamespaces?: Set<string>,\n): OverlapAnalysis {\n const dictNs = dictionaryNamespaces ?? new Set<string>();\n const totalRoutes = analysis.routes.length;\n\n // 1. Map each fully-qualified key → set of routeIds that use it.\n const keyToRoutes = new Map<string, Set<string>>();\n for (const route of analysis.routes) {\n for (const k of route.keys) {\n if (k.dynamic) continue;\n if (!keyToRoutes.has(k.key)) {\n keyToRoutes.set(k.key, new Set());\n }\n keyToRoutes.get(k.key)!.add(route.routeId);\n }\n }\n\n // 2. Build candidates: keys used by >1 route whose namespace is not a\n // dictionary namespace.\n const candidates: DictionaryCandidate[] = [];\n for (const [key, routes] of keyToRoutes) {\n if (routes.size <= 1) continue;\n const dotIndex = key.indexOf('.');\n if (dotIndex === -1) continue;\n const namespace = key.substring(0, dotIndex);\n if (dictNs.has(namespace)) continue;\n const usedByRoutes = Array.from(routes);\n candidates.push({ key, namespace, usedByRoutes, routeCount: usedByRoutes.length });\n }\n\n // Sort for stable output: descending routeCount then alphabetical key.\n candidates.sort((a, b) => b.routeCount - a.routeCount || a.key.localeCompare(b.key));\n\n // 3. Namespace-level analysis: for each namespace, count distinct routes.\n const namespaceToRoutes = new Map<string, Set<string>>();\n for (const route of analysis.routes) {\n for (const k of route.keys) {\n if (k.dynamic) continue;\n const dotIndex = k.key.indexOf('.');\n if (dotIndex === -1) continue;\n const namespace = k.key.substring(0, dotIndex);\n if (!namespaceToRoutes.has(namespace)) {\n namespaceToRoutes.set(namespace, new Set());\n }\n namespaceToRoutes.get(namespace)!.add(route.routeId);\n }\n }\n\n const namespaceUsage: NamespaceUsageEntry[] = [];\n for (const [namespace, routes] of namespaceToRoutes) {\n const routeCount = routes.size;\n const percentage =\n totalRoutes === 0 ? 0 : Math.round((routeCount / totalRoutes) * 100);\n namespaceUsage.push({\n namespace,\n routeCount,\n totalRoutes,\n percentage,\n inDictionary: dictNs.has(namespace),\n });\n }\n\n // Sort descending by routeCount then alphabetically.\n namespaceUsage.sort(\n (a, b) => b.routeCount - a.routeCount || a.namespace.localeCompare(b.namespace),\n );\n\n return { candidates, namespaceUsage };\n}\n\n/**\n * Generate the stats report: summary counts.\n */\nexport function generateStats(\n analysis: ProjectAnalysis,\n availableKeys: Map<string, string[]>,\n): object {\n const totalKeysInFiles = Array.from(availableKeys.values()).reduce(\n (sum, paths) => sum + paths.length,\n 0,\n );\n\n const missingResult = generateMissing(analysis, availableKeys);\n const unusedResult = generateUnused(analysis, availableKeys);\n\n const perRoute: RouteStats[] = analysis.routes.map((route) => ({\n routeId: route.routeId,\n usedKeys: route.keys.filter((k) => !k.dynamic).length,\n availableKeys: totalKeysInFiles,\n prunedKeys: totalKeysInFiles - route.keys.filter((k) => !k.dynamic).length,\n }));\n\n const overlapResult = generateOverlapAnalysis(analysis);\n const sharedKeysCount = new Set(\n overlapResult.candidates.map((c) => c.key),\n ).size;\n const dictionaryCandidates = Array.from(\n new Set(overlapResult.candidates.map((c) => c.namespace)),\n );\n\n return {\n totalKeysInCode: analysis.allKeys.length,\n totalKeysInFiles,\n usedKeys: analysis.allKeys.length,\n missingKeys: missingResult.keys.length,\n unusedKeys: unusedResult.keys.length,\n routes: analysis.routes.length,\n namespaces: analysis.availableNamespaces.length,\n sharedNamespaces: analysis.sharedNamespaces,\n sharedKeysCount,\n dictionaryCandidates,\n perRoute,\n };\n}\n\nexport function generateDictionaryOwnershipReport(\n availableKeys: Map<string, string[]>,\n dictionaries?: Record<string, DictionaryConfig>,\n): DictionaryOwnershipReport {\n const rules = normalizeDictionaries(dictionaries);\n const allKeys = [...availableKeys.entries()].flatMap(([namespace, keys]) =>\n keys.map((key) => `${namespace}.${key}`),\n );\n const ownership = resolveDictionaryOwnership(allKeys, dictionaries);\n\n const collisions: DictionaryCollisionReport[] = [];\n for (const key of allKeys) {\n const matched = rules\n .filter((rule) => rule.include.some((pattern) => keyMatchesPattern(key, pattern)))\n .map((rule) => rule.name);\n if (matched.length > 1) {\n collisions.push({\n key,\n owner: ownership.keyOwner.get(key) ?? matched[0],\n matchedDictionaries: matched,\n });\n }\n }\n\n return {\n rules: rules.map((rule) => ({\n name: rule.name,\n priority: rule.priority,\n include: rule.include,\n ownedKeys: [...(ownership.dictionaryKeys.get(rule.name) ?? new Set())].sort(),\n })),\n collisions: collisions.sort((a, b) => a.key.localeCompare(b.key)),\n unownedKeys: allKeys.filter((key) => !ownership.keyOwner.has(key)).sort(),\n };\n}\n\n/**\n * Orchestrate report generation: flatten locale keys, generate all four\n * reports, and write them as JSON files to outDir.\n */\nexport function generateReports(\n analysis: ProjectAnalysis,\n localesDir: string,\n defaultLocale: string,\n outDir: string,\n dictionaries?: Record<string, DictionaryConfig>,\n): void {\n const availableKeys = flattenLocaleKeys(localesDir, defaultLocale);\n\n const manifest = generateManifest(analysis);\n const missing = generateMissing(analysis, availableKeys);\n const unused = generateUnused(analysis, availableKeys);\n const stats = generateStats(analysis, availableKeys);\n const overlap = generateOverlapAnalysis(analysis);\n const ownership = generateDictionaryOwnershipReport(availableKeys, dictionaries);\n\n fs.mkdirSync(outDir, { recursive: true });\n\n fs.writeFileSync(\n path.join(outDir, 'manifest.json'),\n JSON.stringify(manifest, null, 2),\n );\n fs.writeFileSync(\n path.join(outDir, 'missing.json'),\n JSON.stringify(missing, null, 2),\n );\n fs.writeFileSync(\n path.join(outDir, 'unused.json'),\n JSON.stringify(unused, null, 2),\n );\n fs.writeFileSync(\n path.join(outDir, 'stats.json'),\n JSON.stringify(stats, null, 2),\n );\n fs.writeFileSync(\n path.join(outDir, 'overlap.json'),\n JSON.stringify(overlap, null, 2),\n );\n fs.writeFileSync(\n path.join(outDir, 'ownership.json'),\n JSON.stringify(ownership, null, 2),\n );\n}\n","import ts from 'typescript';\n\n/**\n * Extracts a string value from a node if it's a string literal or\n * a no-substitution template literal. Returns undefined for anything else.\n */\nexport function getStringValue(node: ts.Expression): string | undefined {\n if (ts.isStringLiteral(node)) {\n return node.text;\n }\n if (ts.isNoSubstitutionTemplateLiteral(node)) {\n return node.text;\n }\n return undefined;\n}\n\n/**\n * Extracts the longest static prefix from an expression.\n *\n * For string literals, returns the full string.\n * For template literals, returns the head text (before the first expression), trimmed of trailing dots.\n * For binary `+` expressions, recursively extracts from the left side.\n * For anything else, returns undefined.\n */\nexport function getStaticPrefix(node: ts.Expression): string | undefined {\n if (ts.isStringLiteral(node)) {\n const text = node.text;\n return text.endsWith('.') ? text.slice(0, -1) : text || undefined;\n }\n\n if (ts.isNoSubstitutionTemplateLiteral(node)) {\n const text = node.text;\n return text.endsWith('.') ? text.slice(0, -1) : text || undefined;\n }\n\n if (ts.isTemplateExpression(node)) {\n const head = node.head.text;\n return head.endsWith('.') ? head.slice(0, -1) : head || undefined;\n }\n\n if (ts.isBinaryExpression(node) && node.operatorToken.kind === ts.SyntaxKind.PlusToken) {\n return getStaticPrefix(node.left);\n }\n\n return undefined;\n}\n\n/**\n * Collects all non-type-only import and export-from specifiers from a source file.\n */\nexport function collectImports(sourceFile: ts.SourceFile): string[] {\n const imports: string[] = [];\n\n ts.forEachChild(sourceFile, (node) => {\n if (ts.isImportDeclaration(node)) {\n if (node.importClause?.isTypeOnly) return;\n if (ts.isStringLiteral(node.moduleSpecifier)) {\n imports.push(node.moduleSpecifier.text);\n }\n }\n\n if (ts.isExportDeclaration(node) && node.moduleSpecifier) {\n if (node.isTypeOnly) return;\n if (ts.isStringLiteral(node.moduleSpecifier)) {\n imports.push(node.moduleSpecifier.text);\n }\n }\n });\n\n return imports;\n}\n","import ts from 'typescript';\nimport { getStringValue, getStaticPrefix } from './ast-utils';\nimport type { ExtractionOptions, ExtractedKey } from './types';\n\nconst DEFAULT_KEY_FIELDS = ['labelKey', 'titleKey', 'translationKey'];\n\n/** Function names recognized as translation calls even when not traced to useI18n(). */\nconst TRANSLATION_CALLEE_NAMES = new Set(['t', 'get']);\n\nfunction getKeyFields(options: ExtractionOptions): Set<string> {\n if (!options.keyFields || options.keyFields.length === 0) {\n return new Set(DEFAULT_KEY_FIELDS);\n }\n return new Set([...DEFAULT_KEY_FIELDS, ...options.keyFields]);\n}\nconst PACKAGE_NAMES = new Set([\n 'vite-bundled-i18n',\n 'vite-bundled-i18n/react',\n 'vite-i18n-manager',\n 'vite-i18n-manager/react',\n]);\n\n/**\n * Package specifiers recognized as ours.\n *\n * @param specifier - The import module specifier to check.\n * @param hookSources - Additional module specifiers configured via `extraction.hookSources`.\n */\nfunction isOurPackage(specifier: string, hookSources?: string[]): boolean {\n return (\n PACKAGE_NAMES.has(specifier) ||\n specifier.includes('/core/t') ||\n specifier.includes('/react/useI18n') ||\n matchesHookSource(specifier, hookSources)\n );\n}\n\n/**\n * Checks if a module specifier exports `useI18n`.\n *\n * @param specifier - The import module specifier to check.\n * @param hookSources - Additional module specifiers configured via `extraction.hookSources`.\n */\nfunction isUseI18nPackage(specifier: string, hookSources?: string[]): boolean {\n return (\n specifier === 'vite-bundled-i18n/react' ||\n specifier === 'vite-i18n-manager/react' ||\n specifier.includes('/react/useI18n') ||\n matchesHookSource(specifier, hookSources)\n );\n}\n\n/**\n * Checks if a specifier matches any configured hook source.\n * Uses exact match or endsWith to handle path alias resolution.\n */\nfunction matchesHookSource(specifier: string, hookSources?: string[]): boolean {\n if (!hookSources || hookSources.length === 0) return false;\n return hookSources.some(source => specifier === source || specifier.endsWith(source));\n}\n\n/**\n * Checks if a module specifier is one that exports the global `t`.\n */\nfunction isGlobalTPackage(specifier: string): boolean {\n return (\n specifier === 'vite-bundled-i18n' ||\n specifier === 'vite-i18n-manager' ||\n specifier.includes('/core/t')\n );\n}\n\n/**\n * Extract the fallback string from a t() call's arguments.\n * - t(key, fallback) where fallback is a string literal\n * - t(key, params, fallback) where params is an object literal and fallback is a string literal\n */\nfunction extractFallback(args: ts.NodeArray<ts.Expression>): string | undefined {\n if (args.length >= 2) {\n const second = args[1];\n // t(key, fallbackString)\n const secondStr = getStringValue(second);\n if (secondStr !== undefined) {\n return secondStr;\n }\n // t(key, paramsObject, fallbackString)\n if (args.length >= 3 && ts.isObjectLiteralExpression(second)) {\n const third = args[2];\n const thirdStr = getStringValue(third);\n if (thirdStr !== undefined) {\n return thirdStr;\n }\n }\n }\n return undefined;\n}\n\n/**\n * Finds all t() translation calls in a source file.\n */\nexport function findTranslationCalls(\n sourceFile: ts.SourceFile,\n options: ExtractionOptions,\n): ExtractedKey[] {\n const results: ExtractedKey[] = [];\n const seenStaticFieldKeys = new Set<string>();\n\n // Track which local identifiers map to our global `t`\n // key = local name, value = 'global' | 'useI18n'\n const trackedNames = new Map<string, 'global' | 'useI18n'>();\n\n // Set of local names bound to our `useI18n` import\n const useI18nNames = new Set<string>();\n const i18nKeyNames = new Set<string>();\n const literalConstants = new Map<string, string>();\n /** Tracks `as const` objects and string enums: varName → (propName → stringValue) */\n const constObjectMaps = new Map<string, Map<string, string>>();\n\n // Pass 1: Walk imports\n ts.forEachChild(sourceFile, (node) => {\n if (!ts.isImportDeclaration(node)) return;\n if (!ts.isStringLiteral(node.moduleSpecifier)) return;\n const specifier = node.moduleSpecifier.text;\n if (!isOurPackage(specifier, options.hookSources)) return;\n\n const clause = node.importClause;\n if (!clause) return;\n const bindings = clause.namedBindings;\n if (!bindings || !ts.isNamedImports(bindings)) return;\n\n for (const element of bindings.elements) {\n const importedName = (element.propertyName ?? element.name).text;\n const localName = element.name.text;\n\n if (importedName === 't' && isGlobalTPackage(specifier)) {\n if (options.scope !== 'scoped') {\n trackedNames.set(localName, 'global');\n }\n }\n\n if (importedName === 'useI18n' && isUseI18nPackage(specifier, options.hookSources)) {\n useI18nNames.add(localName);\n }\n\n if (importedName === 'i18nKey' && isOurPackage(specifier, options.hookSources)) {\n i18nKeyNames.add(localName);\n }\n }\n });\n\n // Pass 1b: Collect `as const` objects and string enums\n ts.forEachChild(sourceFile, (node) => {\n // as const objects: const X = { ... } as const\n if (ts.isVariableStatement(node)) {\n for (const decl of node.declarationList.declarations) {\n if (!ts.isIdentifier(decl.name) || !decl.initializer) continue;\n if (!ts.isAsExpression(decl.initializer)) continue;\n const init = decl.initializer.expression;\n if (!ts.isObjectLiteralExpression(init)) continue;\n\n const entries = new Map<string, string>();\n for (const prop of init.properties) {\n if (!ts.isPropertyAssignment(prop)) continue;\n const propName = ts.isIdentifier(prop.name)\n ? prop.name.text\n : ts.isStringLiteral(prop.name)\n ? prop.name.text\n : undefined;\n if (!propName) continue;\n const value = getStringValue(prop.initializer);\n if (value !== undefined) {\n entries.set(propName, value);\n }\n }\n if (entries.size > 0) {\n constObjectMaps.set(decl.name.text, entries);\n }\n }\n }\n\n // String enums\n if (ts.isEnumDeclaration(node) && ts.isIdentifier(node.name)) {\n const entries = new Map<string, string>();\n for (const member of node.members) {\n const memberName = ts.isIdentifier(member.name)\n ? member.name.text\n : ts.isStringLiteral(member.name)\n ? member.name.text\n : undefined;\n if (!memberName || !member.initializer) continue;\n const value = getStringValue(member.initializer);\n if (value !== undefined) {\n entries.set(memberName, value);\n }\n }\n if (entries.size > 0) {\n constObjectMaps.set(node.name.text, entries);\n }\n }\n });\n\n // Pass 2: Walk entire AST to find useI18n destructuring and t() calls\n const keyFields = getKeyFields(options);\n\n function resolveStaticKeys(keyArg: ts.Expression): string[] | undefined {\n const direct = getStringValue(keyArg)\n ?? (ts.isIdentifier(keyArg) ? literalConstants.get(keyArg.text) : undefined);\n if (direct !== undefined) {\n return [direct];\n }\n\n if (ts.isPropertyAccessExpression(keyArg) && ts.isIdentifier(keyArg.expression)) {\n const objMap = constObjectMaps.get(keyArg.expression.text);\n const value = objMap?.get(keyArg.name.text);\n return value === undefined ? undefined : [value];\n }\n\n if (ts.isElementAccessExpression(keyArg) && ts.isIdentifier(keyArg.expression)) {\n const objMap = constObjectMaps.get(keyArg.expression.text);\n if (!objMap) return undefined;\n\n const staticMember = keyArg.argumentExpression\n ? getStringValue(keyArg.argumentExpression)\n : undefined;\n if (staticMember !== undefined) {\n const value = objMap.get(staticMember);\n return value === undefined ? undefined : [value];\n }\n\n return [...objMap.values()];\n }\n\n return undefined;\n }\n\n function pushStaticKeys(\n keys: readonly string[],\n line: number,\n character: number,\n fallback?: string,\n ): void {\n for (const key of keys) {\n results.push({\n key,\n fallback,\n dynamic: false,\n line: line + 1,\n column: character,\n });\n }\n }\n\n function visit(node: ts.Node): void {\n if (\n ts.isVariableDeclaration(node) &&\n ts.isIdentifier(node.name) &&\n node.initializer &&\n getStringValue(node.initializer) !== undefined\n ) {\n literalConstants.set(node.name.text, getStringValue(node.initializer)!);\n }\n\n // Look for: const { t } = useI18n(...) or const { t: alias } = useI18n(...)\n if (\n ts.isVariableDeclaration(node) &&\n node.initializer &&\n ts.isCallExpression(node.initializer) &&\n ts.isIdentifier(node.initializer.expression) &&\n useI18nNames.has(node.initializer.expression.text) &&\n node.name &&\n ts.isObjectBindingPattern(node.name)\n ) {\n for (const element of node.name.elements) {\n if (!ts.isIdentifier(element.name)) continue;\n const propName = element.propertyName\n ? ts.isIdentifier(element.propertyName)\n ? element.propertyName.text\n : undefined\n : element.name.text;\n\n if (propName === 't') {\n const localName = element.name.text;\n trackedNames.set(localName, 'useI18n');\n }\n }\n }\n\n // Look for calls to tracked identifiers\n if (\n ts.isCallExpression(node) &&\n ts.isIdentifier(node.expression) &&\n trackedNames.has(node.expression.text)\n ) {\n const args = node.arguments;\n if (args.length === 0) {\n ts.forEachChild(node, visit);\n return;\n }\n\n const keyArg = args[0];\n const staticKeys = resolveStaticKeys(keyArg);\n const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());\n\n if (staticKeys !== undefined) {\n pushStaticKeys(staticKeys, line, character, extractFallback(args));\n } else {\n // Dynamic key\n const prefix = getStaticPrefix(keyArg);\n results.push({\n key: prefix ? `${prefix}.*` : '*',\n dynamic: true,\n staticPrefix: prefix || undefined,\n line: line + 1,\n column: character,\n });\n }\n }\n\n if (\n ts.isCallExpression(node) &&\n ts.isIdentifier(node.expression) &&\n i18nKeyNames.has(node.expression.text) &&\n node.arguments.length > 0\n ) {\n const keyArg = node.arguments[0];\n const staticKeys = resolveStaticKeys(keyArg);\n const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());\n\n if (staticKeys !== undefined) {\n pushStaticKeys(staticKeys, line, character);\n } else {\n const prefix = getStaticPrefix(keyArg);\n results.push({\n key: prefix ? `${prefix}.*` : '*',\n dynamic: true,\n staticPrefix: prefix || undefined,\n line: line + 1,\n column: character,\n });\n }\n }\n\n // Catch t() / get() calls from untracked sources (e.g., t passed as argument to helpers).\n // Only fires in global extraction mode — scoped mode only tracks traced identifiers.\n if (\n options.scope !== 'scoped' &&\n ts.isCallExpression(node) &&\n ts.isIdentifier(node.expression) &&\n !trackedNames.has(node.expression.text) &&\n !i18nKeyNames.has(node.expression.text) &&\n TRANSLATION_CALLEE_NAMES.has(node.expression.text) &&\n node.arguments.length > 0\n ) {\n const keyArg = node.arguments[0];\n const staticKeys = resolveStaticKeys(keyArg);\n // Only extract if it looks like a dotted translation key (has at least one dot)\n if (staticKeys !== undefined) {\n const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());\n pushStaticKeys(\n staticKeys.filter((key) => key.includes('.')),\n line,\n character,\n );\n }\n }\n\n if (\n ts.isPropertyAssignment(node) &&\n ((ts.isIdentifier(node.name) && keyFields.has(node.name.text))\n || (ts.isStringLiteral(node.name) && keyFields.has(node.name.text)))\n ) {\n const staticKey = getStringValue(node.initializer)\n ?? (ts.isIdentifier(node.initializer) ? literalConstants.get(node.initializer.text) : undefined);\n if (staticKey !== undefined && !seenStaticFieldKeys.has(staticKey)) {\n const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());\n seenStaticFieldKeys.add(staticKey);\n results.push({\n key: staticKey,\n dynamic: false,\n line: line + 1,\n column: character,\n });\n }\n }\n\n ts.forEachChild(node, visit);\n }\n\n visit(sourceFile);\n return results;\n}\n\n/**\n * Extracts scope strings from all useI18n() calls in a source file.\n *\n * @param sourceFile - The parsed TypeScript source file.\n * @param hookSources - Additional module specifiers that export `useI18n`.\n */\nexport function extractScopes(sourceFile: ts.SourceFile, hookSources?: string[]): string[] {\n const scopes: string[] = [];\n\n // First check that useI18n is actually imported from our package\n const useI18nNames = new Set<string>();\n\n ts.forEachChild(sourceFile, (node) => {\n if (!ts.isImportDeclaration(node)) return;\n if (!ts.isStringLiteral(node.moduleSpecifier)) return;\n const specifier = node.moduleSpecifier.text;\n if (!isUseI18nPackage(specifier, hookSources)) return;\n\n const clause = node.importClause;\n if (!clause) return;\n const bindings = clause.namedBindings;\n if (!bindings || !ts.isNamedImports(bindings)) return;\n\n for (const element of bindings.elements) {\n const importedName = (element.propertyName ?? element.name).text;\n const localName = element.name.text;\n if (importedName === 'useI18n') {\n useI18nNames.add(localName);\n }\n }\n });\n\n function visit(node: ts.Node): void {\n if (\n ts.isCallExpression(node) &&\n ts.isIdentifier(node.expression) &&\n useI18nNames.has(node.expression.text) &&\n node.arguments.length > 0\n ) {\n const scopeArg = node.arguments[0];\n const scopeStr = getStringValue(scopeArg);\n if (scopeStr !== undefined) {\n scopes.push(scopeStr);\n }\n }\n\n ts.forEachChild(node, visit);\n }\n\n visit(sourceFile);\n return scopes;\n}\n","import ts from 'typescript';\nimport { collectImports } from './ast-utils';\nimport { findTranslationCalls, extractScopes } from './patterns';\nimport type { ExtractionOptions, ExtractionResult } from './types';\n\nconst DEFAULT_OPTIONS: ExtractionOptions = {\n scope: 'global',\n filePath: '',\n};\n\n/**\n * Extracts translation keys, scopes, and imports from a TypeScript/TSX source string.\n *\n * Parses the source with the TypeScript compiler, walks the AST to find\n * `t()` and `useI18n()` patterns, and returns structured extraction data.\n *\n * @param source - The TypeScript/TSX source code to analyze\n * @param options - Extraction options (scope mode, file path for metadata)\n * @returns The extraction result with keys, scopes, and imports\n */\nexport function extractKeys(\n source: string,\n options?: Partial<ExtractionOptions>,\n): ExtractionResult {\n const opts: ExtractionOptions = { ...DEFAULT_OPTIONS, ...options };\n\n if (!source.trim()) {\n return { filePath: opts.filePath, scopes: [], keys: [], imports: [] };\n }\n\n let sourceFile: ts.SourceFile;\n try {\n sourceFile = ts.createSourceFile(\n opts.filePath || 'source.tsx',\n source,\n ts.ScriptTarget.Latest,\n true,\n ts.ScriptKind.TSX,\n );\n } catch {\n console.warn('vite-bundled-i18n: Failed to parse ' + opts.filePath);\n return { filePath: opts.filePath, scopes: [], keys: [], imports: [] };\n }\n\n const keys = findTranslationCalls(sourceFile, opts);\n const scopes = extractScopes(sourceFile, opts.hookSources);\n const imports = collectImports(sourceFile);\n\n return {\n filePath: opts.filePath,\n scopes,\n keys,\n imports,\n };\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport { globSync } from 'tinyglobby';\nimport ts from 'typescript';\nimport * as extractModule from './extract';\nimport type { ExtractedKey } from './types';\nimport type { ExtractionCache } from './extraction-cache';\nimport type {\n WalkerOptions,\n RouteAnalysis,\n ProjectAnalysis,\n} from './walker-types';\n\nconst RESOLVE_EXTENSIONS = ['.tsx', '.ts', '.jsx', '.js'];\nconst INDEX_EXTENSIONS = ['/index.tsx', '/index.ts'];\nconst tsconfigPathCache = new Map<string, { baseUrl?: string; paths?: Record<string, string[]> }>();\n\nfunction tryResolveBase(base: string): string | undefined {\n for (const ext of RESOLVE_EXTENSIONS) {\n const candidate = base + ext;\n if (fs.existsSync(candidate)) {\n return candidate;\n }\n }\n\n for (const indexSuffix of INDEX_EXTENSIONS) {\n const candidate = base + indexSuffix;\n if (fs.existsSync(candidate)) {\n return candidate;\n }\n }\n\n return undefined;\n}\n\nfunction readTsconfigPaths(rootDir: string): { baseUrl?: string; paths?: Record<string, string[]> } {\n const cached = tsconfigPathCache.get(rootDir);\n if (cached) return cached;\n\n for (const fileName of ['tsconfig.app.json', 'tsconfig.json']) {\n const fullPath = path.join(rootDir, fileName);\n if (!fs.existsSync(fullPath)) continue;\n\n try {\n const configFile = ts.readConfigFile(fullPath, ts.sys.readFile);\n if (configFile.error) continue;\n const parsed = ts.parseJsonConfigFileContent(configFile.config, ts.sys, rootDir);\n const result = {\n baseUrl: parsed.options.baseUrl,\n paths: parsed.options.paths,\n };\n tsconfigPathCache.set(rootDir, result);\n return result;\n } catch {\n // Ignore malformed tsconfig and continue with default resolution.\n }\n }\n\n const empty = {};\n tsconfigPathCache.set(rootDir, empty);\n return empty;\n}\n\nfunction resolveAliasImport(\n specifier: string,\n rootDir: string,\n): string | undefined {\n const { baseUrl, paths } = readTsconfigPaths(rootDir);\n if (!baseUrl || !paths) return undefined;\n\n for (const [pattern, targets] of Object.entries(paths)) {\n const wildcardIndex = pattern.indexOf('*');\n\n if (wildcardIndex === -1) {\n if (specifier !== pattern) continue;\n for (const target of targets) {\n const candidate = tryResolveBase(path.resolve(baseUrl, target));\n if (candidate) return candidate;\n }\n continue;\n }\n\n const prefix = pattern.slice(0, wildcardIndex);\n const suffix = pattern.slice(wildcardIndex + 1);\n if (!specifier.startsWith(prefix) || !specifier.endsWith(suffix)) {\n continue;\n }\n\n const matched = specifier.slice(prefix.length, specifier.length - suffix.length);\n for (const target of targets) {\n const resolvedTarget = target.replace('*', matched);\n const candidate = tryResolveBase(path.resolve(baseUrl, resolvedTarget));\n if (candidate) return candidate;\n }\n }\n\n return undefined;\n}\n\n/**\n * Resolves a relative import specifier to an absolute file path.\n *\n * Only handles relative imports (starting with `.` or `..`).\n * Returns undefined for package/bare imports or if no file is found.\n */\nexport function resolveImport(\n specifier: string,\n fromFile: string,\n rootDir?: string,\n): string | undefined {\n if (specifier.startsWith('.')) {\n const base = path.resolve(path.dirname(fromFile), specifier);\n return tryResolveBase(base);\n }\n\n if (rootDir) {\n return resolveAliasImport(specifier, rootDir);\n }\n\n return undefined;\n}\n\n/**\n * Derives a route identifier from the entry point file path.\n *\n * Strips the rootDir prefix and `src/pages/` prefix, then removes the extension.\n * Falls back to stripping just the rootDir prefix if `src/pages/` is not present.\n */\nexport function deriveRouteId(entryPoint: string, rootDir: string): string {\n let rel = path.relative(rootDir, entryPoint);\n\n const pagesPrefix = path.join('src', 'pages') + path.sep;\n if (rel.startsWith(pagesPrefix)) {\n rel = rel.slice(pagesPrefix.length);\n }\n\n // Strip extension\n const ext = path.extname(rel);\n if (ext) {\n rel = rel.slice(0, -ext.length);\n }\n\n return rel;\n}\n\n/**\n * Discovers namespace names from locale JSON files.\n *\n * Reads `{localesDir}/{defaultLocale}/` and returns sorted `.json`\n * filenames without their extension.\n */\nexport function discoverNamespaces(\n localesDir: string,\n defaultLocale: string,\n): string[] {\n const dir = path.join(localesDir, defaultLocale);\n\n try {\n const entries = fs.readdirSync(dir);\n return entries\n .filter((f) => f.endsWith('.json'))\n .map((f) => f.slice(0, -5))\n .sort();\n } catch {\n return [];\n }\n}\n\n/**\n * Walks a single route's import graph starting from the entry point.\n *\n * Reads each file, extracts translation keys and import specifiers,\n * then recursively follows relative imports. Handles circular imports\n * via a visited set and deduplicates keys by key string.\n */\nexport function walkRoute(\n entryPoint: string,\n options: {\n rootDir: string;\n extractionScope: 'global' | 'scoped';\n hookSources?: string[];\n /** Forwarded to `extractKeys`. Pre-v0.7 the build path silently dropped this. */\n keyFields?: string[];\n cache?: ExtractionCache;\n },\n): RouteAnalysis {\n const visited = new Set<string>();\n const allKeys: ExtractedKey[] = [];\n const allScopes: string[] = [];\n const allFiles: string[] = [];\n const seenKeys = new Set<string>();\n let entryScopes: string[] = [];\n let entryVisited = false;\n\n function applyFileResult(\n keys: readonly ExtractedKey[],\n scopes: readonly string[],\n imports: readonly string[],\n ): void {\n for (const key of keys) {\n if (!seenKeys.has(key.key)) {\n seenKeys.add(key.key);\n allKeys.push(key);\n }\n }\n for (const scope of scopes) {\n if (!allScopes.includes(scope)) {\n allScopes.push(scope);\n }\n }\n for (const importedFile of imports) {\n visit(importedFile);\n }\n }\n\n function visit(filePath: string): void {\n const resolved = path.resolve(filePath);\n const isEntry = !entryVisited;\n if (visited.has(resolved)) {\n return;\n }\n visited.add(resolved);\n\n let stat: fs.Stats;\n try {\n stat = fs.statSync(resolved);\n } catch {\n return;\n }\n\n allFiles.push(resolved);\n\n // Cache fast path: skip AST parse entirely when mtime + size match.\n const cached = options.cache?.get(resolved);\n if (cached && cached.mtime === stat.mtimeMs && cached.size === stat.size) {\n if (isEntry) {\n entryVisited = true;\n entryScopes = [...cached.scopes];\n }\n applyFileResult(cached.keys, cached.scopes, cached.imports);\n return;\n }\n\n let source: string;\n try {\n source = fs.readFileSync(resolved, 'utf-8');\n } catch {\n return;\n }\n\n const result = extractModule.extractKeys(source, {\n scope: options.extractionScope,\n filePath: resolved,\n hookSources: options.hookSources,\n keyFields: options.keyFields,\n });\n if (isEntry) {\n entryVisited = true;\n entryScopes = [...result.scopes];\n }\n\n // Resolve imports now so cached entries can be replayed without re-resolution.\n const resolvedImports: string[] = [];\n for (const imp of result.imports) {\n const importPath = resolveImport(imp, resolved, options.rootDir);\n if (importPath) resolvedImports.push(importPath);\n }\n\n options.cache?.set(resolved, {\n mtime: stat.mtimeMs,\n size: stat.size,\n imports: resolvedImports,\n keys: result.keys,\n scopes: result.scopes,\n });\n\n applyFileResult(result.keys, result.scopes, resolvedImports);\n }\n\n visit(entryPoint);\n\n return {\n entryPoint: path.resolve(entryPoint),\n routeId: deriveRouteId(path.resolve(entryPoint), options.rootDir),\n scopes: allScopes,\n entryScopes,\n keys: allKeys,\n files: allFiles,\n };\n}\n\n/**\n * Walks the entire project: finds page entry points, analyzes each route,\n * discovers namespaces, and computes shared namespace candidates.\n */\nexport function walkAll(options: WalkerOptions): ProjectAnalysis {\n const rootDir = options.rootDir ?? process.cwd();\n const extractionScope = options.extractionScope ?? 'global';\n\n // Find page entry points\n const entryFiles = globSync(options.pages, { cwd: rootDir, absolute: true });\n\n // Walk each route\n const routes = entryFiles.map((entry) =>\n walkRoute(entry, {\n rootDir,\n extractionScope,\n hookSources: options.hookSources,\n keyFields: options.keyFields,\n cache: options.cache,\n }),\n );\n\n // Discover namespaces\n const localesPath = path.isAbsolute(options.localesDir)\n ? options.localesDir\n : path.join(rootDir, options.localesDir);\n const availableNamespaces = discoverNamespaces(\n localesPath,\n options.defaultLocale,\n );\n\n // Deduplicate all keys across routes\n const allKeysMap = new Map<string, ExtractedKey>();\n for (const route of routes) {\n for (const key of route.keys) {\n if (!allKeysMap.has(key.key)) {\n allKeysMap.set(key.key, key);\n }\n }\n }\n const allKeys = Array.from(allKeysMap.values());\n\n // Compute shared namespaces (used by >50% of routes)\n const sharedNamespaces: string[] = [];\n if (routes.length > 0) {\n const nsCounts = new Map<string, number>();\n for (const route of routes) {\n const routeNamespaces = new Set<string>();\n for (const key of route.keys) {\n const ns = key.key.split('.')[0];\n if (ns) {\n routeNamespaces.add(ns);\n }\n }\n for (const ns of routeNamespaces) {\n nsCounts.set(ns, (nsCounts.get(ns) ?? 0) + 1);\n }\n }\n\n const threshold = routes.length / 2;\n for (const [ns, count] of nsCounts) {\n if (count > threshold) {\n sharedNamespaces.push(ns);\n }\n }\n sharedNamespaces.sort();\n }\n\n return {\n routes,\n availableNamespaces,\n allKeys,\n sharedNamespaces,\n };\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport crypto from 'node:crypto';\nimport type { ExtractedKey } from './types';\n\n/**\n * Cache file schema version. Bump when:\n * - the {@link CacheFileEntry} shape changes, OR\n * - we ship a fix that downstream artifacts (manifest, per-scope bundles)\n * may have been corrupted by, so we want every existing on-disk cache\n * discarded as part of the upgrade.\n *\n * v2 (0.7.0): forced rotation following a report of stale downstream\n * artifacts surviving incremental rebuilds. Bumping to v2 means the next\n * load discards every v1 file unconditionally — equivalent to a one-time\n * `rm -rf .i18n/cache` on upgrade, no manual step required.\n */\nexport const CACHE_SCHEMA_VERSION = 2;\n\n/** Relative filename inside the configured cache directory. Encodes the schema version so a v2 build never accidentally loads a v1 file. */\nexport const CACHE_FILE_NAME = 'extraction-v2.json';\n\n/**\n * Per-file extraction snapshot stored in the cache.\n *\n * The fields mirror the walker's per-file analysis output. On subsequent\n * runs, the walker compares `mtime` + `size` from `fs.stat` against the\n * cached entry; if both match, the entry is trusted and the AST parse is\n * skipped entirely.\n */\nexport interface CacheFileEntry {\n /** Modification time in milliseconds, from `fs.statSync(path).mtimeMs`. */\n mtime: number;\n /** File size in bytes — a second signal beyond mtime for filesystems with 1s mtime resolution. */\n size: number;\n /** Resolved absolute import paths from this file. */\n imports: string[];\n /** Translation keys the extractor found in this file. */\n keys: ExtractedKey[];\n /** Scope strings declared via `useI18n(scope)` in this file. */\n scopes: string[];\n}\n\n/**\n * Header written alongside entries. Any mismatch on load discards the entire\n * cache — the entries can't be trusted when the context that produced them\n * has shifted (new plugin version, reshaped config, different Node).\n */\ninterface CacheHeader {\n schemaVersion: number;\n pluginVersion: string;\n configHash: string;\n nodeVersion: string;\n createdAt: string;\n}\n\ninterface CacheFile extends CacheHeader {\n files: Record<string, CacheFileEntry>;\n}\n\n/**\n * Options for {@link createExtractionCache}.\n */\nexport interface ExtractionCacheOptions {\n /** Absolute path to the cache directory. Created on persist if missing. */\n dir: string;\n /** Plugin version (normally from `package.json`). */\n pluginVersion: string;\n /** Config hash — any change invalidates the whole cache. See {@link computeConfigHash}. */\n configHash: string;\n /**\n * Override the detected Node version. Test-only; production callers let it\n * default to `process.version`.\n */\n currentNodeVersion?: string;\n /** When true, emits cache hits/misses/invalidations to stderr. */\n debug?: boolean;\n}\n\n/**\n * In-memory cache of per-file extraction results, backed by a JSON snapshot\n * on disk.\n *\n * Initialization loads the snapshot (if present and valid). The cache is\n * mutated in-memory via {@link set}/{@link invalidate}/{@link clear} and\n * flushed to disk via {@link persistToDisk}. All disk I/O is synchronous —\n * reads happen once at startup, writes happen once at shutdown (or debounced\n * during HMR), so `await` overhead isn't warranted.\n */\nexport interface ExtractionCache {\n /** Look up an entry by absolute file path. */\n get(filePath: string): CacheFileEntry | undefined;\n /** Insert or replace an entry for this file. */\n set(filePath: string, entry: CacheFileEntry): void;\n /** Remove a single entry. */\n invalidate(filePath: string): void;\n /** Drop every entry in memory. Does not touch disk until {@link persistToDisk}. */\n clear(): void;\n /** Number of cached entries. */\n size(): number;\n /**\n * Persist the in-memory entries to disk as a single atomic write\n * (`writeFileSync` to a temp path, then `rename`). Creates the cache\n * directory if it doesn't exist yet.\n */\n persistToDisk(): void;\n}\n\n/**\n * Create a cache instance, eagerly loading from disk if a valid snapshot\n * exists at `{dir}/{CACHE_FILE_NAME}`. A missing, unreadable, or\n * header-mismatched snapshot yields an empty cache — the caller's next walk\n * populates it fresh.\n */\nexport function createExtractionCache(options: ExtractionCacheOptions): ExtractionCache {\n const nodeVersion = options.currentNodeVersion ?? process.version;\n const filePath = path.join(options.dir, CACHE_FILE_NAME);\n const entries = loadEntriesOrEmpty(filePath, {\n pluginVersion: options.pluginVersion,\n configHash: options.configHash,\n nodeVersion,\n debug: options.debug,\n });\n\n /**\n * Structured-format debug logger. Every line carries the PID and an\n * ISO-8601 timestamp so a future investigation can correlate cache\n * activity across processes (e.g. `vite dev` running while\n * `npm run build` fires) without guessing.\n *\n * Enabled by `VITE_I18N_CACHE_DEBUG=1` (resolved upstream into\n * `options.debug`). Off by default — production builds are silent.\n */\n function debugLog(action: string, detail: Record<string, unknown> = {}): void {\n if (!options.debug) return;\n const stamp = new Date().toISOString();\n const fields = Object.entries(detail)\n .map(([k, v]) => `${k}=${typeof v === 'string' ? v : JSON.stringify(v)}`)\n .join(' ');\n console.warn(`[i18n-cache pid=${process.pid} ${stamp}] ${action}${fields ? ' ' + fields : ''}`);\n }\n\n debugLog('init', {\n file: filePath,\n loadedEntries: entries.size,\n pluginVersion: options.pluginVersion,\n configHash: options.configHash.slice(0, 12),\n });\n\n return {\n get(filePath) {\n return entries.get(filePath);\n },\n\n set(filePath, entry) {\n entries.set(filePath, entry);\n },\n\n invalidate(filePath) {\n entries.delete(filePath);\n debugLog('invalidate', { file: filePath });\n },\n\n clear() {\n const before = entries.size;\n entries.clear();\n debugLog('clear', { droppedEntries: before });\n },\n\n size() {\n return entries.size;\n },\n\n persistToDisk() {\n const payload: CacheFile = {\n schemaVersion: CACHE_SCHEMA_VERSION,\n pluginVersion: options.pluginVersion,\n configHash: options.configHash,\n nodeVersion,\n createdAt: new Date().toISOString(),\n files: Object.fromEntries(entries),\n };\n\n try {\n fs.mkdirSync(options.dir, { recursive: true });\n } catch (error) {\n debugLog('persist-failed', { stage: 'mkdir', dir: options.dir, error: (error as Error).message });\n return;\n }\n\n const tmpPath = `${filePath}.${process.pid}.${Date.now()}.tmp`;\n try {\n fs.writeFileSync(tmpPath, JSON.stringify(payload));\n fs.renameSync(tmpPath, filePath);\n // Re-stat after the rename so the logged mtime matches what\n // the next build's `detectStaleness` will see. Useful when a\n // racing process touches the file between rename and stat.\n let mtimeMs: number | null = null;\n try { mtimeMs = fs.statSync(filePath).mtimeMs; } catch { /* swallow */ }\n debugLog('persist', { file: filePath, entries: entries.size, mtimeMs });\n } catch (error) {\n debugLog('persist-failed', { stage: 'write', error: (error as Error).message });\n try { fs.rmSync(tmpPath, { force: true }); } catch { /* swallow */ }\n }\n },\n };\n}\n\n/**\n * Attempt to load + validate a cache file. Returns an empty `Map` on any of:\n * - missing file\n * - corrupt JSON\n * - schema/plugin/config/node-major mismatch\n */\nfunction loadEntriesOrEmpty(\n filePath: string,\n context: { pluginVersion: string; configHash: string; nodeVersion: string; debug?: boolean },\n): Map<string, CacheFileEntry> {\n const empty = new Map<string, CacheFileEntry>();\n\n let raw: string;\n try {\n raw = fs.readFileSync(filePath, 'utf-8');\n } catch {\n return empty;\n }\n\n let parsed: Partial<CacheFile> | null = null;\n try {\n parsed = JSON.parse(raw) as Partial<CacheFile>;\n } catch {\n if (context.debug) {\n console.warn(`[i18n-cache pid=${process.pid} ${new Date().toISOString()}] load-rejected reason=corrupt-json file=${filePath}`);\n }\n return empty;\n }\n\n function reject(reason: string): Map<string, CacheFileEntry> {\n if (context.debug) {\n console.warn(`[i18n-cache pid=${process.pid} ${new Date().toISOString()}] load-rejected reason=${reason} file=${filePath}`);\n }\n return empty;\n }\n\n if (!parsed || typeof parsed !== 'object') return reject('not-object');\n if (parsed.schemaVersion !== CACHE_SCHEMA_VERSION) return reject(`schema-version-mismatch (got=${String(parsed.schemaVersion)} want=${CACHE_SCHEMA_VERSION})`);\n if (parsed.pluginVersion !== context.pluginVersion) return reject(`plugin-version-mismatch (got=${String(parsed.pluginVersion)} want=${context.pluginVersion})`);\n if (parsed.configHash !== context.configHash) return reject('config-hash-mismatch');\n\n if (!isCompatibleNodeVersion(parsed.nodeVersion, context.nodeVersion)) return reject(`node-version-mismatch (got=${String(parsed.nodeVersion)} want=${context.nodeVersion})`);\n\n if (!parsed.files || typeof parsed.files !== 'object') return reject('no-files');\n\n const map = new Map<string, CacheFileEntry>();\n for (const [key, value] of Object.entries(parsed.files)) {\n if (value && typeof value === 'object') {\n map.set(key, value as CacheFileEntry);\n }\n }\n return map;\n}\n\n/**\n * Two Node versions are compatible iff their major components match. Minor\n * and patch differences are ignored — AST parser behavior is stable within a\n * major.\n */\nfunction isCompatibleNodeVersion(\n cached: string | undefined,\n current: string,\n): boolean {\n if (!cached) return false;\n return majorOf(cached) === majorOf(current);\n}\n\nfunction majorOf(version: string): string {\n const trimmed = version.startsWith('v') ? version.slice(1) : version;\n const dot = trimmed.indexOf('.');\n return dot === -1 ? trimmed : trimmed.slice(0, dot);\n}\n\n/**\n * Hash the extraction-relevant slice of config into a stable sha256. Any\n * change to a field that affects the walker's output bumps the hash,\n * invalidating the whole cache.\n *\n * Input is JSON-serialized with sorted keys so object-key ordering doesn't\n * perturb the result.\n */\nexport function computeConfigHash(input: unknown): string {\n const stable = stableStringify(input);\n return crypto.createHash('sha256').update(stable).digest('hex');\n}\n\n/**\n * JSON.stringify with deterministic object-key ordering. Arrays keep their\n * order (they're semantically meaningful — page globs have priority).\n */\nfunction stableStringify(value: unknown): string {\n if (value === null || typeof value !== 'object') {\n return JSON.stringify(value);\n }\n if (Array.isArray(value)) {\n return `[${value.map(stableStringify).join(',')}]`;\n }\n const keys = Object.keys(value as Record<string, unknown>).sort();\n const body = keys\n .map((k) => `${JSON.stringify(k)}:${stableStringify((value as Record<string, unknown>)[k])}`)\n .join(',');\n return `{${body}}`;\n}\n","import path from 'node:path';\n\n/**\n * User-facing cache options on `i18nPlugin` / `i18nDevPlugin`.\n *\n * - `true` (or `undefined`) — cache on with defaults\n * - `false` — cache off\n * - object — fine-grained control\n */\nexport type CacheOptionInput = boolean | CacheOptions | undefined;\n\nexport interface CacheOptions {\n /** Master on/off switch. Default: true. */\n enabled?: boolean;\n /**\n * Cache directory, absolute or relative to the project root.\n * Default: `.i18n/cache`.\n */\n dir?: string;\n /**\n * Whether to write the in-memory cache back to disk. Default: true.\n * Set to false for ephemeral environments where on-disk persistence\n * would be wasted work.\n */\n persist?: boolean;\n}\n\n/**\n * Resolved cache settings after applying config, env vars, and sensible\n * defaults. Consumers (walker, dev plugin, build plugin, CLI) read this\n * shape — they don't look at the raw inputs.\n */\nexport interface ResolvedCacheConfig {\n enabled: boolean;\n dir: string;\n persist: boolean;\n clearBeforeStart: boolean;\n debug: boolean;\n}\n\nexport interface ResolveCacheConfigContext {\n rootDir: string;\n /**\n * Environment variables. Defaults to `process.env`. Accepting an explicit\n * env makes the function trivially testable — no `vi.stubEnv` dance.\n */\n env?: NodeJS.ProcessEnv;\n}\n\nconst DEFAULT_DIR = path.join('.i18n', 'cache');\n\n/**\n * Compute effective cache settings.\n *\n * Precedence, highest wins:\n * 1. Env vars (operator override — always win over code)\n * 2. Explicit plugin config\n * 3. Environment defaults (`NODE_ENV=test` disables)\n * 4. Built-in defaults\n *\n * Env vars that matter:\n * - `VITE_I18N_NO_CACHE=1` — force disable\n * - `VITE_I18N_CLEAR_CACHE=1` — keep enabled, wipe dir before start\n * - `VITE_I18N_CACHE_DEBUG=1` — stream cache events to stderr\n */\nexport function resolveCacheConfig(\n input: CacheOptionInput,\n context: ResolveCacheConfigContext,\n): ResolvedCacheConfig {\n const env = context.env ?? process.env;\n const envFlag = (name: string) => {\n const value = env[name];\n return value !== undefined && value !== '' && value !== '0' && value !== 'false';\n };\n\n const explicit: CacheOptions =\n input === undefined\n ? {}\n : typeof input === 'boolean'\n ? { enabled: input }\n : input;\n\n // Decide enablement.\n let enabled: boolean;\n if (envFlag('VITE_I18N_NO_CACHE')) {\n enabled = false;\n } else if (explicit.enabled !== undefined) {\n enabled = explicit.enabled;\n } else if (env.NODE_ENV === 'test') {\n enabled = false;\n } else {\n enabled = true;\n }\n\n // Resolve directory — absolute passes through, relative joins from rootDir.\n const rawDir = explicit.dir ?? DEFAULT_DIR;\n const dir = path.isAbsolute(rawDir) ? rawDir : path.join(context.rootDir, rawDir);\n\n const persist = explicit.persist ?? true;\n const clearBeforeStart = envFlag('VITE_I18N_CLEAR_CACHE');\n const debug = envFlag('VITE_I18N_CACHE_DEBUG');\n\n return { enabled, dir, persist, clearBeforeStart, debug };\n}\n","/**\n * Plugin version string — injected at build time via Vite's `define`. Falls\n * back to a development placeholder during tests and direct imports before\n * the build step runs.\n */\nexport const PLUGIN_VERSION: string =\n typeof __VITE_BUNDLED_I18N_VERSION__ !== 'undefined'\n ? __VITE_BUNDLED_I18N_VERSION__\n : 'dev';\n","import path from 'node:path';\nimport type { DictionaryConfig } from '../core/types';\nimport type { ProjectAnalysis } from './walker-types';\n\n/** Framework-agnostic page-to-scopes index emitted alongside scope bundles. */\nexport interface ScopeMapFile {\n /** Schema version. Bumped when the shape changes in a non-additive way. */\n version: 1;\n /** Default locale — mirrors the build config, useful for SSR preloading. */\n defaultLocale: string;\n /**\n * Per-page entries keyed by whatever {@link PageIdentifierFn} returned.\n * Consumers use this map at runtime inside their router's async resolve\n * hook to kick off scope loads in parallel with component resolution.\n */\n pages: Record<string, ScopeMapPageEntry>;\n}\n\nexport interface ScopeMapPageEntry {\n /** Scopes this route declared via `useI18n(scope)`, deduplicated and stable. */\n scopes: readonly string[];\n /**\n * All dictionary names configured for this app. Dictionaries are app-wide\n * so every page entry lists the same set — this is a convenience for\n * consumers that want a single source of truth for \"what to preload\".\n */\n dictionaries: readonly string[];\n}\n\n/** Maps an absolute page file path to a stable string identifier. */\nexport type PageIdentifierFn = (absolutePath: string) => string;\n\nexport interface BuildScopeMapOptions {\n /** Absolute project root. Used by the default identifier resolver. */\n rootDir: string;\n /** Default locale — echoed into the emitted file. */\n defaultLocale: string;\n /** App-wide dictionary configurations. */\n dictionaries?: Record<string, DictionaryConfig>;\n /**\n * Custom page identifier resolver. When omitted, {@link defaultPageIdentifier}\n * is used, which strips the `src/pages/` prefix and common extensions.\n */\n pageIdentifier?: PageIdentifierFn;\n}\n\nconst COMPOSITE_PAGE_SUFFIXES = [\n '.page.tsx',\n '.page.ts',\n '.page.jsx',\n '.page.js',\n] as const;\n\nconst SINGLE_EXTENSIONS = new Set(['.tsx', '.ts', '.jsx', '.js']);\n\n/**\n * Default identifier resolver.\n *\n * Produces stable, POSIX-separated identifiers suitable for routers that\n * already think in \"page paths\":\n *\n * /projects/app/src/pages/giftcards/show.tsx → \"giftcards/show\"\n * /projects/app/src/pages/products/show.page.tsx → \"products/show\"\n * /projects/app/app/routes/home.tsx → \"app/routes/home\"\n *\n * The `src/pages/` prefix is stripped when present; composite `.page.tsx`\n * / `.page.ts` suffixes collapse with the extension; single-file\n * `.tsx|.ts|.jsx|.js` extensions are dropped. Everything else passes through.\n */\nexport function defaultPageIdentifier(\n absolutePath: string,\n rootDir: string,\n): string {\n let rel = path.relative(rootDir, absolutePath);\n\n const pagesPrefix = path.join('src', 'pages') + path.sep;\n if (rel.startsWith(pagesPrefix)) {\n rel = rel.slice(pagesPrefix.length);\n }\n\n // Strip composite suffixes first (they end in a known extension too).\n let strippedComposite = false;\n for (const suffix of COMPOSITE_PAGE_SUFFIXES) {\n if (rel.endsWith(suffix)) {\n rel = rel.slice(0, -suffix.length);\n strippedComposite = true;\n break;\n }\n }\n if (!strippedComposite) {\n const ext = path.extname(rel);\n if (SINGLE_EXTENSIONS.has(ext)) {\n rel = rel.slice(0, -ext.length);\n }\n }\n\n // POSIX normalization: collapse `\\` on Windows, leave `/` untouched.\n return rel.split(path.sep).join('/').split('\\\\').join('/');\n}\n\nfunction uniqueOrdered(values: Iterable<string>): string[] {\n const seen = new Set<string>();\n const result: string[] = [];\n for (const value of values) {\n if (seen.has(value)) continue;\n seen.add(value);\n result.push(value);\n }\n return result;\n}\n\n/**\n * Build a {@link ScopeMapFile} from a {@link ProjectAnalysis}.\n *\n * Each route contributes one entry keyed by the configured or default page\n * identifier. When two routes resolve to the same identifier (rare — e.g.\n * duplicate entry-point globs), the later entry wins. Duplicates should\n * usually be surfaced by the `stats.json` report separately.\n */\nexport function buildScopeMap(\n analysis: ProjectAnalysis,\n options: BuildScopeMapOptions,\n): ScopeMapFile {\n const identify: PageIdentifierFn =\n options.pageIdentifier ?? ((abs) => defaultPageIdentifier(abs, options.rootDir));\n\n const dictionaryNames = options.dictionaries\n ? Object.keys(options.dictionaries)\n : [];\n\n const pages: Record<string, ScopeMapPageEntry> = {};\n for (const route of analysis.routes) {\n const id = identify(route.entryPoint);\n pages[id] = {\n scopes: uniqueOrdered(route.scopes),\n dictionaries: dictionaryNames,\n };\n }\n\n return {\n version: 1,\n defaultLocale: options.defaultLocale,\n pages,\n };\n}\n","import type { DictionaryConfig } from '../core/types';\nimport type { ExtractedKey } from './types';\nimport type { ProjectAnalysis, RouteAnalysis } from './walker-types';\nimport { resolveDictionaryOwnership } from './dictionary-ownership';\nimport { inferScopeNamespace } from './scope-bundles';\n\nexport interface ApplyDynamicKeysOptions {\n /** The declared dynamic keys from `bundling.dynamicKeys`. */\n dynamicKeys: readonly string[];\n /** Dictionary config — used to skip keys already claimed by a dictionary. */\n dictionaries?: Record<string, DictionaryConfig>;\n /**\n * Whether `bundling.crossNamespacePacking` is on. When `true`, a dynamic\n * key is also injected into any route that references another key in\n * the same namespace (so the route's extras list picks it up).\n */\n crossNamespacePacking?: boolean;\n}\n\nexport interface ApplyDynamicKeysReport {\n /**\n * Dynamic keys whose namespace isn't covered by any route and isn't\n * claimed by a dictionary. These keys ship nowhere — almost always a\n * misconfiguration. The plugin emits a warning per orphan.\n */\n orphans: string[];\n}\n\n/**\n * Inject declared dynamic keys into the matching routes' extracted sets.\n *\n * For each dynamic key `k` with namespace `ns = k.split('.')[0]`:\n *\n * 1. If any configured dictionary claims `k` → skip (dictionary already\n * guarantees global availability; inlining would duplicate it).\n * 2. For each route whose scope's primary namespace matches `ns`\n * (`inferScopeNamespace(scope) === ns`), add `k` to `route.keys`.\n * 3. When cross-namespace packing is enabled, also add `k` to any route\n * that already references another key in `ns` (so the route's extras\n * bucket picks it up via the normal extractor pipeline).\n * 4. If `k` went into zero routes AND isn't dictionary-owned, report it\n * as an orphan.\n *\n * Mutates the supplied `analysis` in place. Returns a report for the\n * caller to surface orphans via its logger.\n */\nexport function applyDynamicKeys(\n analysis: ProjectAnalysis,\n options: ApplyDynamicKeysOptions,\n): ApplyDynamicKeysReport {\n if (options.dynamicKeys.length === 0) {\n return { orphans: [] };\n }\n\n // Pre-compute dictionary ownership against the full available-key space:\n // we need to know if `k` would be claimed even when no static `t(k)` call\n // exists. Use every route's extracted keys plus the dynamic keys themselves.\n const availableKeys = new Set<string>();\n for (const route of analysis.routes) {\n for (const key of route.keys) {\n if (!key.dynamic) availableKeys.add(key.key);\n }\n }\n for (const k of options.dynamicKeys) availableKeys.add(k);\n\n const ownership = resolveDictionaryOwnership(availableKeys, options.dictionaries);\n\n // Build a per-namespace index of routes for the two inclusion rules.\n // A route enters `scopedInNamespace` when its scope's primary namespace\n // equals the dynamic key's namespace; `hasKeyInNamespace` when cross-ns\n // packing is on and the route references any other key in that namespace.\n const byPrimaryNamespace = new Map<string, RouteAnalysis[]>();\n const byReferencedNamespace = new Map<string, RouteAnalysis[]>();\n\n for (const route of analysis.routes) {\n const primaryNamespaces = new Set<string>();\n for (const scope of route.scopes) {\n primaryNamespaces.add(inferScopeNamespace(scope));\n }\n for (const ns of primaryNamespaces) {\n let list = byPrimaryNamespace.get(ns);\n if (!list) { list = []; byPrimaryNamespace.set(ns, list); }\n list.push(route);\n }\n\n if (options.crossNamespacePacking) {\n const referenced = new Set<string>();\n for (const key of route.keys) {\n const dot = key.key.indexOf('.');\n if (dot === -1) continue;\n referenced.add(key.key.slice(0, dot));\n }\n for (const ns of referenced) {\n if (primaryNamespaces.has(ns)) continue; // already covered\n let list = byReferencedNamespace.get(ns);\n if (!list) { list = []; byReferencedNamespace.set(ns, list); }\n list.push(route);\n }\n }\n }\n\n const orphans: string[] = [];\n for (const key of options.dynamicKeys) {\n const dot = key.indexOf('.');\n if (dot === -1) {\n // A bare key without a namespace can't belong to a scope; treat as orphan.\n if (!ownership.keyOwner.has(key)) orphans.push(key);\n continue;\n }\n const ns = key.slice(0, dot);\n\n // Rule 1: skip if dictionary-owned.\n if (ownership.keyOwner.has(key)) continue;\n\n const targets = new Set<RouteAnalysis>();\n for (const route of byPrimaryNamespace.get(ns) ?? []) targets.add(route);\n if (options.crossNamespacePacking) {\n for (const route of byReferencedNamespace.get(ns) ?? []) targets.add(route);\n }\n\n if (targets.size === 0) {\n orphans.push(key);\n continue;\n }\n\n const injected: ExtractedKey = {\n key,\n dynamic: false, // already resolved to a concrete key string\n line: 0,\n column: 0,\n };\n\n for (const route of targets) {\n if (route.keys.some((k) => !k.dynamic && k.key === key)) continue;\n route.keys.push(injected);\n }\n }\n\n // Refresh allKeys so downstream readers (reports, type-gen) see the\n // injected keys too.\n const allKeysMap = new Map<string, ExtractedKey>();\n for (const route of analysis.routes) {\n for (const key of route.keys) {\n if (!allKeysMap.has(key.key)) allKeysMap.set(key.key, key);\n }\n }\n analysis.allKeys = [...allKeysMap.values()];\n\n return { orphans };\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport type { ProjectAnalysis } from './walker-types';\nimport type { DictionaryConfig } from '../core/types';\nimport { resolveDictionaryOwnership } from './dictionary-ownership';\nimport { buildScopePlans } from './scope-bundles';\n\n/**\n * Options for the module compiler.\n */\nexport interface CompilerOptions {\n /** Absolute path to the locales directory. */\n localesDir: string;\n /** List of locale codes to compile. */\n locales: string[];\n /** Default locale code used for fallback resolution. */\n defaultLocale: string;\n /** Output directory for compiled modules. */\n outDir: string;\n /** Optional dictionary configurations. */\n dictionaries?: Record<string, DictionaryConfig>;\n /**\n * Inline cross-namespace keys (tree-shaken) into each scope module.\n * See `I18nSharedConfig.bundling.crossNamespacePacking`.\n *\n * @default false\n */\n crossNamespacePacking?: boolean;\n}\n\n/**\n * Escapes backslashes and single quotes for use in JS string literals.\n */\nfunction escapeValue(value: string): string {\n return value.replace(/\\\\/g, '\\\\\\\\').replace(/'/g, \"\\\\'\");\n}\n\n/**\n * Flattens a nested translation object into a flat Map with fully qualified keys.\n *\n * @param namespace - The namespace prefix (e.g., 'products')\n * @param data - The nested translation object\n * @param prefix - Internal prefix for recursion\n * @returns A Map of fully qualified keys to string values\n */\nexport function flattenNamespace(\n namespace: string,\n data: Record<string, unknown>,\n prefix?: string,\n): Map<string, string> {\n const result = new Map<string, string>();\n const currentPrefix = prefix ? `${prefix}.` : `${namespace}.`;\n\n for (const [key, value] of Object.entries(data)) {\n const fullKey = `${currentPrefix}${key}`;\n if (typeof value === 'string') {\n result.set(fullKey, value);\n } else if (typeof value === 'object' && value !== null) {\n const nested = flattenNamespace(\n namespace,\n value as Record<string, unknown>,\n fullKey,\n );\n for (const [k, v] of nested) {\n result.set(k, v);\n }\n }\n }\n\n return result;\n}\n\n/**\n * Creates a new map with all keys from primary, plus any missing keys filled from fallback.\n */\nexport function preResolveFallbacks(\n primary: Map<string, string>,\n fallback: Map<string, string>,\n): Map<string, string> {\n const result = new Map(primary);\n for (const [key, value] of fallback) {\n if (!result.has(key)) {\n result.set(key, value);\n }\n }\n return result;\n}\n\n/**\n * Generates a JavaScript module exporting a flat Map of translation entries.\n */\nexport function generateCompiledModule(entries: Map<string, string>): string {\n const lines: string[] = [];\n lines.push('// Auto-generated by vite-bundled-i18n. Do not edit.');\n lines.push('const m = new Map([');\n for (const [key, value] of entries) {\n lines.push(` ['${escapeValue(key)}','${escapeValue(value)}'],`);\n }\n lines.push(']);');\n lines.push('export default m;');\n lines.push('');\n return lines.join('\\n');\n}\n\n/**\n * Reads namespace JSON files for a locale and returns a combined flattened Map.\n */\nfunction buildLocaleMap(\n localesDir: string,\n locale: string,\n namespaces: string[],\n): Map<string, string> {\n const combined = new Map<string, string>();\n for (const ns of namespaces) {\n const filePath = path.join(localesDir, locale, `${ns}.json`);\n if (!fs.existsSync(filePath)) continue;\n const data = JSON.parse(\n fs.readFileSync(filePath, 'utf-8'),\n ) as Record<string, unknown>;\n const flat = flattenNamespace(ns, data);\n for (const [k, v] of flat) {\n combined.set(k, v);\n }\n }\n return combined;\n}\n\n/**\n * Reads ALL namespace JSON files for a locale directory.\n */\nfunction buildFullLocaleMap(\n localesDir: string,\n locale: string,\n): Map<string, string> {\n const localeDir = path.join(localesDir, locale);\n if (!fs.existsSync(localeDir)) return new Map();\n const files = fs.readdirSync(localeDir).filter((f) => f.endsWith('.json'));\n const namespaces = files.map((f) => f.replace(/\\.json$/, ''));\n return buildLocaleMap(localesDir, locale, namespaces);\n}\n\n/**\n * Filters a map to only include entries whose keys are in the given set.\n */\nfunction filterMap(\n map: Map<string, string>,\n keys: Set<string>,\n): Map<string, string> {\n const result = new Map<string, string>();\n for (const [k, v] of map) {\n if (keys.has(k)) {\n result.set(k, v);\n }\n }\n return result;\n}\n\n/**\n * Generates a dictionary module for a locale by reading all dictionary namespace files,\n * flattening them, and pre-resolving fallbacks against the default locale.\n */\nexport function generateDictionaryModule(\n localesDir: string,\n locale: string,\n defaultLocale: string,\n dictionaries: Record<string, DictionaryConfig>,\n dictionaryName: string,\n): string {\n const fullAvailable = buildFullLocaleMap(localesDir, defaultLocale);\n const ownership = resolveDictionaryOwnership(fullAvailable.keys(), dictionaries);\n const ownedKeys = ownership.dictionaryKeys.get(dictionaryName) ?? new Set<string>();\n\n const localeMap = filterMap(buildFullLocaleMap(localesDir, locale), ownedKeys);\n\n if (locale !== defaultLocale) {\n const defaultMap = filterMap(buildFullLocaleMap(localesDir, defaultLocale), ownedKeys);\n const resolved = preResolveFallbacks(localeMap, defaultMap);\n return generateCompiledModule(resolved);\n }\n\n return generateCompiledModule(localeMap);\n}\n\n/**\n * Generates a manifest module with dynamic import mappings for routes and dictionaries.\n */\nexport function generateManifest(\n scopeIds: string[],\n locales: string[],\n dictionaryNames: string[],\n): string {\n const lines: string[] = [];\n lines.push('// Auto-generated by vite-bundled-i18n. Do not edit.');\n lines.push('export const scopes = {');\n for (const scopeId of scopeIds) {\n lines.push(` '${escapeValue(scopeId)}': {`);\n for (const locale of locales) {\n lines.push(\n ` '${escapeValue(locale)}': () => import('./${locale}/${scopeId}.js'),`,\n );\n }\n lines.push(' },');\n }\n lines.push('};');\n lines.push('');\n\n lines.push('export const routes = scopes;');\n lines.push('');\n\n if (dictionaryNames.length > 0) {\n lines.push('export const dictionaries = {');\n for (const name of dictionaryNames) {\n lines.push(` '${escapeValue(name)}': {`);\n for (const locale of locales) {\n lines.push(\n ` '${escapeValue(locale)}': () => import('./${locale}/_dict/${name}.js'),`,\n );\n }\n lines.push(' },');\n }\n lines.push('};');\n lines.push('');\n }\n\n return lines.join('\\n');\n}\n\n/**\n * Orchestrates the full compilation of pre-compiled i18n modules.\n */\nexport function compileAll(\n analysis: ProjectAnalysis,\n options: CompilerOptions,\n): void {\n const { localesDir, locales, defaultLocale, outDir, dictionaries, crossNamespacePacking } = options;\n\n fs.mkdirSync(outDir, { recursive: true });\n\n // Build the default locale full map for fallback resolution\n const defaultFullMap = buildFullLocaleMap(localesDir, defaultLocale);\n\n // Determine which namespaces the routes reference\n const ownership = resolveDictionaryOwnership(defaultFullMap.keys(), dictionaries);\n\n // For each scope + locale: collect used keys, filter, resolve fallbacks, write\n const scopePlans = buildScopePlans(analysis, defaultFullMap.keys(), { crossNamespacePacking });\n for (const plan of scopePlans) {\n const usedKeys = new Set(\n [...plan.keys].filter((key) => !ownership.keyOwner.has(key)),\n );\n if (crossNamespacePacking) {\n for (const extraKeys of plan.extras.values()) {\n for (const key of extraKeys) {\n if (ownership.keyOwner.has(key)) continue;\n usedKeys.add(key);\n }\n }\n }\n for (const locale of locales) {\n const localeDir = path.join(outDir, locale);\n fs.mkdirSync(localeDir, { recursive: true });\n\n const localeMap = buildFullLocaleMap(localesDir, locale);\n const filtered = filterMap(localeMap, usedKeys);\n\n const resolved =\n locale !== defaultLocale\n ? preResolveFallbacks(filtered, filterMap(defaultFullMap, usedKeys))\n : filtered;\n\n const moduleSource = generateCompiledModule(resolved);\n fs.writeFileSync(\n path.join(localeDir, `${plan.scope}.js`),\n moduleSource,\n );\n }\n }\n\n // For each locale: generate per-dictionary modules\n if (dictionaries && Object.keys(dictionaries).length > 0) {\n for (const locale of locales) {\n const localeDir = path.join(outDir, locale);\n const dictDir = path.join(localeDir, '_dict');\n fs.mkdirSync(dictDir, { recursive: true });\n\n for (const dictionaryName of Object.keys(dictionaries)) {\n const dictModule = generateDictionaryModule(\n localesDir,\n locale,\n defaultLocale,\n dictionaries,\n dictionaryName,\n );\n fs.writeFileSync(path.join(dictDir, `${dictionaryName}.js`), dictModule);\n }\n }\n }\n\n // Generate manifest\n const scopeIds = scopePlans.map((plan) => plan.scope);\n const dictionaryNames = dictionaries ? Object.keys(dictionaries) : [];\n const manifestSource = generateManifest(scopeIds, locales, dictionaryNames);\n fs.writeFileSync(path.join(outDir, 'manifest.js'), manifestSource);\n}\n","import path from 'node:path';\nimport type { ProjectAnalysis } from './walker-types';\n\n/**\n * Report entries emitted by {@link checkScopeRegistration}. One entry per\n * page file that has no `useI18n('<literal>')` call in its entry source.\n */\nexport interface ScopeRegistrationViolation {\n /** Absolute path to the page file missing a scope declaration. */\n entryPoint: string;\n /** A short relative path for display, if a rootDir was supplied. */\n relativePath: string;\n}\n\n/**\n * Options controlling the severity + output format of a scope-registration\n * audit. The mode is resolved by the plugin from\n * `bundling.strictScopeRegistration` before calling this function.\n */\nexport interface CheckScopeRegistrationOptions {\n /** Absolute project root, used to derive short display paths. */\n rootDir: string;\n /** Severity mode. `'off'` short-circuits; the function returns empty. */\n mode: 'off' | 'warn' | 'error';\n}\n\nexport interface ScopeRegistrationReport {\n violations: ScopeRegistrationViolation[];\n /** Pre-formatted message lines ready to hand to a logger. */\n messages: string[];\n}\n\n/**\n * Audit page routes for missing scope declarations.\n *\n * A route is **compliant** when *any* file in its import graph — the entry\n * or any transitive child — declares at least one `useI18n('<literal>')`\n * scope. Both patterns are valid:\n *\n * - Entry declares scope: `useI18n('products.show')` at the top of the page.\n * - Entry composes, children declare scopes: page renders\n * `<Sidebar />` / `<MainContent />`; each child component calls\n * `useI18n('its.own.scope')`. Children that don't need to trigger a load\n * can just call `useI18n()` with no args and read the already-loaded cache.\n *\n * The audit fires only when the aggregated scopes across a route are empty —\n * at that point `PAGE_SCOPE_MAP[pageId]` would be `[]` and consumers using\n * the router-integration pattern couldn't preload anything.\n *\n * Caller decides what to do with the result:\n * - `'warn'` — iterate `messages` and pass each to `logger.warn`\n * - `'error'` — if `violations.length > 0`, throw an aggregated error\n * - `'off'` — returns empty synchronously, no work\n */\nexport function checkScopeRegistration(\n analysis: ProjectAnalysis,\n options: CheckScopeRegistrationOptions,\n): ScopeRegistrationReport {\n if (options.mode === 'off') {\n return { violations: [], messages: [] };\n }\n\n const violations: ScopeRegistrationViolation[] = [];\n for (const route of analysis.routes) {\n if (route.scopes.length > 0) continue;\n violations.push({\n entryPoint: route.entryPoint,\n relativePath: path.relative(options.rootDir, route.entryPoint),\n });\n }\n\n const messages = violations.map((v) => formatMessage(v));\n return { violations, messages };\n}\n\nfunction formatMessage(violation: ScopeRegistrationViolation): string {\n return [\n `[vite-bundled-i18n] ${violation.relativePath} registers no scope.`,\n ` Neither the page nor any of its imported components calls \\`useI18n('<scope>')\\`,`,\n ` so this route ships zero translations. Options:`,\n ` - Add \\`useI18n('<scope.id>')\\` at the top of the page.`,\n ` - Add it to any child component that mounts under this page.`,\n ` - Exclude the file via a negative glob if it's not actually a page.`,\n ].join('\\n');\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport type { ProjectAnalysis } from './walker-types';\nimport type { DictionaryConfig } from '../core/types';\nimport {\n checkScopeRegistration,\n type ScopeRegistrationViolation,\n} from './scope-registration';\nimport { flattenLocaleKeys, generateMissing, generateUnused } from './reports';\nimport {\n resolveDictionaryOwnership,\n keyMatchesPattern,\n} from './dictionary-ownership';\n\n/**\n * Severity for an individual extraction check. Mirrors the existing\n * `strictScopeRegistration` shape so callers learn one vocabulary.\n */\nexport type StrictCheckMode = 'off' | 'warn' | 'error';\n\n/**\n * Per-check severity overrides. Any field left undefined inherits from\n * the top-level `mode`. Setting a check to `'off'` disables only that\n * check; the rest still run.\n */\nexport interface StrictExtractionChecks {\n /** Page registers no `useI18n('<scope>')`. Replaces standalone `strictScopeRegistration`. */\n scopeRegistration?: StrictCheckMode;\n /** Static `t('foo.bar')` references a key absent from every locale namespace. */\n missingKeys?: StrictCheckMode;\n /** Locale key never referenced by any route — bloats bundles + indicates dead translations. */\n unusedKeys?: StrictCheckMode;\n /** `bundling.dynamicKeys` entry that matches no route AND no dictionary. */\n orphanDynamic?: StrictCheckMode;\n}\n\n/**\n * Resolved (non-undefined) version of {@link StrictExtractionChecks} —\n * what runs at audit time after defaulting via `mode`.\n */\nexport interface ResolvedStrictExtractionChecks {\n scopeRegistration: StrictCheckMode;\n missingKeys: StrictCheckMode;\n unusedKeys: StrictCheckMode;\n orphanDynamic: StrictCheckMode;\n}\n\n/**\n * The user-facing config shape. Accepts a shorthand string OR an\n * options object. The shorthand is equivalent to setting `mode` to\n * the same value with every check defaulting to it.\n *\n * Backward compat: when the legacy `strictScopeRegistration` is set\n * but no `strictExtraction` is, the legacy value is used as the\n * `scopeRegistration` mode. Other checks default to `'off'`.\n */\nexport type StrictExtractionConfig =\n | StrictCheckMode\n | (StrictExtractionChecks & {\n /** Default severity applied to any check left undefined. Default: `'warn'`. */\n mode?: StrictCheckMode;\n /** Where to write the structured JSON report. Default: `<generatedOutDir>/strict-extraction-report.json`. */\n reportPath?: string;\n });\n\n/**\n * Per-check finding. The shape is uniform so a CI consumer can iterate\n * `findings` regardless of which check produced the entry.\n */\nexport interface StrictExtractionFinding {\n check: keyof ResolvedStrictExtractionChecks;\n severity: 'warn' | 'error';\n /** Short message line, suitable for a logger. */\n message: string;\n /** Free-form payload (file paths, key names, etc.) — useful for CI tooling. */\n details?: Record<string, unknown>;\n}\n\n/**\n * Aggregate output of {@link runStrictExtraction}. Always returned; the\n * caller decides what to do based on `severity` per finding (or the\n * top-level `hasErrors`).\n */\nexport interface StrictExtractionReport {\n resolvedChecks: ResolvedStrictExtractionChecks;\n findings: StrictExtractionFinding[];\n /** True if any finding has `severity: 'error'`. Caller should fail the build. */\n hasErrors: boolean;\n /** Counts per check, for at-a-glance summaries. */\n summary: Record<keyof ResolvedStrictExtractionChecks, { warn: number; error: number }>;\n}\n\n/**\n * Inputs to the audit. Wraps the bits needed by every check so the\n * caller doesn't have to thread `analysis` + `localesDir` + dictionaries\n * into each check individually.\n */\nexport interface RunStrictExtractionInput {\n analysis: ProjectAnalysis;\n rootDir: string;\n localesDir: string;\n defaultLocale: string;\n dictionaries?: Record<string, DictionaryConfig>;\n /** From `bundling.dynamicKeys`. Used by the orphan-dynamic check. */\n dynamicKeys?: readonly string[];\n /** User config (or its legacy equivalent). */\n config: StrictExtractionConfig | undefined;\n /** Used to back-fill `scopeRegistration` when only the legacy field is set. */\n legacyStrictScopeRegistration?: StrictCheckMode;\n /** Where to write the structured report. Defaults to `<generatedOutDir>/strict-extraction-report.json`. */\n defaultReportPath: string;\n}\n\n/**\n * Resolve the user's config (any of: undefined, shorthand string, full\n * object) into a uniform `ResolvedStrictExtractionChecks` plus a\n * `reportPath`. Honors backward-compat with `strictScopeRegistration`.\n *\n * Subtle rule: `orphanDynamic` defaults to `'warn'` when the user\n * didn't explicitly opt out. Pre-v0.7 `applyDynamicKeys` always\n * emitted these warnings; making the unified shorthand `'off'`\n * silently kill them would be a surprising regression. Operators who\n * truly want silence pass `{ orphanDynamic: 'off' }` explicitly.\n */\nexport function resolveStrictExtractionConfig(\n config: StrictExtractionConfig | undefined,\n fallbacks: {\n legacyStrictScopeRegistration?: StrictCheckMode;\n defaultReportPath: string;\n },\n): { checks: ResolvedStrictExtractionChecks; reportPath: string } {\n let mode: StrictCheckMode;\n let perCheck: StrictExtractionChecks = {};\n let reportPath = fallbacks.defaultReportPath;\n\n if (typeof config === 'string') {\n mode = config;\n } else if (config && typeof config === 'object') {\n mode = config.mode ?? 'warn';\n perCheck = config;\n if (config.reportPath) reportPath = config.reportPath;\n } else {\n // No new-style config. Fall back to the legacy field for\n // scope-registration only; everything else stays off (except\n // orphanDynamic, kept on for backward parity with applyDynamicKeys).\n return {\n checks: {\n scopeRegistration: fallbacks.legacyStrictScopeRegistration ?? 'warn',\n missingKeys: 'off',\n unusedKeys: 'off',\n orphanDynamic: 'warn',\n },\n reportPath,\n };\n }\n\n // For the explicit-config path, `orphanDynamic` resolves the same as\n // every other check — `mode` is the default, an explicit per-check\n // value overrides. The one nuance: when `mode` is `'off'` AND the\n // user did NOT explicitly set `orphanDynamic`, keep it at `'warn'`\n // so silencing the unified audit doesn't silently kill warnings the\n // user was previously seeing from `applyDynamicKeys`. This is the\n // single explicit deviation from \"mode applies uniformly.\"\n const orphanDefault: StrictCheckMode = mode === 'off' ? 'warn' : mode;\n\n return {\n checks: {\n scopeRegistration: perCheck.scopeRegistration ?? mode,\n missingKeys: perCheck.missingKeys ?? mode,\n unusedKeys: perCheck.unusedKeys ?? mode,\n orphanDynamic: perCheck.orphanDynamic ?? orphanDefault,\n },\n reportPath,\n };\n}\n\nfunction pushScopeRegistrationFindings(\n violations: ScopeRegistrationViolation[],\n severity: 'warn' | 'error',\n out: StrictExtractionFinding[],\n): void {\n for (const v of violations) {\n out.push({\n check: 'scopeRegistration',\n severity,\n message: `${v.relativePath} registers no scope (no useI18n('<scope>') in entry or imports).`,\n details: { entryPoint: v.entryPoint, relativePath: v.relativePath },\n });\n }\n}\n\nfunction pushMissingKeyFindings(\n analysis: ProjectAnalysis,\n available: Map<string, string[]>,\n defaultLocale: string,\n severity: 'warn' | 'error',\n out: StrictExtractionFinding[],\n): void {\n const missing = generateMissing(analysis, available);\n for (const entry of missing.keys) {\n out.push({\n check: 'missingKeys',\n severity,\n message: `Translation key \"${entry.key}\" used in code but absent from ${defaultLocale} locale files.`,\n details: { key: entry.key, line: entry.line, files: entry.usedIn },\n });\n }\n}\n\nfunction pushUnusedKeyFindings(\n analysis: ProjectAnalysis,\n available: Map<string, string[]>,\n severity: 'warn' | 'error',\n out: StrictExtractionFinding[],\n): void {\n const unused = generateUnused(analysis, available);\n for (const entry of unused.keys) {\n out.push({\n check: 'unusedKeys',\n severity,\n message: `Locale key \"${entry.key}\" is defined but never referenced by any route.`,\n details: { key: entry.key, namespace: entry.namespace },\n });\n }\n}\n\nfunction pushOrphanDynamicFindings(\n analysis: ProjectAnalysis,\n dynamicKeys: readonly string[] | undefined,\n dictionaries: Record<string, DictionaryConfig> | undefined,\n severity: 'warn' | 'error',\n out: StrictExtractionFinding[],\n): void {\n if (!dynamicKeys || dynamicKeys.length === 0) return;\n\n // A dynamic key is an \"orphan\" when its namespace matches no route's\n // primary scope namespace AND it isn't owned by a dictionary. Same\n // semantics as `applyDynamicKeys`'s orphan check, just lifted into\n // the unified report.\n const routeNamespaces = new Set<string>();\n for (const route of analysis.routes) {\n for (const scope of route.scopes) {\n const ns = scope.split('.')[0];\n if (ns) routeNamespaces.add(ns);\n }\n }\n\n const ownership = resolveDictionaryOwnership(new Set(dynamicKeys), dictionaries);\n\n for (const key of dynamicKeys) {\n const ns = key.split('.')[0];\n if (!ns) continue;\n if (routeNamespaces.has(ns)) continue;\n if (ownership.keyOwner.has(key)) continue;\n // Also tolerate keys that match any dict pattern even if not in availableKeys yet.\n let inDict = false;\n for (const rule of ownership.rules) {\n if (rule.include.some((pat) => keyMatchesPattern(key, pat))) {\n inDict = true;\n break;\n }\n }\n if (inDict) continue;\n\n out.push({\n check: 'orphanDynamic',\n severity,\n message: `dynamicKeys entry \"${key}\" matches no route and no dictionary — it won't ship anywhere.`,\n details: { key, namespace: ns },\n });\n }\n}\n\n/**\n * Run every enabled check and return the aggregated report. Pure — no\n * disk side effects (call {@link writeStrictExtractionReport} for that).\n */\nexport function runStrictExtraction(\n input: RunStrictExtractionInput,\n): StrictExtractionReport {\n const { checks } = resolveStrictExtractionConfig(input.config, {\n legacyStrictScopeRegistration: input.legacyStrictScopeRegistration,\n defaultReportPath: input.defaultReportPath,\n });\n\n const findings: StrictExtractionFinding[] = [];\n\n if (checks.scopeRegistration !== 'off') {\n const r = checkScopeRegistration(input.analysis, {\n rootDir: input.rootDir,\n mode: checks.scopeRegistration,\n });\n pushScopeRegistrationFindings(\n r.violations,\n checks.scopeRegistration as 'warn' | 'error',\n findings,\n );\n }\n\n // Both missing/unused checks read the same locale-files map. Hoist\n // the read so we pay the FS+parse cost once even when both checks\n // are enabled — large projects with many namespaces save real time.\n const needsLocaleScan = checks.missingKeys !== 'off' || checks.unusedKeys !== 'off';\n const available = needsLocaleScan\n ? flattenLocaleKeys(input.localesDir, input.defaultLocale)\n : null;\n\n if (checks.missingKeys !== 'off' && available) {\n pushMissingKeyFindings(\n input.analysis,\n available,\n input.defaultLocale,\n checks.missingKeys as 'warn' | 'error',\n findings,\n );\n }\n\n if (checks.unusedKeys !== 'off' && available) {\n pushUnusedKeyFindings(\n input.analysis,\n available,\n checks.unusedKeys as 'warn' | 'error',\n findings,\n );\n }\n\n if (checks.orphanDynamic !== 'off') {\n pushOrphanDynamicFindings(\n input.analysis,\n input.dynamicKeys,\n input.dictionaries,\n checks.orphanDynamic as 'warn' | 'error',\n findings,\n );\n }\n\n // Tally per-check counts for summary display.\n const summary: Record<keyof ResolvedStrictExtractionChecks, { warn: number; error: number }> = {\n scopeRegistration: { warn: 0, error: 0 },\n missingKeys: { warn: 0, error: 0 },\n unusedKeys: { warn: 0, error: 0 },\n orphanDynamic: { warn: 0, error: 0 },\n };\n for (const f of findings) {\n summary[f.check][f.severity]++;\n }\n\n return {\n resolvedChecks: checks,\n findings,\n hasErrors: findings.some((f) => f.severity === 'error'),\n summary,\n };\n}\n\n/**\n * Persist the report to disk as a structured JSON document. CI tooling\n * can parse this without needing to scrape stdout. Atomic write —\n * temp file + rename. Failure is swallowed; the report is observability,\n * never correctness.\n */\nexport function writeStrictExtractionReport(\n reportPath: string,\n report: StrictExtractionReport,\n): void {\n const dir = path.dirname(reportPath);\n try {\n fs.mkdirSync(dir, { recursive: true });\n } catch { return; }\n\n const payload = {\n ...report,\n writtenAt: new Date().toISOString(),\n };\n\n const tmp = `${reportPath}.${process.pid}.${Date.now()}.tmp`;\n try {\n fs.writeFileSync(tmp, JSON.stringify(payload, null, 2));\n fs.renameSync(tmp, reportPath);\n } catch {\n try { fs.rmSync(tmp, { force: true }); } catch { /* swallow */ }\n }\n}\n\n/**\n * Convenience: throw if any finding has severity `'error'`. Used by the\n * build plugin to fail CI when strict mode is set to `'error'`.\n */\nexport function assertNoStrictExtractionErrors(report: StrictExtractionReport): void {\n if (!report.hasErrors) return;\n const lines = report.findings\n .filter((f) => f.severity === 'error')\n .map((f) => ` - [${f.check}] ${f.message}`);\n throw new Error(\n `vite-bundled-i18n: strictExtraction failed with ${lines.length} error(s):\\n\\n${lines.join('\\n')}\\n\\n` +\n `See the structured report for details.`,\n );\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport crypto from 'node:crypto';\nimport type { ProjectAnalysis } from './walker-types';\n\n/**\n * Schema version for `.i18n/build-stamp.json`. Bump when the shape changes.\n *\n * The stamp is an integrity primitive — it records what the previous full\n * build emitted, so the next build can detect when downstream artifacts\n * (manifest, per-scope bundles) might be older than the extraction cache\n * and warn the operator before they ship stale prod assets.\n *\n * The cost is one small JSON file at the end of every build; the value is\n * one clear \"your `.i18n/` is stale, run `npx vite-bundled-i18n clean`\"\n * warning instead of a silent corruption.\n */\nexport const BUILD_STAMP_SCHEMA_VERSION = 1;\n\n/** Filename written under `generatedOutDir` (`.i18n/` by default). */\nexport const BUILD_STAMP_FILE_NAME = 'build-stamp.json';\n\n/**\n * Persisted shape. The fingerprint summarizes the analysis (routes, scopes,\n * keys per route) — when it changes between builds, downstream artifacts\n * MUST be regenerated. The stamp itself doesn't enforce that; it just\n * records the truth so we can verify on the next run.\n *\n * `cacheMtimeAtStampWrite` is the linchpin of the staleness check: it's\n * the mtime of the extraction cache file AT the moment this stamp was\n * written, NOT when the build happened to finish. The next run compares\n * the current cache.mtime against this recorded value, so a build that\n * takes 6 minutes (or a 4-hour dev session followed by a build) doesn't\n * falsely look stale on the next start.\n */\nexport interface BuildStamp {\n schemaVersion: number;\n pluginVersion: string;\n configHash: string;\n /** sha256 of the analysis fingerprint (see {@link computeAnalysisFingerprint}). */\n analysisFingerprint: string;\n /** Number of routes / unique keys for at-a-glance debugging. */\n routeCount: number;\n keyCount: number;\n /**\n * mtime (epoch ms) of the extraction cache file at the moment this\n * stamp was written. `null` when no cache existed at write time\n * (cache disabled). The next staleness check compares\n * `currentCacheStat.mtimeMs > this + grace` to detect \"the cache has\n * been advanced since we last completed a build.\"\n */\n cacheMtimeAtStampWrite: number | null;\n /** When the stamp was written. ISO-8601 UTC. */\n writtenAt: string;\n}\n\n/**\n * Stable hash of the analysis. Fingerprints route ids → scopes + sorted\n * extracted key names (NOT call-site metadata like line/column, which\n * shouldn't gate downstream regeneration).\n *\n * Stable across reorderings — routes, scopes, and keys are sorted before\n * hashing.\n */\nexport function computeAnalysisFingerprint(analysis: ProjectAnalysis): string {\n const routes = [...analysis.routes]\n .map((route) => ({\n id: route.routeId,\n scopes: [...route.scopes].sort(),\n keys: [...new Set(route.keys.map((k) => k.key))].sort(),\n }))\n .sort((a, b) => a.id.localeCompare(b.id));\n\n const sharedNs = [...analysis.sharedNamespaces].sort();\n const availableNs = [...analysis.availableNamespaces].sort();\n\n const payload = JSON.stringify({ routes, sharedNs, availableNs });\n return crypto.createHash('sha256').update(payload).digest('hex');\n}\n\n/**\n * Read the stamp at `dir/build-stamp.json` if present and parseable. Returns\n * `null` for missing/corrupt files — every consumer treats those identically\n * (no point distinguishing).\n */\nexport function readBuildStamp(dir: string): BuildStamp | null {\n const filePath = path.join(dir, BUILD_STAMP_FILE_NAME);\n let raw: string;\n try {\n raw = fs.readFileSync(filePath, 'utf-8');\n } catch {\n return null;\n }\n\n let parsed: Partial<BuildStamp> | null;\n try {\n parsed = JSON.parse(raw) as Partial<BuildStamp>;\n } catch {\n return null;\n }\n\n if (!parsed || typeof parsed !== 'object') return null;\n if (parsed.schemaVersion !== BUILD_STAMP_SCHEMA_VERSION) return null;\n if (typeof parsed.pluginVersion !== 'string') return null;\n if (typeof parsed.configHash !== 'string') return null;\n if (typeof parsed.analysisFingerprint !== 'string') return null;\n\n // `cacheMtimeAtStampWrite` is allowed to be `number | null`. Anything\n // else means the file was hand-edited or the schema drifted — bail.\n const cm = parsed.cacheMtimeAtStampWrite;\n if (cm !== null && typeof cm !== 'number') return null;\n\n return parsed as BuildStamp;\n}\n\n/**\n * Write the stamp atomically (`writeFileSync` to a temp path, then rename).\n * Creates the parent directory if it doesn't exist. All failures are\n * swallowed — the stamp is observability, not correctness, so a failed\n * write must never break the build.\n */\nexport function writeBuildStamp(dir: string, stamp: BuildStamp): void {\n try {\n fs.mkdirSync(dir, { recursive: true });\n } catch {\n return;\n }\n\n const filePath = path.join(dir, BUILD_STAMP_FILE_NAME);\n const tmpPath = `${filePath}.${process.pid}.${Date.now()}.tmp`;\n try {\n fs.writeFileSync(tmpPath, JSON.stringify(stamp, null, 2));\n fs.renameSync(tmpPath, filePath);\n } catch {\n try { fs.rmSync(tmpPath, { force: true }); } catch { /* swallow */ }\n }\n}\n\n/**\n * Inspect on-disk state and decide whether the operator should be warned\n * about likely staleness.\n *\n * Conditions that produce a warning:\n * - extraction cache file exists, but no build stamp at all → previous\n * build never finished, or the stamp was deleted.\n * - build stamp exists but `pluginVersion` differs → upgrade happened\n * without a clean rebuild.\n * - build stamp exists but `configHash` differs → config changed without\n * a clean rebuild (cache itself will invalidate, but the user should\n * know the prior bundle isn't trustworthy).\n * - extraction cache mtime > build stamp mtime by more than `gracePeriodMs`\n * → cache has been advanced (likely by dev mode) without a full build,\n * so any consumer reading prod bundle output is reading stale data.\n *\n * Returns `null` if everything looks fresh.\n */\nexport interface StalenessCheckOptions {\n generatedOutDir: string;\n cacheFilePath: string;\n pluginVersion: string;\n configHash: string;\n /** mtime delta tolerated before flagging the cache as \"newer than stamp\". Default: 5 minutes. */\n gracePeriodMs?: number;\n}\n\nexport interface StalenessReport {\n reason:\n | 'cache-without-stamp'\n | 'plugin-version-changed'\n | 'config-changed'\n | 'cache-newer-than-stamp';\n message: string;\n}\n\nexport function detectStaleness(options: StalenessCheckOptions): StalenessReport | null {\n const { generatedOutDir, cacheFilePath, pluginVersion, configHash } = options;\n const grace = options.gracePeriodMs ?? 5 * 60 * 1000;\n\n let cacheStat: fs.Stats | null;\n try {\n cacheStat = fs.statSync(cacheFilePath);\n } catch {\n cacheStat = null;\n }\n\n const stamp = readBuildStamp(generatedOutDir);\n\n if (cacheStat && !stamp) {\n return {\n reason: 'cache-without-stamp',\n message:\n `vite-bundled-i18n: extraction cache exists at ${cacheFilePath} but no build-stamp at ${path.join(generatedOutDir, BUILD_STAMP_FILE_NAME)}. ` +\n `Previous build may not have completed. If your prod bundles look stale, run: npx vite-bundled-i18n clean && <your-build-cmd>`,\n };\n }\n\n if (!stamp) return null;\n\n if (stamp.pluginVersion !== pluginVersion) {\n return {\n reason: 'plugin-version-changed',\n message:\n `vite-bundled-i18n: build-stamp records previous plugin version ${stamp.pluginVersion}, current is ${pluginVersion}. ` +\n `Downstream artifacts in ${generatedOutDir} may be stale until the next full build completes.`,\n };\n }\n\n if (stamp.configHash !== configHash) {\n return {\n reason: 'config-changed',\n message:\n `vite-bundled-i18n: extraction-relevant config changed since the last build-stamp. ` +\n `If your prod bundles look stale, run: npx vite-bundled-i18n clean && <your-build-cmd>`,\n };\n }\n\n if (cacheStat && stamp.cacheMtimeAtStampWrite !== null) {\n // Compare against the cache mtime the stamp OBSERVED, not the stamp\n // file's own mtime. This is the only correct anchor — a 6-minute\n // build (cache written first, stamp written last) would otherwise\n // look like 6 minutes of staleness on the next run.\n const drift = cacheStat.mtimeMs - stamp.cacheMtimeAtStampWrite;\n if (drift > grace) {\n const summary =\n stamp.routeCount && stamp.keyCount\n ? ` (last build saw ${stamp.routeCount} route(s), ${stamp.keyCount} key(s))`\n : '';\n return {\n reason: 'cache-newer-than-stamp',\n message:\n `vite-bundled-i18n: extraction cache has advanced ${formatDuration(drift)} since the last successful production build${summary}. ` +\n `If you've only been running \\`vite dev\\`, this is expected — the next \\`vite build\\` will reconcile. ` +\n `If you're seeing stale prod bundles, run: npx vite-bundled-i18n clean && <your-build-cmd>.`,\n };\n }\n }\n\n return null;\n}\n\nfunction formatDuration(ms: number): string {\n if (ms < 60_000) return `${Math.round(ms / 1000)}s`;\n if (ms < 3_600_000) return `${Math.round(ms / 60_000)}m`;\n if (ms < 86_400_000) return `${Math.round(ms / 3_600_000)}h`;\n return `${Math.round(ms / 86_400_000)}d`;\n}\n"],"mappings":";;;;;;AAkBA,SAAgB,6BAA6B,MAAkC;AAE7E,QAAO,CAAC,IADU,KAAK,QAAQ,EAAE,EAAE,KAAK,QAAQ,GAAG,IAAI,IAAI,EACtC,GAAI,KAAK,WAAW,EAAE,CAAE;;AAG/C,SAAgB,sBACd,cAC4B;AAC5B,KAAI,CAAC,aAAc,QAAO,EAAE;AAE5B,QAAO,OAAO,QAAQ,aAAa,CAChC,KAAK,CAAC,MAAM,OAAO,WAAW;EAC7B;EACA,SAAS,6BAA6B,KAAK;EAC3C,SAAS,KAAK,WAAW,EAAE;EAC3B,UAAU,KAAK,YAAY;EAC3B,QAAQ,KAAK,UAAU;EACvB;EACD,EAAE,CACF,QAAQ,SAAS,KAAK,QAAQ,SAAS,EAAE,CACzC,MAAM,GAAG,MAAM,EAAE,WAAW,EAAE,YAAY,EAAE,QAAQ,EAAE,MAAM;;AAGjE,SAAgB,kBAAkB,KAAa,SAA0B;AACvE,KAAI,QAAQ,SAAS,IAAI,EAAE;AACzB,MAAI,QAAQ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