@intlayer/babel 8.12.1 → 8.12.2

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.
@@ -14,6 +14,80 @@ const createPruneContext = () => ({
14
14
  /** Canonical intlayer caller names that trigger usage analysis. */
15
15
  const INTLAYER_CALLER_NAMES = ["useIntlayer", "getIntlayer"];
16
16
  /**
17
+ * Default registry of compat namespace callers, covering every first-party
18
+ * `@intlayer/*` adapter package and its underlying i18n library.
19
+ */
20
+ const DEFAULT_COMPAT_CALLERS = [
21
+ {
22
+ callerName: "useTranslation",
23
+ importSources: [
24
+ "react-i18next",
25
+ "@intlayer/react-i18next",
26
+ "next-i18next",
27
+ "@intlayer/next-i18next"
28
+ ],
29
+ namespace: {
30
+ from: "argument",
31
+ index: 0
32
+ },
33
+ keyPrefix: {
34
+ from: "option",
35
+ argumentIndex: 1,
36
+ property: "keyPrefix"
37
+ },
38
+ translationFunction: "destructured-t"
39
+ },
40
+ {
41
+ callerName: "useTranslations",
42
+ importSources: ["next-intl", "@intlayer/next-intl"],
43
+ namespace: {
44
+ from: "argument",
45
+ index: 0
46
+ },
47
+ translationFunction: "return-value"
48
+ },
49
+ {
50
+ callerName: "getTranslations",
51
+ importSources: [
52
+ "next-intl/server",
53
+ "@intlayer/next-intl/server",
54
+ "next-intl",
55
+ "@intlayer/next-intl"
56
+ ],
57
+ namespace: {
58
+ from: "argument",
59
+ index: 0
60
+ },
61
+ translationFunction: "return-value"
62
+ },
63
+ {
64
+ callerName: "getFixedT",
65
+ importSources: ["i18next", "@intlayer/i18next"],
66
+ matchAsMethod: true,
67
+ namespace: {
68
+ from: "argument",
69
+ index: 1
70
+ },
71
+ keyPrefix: {
72
+ from: "argument",
73
+ index: 2
74
+ },
75
+ translationFunction: "return-value"
76
+ },
77
+ {
78
+ callerName: "useI18n",
79
+ importSources: ["vue-i18n", "@intlayer/vue-i18n"],
80
+ namespace: {
81
+ from: "option",
82
+ argumentIndex: 0,
83
+ property: "namespace"
84
+ },
85
+ translationFunction: "destructured-t"
86
+ }
87
+ ];
88
+ /** Default namespace used by compat callers when no namespace argument is given. */
89
+ const DEFAULT_COMPAT_NAMESPACE = "translation";
90
+ /**
17
91
  * Records the usage of a specific dictionary key's fields into `pruneContext`.
18
92
  * Merges with any previously recorded usage for the same key.
19
93
  */
@@ -175,46 +249,232 @@ const analyzeCallExpressionUsage = (babelTypes, pruneContext, callExpressionPath
175
249
  markUntrackedBinding();
176
250
  };
177
251
  /**
252
+ * Reads a fully-static string from an AST node. Returns `undefined` for
253
+ * dynamic values (identifiers, expressions, template literals with
254
+ * interpolations, …).
255
+ */
256
+ const readStaticString = (babelTypes, node) => {
257
+ if (!node) return void 0;
258
+ if (babelTypes.isStringLiteral(node)) return node.value;
259
+ if (babelTypes.isTemplateLiteral(node) && node.expressions.length === 0 && node.quasis.length === 1) return node.quasis[0]?.value.cooked ?? node.quasis[0]?.value.raw;
260
+ };
261
+ /** Returns the first dot-path segment of a key, e.g. `'a.b.c'` → `'a'`. */
262
+ const firstPathSegment = (path) => path.split(".")[0] ?? path;
263
+ /**
264
+ * Reads the static first dot-path segment from a `t()` first-argument node.
265
+ *
266
+ * t('counter.label') → 'counter'
267
+ * t(`counter.${x}`) → 'counter' (static prefix before the first dot)
268
+ * t(`${x}.label`) → undefined (dynamic first segment)
269
+ * t(someVariable) → undefined
270
+ */
271
+ const readStaticFirstSegment = (babelTypes, node) => {
272
+ const staticString = readStaticString(babelTypes, node);
273
+ if (staticString !== void 0) return firstPathSegment(staticString);
274
+ if (babelTypes.isTemplateLiteral(node) && node.quasis.length > 0) {
275
+ const firstQuasi = node.quasis[0]?.value.cooked ?? node.quasis[0]?.value.raw;
276
+ if (firstQuasi?.includes(".")) return firstPathSegment(firstQuasi);
277
+ }
278
+ };
279
+ /**
280
+ * Reads a static string property from an object expression. Returns
281
+ * `'__default__'` when the property is absent and `undefined` when present but
282
+ * dynamic.
283
+ */
284
+ const readObjectProperty = (babelTypes, objectExpression, propertyName) => {
285
+ for (const property of objectExpression.properties) {
286
+ if (!babelTypes.isObjectProperty(property)) continue;
287
+ if (!(babelTypes.isIdentifier(property.key) && property.key.name === propertyName || babelTypes.isStringLiteral(property.key) && property.key.value === propertyName)) continue;
288
+ return readStaticString(babelTypes, property.value) ?? void 0;
289
+ }
290
+ return "__default__";
291
+ };
292
+ /**
293
+ * Resolves the namespace (dictionary key) for a compat caller call-site from
294
+ * its `CompatNamespaceSource` configuration. Returns the static key, or
295
+ * `'__default__'` when the configured argument is absent (caller falls back to
296
+ * its default namespace), or `undefined` when the value is present but dynamic.
297
+ */
298
+ const resolveCompatNamespace = (babelTypes, callArguments, source) => {
299
+ if (source.from === "argument") {
300
+ const argument = callArguments[source.index];
301
+ if (argument === void 0) return "__default__";
302
+ const staticString = readStaticString(babelTypes, argument);
303
+ if (staticString !== void 0) return staticString;
304
+ if (babelTypes.isObjectExpression(argument)) return readObjectProperty(babelTypes, argument, "namespace");
305
+ return;
306
+ }
307
+ const optionsArgument = callArguments[source.argumentIndex];
308
+ if (optionsArgument === void 0) return "__default__";
309
+ if (!babelTypes.isObjectExpression(optionsArgument)) return void 0;
310
+ return readObjectProperty(babelTypes, optionsArgument, source.property);
311
+ };
312
+ /**
313
+ * Resolves an optional `keyPrefix` for a compat caller. Returns the static
314
+ * prefix string, `null` when no prefix is configured/present, or `undefined`
315
+ * when a prefix is present but dynamic.
316
+ */
317
+ const resolveCompatKeyPrefix = (babelTypes, callArguments, source) => {
318
+ if (!source) return null;
319
+ const resolved = resolveCompatNamespace(babelTypes, callArguments, source);
320
+ if (resolved === "__default__") return null;
321
+ return resolved;
322
+ };
323
+ /**
324
+ * Climbs past an enclosing `await` expression so that
325
+ * `const t = await getTranslations('ns')` is resolved to its variable
326
+ * declarator the same way the synchronous form is.
327
+ */
328
+ const unwrapAwait = (babelTypes, path) => {
329
+ const parentPath = path.parentPath;
330
+ if (parentPath && babelTypes.isAwaitExpression(parentPath.node)) return parentPath;
331
+ return path;
332
+ };
333
+ /**
334
+ * Analyses how the translation function produced by a compat namespace caller
335
+ * (`useTranslation`, `useTranslations`, `getTranslations`, `getFixedT`,
336
+ * `useI18n`) is consumed, then records the accessed top-level dictionary fields
337
+ * into `pruneContext`.
338
+ *
339
+ * Dictionaries consumed this way are always added to
340
+ * `dictionariesSkippingFieldRename`: the field accesses are string-literal
341
+ * dot-paths inside `t()` calls, which the field-rename plugin cannot rewrite,
342
+ * so renaming the compiled JSON keys would break runtime lookups. Pruning
343
+ * (top-level field removal) remains safe because it preserves field names.
344
+ */
345
+ const analyzeNamespaceCallerUsage = (babelTypes, pruneContext, callExpressionPath, callerConfig, isSfcFile) => {
346
+ const callArguments = callExpressionPath.node.arguments;
347
+ const resolvedNamespace = resolveCompatNamespace(babelTypes, callArguments, callerConfig.namespace);
348
+ if (resolvedNamespace === void 0) return;
349
+ const namespaceString = resolvedNamespace === "__default__" ? DEFAULT_COMPAT_NAMESPACE : resolvedNamespace;
350
+ const namespaceSegments = namespaceString.split(".");
351
+ const dictionaryKey = namespaceSegments[0] ?? namespaceString;
352
+ const namespacePrefix = namespaceSegments.length > 1 ? namespaceSegments.slice(1).join(".") : null;
353
+ pruneContext.dictionariesSkippingFieldRename.add(dictionaryKey);
354
+ if (isSfcFile) {
355
+ recordFieldUsage(pruneContext, dictionaryKey, "all");
356
+ return;
357
+ }
358
+ const explicitKeyPrefix = resolveCompatKeyPrefix(babelTypes, callArguments, callerConfig.keyPrefix);
359
+ if (explicitKeyPrefix === void 0) {
360
+ recordFieldUsage(pruneContext, dictionaryKey, "all");
361
+ return;
362
+ }
363
+ const effectivePrefix = namespacePrefix ?? explicitKeyPrefix;
364
+ if (effectivePrefix !== null) {
365
+ recordFieldUsage(pruneContext, dictionaryKey, new Set([firstPathSegment(effectivePrefix)]));
366
+ return;
367
+ }
368
+ let translationBinding = null;
369
+ if (callerConfig.translationFunction === "destructured-t") {
370
+ const parentNode = callExpressionPath.parent;
371
+ if (babelTypes.isVariableDeclarator(parentNode) && babelTypes.isObjectPattern(parentNode.id)) {
372
+ for (const property of parentNode.id.properties) if (babelTypes.isObjectProperty(property) && babelTypes.isIdentifier(property.key) && property.key.name === "t" && babelTypes.isIdentifier(property.value)) translationBinding = callExpressionPath.scope.getBinding(property.value.name) ?? null;
373
+ }
374
+ } else {
375
+ const parentNode = unwrapAwait(babelTypes, callExpressionPath).parent;
376
+ if (babelTypes.isVariableDeclarator(parentNode) && babelTypes.isIdentifier(parentNode.id)) translationBinding = callExpressionPath.scope.getBinding(parentNode.id.name) ?? null;
377
+ }
378
+ if (!translationBinding) {
379
+ recordFieldUsage(pruneContext, dictionaryKey, "all");
380
+ return;
381
+ }
382
+ const accessedFields = /* @__PURE__ */ new Set();
383
+ let hasUntrackedUsage = false;
384
+ for (const referencePath of translationBinding.referencePaths) {
385
+ const parentNode = referencePath.parent;
386
+ if (!((babelTypes.isCallExpression(parentNode) || babelTypes.isOptionalCallExpression(parentNode)) && parentNode.callee === referencePath.node)) {
387
+ hasUntrackedUsage = true;
388
+ break;
389
+ }
390
+ const firstArgument = parentNode.arguments[0];
391
+ const segment = readStaticFirstSegment(babelTypes, firstArgument);
392
+ if (segment === void 0) {
393
+ hasUntrackedUsage = true;
394
+ break;
395
+ }
396
+ accessedFields.add(segment);
397
+ }
398
+ if (hasUntrackedUsage) {
399
+ recordFieldUsage(pruneContext, dictionaryKey, "all");
400
+ return;
401
+ }
402
+ if (accessedFields.size > 0) recordFieldUsage(pruneContext, dictionaryKey, accessedFields);
403
+ };
404
+ /**
178
405
  * Creates a Babel plugin that traverses source files and records which
179
- * top-level dictionary fields each `useIntlayer` / `getIntlayer` call-site
180
- * accesses. Results are accumulated into `pruneContext`.
406
+ * top-level dictionary fields each `useIntlayer` / `getIntlayer` call-site
407
+ * and each configured compat namespace caller — accesses. Results are
408
+ * accumulated into `pruneContext`.
181
409
  *
182
410
  * This plugin is analysis-only: it does not transform the code (`code: false`
183
411
  * should be passed to `transformAsync` when using it).
412
+ *
413
+ * @param pruneContext - Shared mutable state written by this plugin.
414
+ * @param options - Optional overrides. `compatCallers` defaults to
415
+ * {@link DEFAULT_COMPAT_CALLERS}; pass `[]` to disable
416
+ * compat-adapter analysis entirely.
184
417
  */
185
- const makeUsageAnalyzerBabelPlugin = (pruneContext) => ({ types: babelTypes }) => ({
186
- name: "intlayer-usage-analyzer",
187
- visitor: { Program: { exit: (programPath, state) => {
188
- const currentSourceFilePath = state.file.opts.filename ?? "unknown file";
189
- const isSfcFile = currentSourceFilePath.endsWith(".vue") || currentSourceFilePath.endsWith(".svelte") || currentSourceFilePath.endsWith(".astro");
190
- const intlayerCallerLocalNameMap = /* @__PURE__ */ new Map();
191
- programPath.traverse({ ImportDeclaration: (importDeclarationPath) => {
192
- for (const importSpecifier of importDeclarationPath.node.specifiers) {
193
- if (!babelTypes.isImportSpecifier(importSpecifier)) continue;
194
- const importedName = babelTypes.isIdentifier(importSpecifier.imported) ? importSpecifier.imported.name : importSpecifier.imported.value;
195
- if (INTLAYER_CALLER_NAMES.includes(importedName)) intlayerCallerLocalNameMap.set(importSpecifier.local.name, importedName);
196
- }
197
- } });
198
- if (intlayerCallerLocalNameMap.size === 0) return;
199
- programPath.traverse({ CallExpression: (callExpressionPath) => {
200
- const calleeNode = callExpressionPath.node.callee;
201
- let localCallerName;
202
- if (babelTypes.isIdentifier(calleeNode)) localCallerName = calleeNode.name;
203
- else if (babelTypes.isMemberExpression(calleeNode) && babelTypes.isIdentifier(calleeNode.property)) localCallerName = calleeNode.property.name;
204
- if (!localCallerName || !intlayerCallerLocalNameMap.has(localCallerName)) return;
205
- const callArguments = callExpressionPath.node.arguments;
206
- if (callArguments.length === 0) return;
207
- const firstArgument = callArguments[0];
208
- let dictionaryKey;
209
- if (babelTypes.isStringLiteral(firstArgument)) dictionaryKey = firstArgument.value;
210
- else if (babelTypes.isTemplateLiteral(firstArgument) && firstArgument.expressions.length === 0 && firstArgument.quasis.length === 1) dictionaryKey = firstArgument.quasis[0]?.value.cooked ?? firstArgument.quasis[0]?.value.raw;
211
- if (!dictionaryKey) return;
212
- analyzeCallExpressionUsage(babelTypes, pruneContext, callExpressionPath, dictionaryKey, currentSourceFilePath, isSfcFile);
213
- } });
214
- } } }
215
- });
418
+ const makeUsageAnalyzerBabelPlugin = (pruneContext, options) => ({ types: babelTypes }) => {
419
+ const compatCallers = options?.compatCallers ?? DEFAULT_COMPAT_CALLERS;
420
+ return {
421
+ name: "intlayer-usage-analyzer",
422
+ visitor: { Program: { exit: (programPath, state) => {
423
+ const currentSourceFilePath = state.file.opts.filename ?? "unknown file";
424
+ const isSfcFile = currentSourceFilePath.endsWith(".vue") || currentSourceFilePath.endsWith(".svelte") || currentSourceFilePath.endsWith(".astro");
425
+ const intlayerCallerLocalNameMap = /* @__PURE__ */ new Map();
426
+ const compatCallerLocalNameMap = /* @__PURE__ */ new Map();
427
+ const methodCompatCallers = compatCallers.filter((caller) => caller.matchAsMethod);
428
+ programPath.traverse({ ImportDeclaration: (importDeclarationPath) => {
429
+ const importSource = importDeclarationPath.node.source.value;
430
+ for (const importSpecifier of importDeclarationPath.node.specifiers) {
431
+ if (!babelTypes.isImportSpecifier(importSpecifier)) continue;
432
+ const importedName = babelTypes.isIdentifier(importSpecifier.imported) ? importSpecifier.imported.name : importSpecifier.imported.value;
433
+ if (INTLAYER_CALLER_NAMES.includes(importedName)) {
434
+ intlayerCallerLocalNameMap.set(importSpecifier.local.name, importedName);
435
+ continue;
436
+ }
437
+ const compatCaller = compatCallers.find((caller) => caller.callerName === importedName && caller.importSources.includes(importSource));
438
+ if (compatCaller) compatCallerLocalNameMap.set(importSpecifier.local.name, compatCaller);
439
+ }
440
+ } });
441
+ const hasNativeCallers = intlayerCallerLocalNameMap.size > 0;
442
+ const hasCompatCallers = compatCallerLocalNameMap.size > 0 || methodCompatCallers.length > 0;
443
+ if (!hasNativeCallers && !hasCompatCallers) return;
444
+ programPath.traverse({ CallExpression: (callExpressionPath) => {
445
+ const calleeNode = callExpressionPath.node.callee;
446
+ let localCallerName;
447
+ let isMethodCall = false;
448
+ if (babelTypes.isIdentifier(calleeNode)) localCallerName = calleeNode.name;
449
+ else if (babelTypes.isMemberExpression(calleeNode) && babelTypes.isIdentifier(calleeNode.property)) {
450
+ localCallerName = calleeNode.property.name;
451
+ isMethodCall = true;
452
+ }
453
+ if (!localCallerName) return;
454
+ if (intlayerCallerLocalNameMap.has(localCallerName)) {
455
+ const callArguments = callExpressionPath.node.arguments;
456
+ if (callArguments.length === 0) return;
457
+ const dictionaryKey = readStaticString(babelTypes, callArguments[0]);
458
+ if (!dictionaryKey) return;
459
+ analyzeCallExpressionUsage(babelTypes, pruneContext, callExpressionPath, dictionaryKey, currentSourceFilePath, isSfcFile);
460
+ return;
461
+ }
462
+ const importedCompatCaller = compatCallerLocalNameMap.get(localCallerName);
463
+ if (importedCompatCaller && !isMethodCall) {
464
+ analyzeNamespaceCallerUsage(babelTypes, pruneContext, callExpressionPath, importedCompatCaller, isSfcFile);
465
+ return;
466
+ }
467
+ if (isMethodCall) {
468
+ const methodCaller = methodCompatCallers.find((caller) => caller.callerName === localCallerName);
469
+ if (methodCaller) analyzeNamespaceCallerUsage(babelTypes, pruneContext, callExpressionPath, methodCaller, isSfcFile);
470
+ }
471
+ } });
472
+ } } }
473
+ };
474
+ };
216
475
 
217
476
  //#endregion
477
+ exports.DEFAULT_COMPAT_CALLERS = DEFAULT_COMPAT_CALLERS;
218
478
  exports.INTLAYER_CALLER_NAMES = INTLAYER_CALLER_NAMES;
219
479
  exports.createPruneContext = createPruneContext;
220
480
  exports.makeUsageAnalyzerBabelPlugin = makeUsageAnalyzerBabelPlugin;
@@ -1 +1 @@
1
- {"version":3,"file":"babel-plugin-intlayer-usage-analyzer.cjs","names":[],"sources":["../../src/babel-plugin-intlayer-usage-analyzer.ts"],"sourcesContent":["import type { NodePath, PluginObj, PluginPass } from '@babel/core';\nimport type * as BabelTypes from '@babel/types';\n\n// ── PruneContext types ────────────────────────────────────────────────────────\n\n/**\n * Dictionary field usage result for a single dictionary key.\n *\n * 'all' → could not determine statically which fields are used;\n * keep every field (no pruning possible).\n * Set<string> → the exact top-level content field names that were accessed.\n */\nexport type DictionaryFieldUsage = Set<string> | 'all';\n\n/**\n * One node in the nested field-rename tree.\n *\n * shortName – the compact alias assigned to this field name.\n * children – rename table for the next level of user-defined keys inside\n * this field's value (empty when the value is a leaf / primitive).\n */\nexport type NestedRenameEntry = {\n shortName: string;\n children: NestedRenameMap;\n};\n\n/** A level of the field-rename tree, mapping original field names to entries. */\nexport type NestedRenameMap = Map<string, NestedRenameEntry>;\n\n/**\n * Shared mutable state created once by the vite plugin and passed by reference\n * to the usage-analyzer (writer) and the prune/minify plugins (readers).\n *\n * All mutations happen during the usage-analysis `buildStart` phase; readers\n * only access this state during the subsequent `transform` phase.\n */\nexport type PruneContext = {\n /**\n * Maps every dictionary key seen in source files to the set of top-level\n * content fields statically accessed, or `'all'` when the access pattern\n * could not be determined.\n */\n dictionaryKeyToFieldUsageMap: Map<string, DictionaryFieldUsage>;\n\n /**\n * Dictionary keys for which the prune/minify step must be skipped entirely\n * because an edge case was detected during analysis or structure recognition.\n */\n dictionariesWithEdgeCases: Set<string>;\n\n /**\n * True if at least one source file failed to parse during the analysis phase.\n * The prune plugin uses this flag conservatively: any dictionary key without\n * a usage entry might have been referenced by the unparsable file.\n */\n hasUnparsableSourceFiles: boolean;\n\n /**\n * Maps dictionary keys to the source file paths where the result of\n * `useIntlayer` / `getIntlayer` was assigned to a plain variable, making\n * static field analysis impossible.\n */\n dictionaryKeysWithUntrackedBindings: Map<string, string[]>;\n\n /**\n * Maps each dictionary key to a nested field-rename tree built after the\n * usage analysis phase (only populated when `build.minify` is active and\n * the field usage for that dictionary is a finite `Set<string>`).\n */\n dictionaryKeyToFieldRenameMap: Map<string, NestedRenameMap>;\n\n /**\n * Maps each dictionary key to a per-field list of source locations where\n * the field value is consumed \"opaquely\" (passed as-is to a child component\n * or function argument). When a field is opaque AND has nested user-defined\n * structure, its children must not be renamed.\n *\n * Structure: dictionaryKey → fieldName → [\"filePath:line\", …]\n */\n dictionaryKeysWithOpaqueTopLevelFields: Map<string, Map<string, string[]>>;\n\n /**\n * Dictionary keys for which field-key renaming must be skipped even if a\n * finite field-usage set was determined.\n *\n * Populated for dictionaries whose plain-variable bindings were resolved by\n * the framework-specific extractor (Vue / Svelte SFCs), because the Babel\n * rename plugin cannot update the source-code property accesses for those\n * indirect patterns (Vue `.value.field` / Svelte `$store.field`).\n *\n * Pruning and basic minification still apply; only field-key renaming is\n * suppressed.\n */\n dictionariesSkippingFieldRename: Set<string>;\n\n /**\n * Plain variable bindings that require a framework-specific secondary pass.\n *\n * Populated during the Babel analysis phase for `.vue` and `.svelte` source\n * files where direct field access is not visible to Babel scope analysis:\n * - Vue: `content.value.fieldName` – the `.value` ref-accessor is hidden\n * - Svelte: `$varName.fieldName` – the `$` prefix creates a new identifier\n *\n * Structure: filePath → [{variableName, dictionaryKey}, …]\n */\n pendingFrameworkAnalysis: Map<\n string,\n { variableName: string; dictionaryKey: string }[]\n >;\n};\n\nexport const createPruneContext = (): PruneContext => ({\n dictionaryKeyToFieldUsageMap: new Map(),\n dictionariesWithEdgeCases: new Set(),\n hasUnparsableSourceFiles: false,\n dictionaryKeysWithUntrackedBindings: new Map(),\n dictionaryKeyToFieldRenameMap: new Map(),\n dictionaryKeysWithOpaqueTopLevelFields: new Map<\n string,\n Map<string, string[]>\n >(),\n dictionariesSkippingFieldRename: new Set(),\n pendingFrameworkAnalysis: new Map(),\n});\n\n// ── Usage-analyzer Babel plugin ───────────────────────────────────────────────\n\n/** Canonical intlayer caller names that trigger usage analysis. */\nexport const INTLAYER_CALLER_NAMES = ['useIntlayer', 'getIntlayer'] as const;\nexport type IntlayerCallerName = (typeof INTLAYER_CALLER_NAMES)[number];\n\n/**\n * Records the usage of a specific dictionary key's fields into `pruneContext`.\n * Merges with any previously recorded usage for the same key.\n */\nconst recordFieldUsage = (\n pruneContext: PruneContext,\n dictionaryKey: string,\n fieldUsage: DictionaryFieldUsage\n): void => {\n const existingUsage =\n pruneContext.dictionaryKeyToFieldUsageMap.get(dictionaryKey);\n\n if (existingUsage === 'all') return; // already saturated\n\n if (fieldUsage === 'all') {\n pruneContext.dictionaryKeyToFieldUsageMap.set(dictionaryKey, 'all');\n return;\n }\n\n const mergedFieldSet =\n existingUsage instanceof Set\n ? new Set([...existingUsage, ...fieldUsage])\n : new Set(fieldUsage);\n\n pruneContext.dictionaryKeyToFieldUsageMap.set(dictionaryKey, mergedFieldSet);\n};\n\n/**\n * Analyses how the result of a single `useIntlayer('key')` / `getIntlayer('key')`\n * call expression is consumed, then records the field usage into `pruneContext`.\n *\n * Recognised patterns:\n * const { fieldA, fieldB } = useIntlayer('key') → records {fieldA, fieldB}\n * useIntlayer('key').fieldA → records {fieldA}\n * useIntlayer('key')['fieldA'] → records {fieldA}\n * const { ...rest } = useIntlayer('key') → records 'all' (spread)\n * const result = useIntlayer('key') → records 'all' (untracked binding)\n */\nconst analyzeCallExpressionUsage = (\n babelTypes: typeof BabelTypes,\n pruneContext: PruneContext,\n callExpressionPath: NodePath<BabelTypes.CallExpression>,\n dictionaryKey: string,\n currentSourceFilePath: string,\n isSfcFile: boolean\n): void => {\n const parentNode = callExpressionPath.parent;\n\n /** Mark the dictionary key as having an untracked binding in this file. */\n const markUntrackedBinding = (): void => {\n const existingPaths =\n pruneContext.dictionaryKeysWithUntrackedBindings.get(dictionaryKey) ?? [];\n if (!existingPaths.includes(currentSourceFilePath)) {\n pruneContext.dictionaryKeysWithUntrackedBindings.set(dictionaryKey, [\n ...existingPaths,\n currentSourceFilePath,\n ]);\n }\n recordFieldUsage(pruneContext, dictionaryKey, 'all');\n };\n\n /** Record that a field value is consumed opaquely (not further destructured). */\n const markOpaqueField = (\n fieldName: string,\n line: number | undefined\n ): void => {\n const fieldToLocations =\n pruneContext.dictionaryKeysWithOpaqueTopLevelFields.get(dictionaryKey) ??\n new Map<string, string[]>();\n const location =\n line !== undefined\n ? `${currentSourceFilePath}:${line}`\n : currentSourceFilePath;\n const locations = fieldToLocations.get(fieldName) ?? [];\n if (!locations.includes(location)) locations.push(location);\n fieldToLocations.set(fieldName, locations);\n pruneContext.dictionaryKeysWithOpaqueTopLevelFields.set(\n dictionaryKey,\n fieldToLocations\n );\n };\n\n /** Register a plain variable binding in an SFC file for a second-pass analysis. */\n const deferFrameworkAnalysis = (variableName: string): void => {\n const existing =\n pruneContext.pendingFrameworkAnalysis.get(currentSourceFilePath) ?? [];\n if (\n !existing.some(\n (e) =>\n e.variableName === variableName && e.dictionaryKey === dictionaryKey\n )\n ) {\n existing.push({ variableName, dictionaryKey });\n }\n pruneContext.pendingFrameworkAnalysis.set(currentSourceFilePath, existing);\n };\n\n /**\n * Analyses usage of a variable or member access to detect opaque\n * consumption (passing a dictionary field as-is to a prop or function).\n *\n * If a direct, non-chained consumption is found, it calls `markOpaqueField`.\n * Chained accesses (e.g. `field.sub`) are NOT considered opaque for `field`\n * because the renamer can safely track and update them.\n */\n const analyzeOpaqueUsage = (\n refPath: NodePath<BabelTypes.Node>,\n fieldName: string\n ): void => {\n const parentNode = refPath.parent;\n\n // 1. Chained member access (e.g. field.sub or field?.sub)\n if (\n (babelTypes.isMemberExpression(parentNode) ||\n babelTypes.isOptionalMemberExpression(parentNode)) &&\n (parentNode as BabelTypes.MemberExpression).object === refPath.node\n ) {\n // Chained access is safe: the renamer correctly updates it.\n return;\n }\n\n // 2. Destructuring (e.g. const { sub } = field)\n if (\n babelTypes.isVariableDeclarator(parentNode) &&\n babelTypes.isObjectPattern(parentNode.id) &&\n parentNode.init === refPath.node\n ) {\n // Destructuring is analogous to member access: safe.\n return;\n }\n\n // 3. Ignored patterns (e.g. array literals [content])\n if (babelTypes.isArrayExpression(parentNode)) {\n return;\n }\n\n // 4. Opaque consumption (passed to prop, function, etc.)\n markOpaqueField(fieldName, refPath.node.loc?.start.line);\n };\n\n /**\n * Helper to collect field names from an ObjectPattern (destructuring).\n * Returns true if successful, false if a rest element was found (meaning 'all').\n */\n const collectFieldsFromObjectPattern = (\n pattern: BabelTypes.ObjectPattern,\n initPath: NodePath<BabelTypes.Node>,\n targetSet: Set<string>\n ): boolean => {\n if (pattern.properties.some((prop) => babelTypes.isRestElement(prop))) {\n return false;\n }\n\n for (const property of pattern.properties) {\n let fieldName: string | undefined;\n\n if (\n babelTypes.isObjectProperty(property) &&\n babelTypes.isIdentifier(property.key)\n ) {\n fieldName = property.key.name;\n } else if (\n babelTypes.isObjectProperty(property) &&\n babelTypes.isStringLiteral(property.key)\n ) {\n fieldName = property.key.value;\n }\n\n if (fieldName) {\n targetSet.add(fieldName);\n\n if (\n babelTypes.isObjectProperty(property) &&\n babelTypes.isIdentifier(property.value)\n ) {\n const variableBinding = initPath.scope.getBinding(\n property.value.name\n );\n if (variableBinding) {\n for (const refPath of variableBinding.referencePaths) {\n analyzeOpaqueUsage(refPath, fieldName);\n }\n }\n }\n }\n }\n return true;\n };\n\n // ── Pattern 1: const { fieldA, fieldB } = useIntlayer('key') ──────────────\n if (\n babelTypes.isVariableDeclarator(parentNode) &&\n babelTypes.isObjectPattern(parentNode.id)\n ) {\n const accessedFieldNames = new Set<string>();\n if (\n collectFieldsFromObjectPattern(\n parentNode.id,\n callExpressionPath,\n accessedFieldNames\n )\n ) {\n recordFieldUsage(pruneContext, dictionaryKey, accessedFieldNames);\n } else {\n recordFieldUsage(pruneContext, dictionaryKey, 'all');\n }\n return;\n }\n\n // ── Pattern 2: useIntlayer('key').fieldA / useIntlayer('key')?.fieldA ──────\n if (\n (babelTypes.isMemberExpression(parentNode) ||\n babelTypes.isOptionalMemberExpression(parentNode)) &&\n (parentNode as BabelTypes.MemberExpression).object ===\n callExpressionPath.node\n ) {\n let fieldName: string | undefined;\n\n if (!parentNode.computed && babelTypes.isIdentifier(parentNode.property)) {\n fieldName = parentNode.property.name;\n } else if (\n parentNode.computed &&\n babelTypes.isStringLiteral(parentNode.property)\n ) {\n fieldName = parentNode.property.value;\n }\n\n if (fieldName) {\n recordFieldUsage(pruneContext, dictionaryKey, new Set([fieldName]));\n\n // Check for opaque usage (e.g. passed directly to a prop)\n const memberExprPath = callExpressionPath.parentPath;\n if (memberExprPath) {\n analyzeOpaqueUsage(memberExprPath, fieldName);\n }\n } else {\n markUntrackedBinding();\n }\n return;\n }\n\n // ── Pattern 3: const content = useIntlayer('key') ─────────────────────────\n if (\n babelTypes.isVariableDeclarator(parentNode) &&\n babelTypes.isIdentifier(parentNode.id)\n ) {\n const variableName = parentNode.id.name;\n const variableBinding = callExpressionPath.scope.getBinding(variableName);\n\n if (!variableBinding) {\n markUntrackedBinding();\n return;\n }\n\n const accessedTopLevelFieldNames = new Set<string>();\n let hasUntrackedReferenceAccess = false;\n\n for (const variableReferencePath of variableBinding.referencePaths) {\n const referenceParentNode = variableReferencePath.parent;\n\n if (\n (babelTypes.isMemberExpression(referenceParentNode) ||\n babelTypes.isOptionalMemberExpression(referenceParentNode)) &&\n (referenceParentNode as BabelTypes.MemberExpression).object ===\n variableReferencePath.node\n ) {\n const memberExpressionNode =\n referenceParentNode as BabelTypes.MemberExpression;\n let fieldName: string | undefined;\n\n if (\n !memberExpressionNode.computed &&\n babelTypes.isIdentifier(memberExpressionNode.property)\n ) {\n fieldName = memberExpressionNode.property.name;\n } else if (\n memberExpressionNode.computed &&\n babelTypes.isStringLiteral(memberExpressionNode.property)\n ) {\n fieldName = memberExpressionNode.property.value;\n }\n\n if (fieldName) {\n accessedTopLevelFieldNames.add(fieldName);\n\n // Check usage of the field to look for opaque consumption\n const memberExprPath = variableReferencePath.parentPath;\n if (memberExprPath) {\n analyzeOpaqueUsage(memberExprPath, fieldName);\n }\n } else {\n // Dynamic computed access – cannot resolve statically\n hasUntrackedReferenceAccess = true;\n break;\n }\n } else if (babelTypes.isArrayExpression(referenceParentNode)) {\n // Ignore array literals (e.g. [content]) – uncommon but benign\n } else if (\n // Solid / Angular: content() signal accessor → content().field\n (babelTypes.isCallExpression(referenceParentNode) ||\n babelTypes.isOptionalCallExpression(referenceParentNode)) &&\n (referenceParentNode as BabelTypes.CallExpression).callee ===\n variableReferencePath.node\n ) {\n const callExprPath = variableReferencePath.parentPath;\n const callParent = callExprPath?.parent;\n\n if (\n callParent &&\n (babelTypes.isMemberExpression(callParent) ||\n babelTypes.isOptionalMemberExpression(callParent)) &&\n (callParent as BabelTypes.MemberExpression).object ===\n callExprPath?.node\n ) {\n // content().field\n const memberExpr = callParent as BabelTypes.MemberExpression;\n let fieldName: string | undefined;\n\n if (\n !memberExpr.computed &&\n babelTypes.isIdentifier(memberExpr.property)\n ) {\n fieldName = memberExpr.property.name;\n } else if (\n memberExpr.computed &&\n babelTypes.isStringLiteral(memberExpr.property)\n ) {\n fieldName = memberExpr.property.value;\n }\n\n if (fieldName) {\n accessedTopLevelFieldNames.add(fieldName);\n const memberExprPath = callExprPath?.parentPath;\n if (memberExprPath) analyzeOpaqueUsage(memberExprPath, fieldName);\n } else {\n // content()[dynamicKey] – cannot resolve statically\n hasUntrackedReferenceAccess = true;\n break;\n }\n } else if (\n callParent &&\n babelTypes.isVariableDeclarator(callParent) &&\n babelTypes.isObjectPattern(callParent.id) &&\n callExprPath &&\n collectFieldsFromObjectPattern(\n callParent.id,\n callExprPath,\n accessedTopLevelFieldNames\n )\n ) {\n // const { title } = content()\n // fields already added to accessedTopLevelFieldNames by collectFieldsFromObjectPattern\n } else {\n // content() with no field access or passed opaquely → cannot prune\n hasUntrackedReferenceAccess = true;\n break;\n }\n } else {\n // Variable used in a non-member-access context (spread, function arg, etc.)\n hasUntrackedReferenceAccess = true;\n break;\n }\n }\n\n if (hasUntrackedReferenceAccess) {\n markUntrackedBinding();\n } else if (isSfcFile) {\n // Vue / Svelte SFC: defer to the framework-specific extractor because\n // Babel scope analysis cannot see through `.value` or `$` indirection.\n deferFrameworkAnalysis(variableName);\n } else if (variableBinding.referencePaths.length === 0) {\n // Non-SFC file with no visible references – conservatively keep all fields.\n markUntrackedBinding();\n } else {\n recordFieldUsage(pruneContext, dictionaryKey, accessedTopLevelFieldNames);\n }\n return;\n }\n\n // ── Pattern 4: bare call – result is discarded ─────────────────────────────\n if (babelTypes.isExpressionStatement(parentNode)) {\n return; // no usage to record\n }\n\n // ── Fallback: result passed as argument, used in ternary, etc. ─────────────\n markUntrackedBinding();\n};\n\n/**\n * Creates a Babel plugin that traverses source files and records which\n * top-level dictionary fields each `useIntlayer` / `getIntlayer` call-site\n * accesses. Results are accumulated into `pruneContext`.\n *\n * This plugin is analysis-only: it does not transform the code (`code: false`\n * should be passed to `transformAsync` when using it).\n */\nexport const makeUsageAnalyzerBabelPlugin =\n (pruneContext: PruneContext) =>\n ({ types: babelTypes }: { types: typeof BabelTypes }): PluginObj => ({\n name: 'intlayer-usage-analyzer',\n visitor: {\n Program: {\n exit: (programPath, state: PluginPass) => {\n const currentSourceFilePath =\n state.file.opts.filename ?? 'unknown file';\n const isSfcFile =\n currentSourceFilePath.endsWith('.vue') ||\n currentSourceFilePath.endsWith('.svelte') ||\n currentSourceFilePath.endsWith('.astro');\n\n // Phase 1: collect local aliases for useIntlayer / getIntlayer\n const intlayerCallerLocalNameMap = new Map<string, string>();\n\n programPath.traverse({\n ImportDeclaration: (importDeclarationPath) => {\n for (const importSpecifier of importDeclarationPath.node\n .specifiers) {\n if (!babelTypes.isImportSpecifier(importSpecifier)) continue;\n\n const importedName = babelTypes.isIdentifier(\n importSpecifier.imported\n )\n ? importSpecifier.imported.name\n : (importSpecifier.imported as BabelTypes.StringLiteral)\n .value;\n\n if (\n INTLAYER_CALLER_NAMES.includes(\n importedName as IntlayerCallerName\n )\n ) {\n intlayerCallerLocalNameMap.set(\n importSpecifier.local.name,\n importedName\n );\n }\n }\n },\n });\n\n if (intlayerCallerLocalNameMap.size === 0) return;\n\n // Phase 2: analyse each call-site\n programPath.traverse({\n CallExpression: (callExpressionPath) => {\n const calleeNode = callExpressionPath.node.callee;\n let localCallerName: string | undefined;\n\n if (babelTypes.isIdentifier(calleeNode)) {\n localCallerName = calleeNode.name;\n } else if (\n babelTypes.isMemberExpression(calleeNode) &&\n babelTypes.isIdentifier(calleeNode.property)\n ) {\n localCallerName = calleeNode.property.name;\n }\n\n if (\n !localCallerName ||\n !intlayerCallerLocalNameMap.has(localCallerName)\n )\n return;\n\n const callArguments = callExpressionPath.node.arguments;\n if (callArguments.length === 0) return;\n\n const firstArgument = callArguments[0];\n let dictionaryKey: string | undefined;\n\n if (babelTypes.isStringLiteral(firstArgument)) {\n dictionaryKey = firstArgument.value;\n } else if (\n babelTypes.isTemplateLiteral(firstArgument) &&\n firstArgument.expressions.length === 0 &&\n firstArgument.quasis.length === 1\n ) {\n dictionaryKey =\n firstArgument.quasis[0]?.value.cooked ??\n firstArgument.quasis[0]?.value.raw;\n }\n\n if (!dictionaryKey) return; // dynamic key – cannot resolve which dictionary\n\n analyzeCallExpressionUsage(\n babelTypes,\n pruneContext,\n callExpressionPath,\n dictionaryKey,\n currentSourceFilePath,\n isSfcFile\n );\n },\n });\n },\n },\n },\n });\n"],"mappings":";;;AA+GA,MAAa,4BAA0C;CACrD,8CAA8B,IAAI,IAAI;CACtC,2CAA2B,IAAI,IAAI;CACnC,0BAA0B;CAC1B,qDAAqC,IAAI,IAAI;CAC7C,+CAA+B,IAAI,IAAI;CACvC,wDAAwC,IAAI,IAG1C;CACF,iDAAiC,IAAI,IAAI;CACzC,0CAA0B,IAAI,IAAI;AACpC;;AAKA,MAAa,wBAAwB,CAAC,eAAe,aAAa;;;;;AAOlE,MAAM,oBACJ,cACA,eACA,eACS;CACT,MAAM,gBACJ,aAAa,6BAA6B,IAAI,aAAa;CAE7D,IAAI,kBAAkB,OAAO;CAE7B,IAAI,eAAe,OAAO;EACxB,aAAa,6BAA6B,IAAI,eAAe,KAAK;EAClE;CACF;CAEA,MAAM,iBACJ,yBAAyB,MACrB,IAAI,IAAI,CAAC,GAAG,eAAe,GAAG,UAAU,CAAC,IACzC,IAAI,IAAI,UAAU;CAExB,aAAa,6BAA6B,IAAI,eAAe,cAAc;AAC7E;;;;;;;;;;;;AAaA,M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EJ;EACF,EACF,CAAC;EAED,IAAI,2BAA2B,SAAS,GAAG;EAG3C,YAAY,SAAS,EACnB,iBAAiB,uBAAuB;GACtC,MAAM,aAAa,mBAAmB,KAAK;GAC3C,IAAI;GAEJ,IAAI,WAAW,aAAa,UAAU,GACpC,kBAAkB,WAAW;QACxB,IACL,WAAW,mBAAmB,UAAU,KACxC,WAAW,aAAa,WAAW,QAAQ,GAE3C,kBAAkB,WAAW,SAAS;GAGxC,IACE,CAAC,mBACD,CAAC,2BAA2B,IAAI,eAAe,GAE/C;GAEF,MAAM,gBAAgB,mBAAmB,KAAK;GAC9C,IAAI,cAAc,WAAW,GAAG;GAEhC,MAAM,gBAAgB,cAAc;GACpC,IAAI;GAEJ,IAAI,WAAW,gBAAgB,aAAa,GAC1C,gBAAgB,cAAc;QACzB,IACL,WAAW,kBAAkB,aAAa,KAC1C,cAAc,YAAY,WAAW,KACrC,cAAc,OAAO,WAAW,GAEhC,gBACE,cAAc,OAAO,IAAI,MAAM,UAC/B,cAAc,OAAO,IAAI,MAAM;GAGnC,IAAI,CAAC,eAAe;GAEpB,2BACE,YACA,cACA,oBACA,eACA,uBACA,SACF;EACF,EACF,CAAC;CACH,EACF,EACF;AACF"}
1
+ {"version":3,"file":"babel-plugin-intlayer-usage-analyzer.cjs","names":[],"sources":["../../src/babel-plugin-intlayer-usage-analyzer.ts"],"sourcesContent":["import type { NodePath, PluginObj, PluginPass } from '@babel/core';\nimport type * as BabelTypes from '@babel/types';\n\n// ── PruneContext types ────────────────────────────────────────────────────────\n\n/**\n * Dictionary field usage result for a single dictionary key.\n *\n * 'all' → could not determine statically which fields are used;\n * keep every field (no pruning possible).\n * Set<string> → the exact top-level content field names that were accessed.\n */\nexport type DictionaryFieldUsage = Set<string> | 'all';\n\n/**\n * One node in the nested field-rename tree.\n *\n * shortName – the compact alias assigned to this field name.\n * children – rename table for the next level of user-defined keys inside\n * this field's value (empty when the value is a leaf / primitive).\n */\nexport type NestedRenameEntry = {\n shortName: string;\n children: NestedRenameMap;\n};\n\n/** A level of the field-rename tree, mapping original field names to entries. */\nexport type NestedRenameMap = Map<string, NestedRenameEntry>;\n\n/**\n * Shared mutable state created once by the vite plugin and passed by reference\n * to the usage-analyzer (writer) and the prune/minify plugins (readers).\n *\n * All mutations happen during the usage-analysis `buildStart` phase; readers\n * only access this state during the subsequent `transform` phase.\n */\nexport type PruneContext = {\n /**\n * Maps every dictionary key seen in source files to the set of top-level\n * content fields statically accessed, or `'all'` when the access pattern\n * could not be determined.\n */\n dictionaryKeyToFieldUsageMap: Map<string, DictionaryFieldUsage>;\n\n /**\n * Dictionary keys for which the prune/minify step must be skipped entirely\n * because an edge case was detected during analysis or structure recognition.\n */\n dictionariesWithEdgeCases: Set<string>;\n\n /**\n * True if at least one source file failed to parse during the analysis phase.\n * The prune plugin uses this flag conservatively: any dictionary key without\n * a usage entry might have been referenced by the unparsable file.\n */\n hasUnparsableSourceFiles: boolean;\n\n /**\n * Maps dictionary keys to the source file paths where the result of\n * `useIntlayer` / `getIntlayer` was assigned to a plain variable, making\n * static field analysis impossible.\n */\n dictionaryKeysWithUntrackedBindings: Map<string, string[]>;\n\n /**\n * Maps each dictionary key to a nested field-rename tree built after the\n * usage analysis phase (only populated when `build.minify` is active and\n * the field usage for that dictionary is a finite `Set<string>`).\n */\n dictionaryKeyToFieldRenameMap: Map<string, NestedRenameMap>;\n\n /**\n * Maps each dictionary key to a per-field list of source locations where\n * the field value is consumed \"opaquely\" (passed as-is to a child component\n * or function argument). When a field is opaque AND has nested user-defined\n * structure, its children must not be renamed.\n *\n * Structure: dictionaryKey → fieldName → [\"filePath:line\", …]\n */\n dictionaryKeysWithOpaqueTopLevelFields: Map<string, Map<string, string[]>>;\n\n /**\n * Dictionary keys for which field-key renaming must be skipped even if a\n * finite field-usage set was determined.\n *\n * Populated for dictionaries whose plain-variable bindings were resolved by\n * the framework-specific extractor (Vue / Svelte SFCs), because the Babel\n * rename plugin cannot update the source-code property accesses for those\n * indirect patterns (Vue `.value.field` / Svelte `$store.field`).\n *\n * Pruning and basic minification still apply; only field-key renaming is\n * suppressed.\n */\n dictionariesSkippingFieldRename: Set<string>;\n\n /**\n * Plain variable bindings that require a framework-specific secondary pass.\n *\n * Populated during the Babel analysis phase for `.vue` and `.svelte` source\n * files where direct field access is not visible to Babel scope analysis:\n * - Vue: `content.value.fieldName` – the `.value` ref-accessor is hidden\n * - Svelte: `$varName.fieldName` – the `$` prefix creates a new identifier\n *\n * Structure: filePath → [{variableName, dictionaryKey}, …]\n */\n pendingFrameworkAnalysis: Map<\n string,\n { variableName: string; dictionaryKey: string }[]\n >;\n};\n\nexport const createPruneContext = (): PruneContext => ({\n dictionaryKeyToFieldUsageMap: new Map(),\n dictionariesWithEdgeCases: new Set(),\n hasUnparsableSourceFiles: false,\n dictionaryKeysWithUntrackedBindings: new Map(),\n dictionaryKeyToFieldRenameMap: new Map(),\n dictionaryKeysWithOpaqueTopLevelFields: new Map<\n string,\n Map<string, string[]>\n >(),\n dictionariesSkippingFieldRename: new Set(),\n pendingFrameworkAnalysis: new Map(),\n});\n\n// ── Usage-analyzer Babel plugin ───────────────────────────────────────────────\n\n/** Canonical intlayer caller names that trigger usage analysis. */\nexport const INTLAYER_CALLER_NAMES = ['useIntlayer', 'getIntlayer'] as const;\nexport type IntlayerCallerName = (typeof INTLAYER_CALLER_NAMES)[number];\n\n// ── Compat-adapter namespace callers ──────────────────────────────────────────\n\n/**\n * Describes how a compat-adapter \"namespace caller\" exposes the dictionary key\n * (namespace) and the translation function `t`.\n *\n * Compat adapters (`@intlayer/react-i18next`, `@intlayer/next-intl`, …) expose\n * the original i18n library API while delegating to intlayer under the hood.\n * Their call sites look like:\n *\n * const { t } = useTranslation('about'); t('counter.label')\n * const t = useTranslations('about'); t('counter.label')\n * const t = await getTranslations('about');\n * const t = i18n.getFixedT(null, 'about', 'counter');\n * const { t } = useI18n({ namespace: 'about' });\n *\n * The dictionary key is the *namespace* argument and the consumed top-level\n * field is the **first segment** of every dot-path passed to `t()` (or the\n * first segment of `keyPrefix` when one is supplied).\n */\nexport type CompatNamespaceSource =\n /** Namespace is a positional argument (string literal or `{ namespace }`). */\n | { from: 'argument'; index: number }\n /** Namespace is a property of an options object argument. */\n | { from: 'option'; argumentIndex: number; property: string };\n\n/**\n * Configuration entry for a single compat namespace caller.\n */\nexport type CompatCallerConfig = {\n /** The imported (or method) function name, e.g. `'useTranslation'`. */\n callerName: string;\n /**\n * Module specifiers from which `callerName` must be imported to be treated as\n * a compat caller. Includes both the original library names and their\n * `@intlayer/*` adapter equivalents, because the bundler aliases the former\n * to the latter but user source code may import either.\n *\n * Ignored when `matchAsMethod` is `true`.\n */\n importSources: string[];\n /**\n * When `true`, the caller is matched by method name on any object\n * (`x.getFixedT(...)`) without an import check. Used for `i18next` instance\n * methods that are never imported as named specifiers.\n */\n matchAsMethod?: boolean;\n /** How the dictionary key (namespace) is read from the call arguments. */\n namespace: CompatNamespaceSource;\n /**\n * Optional location of a `keyPrefix` that prefixes every `t()` path. When a\n * static prefix is present, the only consumed top-level field is the first\n * segment of the prefix.\n */\n keyPrefix?: CompatNamespaceSource;\n /** How the translation function is obtained from the call result. */\n translationFunction: 'return-value' | 'destructured-t';\n};\n\n/**\n * Default registry of compat namespace callers, covering every first-party\n * `@intlayer/*` adapter package and its underlying i18n library.\n */\nexport const DEFAULT_COMPAT_CALLERS: CompatCallerConfig[] = [\n // react-i18next / next-i18next → useTranslation('ns', { keyPrefix }) → { t }\n {\n callerName: 'useTranslation',\n importSources: [\n 'react-i18next',\n '@intlayer/react-i18next',\n 'next-i18next',\n '@intlayer/next-i18next',\n ],\n namespace: { from: 'argument', index: 0 },\n keyPrefix: { from: 'option', argumentIndex: 1, property: 'keyPrefix' },\n translationFunction: 'destructured-t',\n },\n // next-intl (client) → useTranslations('ns') → t\n {\n callerName: 'useTranslations',\n importSources: ['next-intl', '@intlayer/next-intl'],\n namespace: { from: 'argument', index: 0 },\n translationFunction: 'return-value',\n },\n // next-intl (server) → await getTranslations('ns') → t\n {\n callerName: 'getTranslations',\n importSources: [\n 'next-intl/server',\n '@intlayer/next-intl/server',\n 'next-intl',\n '@intlayer/next-intl',\n ],\n namespace: { from: 'argument', index: 0 },\n translationFunction: 'return-value',\n },\n // i18next → i18n.getFixedT(lng, 'ns', keyPrefix) → t\n {\n callerName: 'getFixedT',\n importSources: ['i18next', '@intlayer/i18next'],\n matchAsMethod: true,\n namespace: { from: 'argument', index: 1 },\n keyPrefix: { from: 'argument', index: 2 },\n translationFunction: 'return-value',\n },\n // vue-i18n → useI18n({ namespace: 'ns' }) → { t }\n {\n callerName: 'useI18n',\n importSources: ['vue-i18n', '@intlayer/vue-i18n'],\n namespace: { from: 'option', argumentIndex: 0, property: 'namespace' },\n translationFunction: 'destructured-t',\n },\n];\n\n/** Default namespace used by compat callers when no namespace argument is given. */\nconst DEFAULT_COMPAT_NAMESPACE = 'translation';\n\n/**\n * Records the usage of a specific dictionary key's fields into `pruneContext`.\n * Merges with any previously recorded usage for the same key.\n */\nconst recordFieldUsage = (\n pruneContext: PruneContext,\n dictionaryKey: string,\n fieldUsage: DictionaryFieldUsage\n): void => {\n const existingUsage =\n pruneContext.dictionaryKeyToFieldUsageMap.get(dictionaryKey);\n\n if (existingUsage === 'all') return; // already saturated\n\n if (fieldUsage === 'all') {\n pruneContext.dictionaryKeyToFieldUsageMap.set(dictionaryKey, 'all');\n return;\n }\n\n const mergedFieldSet =\n existingUsage instanceof Set\n ? new Set([...existingUsage, ...fieldUsage])\n : new Set(fieldUsage);\n\n pruneContext.dictionaryKeyToFieldUsageMap.set(dictionaryKey, mergedFieldSet);\n};\n\n/**\n * Analyses how the result of a single `useIntlayer('key')` / `getIntlayer('key')`\n * call expression is consumed, then records the field usage into `pruneContext`.\n *\n * Recognised patterns:\n * const { fieldA, fieldB } = useIntlayer('key') → records {fieldA, fieldB}\n * useIntlayer('key').fieldA → records {fieldA}\n * useIntlayer('key')['fieldA'] → records {fieldA}\n * const { ...rest } = useIntlayer('key') → records 'all' (spread)\n * const result = useIntlayer('key') → records 'all' (untracked binding)\n */\nconst analyzeCallExpressionUsage = (\n babelTypes: typeof BabelTypes,\n pruneContext: PruneContext,\n callExpressionPath: NodePath<BabelTypes.CallExpression>,\n dictionaryKey: string,\n currentSourceFilePath: string,\n isSfcFile: boolean\n): void => {\n const parentNode = callExpressionPath.parent;\n\n /** Mark the dictionary key as having an untracked binding in this file. */\n const markUntrackedBinding = (): void => {\n const existingPaths =\n pruneContext.dictionaryKeysWithUntrackedBindings.get(dictionaryKey) ?? [];\n if (!existingPaths.includes(currentSourceFilePath)) {\n pruneContext.dictionaryKeysWithUntrackedBindings.set(dictionaryKey, [\n ...existingPaths,\n currentSourceFilePath,\n ]);\n }\n recordFieldUsage(pruneContext, dictionaryKey, 'all');\n };\n\n /** Record that a field value is consumed opaquely (not further destructured). */\n const markOpaqueField = (\n fieldName: string,\n line: number | undefined\n ): void => {\n const fieldToLocations =\n pruneContext.dictionaryKeysWithOpaqueTopLevelFields.get(dictionaryKey) ??\n new Map<string, string[]>();\n const location =\n line !== undefined\n ? `${currentSourceFilePath}:${line}`\n : currentSourceFilePath;\n const locations = fieldToLocations.get(fieldName) ?? [];\n if (!locations.includes(location)) locations.push(location);\n fieldToLocations.set(fieldName, locations);\n pruneContext.dictionaryKeysWithOpaqueTopLevelFields.set(\n dictionaryKey,\n fieldToLocations\n );\n };\n\n /** Register a plain variable binding in an SFC file for a second-pass analysis. */\n const deferFrameworkAnalysis = (variableName: string): void => {\n const existing =\n pruneContext.pendingFrameworkAnalysis.get(currentSourceFilePath) ?? [];\n if (\n !existing.some(\n (e) =>\n e.variableName === variableName && e.dictionaryKey === dictionaryKey\n )\n ) {\n existing.push({ variableName, dictionaryKey });\n }\n pruneContext.pendingFrameworkAnalysis.set(currentSourceFilePath, existing);\n };\n\n /**\n * Analyses usage of a variable or member access to detect opaque\n * consumption (passing a dictionary field as-is to a prop or function).\n *\n * If a direct, non-chained consumption is found, it calls `markOpaqueField`.\n * Chained accesses (e.g. `field.sub`) are NOT considered opaque for `field`\n * because the renamer can safely track and update them.\n */\n const analyzeOpaqueUsage = (\n refPath: NodePath<BabelTypes.Node>,\n fieldName: string\n ): void => {\n const parentNode = refPath.parent;\n\n // 1. Chained member access (e.g. field.sub or field?.sub)\n if (\n (babelTypes.isMemberExpression(parentNode) ||\n babelTypes.isOptionalMemberExpression(parentNode)) &&\n (parentNode as BabelTypes.MemberExpression).object === refPath.node\n ) {\n // Chained access is safe: the renamer correctly updates it.\n return;\n }\n\n // 2. Destructuring (e.g. const { sub } = field)\n if (\n babelTypes.isVariableDeclarator(parentNode) &&\n babelTypes.isObjectPattern(parentNode.id) &&\n parentNode.init === refPath.node\n ) {\n // Destructuring is analogous to member access: safe.\n return;\n }\n\n // 3. Ignored patterns (e.g. array literals [content])\n if (babelTypes.isArrayExpression(parentNode)) {\n return;\n }\n\n // 4. Opaque consumption (passed to prop, function, etc.)\n markOpaqueField(fieldName, refPath.node.loc?.start.line);\n };\n\n /**\n * Helper to collect field names from an ObjectPattern (destructuring).\n * Returns true if successful, false if a rest element was found (meaning 'all').\n */\n const collectFieldsFromObjectPattern = (\n pattern: BabelTypes.ObjectPattern,\n initPath: NodePath<BabelTypes.Node>,\n targetSet: Set<string>\n ): boolean => {\n if (pattern.properties.some((prop) => babelTypes.isRestElement(prop))) {\n return false;\n }\n\n for (const property of pattern.properties) {\n let fieldName: string | undefined;\n\n if (\n babelTypes.isObjectProperty(property) &&\n babelTypes.isIdentifier(property.key)\n ) {\n fieldName = property.key.name;\n } else if (\n babelTypes.isObjectProperty(property) &&\n babelTypes.isStringLiteral(property.key)\n ) {\n fieldName = property.key.value;\n }\n\n if (fieldName) {\n targetSet.add(fieldName);\n\n if (\n babelTypes.isObjectProperty(property) &&\n babelTypes.isIdentifier(property.value)\n ) {\n const variableBinding = initPath.scope.getBinding(\n property.value.name\n );\n if (variableBinding) {\n for (const refPath of variableBinding.referencePaths) {\n analyzeOpaqueUsage(refPath, fieldName);\n }\n }\n }\n }\n }\n return true;\n };\n\n // ── Pattern 1: const { fieldA, fieldB } = useIntlayer('key') ──────────────\n if (\n babelTypes.isVariableDeclarator(parentNode) &&\n babelTypes.isObjectPattern(parentNode.id)\n ) {\n const accessedFieldNames = new Set<string>();\n if (\n collectFieldsFromObjectPattern(\n parentNode.id,\n callExpressionPath,\n accessedFieldNames\n )\n ) {\n recordFieldUsage(pruneContext, dictionaryKey, accessedFieldNames);\n } else {\n recordFieldUsage(pruneContext, dictionaryKey, 'all');\n }\n return;\n }\n\n // ── Pattern 2: useIntlayer('key').fieldA / useIntlayer('key')?.fieldA ──────\n if (\n (babelTypes.isMemberExpression(parentNode) ||\n babelTypes.isOptionalMemberExpression(parentNode)) &&\n (parentNode as BabelTypes.MemberExpression).object ===\n callExpressionPath.node\n ) {\n let fieldName: string | undefined;\n\n if (!parentNode.computed && babelTypes.isIdentifier(parentNode.property)) {\n fieldName = parentNode.property.name;\n } else if (\n parentNode.computed &&\n babelTypes.isStringLiteral(parentNode.property)\n ) {\n fieldName = parentNode.property.value;\n }\n\n if (fieldName) {\n recordFieldUsage(pruneContext, dictionaryKey, new Set([fieldName]));\n\n // Check for opaque usage (e.g. passed directly to a prop)\n const memberExprPath = callExpressionPath.parentPath;\n if (memberExprPath) {\n analyzeOpaqueUsage(memberExprPath, fieldName);\n }\n } else {\n markUntrackedBinding();\n }\n return;\n }\n\n // ── Pattern 3: const content = useIntlayer('key') ─────────────────────────\n if (\n babelTypes.isVariableDeclarator(parentNode) &&\n babelTypes.isIdentifier(parentNode.id)\n ) {\n const variableName = parentNode.id.name;\n const variableBinding = callExpressionPath.scope.getBinding(variableName);\n\n if (!variableBinding) {\n markUntrackedBinding();\n return;\n }\n\n const accessedTopLevelFieldNames = new Set<string>();\n let hasUntrackedReferenceAccess = false;\n\n for (const variableReferencePath of variableBinding.referencePaths) {\n const referenceParentNode = variableReferencePath.parent;\n\n if (\n (babelTypes.isMemberExpression(referenceParentNode) ||\n babelTypes.isOptionalMemberExpression(referenceParentNode)) &&\n (referenceParentNode as BabelTypes.MemberExpression).object ===\n variableReferencePath.node\n ) {\n const memberExpressionNode =\n referenceParentNode as BabelTypes.MemberExpression;\n let fieldName: string | undefined;\n\n if (\n !memberExpressionNode.computed &&\n babelTypes.isIdentifier(memberExpressionNode.property)\n ) {\n fieldName = memberExpressionNode.property.name;\n } else if (\n memberExpressionNode.computed &&\n babelTypes.isStringLiteral(memberExpressionNode.property)\n ) {\n fieldName = memberExpressionNode.property.value;\n }\n\n if (fieldName) {\n accessedTopLevelFieldNames.add(fieldName);\n\n // Check usage of the field to look for opaque consumption\n const memberExprPath = variableReferencePath.parentPath;\n if (memberExprPath) {\n analyzeOpaqueUsage(memberExprPath, fieldName);\n }\n } else {\n // Dynamic computed access – cannot resolve statically\n hasUntrackedReferenceAccess = true;\n break;\n }\n } else if (babelTypes.isArrayExpression(referenceParentNode)) {\n // Ignore array literals (e.g. [content]) – uncommon but benign\n } else if (\n // Solid / Angular: content() signal accessor → content().field\n (babelTypes.isCallExpression(referenceParentNode) ||\n babelTypes.isOptionalCallExpression(referenceParentNode)) &&\n (referenceParentNode as BabelTypes.CallExpression).callee ===\n variableReferencePath.node\n ) {\n const callExprPath = variableReferencePath.parentPath;\n const callParent = callExprPath?.parent;\n\n if (\n callParent &&\n (babelTypes.isMemberExpression(callParent) ||\n babelTypes.isOptionalMemberExpression(callParent)) &&\n (callParent as BabelTypes.MemberExpression).object ===\n callExprPath?.node\n ) {\n // content().field\n const memberExpr = callParent as BabelTypes.MemberExpression;\n let fieldName: string | undefined;\n\n if (\n !memberExpr.computed &&\n babelTypes.isIdentifier(memberExpr.property)\n ) {\n fieldName = memberExpr.property.name;\n } else if (\n memberExpr.computed &&\n babelTypes.isStringLiteral(memberExpr.property)\n ) {\n fieldName = memberExpr.property.value;\n }\n\n if (fieldName) {\n accessedTopLevelFieldNames.add(fieldName);\n const memberExprPath = callExprPath?.parentPath;\n if (memberExprPath) analyzeOpaqueUsage(memberExprPath, fieldName);\n } else {\n // content()[dynamicKey] – cannot resolve statically\n hasUntrackedReferenceAccess = true;\n break;\n }\n } else if (\n callParent &&\n babelTypes.isVariableDeclarator(callParent) &&\n babelTypes.isObjectPattern(callParent.id) &&\n callExprPath &&\n collectFieldsFromObjectPattern(\n callParent.id,\n callExprPath,\n accessedTopLevelFieldNames\n )\n ) {\n // const { title } = content()\n // fields already added to accessedTopLevelFieldNames by collectFieldsFromObjectPattern\n } else {\n // content() with no field access or passed opaquely → cannot prune\n hasUntrackedReferenceAccess = true;\n break;\n }\n } else {\n // Variable used in a non-member-access context (spread, function arg, etc.)\n hasUntrackedReferenceAccess = true;\n break;\n }\n }\n\n if (hasUntrackedReferenceAccess) {\n markUntrackedBinding();\n } else if (isSfcFile) {\n // Vue / Svelte SFC: defer to the framework-specific extractor because\n // Babel scope analysis cannot see through `.value` or `$` indirection.\n deferFrameworkAnalysis(variableName);\n } else if (variableBinding.referencePaths.length === 0) {\n // Non-SFC file with no visible references – conservatively keep all fields.\n markUntrackedBinding();\n } else {\n recordFieldUsage(pruneContext, dictionaryKey, accessedTopLevelFieldNames);\n }\n return;\n }\n\n // ── Pattern 4: bare call – result is discarded ─────────────────────────────\n if (babelTypes.isExpressionStatement(parentNode)) {\n return; // no usage to record\n }\n\n // ── Fallback: result passed as argument, used in ternary, etc. ─────────────\n markUntrackedBinding();\n};\n\n// ── Compat namespace-caller analysis ──────────────────────────────────────────\n\n/**\n * Reads a fully-static string from an AST node. Returns `undefined` for\n * dynamic values (identifiers, expressions, template literals with\n * interpolations, …).\n */\nconst readStaticString = (\n babelTypes: typeof BabelTypes,\n node: BabelTypes.Node | null | undefined\n): string | undefined => {\n if (!node) return undefined;\n if (babelTypes.isStringLiteral(node)) return node.value;\n if (\n babelTypes.isTemplateLiteral(node) &&\n node.expressions.length === 0 &&\n node.quasis.length === 1\n ) {\n return node.quasis[0]?.value.cooked ?? node.quasis[0]?.value.raw;\n }\n return undefined;\n};\n\n/** Returns the first dot-path segment of a key, e.g. `'a.b.c'` → `'a'`. */\nconst firstPathSegment = (path: string): string => path.split('.')[0] ?? path;\n\n/**\n * Reads the static first dot-path segment from a `t()` first-argument node.\n *\n * t('counter.label') → 'counter'\n * t(`counter.${x}`) → 'counter' (static prefix before the first dot)\n * t(`${x}.label`) → undefined (dynamic first segment)\n * t(someVariable) → undefined\n */\nconst readStaticFirstSegment = (\n babelTypes: typeof BabelTypes,\n node: BabelTypes.Node | null | undefined\n): string | undefined => {\n const staticString = readStaticString(babelTypes, node);\n if (staticString !== undefined) return firstPathSegment(staticString);\n\n // Template literal whose first quasi already contains the dot delimiter, e.g.\n // `counter.${index}` → the leading `counter` segment is statically known.\n if (babelTypes.isTemplateLiteral(node) && node.quasis.length > 0) {\n const firstQuasi =\n node.quasis[0]?.value.cooked ?? node.quasis[0]?.value.raw;\n if (firstQuasi?.includes('.')) {\n return firstPathSegment(firstQuasi);\n }\n }\n return undefined;\n};\n\n/**\n * Reads a static string property from an object expression. Returns\n * `'__default__'` when the property is absent and `undefined` when present but\n * dynamic.\n */\nconst readObjectProperty = (\n babelTypes: typeof BabelTypes,\n objectExpression: BabelTypes.ObjectExpression,\n propertyName: string\n): string | '__default__' | undefined => {\n for (const property of objectExpression.properties) {\n if (!babelTypes.isObjectProperty(property)) continue;\n const keyMatches =\n (babelTypes.isIdentifier(property.key) &&\n property.key.name === propertyName) ||\n (babelTypes.isStringLiteral(property.key) &&\n property.key.value === propertyName);\n if (!keyMatches) continue;\n const staticValue = readStaticString(babelTypes, property.value);\n return staticValue ?? undefined; // present but dynamic → undefined\n }\n return '__default__'; // property absent\n};\n\n/**\n * Resolves the namespace (dictionary key) for a compat caller call-site from\n * its `CompatNamespaceSource` configuration. Returns the static key, or\n * `'__default__'` when the configured argument is absent (caller falls back to\n * its default namespace), or `undefined` when the value is present but dynamic.\n */\nconst resolveCompatNamespace = (\n babelTypes: typeof BabelTypes,\n callArguments: BabelTypes.CallExpression['arguments'],\n source: CompatNamespaceSource\n): string | '__default__' | undefined => {\n if (source.from === 'argument') {\n const argument = callArguments[source.index];\n if (argument === undefined) return '__default__';\n\n // Direct string namespace: useTranslations('about')\n const staticString = readStaticString(babelTypes, argument);\n if (staticString !== undefined) return staticString;\n\n // Object form: getTranslations({ locale, namespace: 'about' })\n if (babelTypes.isObjectExpression(argument)) {\n return readObjectProperty(babelTypes, argument, 'namespace');\n }\n return undefined; // present but dynamic\n }\n\n // from === 'option'\n const optionsArgument = callArguments[source.argumentIndex];\n if (optionsArgument === undefined) return '__default__';\n if (!babelTypes.isObjectExpression(optionsArgument)) return undefined;\n return readObjectProperty(babelTypes, optionsArgument, source.property);\n};\n\n/**\n * Resolves an optional `keyPrefix` for a compat caller. Returns the static\n * prefix string, `null` when no prefix is configured/present, or `undefined`\n * when a prefix is present but dynamic.\n */\nconst resolveCompatKeyPrefix = (\n babelTypes: typeof BabelTypes,\n callArguments: BabelTypes.CallExpression['arguments'],\n source: CompatNamespaceSource | undefined\n): string | null | undefined => {\n if (!source) return null;\n const resolved = resolveCompatNamespace(babelTypes, callArguments, source);\n if (resolved === '__default__') return null; // prefix absent\n return resolved; // string or undefined (dynamic)\n};\n\n/**\n * Climbs past an enclosing `await` expression so that\n * `const t = await getTranslations('ns')` is resolved to its variable\n * declarator the same way the synchronous form is.\n */\nconst unwrapAwait = (\n babelTypes: typeof BabelTypes,\n path: NodePath<BabelTypes.Node>\n): NodePath<BabelTypes.Node> => {\n const parentPath = path.parentPath;\n if (parentPath && babelTypes.isAwaitExpression(parentPath.node)) {\n return parentPath;\n }\n return path;\n};\n\n/**\n * Analyses how the translation function produced by a compat namespace caller\n * (`useTranslation`, `useTranslations`, `getTranslations`, `getFixedT`,\n * `useI18n`) is consumed, then records the accessed top-level dictionary fields\n * into `pruneContext`.\n *\n * Dictionaries consumed this way are always added to\n * `dictionariesSkippingFieldRename`: the field accesses are string-literal\n * dot-paths inside `t()` calls, which the field-rename plugin cannot rewrite,\n * so renaming the compiled JSON keys would break runtime lookups. Pruning\n * (top-level field removal) remains safe because it preserves field names.\n */\nconst analyzeNamespaceCallerUsage = (\n babelTypes: typeof BabelTypes,\n pruneContext: PruneContext,\n callExpressionPath: NodePath<BabelTypes.CallExpression>,\n callerConfig: CompatCallerConfig,\n isSfcFile: boolean\n): void => {\n const callArguments = callExpressionPath.node.arguments;\n\n // 1. Resolve the dictionary key (namespace).\n const resolvedNamespace = resolveCompatNamespace(\n babelTypes,\n callArguments,\n callerConfig.namespace\n );\n if (resolvedNamespace === undefined) return; // dynamic key – cannot attribute\n const namespaceString =\n resolvedNamespace === '__default__'\n ? DEFAULT_COMPAT_NAMESPACE\n : resolvedNamespace;\n\n // next-intl scopes nested objects through a dotted namespace\n // (`'about.counter'`): the dictionary key is the first segment and the\n // remainder is an implicit key prefix applied to every t() lookup.\n const namespaceSegments = namespaceString.split('.');\n const dictionaryKey = namespaceSegments[0] ?? namespaceString;\n const namespacePrefix =\n namespaceSegments.length > 1 ? namespaceSegments.slice(1).join('.') : null;\n\n // Compat string-path access is never renamable.\n pruneContext.dictionariesSkippingFieldRename.add(dictionaryKey);\n\n // 2. SFC files (Vue / Svelte / Astro): the translation function is typically\n // invoked from the template, which Babel cannot see. Conservatively keep\n // every field to avoid pruning a template-only access.\n if (isSfcFile) {\n recordFieldUsage(pruneContext, dictionaryKey, 'all');\n return;\n }\n\n // 3. Resolve an optional explicit keyPrefix (e.g. react-i18next's\n // `{ keyPrefix }` option). A static prefix fixes the single consumed\n // top-level field regardless of the individual t() paths.\n const explicitKeyPrefix = resolveCompatKeyPrefix(\n babelTypes,\n callArguments,\n callerConfig.keyPrefix\n );\n if (explicitKeyPrefix === undefined) {\n // Prefix present but dynamic → unknown field set.\n recordFieldUsage(pruneContext, dictionaryKey, 'all');\n return;\n }\n\n // The namespace-derived prefix (next-intl) and the explicit keyPrefix option\n // (react-i18next / i18next) never coexist in practice; prefer whichever is\n // present. Either way, the consumed top-level field is the prefix's first\n // segment.\n const effectivePrefix = namespacePrefix ?? explicitKeyPrefix;\n if (effectivePrefix !== null) {\n recordFieldUsage(\n pruneContext,\n dictionaryKey,\n new Set([firstPathSegment(effectivePrefix)])\n );\n return;\n }\n\n // 4. Locate the `t` function binding.\n let translationBinding: ReturnType<NodePath['scope']['getBinding']> | null =\n null;\n\n if (callerConfig.translationFunction === 'destructured-t') {\n // const { t } = useTranslation('ns')\n const parentNode = callExpressionPath.parent;\n if (\n babelTypes.isVariableDeclarator(parentNode) &&\n babelTypes.isObjectPattern(parentNode.id)\n ) {\n for (const property of parentNode.id.properties) {\n if (\n babelTypes.isObjectProperty(property) &&\n babelTypes.isIdentifier(property.key) &&\n property.key.name === 't' &&\n babelTypes.isIdentifier(property.value)\n ) {\n translationBinding =\n callExpressionPath.scope.getBinding(property.value.name) ?? null;\n }\n }\n }\n } else {\n // const t = useTranslations('ns') / const t = await getTranslations('ns')\n const resultPath = unwrapAwait(babelTypes, callExpressionPath);\n const parentNode = resultPath.parent;\n if (\n babelTypes.isVariableDeclarator(parentNode) &&\n babelTypes.isIdentifier(parentNode.id)\n ) {\n translationBinding =\n callExpressionPath.scope.getBinding(parentNode.id.name) ?? null;\n }\n }\n\n // Could not statically locate `t` (e.g. result stored whole, re-exported) →\n // conservatively keep all fields.\n if (!translationBinding) {\n recordFieldUsage(pruneContext, dictionaryKey, 'all');\n return;\n }\n\n // 5. Inspect every reference to `t`.\n const accessedFields = new Set<string>();\n let hasUntrackedUsage = false;\n\n for (const referencePath of translationBinding.referencePaths) {\n const parentNode = referencePath.parent;\n\n // Must be a direct call: t('path')\n const isDirectCall =\n (babelTypes.isCallExpression(parentNode) ||\n babelTypes.isOptionalCallExpression(parentNode)) &&\n (parentNode as BabelTypes.CallExpression).callee === referencePath.node;\n\n if (!isDirectCall) {\n // t passed as a prop / argument / reassigned → fields unknown.\n hasUntrackedUsage = true;\n break;\n }\n\n const firstArgument = (parentNode as BabelTypes.CallExpression)\n .arguments[0];\n const segment = readStaticFirstSegment(babelTypes, firstArgument);\n if (segment === undefined) {\n hasUntrackedUsage = true;\n break;\n }\n accessedFields.add(segment);\n }\n\n if (hasUntrackedUsage) {\n recordFieldUsage(pruneContext, dictionaryKey, 'all');\n return;\n }\n\n // Only record a finite field set when at least one field was actually\n // accessed. Recording an empty set would prune every field even though the\n // dictionary may be consumed elsewhere.\n if (accessedFields.size > 0) {\n recordFieldUsage(pruneContext, dictionaryKey, accessedFields);\n }\n};\n\n/**\n * Creates a Babel plugin that traverses source files and records which\n * top-level dictionary fields each `useIntlayer` / `getIntlayer` call-site —\n * and each configured compat namespace caller — accesses. Results are\n * accumulated into `pruneContext`.\n *\n * This plugin is analysis-only: it does not transform the code (`code: false`\n * should be passed to `transformAsync` when using it).\n *\n * @param pruneContext - Shared mutable state written by this plugin.\n * @param options - Optional overrides. `compatCallers` defaults to\n * {@link DEFAULT_COMPAT_CALLERS}; pass `[]` to disable\n * compat-adapter analysis entirely.\n */\nexport const makeUsageAnalyzerBabelPlugin =\n (\n pruneContext: PruneContext,\n options?: { compatCallers?: CompatCallerConfig[] }\n ) =>\n ({ types: babelTypes }: { types: typeof BabelTypes }): PluginObj => {\n const compatCallers = options?.compatCallers ?? DEFAULT_COMPAT_CALLERS;\n\n return {\n name: 'intlayer-usage-analyzer',\n visitor: {\n Program: {\n exit: (programPath, state: PluginPass) => {\n const currentSourceFilePath =\n state.file.opts.filename ?? 'unknown file';\n const isSfcFile =\n currentSourceFilePath.endsWith('.vue') ||\n currentSourceFilePath.endsWith('.svelte') ||\n currentSourceFilePath.endsWith('.astro');\n\n // Phase 1: collect local aliases for native intlayer callers and\n // for compat namespace callers (gated by import source).\n const intlayerCallerLocalNameMap = new Map<string, string>();\n const compatCallerLocalNameMap = new Map<\n string,\n CompatCallerConfig\n >();\n\n // Method-matched compat callers (e.g. i18next `getFixedT`) need no\n // import and are recognised by method name on any object.\n const methodCompatCallers = compatCallers.filter(\n (caller) => caller.matchAsMethod\n );\n\n programPath.traverse({\n ImportDeclaration: (importDeclarationPath) => {\n const importSource = importDeclarationPath.node.source.value;\n\n for (const importSpecifier of importDeclarationPath.node\n .specifiers) {\n if (!babelTypes.isImportSpecifier(importSpecifier)) continue;\n\n const importedName = babelTypes.isIdentifier(\n importSpecifier.imported\n )\n ? importSpecifier.imported.name\n : (importSpecifier.imported as BabelTypes.StringLiteral)\n .value;\n\n if (\n INTLAYER_CALLER_NAMES.includes(\n importedName as IntlayerCallerName\n )\n ) {\n intlayerCallerLocalNameMap.set(\n importSpecifier.local.name,\n importedName\n );\n continue;\n }\n\n const compatCaller = compatCallers.find(\n (caller) =>\n caller.callerName === importedName &&\n caller.importSources.includes(importSource)\n );\n if (compatCaller) {\n compatCallerLocalNameMap.set(\n importSpecifier.local.name,\n compatCaller\n );\n }\n }\n },\n });\n\n const hasNativeCallers = intlayerCallerLocalNameMap.size > 0;\n const hasCompatCallers =\n compatCallerLocalNameMap.size > 0 ||\n methodCompatCallers.length > 0;\n\n if (!hasNativeCallers && !hasCompatCallers) return;\n\n // Phase 2: analyse each call-site\n programPath.traverse({\n CallExpression: (callExpressionPath) => {\n const calleeNode = callExpressionPath.node.callee;\n let localCallerName: string | undefined;\n let isMethodCall = false;\n\n if (babelTypes.isIdentifier(calleeNode)) {\n localCallerName = calleeNode.name;\n } else if (\n babelTypes.isMemberExpression(calleeNode) &&\n babelTypes.isIdentifier(calleeNode.property)\n ) {\n localCallerName = calleeNode.property.name;\n isMethodCall = true;\n }\n\n if (!localCallerName) return;\n\n // Native intlayer caller (useIntlayer / getIntlayer)\n if (intlayerCallerLocalNameMap.has(localCallerName)) {\n const callArguments = callExpressionPath.node.arguments;\n if (callArguments.length === 0) return;\n\n const dictionaryKey = readStaticString(\n babelTypes,\n callArguments[0]\n );\n if (!dictionaryKey) return; // dynamic key\n\n analyzeCallExpressionUsage(\n babelTypes,\n pruneContext,\n callExpressionPath,\n dictionaryKey,\n currentSourceFilePath,\n isSfcFile\n );\n return;\n }\n\n // Compat namespace caller (imported)\n const importedCompatCaller =\n compatCallerLocalNameMap.get(localCallerName);\n if (importedCompatCaller && !isMethodCall) {\n analyzeNamespaceCallerUsage(\n babelTypes,\n pruneContext,\n callExpressionPath,\n importedCompatCaller,\n isSfcFile\n );\n return;\n }\n\n // Compat namespace caller (method-matched, e.g. getFixedT)\n if (isMethodCall) {\n const methodCaller = methodCompatCallers.find(\n (caller) => caller.callerName === localCallerName\n );\n if (methodCaller) {\n analyzeNamespaceCallerUsage(\n babelTypes,\n pruneContext,\n callExpressionPath,\n methodCaller,\n isSfcFile\n );\n }\n }\n },\n });\n },\n },\n },\n };\n };\n"],"mappings":";;;AA+GA,MAAa,4BAA0C;CACrD,8CAA8B,IAAI,IAAI;CACtC,2CAA2B,IAAI,IAAI;CACnC,0BAA0B;CAC1B,qDAAqC,IAAI,IAAI;CAC7C,+CAA+B,IAAI,IAAI;CACvC,wDAAwC,IAAI,IAG1C;CACF,iDAAiC,IAAI,IAAI;CACzC,0CAA0B,IAAI,IAAI;AACpC;;AAKA,MAAa,wBAAwB,CAAC,eAAe,aAAa;;;;;AAkElE,MAAa,yBAA+C;CAE1D;EACE,YAAY;EACZ,eAAe;GACb;GACA;GACA;GACA;EACF;EACA,WAAW;GAAE,MAAM;GAAY,OAAO;EAAE;EACxC,WAAW;GAAE,MAAM;GAAU,eAAe;GAAG,UAAU;EAAY;EACrE,qBAAqB;CACvB;CAEA;EACE,YAAY;EACZ,eAAe,CAAC,aAAa,qBAAqB;EAClD,WAAW;GAAE,MAAM;GAAY,OAAO;EAAE;EACxC,qBAAqB;CACvB;CAEA;EACE,YAAY;EACZ,eAAe;GACb;GACA;GACA;GACA;EACF;EACA,WAAW;GAAE,MAAM;GAAY,OAAO;EAAE;EACxC,qBAAqB;CACvB;CAEA;EACE,YAAY;EACZ,eAAe,CAAC,WAAW,mBAAmB;EAC9C,eAAe;EACf,WAAW;GAAE,MAAM;GAAY,OAAO;EAAE;EACxC,WAAW;GAAE,MAAM;GAAY,OAAO;EAAE;EACxC,qBAAqB;CACvB;CAEA;EACE,YAAY;EACZ,eAAe,C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AM,gBAAgB,mBAAmB,KAAK;KAC9C,IAAI,cAAc,WAAW,GAAG;KAEhC,MAAM,gBAAgB,iBACpB,YACA,cAAc,EAChB;KACA,IAAI,CAAC,eAAe;KAEpB,2BACE,YACA,cACA,oBACA,eACA,uBACA,SACF;KACA;IACF;IAGA,MAAM,uBACJ,yBAAyB,IAAI,eAAe;IAC9C,IAAI,wBAAwB,CAAC,cAAc;KACzC,4BACE,YACA,cACA,oBACA,sBACA,SACF;KACA;IACF;IAGA,IAAI,cAAc;KAChB,MAAM,eAAe,oBAAoB,MACtC,WAAW,OAAO,eAAe,eACpC;KACA,IAAI,cACF,4BACE,YACA,cACA,oBACA,cACA,SACF;IAEJ;GACF,EACF,CAAC;EACH,EACF,EACF;CACF;AACF"}
@@ -18,7 +18,10 @@ const require_transformers = require('./transformers.cjs');
18
18
 
19
19
  exports.ATTRIBUTES_TO_EXTRACT = require_extractContent_utils_constants.ATTRIBUTES_TO_EXTRACT;
20
20
  exports.BABEL_PARSER_OPTIONS = require_transformers.BABEL_PARSER_OPTIONS;
21
+ exports.COMPAT_USAGE_REGEX = require_transformers.COMPAT_USAGE_REGEX;
22
+ exports.DEFAULT_COMPAT_CALLERS = require_babel_plugin_intlayer_usage_analyzer.DEFAULT_COMPAT_CALLERS;
21
23
  exports.INTLAYER_CALLER_NAMES = require_babel_plugin_intlayer_usage_analyzer.INTLAYER_CALLER_NAMES;
24
+ exports.INTLAYER_OR_COMPAT_USAGE_REGEX = require_transformers.INTLAYER_OR_COMPAT_USAGE_REGEX;
22
25
  exports.INTLAYER_USAGE_REGEX = require_transformers.INTLAYER_USAGE_REGEX;
23
26
  exports.SERVER_CAPABLE_PACKAGES = require_extractContent_utils_constants.SERVER_CAPABLE_PACKAGES;
24
27
  exports.SOURCE_FILE_REGEX = require_transformers.SOURCE_FILE_REGEX;
@@ -29,11 +29,23 @@ const BABEL_PARSER_OPTIONS = {
29
29
  ]
30
30
  };
31
31
  /**
32
- * Fast pre-check: matches files that could contain intlayer calls.
33
- * Avoids running Babel on files with no relevant identifiers.
32
+ * Fast pre-check: matches files that could contain native intlayer calls
33
+ * (`useIntlayer` / `getIntlayer`). Used by the optimize/transform pass, which
34
+ * only rewrites native calls.
34
35
  */
35
36
  const INTLAYER_USAGE_REGEX = /\b(use|get)Intlayer\b/;
36
37
  /**
38
+ * Fast pre-check: matches files that could contain compat-adapter namespace
39
+ * callers (`useTranslation`, `useTranslations`, `getTranslations`, `getFixedT`,
40
+ * `useI18n`). These are analysed for field usage (pruning) but never rewritten.
41
+ */
42
+ const COMPAT_USAGE_REGEX = /\b(useTranslation|useTranslations|getTranslations|getFixedT|useI18n)\b/;
43
+ /**
44
+ * Fast pre-check for the usage-analysis phase: matches files containing either
45
+ * native intlayer calls or compat-adapter namespace callers.
46
+ */
47
+ const INTLAYER_OR_COMPAT_USAGE_REGEX = /\b(useIntlayer|getIntlayer|useTranslation|useTranslations|getTranslations|getFixedT|useI18n)\b/;
48
+ /**
37
49
  * Matches source files that are valid targets for usage analysis and Babel
38
50
  * transformation. Excludes sourcemap files, declaration files, and other
39
51
  * non-source extensions.
@@ -45,10 +57,10 @@ const SOURCE_FILE_REGEX = /\.(tsx?|[mc]?jsx?|vue|svelte|astro)$/;
45
57
  * This is analysis-only: the transformed code output is discarded.
46
58
  * Throws if Babel cannot parse the content.
47
59
  */
48
- const analyzeScriptContent = async (scriptContent, sourceFilePath, pruneContext) => {
60
+ const analyzeScriptContent = async (scriptContent, sourceFilePath, pruneContext, compatCallers) => {
49
61
  await (0, _babel_core.transformAsync)(scriptContent, {
50
62
  filename: sourceFilePath,
51
- plugins: [require_babel_plugin_intlayer_usage_analyzer.makeUsageAnalyzerBabelPlugin(pruneContext)],
63
+ plugins: [require_babel_plugin_intlayer_usage_analyzer.makeUsageAnalyzerBabelPlugin(pruneContext, { compatCallers })],
52
64
  parserOpts: BABEL_PARSER_OPTIONS,
53
65
  ast: false,
54
66
  code: false
@@ -66,11 +78,11 @@ const analyzeScriptContent = async (scriptContent, sourceFilePath, pruneContext)
66
78
  * Throws if Babel cannot parse the file (caller should handle and flag
67
79
  * `pruneContext.hasUnparsableSourceFiles`).
68
80
  */
69
- const analyzeFieldUsageInFile = async (sourceFilePath, code, pruneContext) => {
81
+ const analyzeFieldUsageInFile = async (sourceFilePath, code, pruneContext, compatCallers) => {
70
82
  const scriptBlocks = require_extractScriptBlocks.extractScriptBlocks(sourceFilePath, code);
71
83
  for (const block of scriptBlocks) {
72
- if (!INTLAYER_USAGE_REGEX.test(block.content)) continue;
73
- await analyzeScriptContent(block.content, sourceFilePath, pruneContext);
84
+ if (!INTLAYER_OR_COMPAT_USAGE_REGEX.test(block.content)) continue;
85
+ await analyzeScriptContent(block.content, sourceFilePath, pruneContext, compatCallers);
74
86
  }
75
87
  };
76
88
  /**
@@ -140,6 +152,8 @@ const optimizeSourceFile = async (code, sourceFilePath, options) => {
140
152
 
141
153
  //#endregion
142
154
  exports.BABEL_PARSER_OPTIONS = BABEL_PARSER_OPTIONS;
155
+ exports.COMPAT_USAGE_REGEX = COMPAT_USAGE_REGEX;
156
+ exports.INTLAYER_OR_COMPAT_USAGE_REGEX = INTLAYER_OR_COMPAT_USAGE_REGEX;
143
157
  exports.INTLAYER_USAGE_REGEX = INTLAYER_USAGE_REGEX;
144
158
  exports.SOURCE_FILE_REGEX = SOURCE_FILE_REGEX;
145
159
  exports.analyzeFieldUsageInFile = analyzeFieldUsageInFile;