@intlayer/babel 8.4.4 → 8.4.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (139) hide show
  1. package/dist/cjs/_virtual/_rolldown/runtime.cjs +29 -0
  2. package/dist/cjs/babel-plugin-intlayer-extract.cjs +75 -1
  3. package/dist/cjs/babel-plugin-intlayer-extract.cjs.map +1 -1
  4. package/dist/cjs/babel-plugin-intlayer-optimize.cjs +306 -1
  5. package/dist/cjs/babel-plugin-intlayer-optimize.cjs.map +1 -1
  6. package/dist/cjs/extractContent/babelProcessor.cjs +261 -1
  7. package/dist/cjs/extractContent/babelProcessor.cjs.map +1 -1
  8. package/dist/cjs/extractContent/contentWriter.cjs +134 -1
  9. package/dist/cjs/extractContent/contentWriter.cjs.map +1 -1
  10. package/dist/cjs/extractContent/extractContent.cjs +184 -1
  11. package/dist/cjs/extractContent/extractContent.cjs.map +1 -1
  12. package/dist/cjs/extractContent/index.cjs +26 -1
  13. package/dist/cjs/extractContent/processTsxFile.cjs +263 -5
  14. package/dist/cjs/extractContent/processTsxFile.cjs.map +1 -1
  15. package/dist/cjs/extractContent/utils/constants.cjs +42 -1
  16. package/dist/cjs/extractContent/utils/constants.cjs.map +1 -1
  17. package/dist/cjs/extractContent/utils/detectPackageName.cjs +26 -1
  18. package/dist/cjs/extractContent/utils/detectPackageName.cjs.map +1 -1
  19. package/dist/cjs/extractContent/utils/extractDictionaryInfo.cjs +103 -1
  20. package/dist/cjs/extractContent/utils/extractDictionaryInfo.cjs.map +1 -1
  21. package/dist/cjs/extractContent/utils/extractDictionaryKey.cjs +29 -1
  22. package/dist/cjs/extractContent/utils/extractDictionaryKey.cjs.map +1 -1
  23. package/dist/cjs/extractContent/utils/generateKey.cjs +16 -1
  24. package/dist/cjs/extractContent/utils/generateKey.cjs.map +1 -1
  25. package/dist/cjs/extractContent/utils/getComponentName.cjs +18 -1
  26. package/dist/cjs/extractContent/utils/getComponentName.cjs.map +1 -1
  27. package/dist/cjs/extractContent/utils/getExistingIntlayerInfo.cjs +50 -1
  28. package/dist/cjs/extractContent/utils/getExistingIntlayerInfo.cjs.map +1 -1
  29. package/dist/cjs/extractContent/utils/getOrGenerateKey.cjs +19 -1
  30. package/dist/cjs/extractContent/utils/getOrGenerateKey.cjs.map +1 -1
  31. package/dist/cjs/extractContent/utils/index.cjs +27 -1
  32. package/dist/cjs/extractContent/utils/resolveDictionaryKey.cjs +34 -1
  33. package/dist/cjs/extractContent/utils/resolveDictionaryKey.cjs.map +1 -1
  34. package/dist/cjs/extractContent/utils/shouldExtract.cjs +23 -1
  35. package/dist/cjs/extractContent/utils/shouldExtract.cjs.map +1 -1
  36. package/dist/cjs/getExtractPluginOptions.cjs +41 -1
  37. package/dist/cjs/getExtractPluginOptions.cjs.map +1 -1
  38. package/dist/cjs/getOptimizePluginOptions.cjs +63 -1
  39. package/dist/cjs/getOptimizePluginOptions.cjs.map +1 -1
  40. package/dist/cjs/index.cjs +34 -1
  41. package/dist/esm/_virtual/_rolldown/runtime.mjs +8 -0
  42. package/dist/esm/babel-plugin-intlayer-extract.mjs +72 -1
  43. package/dist/esm/babel-plugin-intlayer-extract.mjs.map +1 -1
  44. package/dist/esm/babel-plugin-intlayer-optimize.mjs +304 -1
  45. package/dist/esm/babel-plugin-intlayer-optimize.mjs.map +1 -1
  46. package/dist/esm/extractContent/babelProcessor.mjs +255 -1
  47. package/dist/esm/extractContent/babelProcessor.mjs.map +1 -1
  48. package/dist/esm/extractContent/contentWriter.mjs +129 -1
  49. package/dist/esm/extractContent/contentWriter.mjs.map +1 -1
  50. package/dist/esm/extractContent/extractContent.mjs +180 -1
  51. package/dist/esm/extractContent/extractContent.mjs.map +1 -1
  52. package/dist/esm/extractContent/index.mjs +10 -1
  53. package/dist/esm/extractContent/processTsxFile.mjs +259 -5
  54. package/dist/esm/extractContent/processTsxFile.mjs.map +1 -1
  55. package/dist/esm/extractContent/utils/constants.mjs +38 -1
  56. package/dist/esm/extractContent/utils/constants.mjs.map +1 -1
  57. package/dist/esm/extractContent/utils/detectPackageName.mjs +24 -1
  58. package/dist/esm/extractContent/utils/detectPackageName.mjs.map +1 -1
  59. package/dist/esm/extractContent/utils/extractDictionaryInfo.mjs +98 -1
  60. package/dist/esm/extractContent/utils/extractDictionaryInfo.mjs.map +1 -1
  61. package/dist/esm/extractContent/utils/extractDictionaryKey.mjs +26 -1
  62. package/dist/esm/extractContent/utils/extractDictionaryKey.mjs.map +1 -1
  63. package/dist/esm/extractContent/utils/generateKey.mjs +14 -1
  64. package/dist/esm/extractContent/utils/generateKey.mjs.map +1 -1
  65. package/dist/esm/extractContent/utils/getComponentName.mjs +15 -1
  66. package/dist/esm/extractContent/utils/getComponentName.mjs.map +1 -1
  67. package/dist/esm/extractContent/utils/getExistingIntlayerInfo.mjs +47 -1
  68. package/dist/esm/extractContent/utils/getExistingIntlayerInfo.mjs.map +1 -1
  69. package/dist/esm/extractContent/utils/getOrGenerateKey.mjs +18 -1
  70. package/dist/esm/extractContent/utils/getOrGenerateKey.mjs.map +1 -1
  71. package/dist/esm/extractContent/utils/index.mjs +12 -1
  72. package/dist/esm/extractContent/utils/resolveDictionaryKey.mjs +32 -1
  73. package/dist/esm/extractContent/utils/resolveDictionaryKey.mjs.map +1 -1
  74. package/dist/esm/extractContent/utils/shouldExtract.mjs +21 -1
  75. package/dist/esm/extractContent/utils/shouldExtract.mjs.map +1 -1
  76. package/dist/esm/getExtractPluginOptions.mjs +38 -1
  77. package/dist/esm/getExtractPluginOptions.mjs.map +1 -1
  78. package/dist/esm/getOptimizePluginOptions.mjs +63 -1
  79. package/dist/esm/getOptimizePluginOptions.mjs.map +1 -0
  80. package/dist/esm/index.mjs +14 -1
  81. package/dist/types/babel-plugin-intlayer-extract.d.ts +1 -1
  82. package/dist/types/extractContent/contentWriter.d.ts +36 -2
  83. package/dist/types/extractContent/contentWriter.d.ts.map +1 -0
  84. package/dist/types/extractContent/extractContent.d.ts +37 -2
  85. package/dist/types/extractContent/extractContent.d.ts.map +1 -0
  86. package/dist/types/extractContent/index.d.ts +8 -8
  87. package/dist/types/extractContent/processTsxFile.d.ts +1 -1
  88. package/dist/types/extractContent/processTsxFile.d.ts.map +1 -1
  89. package/dist/types/extractContent/utils/constants.d.ts +20 -2
  90. package/dist/types/extractContent/utils/constants.d.ts.map +1 -0
  91. package/dist/types/extractContent/utils/detectPackageName.d.ts +10 -2
  92. package/dist/types/extractContent/utils/detectPackageName.d.ts.map +1 -0
  93. package/dist/types/extractContent/utils/extractDictionaryInfo.d.ts +28 -2
  94. package/dist/types/extractContent/utils/extractDictionaryInfo.d.ts.map +1 -0
  95. package/dist/types/extractContent/utils/extractDictionaryKey.d.ts +11 -2
  96. package/dist/types/extractContent/utils/extractDictionaryKey.d.ts.map +1 -0
  97. package/dist/types/extractContent/utils/generateKey.d.ts +5 -2
  98. package/dist/types/extractContent/utils/generateKey.d.ts.map +1 -0
  99. package/dist/types/extractContent/utils/getComponentName.d.ts +10 -2
  100. package/dist/types/extractContent/utils/getComponentName.d.ts.map +1 -0
  101. package/dist/types/extractContent/utils/getExistingIntlayerInfo.d.ts +19 -2
  102. package/dist/types/extractContent/utils/getExistingIntlayerInfo.d.ts.map +1 -0
  103. package/dist/types/extractContent/utils/getOrGenerateKey.d.ts +8 -2
  104. package/dist/types/extractContent/utils/getOrGenerateKey.d.ts.map +1 -0
  105. package/dist/types/extractContent/utils/index.d.ts +10 -10
  106. package/dist/types/extractContent/utils/resolveDictionaryKey.d.ts +12 -2
  107. package/dist/types/extractContent/utils/resolveDictionaryKey.d.ts.map +1 -0
  108. package/dist/types/extractContent/utils/shouldExtract.d.ts +14 -2
  109. package/dist/types/extractContent/utils/shouldExtract.d.ts.map +1 -0
  110. package/dist/types/index.d.ts +8 -8
  111. package/package.json +9 -9
  112. package/dist/cjs/chunk-Bmb41Sf3.cjs +0 -1
  113. package/dist/esm/getOptimizePluginOptions-BAFPfVq5.mjs +0 -2
  114. package/dist/esm/getOptimizePluginOptions-BAFPfVq5.mjs.map +0 -1
  115. package/dist/types/constants-BLArAqsA.d.ts +0 -20
  116. package/dist/types/constants-BLArAqsA.d.ts.map +0 -1
  117. package/dist/types/contentWriter-I2Ch5yQY.d.ts +0 -36
  118. package/dist/types/contentWriter-I2Ch5yQY.d.ts.map +0 -1
  119. package/dist/types/detectPackageName-C0TfbHa3.d.ts +0 -10
  120. package/dist/types/detectPackageName-C0TfbHa3.d.ts.map +0 -1
  121. package/dist/types/extractContent-AFk68B7L.d.ts +0 -37
  122. package/dist/types/extractContent-AFk68B7L.d.ts.map +0 -1
  123. package/dist/types/extractDictionaryInfo-5GLZsA_I.d.ts +0 -28
  124. package/dist/types/extractDictionaryInfo-5GLZsA_I.d.ts.map +0 -1
  125. package/dist/types/extractDictionaryKey-CHgfwRo6.d.ts +0 -11
  126. package/dist/types/extractDictionaryKey-CHgfwRo6.d.ts.map +0 -1
  127. package/dist/types/generateKey-Cgdh6seq.d.ts +0 -5
  128. package/dist/types/generateKey-Cgdh6seq.d.ts.map +0 -1
  129. package/dist/types/getComponentName-DGlmJa-F.d.ts +0 -10
  130. package/dist/types/getComponentName-DGlmJa-F.d.ts.map +0 -1
  131. package/dist/types/getExistingIntlayerInfo-Cy6Vpcfb.d.ts +0 -19
  132. package/dist/types/getExistingIntlayerInfo-Cy6Vpcfb.d.ts.map +0 -1
  133. package/dist/types/getOrGenerateKey-DtIR0WeU.d.ts +0 -8
  134. package/dist/types/getOrGenerateKey-DtIR0WeU.d.ts.map +0 -1
  135. package/dist/types/index-DK_kKFOF.d.ts +0 -1
  136. package/dist/types/resolveDictionaryKey-CcbieIfX.d.ts +0 -12
  137. package/dist/types/resolveDictionaryKey-CcbieIfX.d.ts.map +0 -1
  138. package/dist/types/shouldExtract-BRaeB9eg.d.ts +0 -14
  139. package/dist/types/shouldExtract-BRaeB9eg.d.ts.map +0 -1
@@ -0,0 +1,29 @@
1
+ //#region \0rolldown/runtime.js
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __copyProps = (to, from, except, desc) => {
9
+ if (from && typeof from === "object" || typeof from === "function") {
10
+ for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
11
+ key = keys[i];
12
+ if (!__hasOwnProp.call(to, key) && key !== except) {
13
+ __defProp(to, key, {
14
+ get: ((k) => from[k]).bind(null, key),
15
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
16
+ });
17
+ }
18
+ }
19
+ }
20
+ return to;
21
+ };
22
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
23
+ value: mod,
24
+ enumerable: true
25
+ }) : target, mod));
26
+
27
+ //#endregion
28
+
29
+ exports.__toESM = __toESM;
@@ -1,2 +1,76 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./chunk-Bmb41Sf3.cjs`),t=require(`./extractContent/utils/detectPackageName.cjs`),n=require(`./extractContent/extractContent.cjs`);let r=require(`@intlayer/config/colors`);r=e.t(r);let i=require(`@intlayer/config/logger`),a=require(`node:path`),o=require(`@babel/parser`);const s=e=>({name:`babel-plugin-intlayer-extract`,visitor:{Program:{enter(e,s){let c=s.opts;if(c.enabled===!1)return;let l=s.file.opts.filename;if(!l||c.filesList&&!c.filesList.includes(l))return;let u=s.file.code??``;if(!u)return;let d=(0,i.getAppLogger)(c.configuration),f=c.packageName??t.detectPackageName(l),{saveComponents:p}=c.configuration.compiler,m=n.extractContentSync(l,f,{configuration:c.configuration,code:u,onExtract:e=>{c.onExtract&&c.onExtract({dictionaryKey:e.key,filePath:l,content:e.content,locale:c.configuration.internationalization.defaultLocale})},declarationOnly:!p});if(!m)return;let{transformedCode:h}=m;if(h)try{let t=(0,o.parse)(h,{sourceType:`module`,plugins:[`jsx`,`typescript`]});e.node.body=t.program.body,e.node.directives=t.program.directives,d(`${(0,i.colorize)(`Compiler:`,r.GREY_DARK)} Extracted content from ${(0,i.colorizePath)((0,a.relative)(c.configuration.system.baseDir,l))}`,{level:`debug`})}catch(e){d([`Failed to parse transformed code for ${(0,i.colorizePath)((0,a.relative)(c.configuration.system.baseDir,l))}:`,e],{level:`error`})}}}}});exports.intlayerExtractBabelPlugin=s;
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
+ const require_runtime = require('./_virtual/_rolldown/runtime.cjs');
3
+ const require_extractContent_utils_detectPackageName = require('./extractContent/utils/detectPackageName.cjs');
4
+ const require_extractContent_extractContent = require('./extractContent/extractContent.cjs');
5
+ let _intlayer_config_colors = require("@intlayer/config/colors");
6
+ _intlayer_config_colors = require_runtime.__toESM(_intlayer_config_colors);
7
+ let _intlayer_config_logger = require("@intlayer/config/logger");
8
+ let node_path = require("node:path");
9
+ let _babel_parser = require("@babel/parser");
10
+
11
+ //#region src/babel-plugin-intlayer-extract.ts
12
+ /**
13
+ * Babel plugin that extracts translatable content from source files and
14
+ * injects Intlayer hooks (`useIntlayer` / `getIntlayer`) automatically.
15
+ *
16
+ * Designed for use with Babel-based build tools such as Next.js and Webpack.
17
+ *
18
+ * @example babel.config.js
19
+ * ```js
20
+ * const { intlayerExtractBabelPlugin, getExtractPluginOptions } = require('@intlayer/babel');
21
+ * module.exports = {
22
+ * presets: ['next/babel'],
23
+ * plugins: [
24
+ * [intlayerExtractBabelPlugin, getExtractPluginOptions()],
25
+ * ],
26
+ * };
27
+ * ```
28
+ */
29
+ const intlayerExtractBabelPlugin = (_babel) => {
30
+ return {
31
+ name: "babel-plugin-intlayer-extract",
32
+ visitor: { Program: { enter(programPath, state) {
33
+ const opts = state.opts;
34
+ if (opts.enabled === false) return;
35
+ const filename = state.file.opts.filename;
36
+ if (!filename) return;
37
+ if (opts.filesList && !opts.filesList.includes(filename)) return;
38
+ const fileCode = state.file.code ?? "";
39
+ if (!fileCode) return;
40
+ const appLogger = (0, _intlayer_config_logger.getAppLogger)(opts.configuration);
41
+ const packageName = opts.packageName ?? require_extractContent_utils_detectPackageName.detectPackageName(filename);
42
+ const { saveComponents } = opts.configuration.compiler;
43
+ const result = require_extractContent_extractContent.extractContentSync(filename, packageName, {
44
+ configuration: opts.configuration,
45
+ code: fileCode,
46
+ onExtract: (extractResult) => {
47
+ if (opts.onExtract) opts.onExtract({
48
+ dictionaryKey: extractResult.key,
49
+ filePath: filename,
50
+ content: extractResult.content,
51
+ locale: opts.configuration.internationalization.defaultLocale
52
+ });
53
+ },
54
+ declarationOnly: !saveComponents
55
+ });
56
+ if (!result) return;
57
+ const { transformedCode: modifiedCode } = result;
58
+ if (!modifiedCode) return;
59
+ try {
60
+ const newAst = (0, _babel_parser.parse)(modifiedCode, {
61
+ sourceType: "module",
62
+ plugins: ["jsx", "typescript"]
63
+ });
64
+ programPath.node.body = newAst.program.body;
65
+ programPath.node.directives = newAst.program.directives;
66
+ appLogger(`${(0, _intlayer_config_logger.colorize)("Compiler:", _intlayer_config_colors.GREY_DARK)} Extracted content from ${(0, _intlayer_config_logger.colorizePath)((0, node_path.relative)(opts.configuration.system.baseDir, filename))}`, { level: "debug" });
67
+ } catch (error) {
68
+ appLogger([`Failed to parse transformed code for ${(0, _intlayer_config_logger.colorizePath)((0, node_path.relative)(opts.configuration.system.baseDir, filename))}:`, error], { level: "error" });
69
+ }
70
+ } } }
71
+ };
72
+ };
73
+
74
+ //#endregion
75
+ exports.intlayerExtractBabelPlugin = intlayerExtractBabelPlugin;
2
76
  //# sourceMappingURL=babel-plugin-intlayer-extract.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"babel-plugin-intlayer-extract.cjs","names":["detectPackageName","extractContentSync","ANSIColors"],"sources":["../../src/babel-plugin-intlayer-extract.ts"],"sourcesContent":["import { relative } from 'node:path';\nimport type { PluginObj, PluginPass } from '@babel/core';\nimport { parse } from '@babel/parser';\nimport type * as BabelTypes from '@babel/types';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport { colorize, colorizePath, getAppLogger } from '@intlayer/config/logger';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { FilePathPattern } from '@intlayer/types/filePathPattern';\nimport { extractContentSync } from './extractContent/extractContent';\nimport type { PackageName } from './extractContent/utils/constants';\nimport { detectPackageName } from './extractContent/utils/detectPackageName';\n\nexport type ExtractResult = {\n dictionaryKey: string;\n filePath: string;\n content: Record<string, string>;\n locale: Locale;\n};\n\nexport type ExtractPluginOptions = {\n packageName?: PackageName;\n filesList: string[];\n enabled: boolean;\n\n shouldExtract?: (text: string) => boolean;\n configuration: IntlayerConfig;\n /**\n * Callback invoked for each extracted dictionary key/content pair.\n * Used by `getExtractPluginOptions` to write dictionaries to disk.\n * May be async — the plugin will fire-and-forget (Babel transforms are sync).\n */\n onExtract?: (result: ExtractResult) => void | Promise<void>;\n /**\n * Defines the output files path.\n */\n output?: FilePathPattern;\n};\n\ntype State = PluginPass & { opts: ExtractPluginOptions };\n\n/**\n * Babel plugin that extracts translatable content from source files and\n * injects Intlayer hooks (`useIntlayer` / `getIntlayer`) automatically.\n *\n * Designed for use with Babel-based build tools such as Next.js and Webpack.\n *\n * @example babel.config.js\n * ```js\n * const { intlayerExtractBabelPlugin, getExtractPluginOptions } = require('@intlayer/babel');\n * module.exports = {\n * presets: ['next/babel'],\n * plugins: [\n * [intlayerExtractBabelPlugin, getExtractPluginOptions()],\n * ],\n * };\n * ```\n */\nexport const intlayerExtractBabelPlugin = (_babel: {\n types: typeof BabelTypes;\n}): PluginObj<State> => {\n return {\n name: 'babel-plugin-intlayer-extract',\n\n visitor: {\n Program: {\n enter(programPath, state) {\n const opts = state.opts;\n\n // Merge plugin options with the unified compiler config\n const isEnabled = opts.enabled;\n\n if (isEnabled === false) return;\n\n const filename = state.file.opts.filename;\n\n if (!filename) return;\n\n if (opts.filesList && !opts.filesList.includes(filename)) return;\n\n const fileCode: string = state.file.code ?? '';\n if (!fileCode) return;\n\n const appLogger = getAppLogger(opts.configuration);\n const packageName = opts.packageName ?? detectPackageName(filename);\n\n const { saveComponents } = opts.configuration.compiler;\n\n const result = extractContentSync(filename, packageName, {\n configuration: opts.configuration,\n code: fileCode,\n onExtract: (extractResult: {\n key: string;\n content: Record<string, string>;\n }) => {\n if (opts.onExtract) {\n opts.onExtract({\n dictionaryKey: extractResult.key,\n filePath: filename,\n content: extractResult.content,\n locale: opts.configuration.internationalization.defaultLocale,\n });\n }\n },\n declarationOnly: !saveComponents,\n });\n\n if (!result) return;\n\n const { transformedCode: modifiedCode } = result;\n\n if (!modifiedCode) return;\n\n // Replace the Babel AST with the transformed code by re-parsing it.\n // This lets Babel serialise the injected hooks/imports through its\n // own code generator, preserving compatibility with other plugins.\n try {\n const newAst = parse(modifiedCode, {\n sourceType: 'module',\n plugins: ['jsx', 'typescript'],\n });\n\n programPath.node.body = newAst.program.body;\n programPath.node.directives = newAst.program.directives;\n\n appLogger(\n `${colorize('Compiler:', ANSIColors.GREY_DARK)} Extracted content from ${colorizePath(relative(opts.configuration.system.baseDir, filename))}`,\n { level: 'debug' }\n );\n } catch (error) {\n appLogger(\n [\n `Failed to parse transformed code for ${colorizePath(relative(opts.configuration.system.baseDir, filename))}:`,\n error,\n ],\n { level: 'error' }\n );\n }\n },\n },\n },\n };\n};\n"],"mappings":"mWA0DA,MAAa,EAA8B,IAGlC,CACL,KAAM,gCAEN,QAAS,CACP,QAAS,CACP,MAAM,EAAa,EAAO,CACxB,IAAM,EAAO,EAAM,KAKnB,GAFkB,EAAK,UAEL,GAAO,OAEzB,IAAM,EAAW,EAAM,KAAK,KAAK,SAIjC,GAFI,CAAC,GAED,EAAK,WAAa,CAAC,EAAK,UAAU,SAAS,EAAS,CAAE,OAE1D,IAAM,EAAmB,EAAM,KAAK,MAAQ,GAC5C,GAAI,CAAC,EAAU,OAEf,IAAM,GAAA,EAAA,EAAA,cAAyB,EAAK,cAAc,CAC5C,EAAc,EAAK,aAAeA,EAAAA,kBAAkB,EAAS,CAE7D,CAAE,kBAAmB,EAAK,cAAc,SAExC,EAASC,EAAAA,mBAAmB,EAAU,EAAa,CACvD,cAAe,EAAK,cACpB,KAAM,EACN,UAAY,GAGN,CACA,EAAK,WACP,EAAK,UAAU,CACb,cAAe,EAAc,IAC7B,SAAU,EACV,QAAS,EAAc,QACvB,OAAQ,EAAK,cAAc,qBAAqB,cACjD,CAAC,EAGN,gBAAiB,CAAC,EACnB,CAAC,CAEF,GAAI,CAAC,EAAQ,OAEb,GAAM,CAAE,gBAAiB,GAAiB,EAErC,KAKL,GAAI,CACF,IAAM,GAAA,EAAA,EAAA,OAAe,EAAc,CACjC,WAAY,SACZ,QAAS,CAAC,MAAO,aAAa,CAC/B,CAAC,CAEF,EAAY,KAAK,KAAO,EAAO,QAAQ,KACvC,EAAY,KAAK,WAAa,EAAO,QAAQ,WAE7C,EACE,IAAA,EAAA,EAAA,UAAY,YAAaC,EAAW,UAAU,CAAC,2BAAA,EAAA,EAAA,eAAA,EAAA,EAAA,UAAgD,EAAK,cAAc,OAAO,QAAS,EAAS,CAAC,GAC5I,CAAE,MAAO,QAAS,CACnB,OACM,EAAO,CACd,EACE,CACE,yCAAA,EAAA,EAAA,eAAA,EAAA,EAAA,UAA8D,EAAK,cAAc,OAAO,QAAS,EAAS,CAAC,CAAC,GAC5G,EACD,CACD,CAAE,MAAO,QAAS,CACnB,GAGN,CACF,CACF"}
1
+ {"version":3,"file":"babel-plugin-intlayer-extract.cjs","names":["detectPackageName","extractContentSync","ANSIColors"],"sources":["../../src/babel-plugin-intlayer-extract.ts"],"sourcesContent":["import { relative } from 'node:path';\nimport type { PluginObj, PluginPass } from '@babel/core';\nimport { parse } from '@babel/parser';\nimport type * as BabelTypes from '@babel/types';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport { colorize, colorizePath, getAppLogger } from '@intlayer/config/logger';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { FilePathPattern } from '@intlayer/types/filePathPattern';\nimport { extractContentSync } from './extractContent/extractContent';\nimport type { PackageName } from './extractContent/utils/constants';\nimport { detectPackageName } from './extractContent/utils/detectPackageName';\n\nexport type ExtractResult = {\n dictionaryKey: string;\n filePath: string;\n content: Record<string, string>;\n locale: Locale;\n};\n\nexport type ExtractPluginOptions = {\n packageName?: PackageName;\n filesList: string[];\n enabled: boolean;\n\n shouldExtract?: (text: string) => boolean;\n configuration: IntlayerConfig;\n /**\n * Callback invoked for each extracted dictionary key/content pair.\n * Used by `getExtractPluginOptions` to write dictionaries to disk.\n * May be async — the plugin will fire-and-forget (Babel transforms are sync).\n */\n onExtract?: (result: ExtractResult) => void | Promise<void>;\n /**\n * Defines the output files path.\n */\n output?: FilePathPattern;\n};\n\ntype State = PluginPass & { opts: ExtractPluginOptions };\n\n/**\n * Babel plugin that extracts translatable content from source files and\n * injects Intlayer hooks (`useIntlayer` / `getIntlayer`) automatically.\n *\n * Designed for use with Babel-based build tools such as Next.js and Webpack.\n *\n * @example babel.config.js\n * ```js\n * const { intlayerExtractBabelPlugin, getExtractPluginOptions } = require('@intlayer/babel');\n * module.exports = {\n * presets: ['next/babel'],\n * plugins: [\n * [intlayerExtractBabelPlugin, getExtractPluginOptions()],\n * ],\n * };\n * ```\n */\nexport const intlayerExtractBabelPlugin = (_babel: {\n types: typeof BabelTypes;\n}): PluginObj<State> => {\n return {\n name: 'babel-plugin-intlayer-extract',\n\n visitor: {\n Program: {\n enter(programPath, state) {\n const opts = state.opts;\n\n // Merge plugin options with the unified compiler config\n const isEnabled = opts.enabled;\n\n if (isEnabled === false) return;\n\n const filename = state.file.opts.filename;\n\n if (!filename) return;\n\n if (opts.filesList && !opts.filesList.includes(filename)) return;\n\n const fileCode: string = state.file.code ?? '';\n if (!fileCode) return;\n\n const appLogger = getAppLogger(opts.configuration);\n const packageName = opts.packageName ?? detectPackageName(filename);\n\n const { saveComponents } = opts.configuration.compiler;\n\n const result = extractContentSync(filename, packageName, {\n configuration: opts.configuration,\n code: fileCode,\n onExtract: (extractResult: {\n key: string;\n content: Record<string, string>;\n }) => {\n if (opts.onExtract) {\n opts.onExtract({\n dictionaryKey: extractResult.key,\n filePath: filename,\n content: extractResult.content,\n locale: opts.configuration.internationalization.defaultLocale,\n });\n }\n },\n declarationOnly: !saveComponents,\n });\n\n if (!result) return;\n\n const { transformedCode: modifiedCode } = result;\n\n if (!modifiedCode) return;\n\n // Replace the Babel AST with the transformed code by re-parsing it.\n // This lets Babel serialise the injected hooks/imports through its\n // own code generator, preserving compatibility with other plugins.\n try {\n const newAst = parse(modifiedCode, {\n sourceType: 'module',\n plugins: ['jsx', 'typescript'],\n });\n\n programPath.node.body = newAst.program.body;\n programPath.node.directives = newAst.program.directives;\n\n appLogger(\n `${colorize('Compiler:', ANSIColors.GREY_DARK)} Extracted content from ${colorizePath(relative(opts.configuration.system.baseDir, filename))}`,\n { level: 'debug' }\n );\n } catch (error) {\n appLogger(\n [\n `Failed to parse transformed code for ${colorizePath(relative(opts.configuration.system.baseDir, filename))}:`,\n error,\n ],\n { level: 'error' }\n );\n }\n },\n },\n },\n };\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0DA,MAAa,8BAA8B,WAEnB;AACtB,QAAO;EACL,MAAM;EAEN,SAAS,EACP,SAAS,EACP,MAAM,aAAa,OAAO;GACxB,MAAM,OAAO,MAAM;AAKnB,OAFkB,KAAK,YAEL,MAAO;GAEzB,MAAM,WAAW,MAAM,KAAK,KAAK;AAEjC,OAAI,CAAC,SAAU;AAEf,OAAI,KAAK,aAAa,CAAC,KAAK,UAAU,SAAS,SAAS,CAAE;GAE1D,MAAM,WAAmB,MAAM,KAAK,QAAQ;AAC5C,OAAI,CAAC,SAAU;GAEf,MAAM,sDAAyB,KAAK,cAAc;GAClD,MAAM,cAAc,KAAK,eAAeA,iEAAkB,SAAS;GAEnE,MAAM,EAAE,mBAAmB,KAAK,cAAc;GAE9C,MAAM,SAASC,yDAAmB,UAAU,aAAa;IACvD,eAAe,KAAK;IACpB,MAAM;IACN,YAAY,kBAGN;AACJ,SAAI,KAAK,UACP,MAAK,UAAU;MACb,eAAe,cAAc;MAC7B,UAAU;MACV,SAAS,cAAc;MACvB,QAAQ,KAAK,cAAc,qBAAqB;MACjD,CAAC;;IAGN,iBAAiB,CAAC;IACnB,CAAC;AAEF,OAAI,CAAC,OAAQ;GAEb,MAAM,EAAE,iBAAiB,iBAAiB;AAE1C,OAAI,CAAC,aAAc;AAKnB,OAAI;IACF,MAAM,kCAAe,cAAc;KACjC,YAAY;KACZ,SAAS,CAAC,OAAO,aAAa;KAC/B,CAAC;AAEF,gBAAY,KAAK,OAAO,OAAO,QAAQ;AACvC,gBAAY,KAAK,aAAa,OAAO,QAAQ;AAE7C,cACE,yCAAY,aAAaC,wBAAW,UAAU,CAAC,4FAAgD,KAAK,cAAc,OAAO,SAAS,SAAS,CAAC,IAC5I,EAAE,OAAO,SAAS,CACnB;YACM,OAAO;AACd,cACE,CACE,0GAA8D,KAAK,cAAc,OAAO,SAAS,SAAS,CAAC,CAAC,IAC5G,MACD,EACD,EAAE,OAAO,SAAS,CACnB;;KAGN,EACF;EACF"}
@@ -1,2 +1,307 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`}),require(`./chunk-Bmb41Sf3.cjs`);let e=require(`@intlayer/chokidar/utils`),t=require(`node:path`),n=require(`@intlayer/config/utils`);const r=[`intlayer`,`@intlayer/core`,`react-intlayer`,`react-intlayer/client`,`react-intlayer/server`,`next-intlayer`,`next-intlayer/client`,`next-intlayer/server`,`svelte-intlayer`,`vue-intlayer`,`angular-intlayer`,`preact-intlayer`,`solid-intlayer`],i=[`useIntlayer`,`getIntlayer`],a=[`react-intlayer`,`react-intlayer/client`,`react-intlayer/server`,`next-intlayer`,`next-intlayer/client`,`next-intlayer/server`,`preact-intlayer`,`vue-intlayer`,`solid-intlayer`,`svelte-intlayer`,`angular-intlayer`],o={getIntlayer:`getDictionary`,useIntlayer:`useDictionary`},s={useIntlayer:`useDictionaryDynamic`},c=(t,n)=>{let r=(0,e.getPathHash)(t);return n.identifier(`_${r}`)},l=(e,r,i,a,o,s)=>{let c=(0,t.join)(r,`${o}.json`);s===`fetch`&&(c=(0,t.join)(a,`${o}.mjs`)),s===`dynamic`&&(c=(0,t.join)(i,`${o}.mjs`));let l=(0,t.relative)((0,t.dirname)(e),c);return l=(0,n.normalizePath)(l),!l.startsWith(`./`)&&!l.startsWith(`../`)&&(l=`./${l}`),l},u=t=>{let{types:n}=t;return{name:`babel-plugin-intlayer-transform`,pre(){if(this._newStaticImports=new Map,this._newDynamicImports=new Map,this._callerMap=new Map,this._isIncluded=!0,this._hasValidImport=!1,this._isDictEntry=!1,this._useDynamicHelpers=!1,this.opts.optimize===!1){this._isIncluded=!1;return}let e=this.file.opts.filename;if(this.opts.filesList&&e&&!this.opts.filesList.includes(e)){this._isIncluded=!1;return}},visitor:{Program:{enter(e,t){let r=t.file.opts.filename;t.opts.replaceDictionaryEntry&&r===t.opts.dictionariesEntryPath&&(t._isDictEntry=!0,e.traverse({ImportDeclaration(e){e.remove()},VariableDeclarator(e){n.isObjectExpression(e.node.init)&&(e.node.init.properties=[])}}))},exit(t,u){if(u._isDictEntry||!u._isIncluded)return;let d=!1;if(t.traverse({CallExpression(e){let t=e.node.callee;if(!n.isIdentifier(t)||u._callerMap?.get(t.name)!==`useIntlayer`)return;let r=e.node.arguments[0],i;if(r&&n.isStringLiteral(r)?i=r.value:r&&n.isTemplateLiteral(r)&&r.expressions.length===0&&r.quasis.length===1&&(i=r.quasis[0].value.cooked??r.quasis[0].value.raw),!i)return;let a=u.opts.dictionaryModeMap?.[i];(a===`dynamic`||a===`fetch`)&&(d=!0)}}),t.traverse({ImportDeclaration(e){let t=e.node.source.value;if(r.includes(t)){u._hasValidImport=!0;for(let r of e.node.specifiers){if(!n.isImportSpecifier(r))continue;let e=n.isIdentifier(r.imported)?r.imported.name:r.imported.value;i.includes(e)&&u._callerMap?.set(r.local.name,e);let c=u.opts.importMode,l=(c===`dynamic`||c===`fetch`||d)&&a.includes(t);l&&(u._useDynamicHelpers=!0);let f;f=l?{...o,...s}:o;let p=f[e];p&&(r.imported=n.identifier(p))}}},CallExpression(t){let r=t.node.callee;if(!n.isIdentifier(r))return;let i=u._callerMap?.get(r.name);if(!i)return;u._hasValidImport=!0;let a=t.node.arguments[0],o;if(a&&n.isStringLiteral(a)?o=a.value:a&&n.isTemplateLiteral(a)&&a.expressions.length===0&&a.quasis.length===1&&(o=a.quasis[0].value.cooked??a.quasis[0].value.raw),!o)return;let s=u.opts.importMode,l=i===`useIntlayer`,d=!!u._useDynamicHelpers,f=`static`,p=u.opts.dictionaryModeMap?.[o];l&&d?p?f=p:s===`dynamic`?f=`dynamic`:s===`fetch`&&(f=`fetch`):l&&!d&&(p===`dynamic`||p===`fetch`)&&(f=p);let m;if(f===`fetch`){let r=u._newDynamicImports?.get(o);if(!r){let t=(0,e.getPathHash)(o);r=n.identifier(`_${t}_fetch`),u._newDynamicImports?.set(o,r)}m=r,t.node.arguments=[n.identifier(m.name),...t.node.arguments]}else if(f===`dynamic`){let r=u._newDynamicImports?.get(o);if(!r){let t=(0,e.getPathHash)(o);r=n.identifier(`_${t}_dyn`),u._newDynamicImports?.set(o,r)}m=r,t.node.arguments=[n.identifier(m.name),...t.node.arguments]}else{let e=u._newStaticImports?.get(o);e||(e=c(o,n),u._newStaticImports?.set(o,e)),m=e,t.node.arguments[0]=n.identifier(m.name)}}}),!u._hasValidImport)return;let f=u.file.opts.filename,p=u.opts.dictionariesDir,m=u.opts.dynamicDictionariesDir,h=u.opts.fetchDictionariesDir,g=[];for(let[e,t]of u._newStaticImports){let r=l(f,p,m,h,e,`static`),i=n.importDeclaration([n.importDefaultSpecifier(n.identifier(t.name))],n.stringLiteral(r));i.attributes=[n.importAttribute(n.identifier(`type`),n.stringLiteral(`json`))],g.push(i)}for(let[e,t]of u._newDynamicImports){let r=l(f,p,m,h,e,t.name.endsWith(`_fetch`)?`fetch`:`dynamic`);g.push(n.importDeclaration([n.importDefaultSpecifier(n.identifier(t.name))],n.stringLiteral(r)))}if(!g.length)return;let _=t.get(`body`),v=0;for(let e of _){let t=e.node;if(n.isExpressionStatement(t)&&n.isStringLiteral(t.expression)&&!t.expression.value.startsWith(`import`)&&!t.expression.value.startsWith(`require`))v+=1;else break}t.node.body.splice(v,0,...g)}}}}};exports.intlayerOptimizeBabelPlugin=u;
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
+ const require_runtime = require('./_virtual/_rolldown/runtime.cjs');
3
+ let _intlayer_chokidar_utils = require("@intlayer/chokidar/utils");
4
+ let node_path = require("node:path");
5
+ let _intlayer_config_utils = require("@intlayer/config/utils");
6
+
7
+ //#region src/babel-plugin-intlayer-optimize.ts
8
+ const PACKAGE_LIST = [
9
+ "intlayer",
10
+ "@intlayer/core",
11
+ "react-intlayer",
12
+ "react-intlayer/client",
13
+ "react-intlayer/server",
14
+ "next-intlayer",
15
+ "next-intlayer/client",
16
+ "next-intlayer/server",
17
+ "svelte-intlayer",
18
+ "vue-intlayer",
19
+ "angular-intlayer",
20
+ "preact-intlayer",
21
+ "solid-intlayer"
22
+ ];
23
+ const CALLER_LIST = ["useIntlayer", "getIntlayer"];
24
+ /**
25
+ * Packages that support dynamic import
26
+ */
27
+ const PACKAGE_LIST_DYNAMIC = [
28
+ "react-intlayer",
29
+ "react-intlayer/client",
30
+ "react-intlayer/server",
31
+ "next-intlayer",
32
+ "next-intlayer/client",
33
+ "next-intlayer/server",
34
+ "preact-intlayer",
35
+ "vue-intlayer",
36
+ "solid-intlayer",
37
+ "svelte-intlayer",
38
+ "angular-intlayer"
39
+ ];
40
+ const STATIC_IMPORT_FUNCTION = {
41
+ getIntlayer: "getDictionary",
42
+ useIntlayer: "useDictionary"
43
+ };
44
+ const DYNAMIC_IMPORT_FUNCTION = { useIntlayer: "useDictionaryDynamic" };
45
+ /**
46
+ * Replicates the xxHash64 → Base-62 algorithm used by the SWC version
47
+ * and prefixes an underscore so the generated identifiers never collide
48
+ * with user-defined ones.
49
+ */
50
+ const makeIdent = (key, t) => {
51
+ const hash = (0, _intlayer_chokidar_utils.getPathHash)(key);
52
+ return t.identifier(`_${hash}`);
53
+ };
54
+ const computeImport = (fromFile, dictionariesDir, dynamicDictionariesDir, fetchDictionariesDir, key, importMode) => {
55
+ let relativePath = (0, node_path.join)(dictionariesDir, `${key}.json`);
56
+ if (importMode === "fetch") relativePath = (0, node_path.join)(fetchDictionariesDir, `${key}.mjs`);
57
+ if (importMode === "dynamic") relativePath = (0, node_path.join)(dynamicDictionariesDir, `${key}.mjs`);
58
+ let rel = (0, node_path.relative)((0, node_path.dirname)(fromFile), relativePath);
59
+ rel = (0, _intlayer_config_utils.normalizePath)(rel);
60
+ if (!rel.startsWith("./") && !rel.startsWith("../")) rel = `./${rel}`;
61
+ return rel;
62
+ };
63
+ /**
64
+ * Babel plugin that transforms Intlayer function calls and auto-imports dictionaries.
65
+ *
66
+ * This plugin transforms calls to `useIntlayer()` and `getIntlayer()` from various Intlayer
67
+ * packages into optimized dictionary access patterns, automatically importing the required
68
+ * dictionary files based on the configured import mode.
69
+ *
70
+ * ## Supported Input Patterns
71
+ *
72
+ * The plugin recognizes these function calls:
73
+ *
74
+ * ```ts
75
+ * // useIntlayer
76
+ * import { useIntlayer } from 'react-intlayer';
77
+ * import { useIntlayer } from 'next-intlayer';
78
+ *
79
+ * // getIntlayer
80
+ * import { getIntlayer } from 'intlayer';
81
+ *
82
+ * // Usage
83
+ * const content = useIntlayer('app');
84
+ * const content = getIntlayer('app');
85
+ * ```
86
+ *
87
+ * ## Transformation Modes
88
+ *
89
+ * ### Static Mode (default: `importMode = "static"`)
90
+ *
91
+ * Imports JSON dictionaries directly and replaces function calls with dictionary access:
92
+ *
93
+ * **Output:**
94
+ * ```ts
95
+ * import _dicHash from '../../.intlayer/dictionaries/app.json' with { type: 'json' };
96
+ * import { useDictionary as useIntlayer } from 'react-intlayer';
97
+ * import { getDictionary as getIntlayer } from 'intlayer';
98
+ *
99
+ * const content1 = useIntlayer(_dicHash);
100
+ * const content2 = getIntlayer(_dicHash);
101
+ * ```
102
+ *
103
+ * ### Dynamic Mode (`importMode = "dynamic"`)
104
+ *
105
+ * Uses dynamic dictionary loading with Suspense support:
106
+ *
107
+ * **Output:**
108
+ * ```ts
109
+ * import _dicHash from '../../.intlayer/dictionaries/app.json' with { type: 'json' };
110
+ * import _dicHash_dyn from '../../.intlayer/dynamic_dictionaries/app.mjs';
111
+ * import { useDictionaryDynamic as useIntlayer } from 'react-intlayer';
112
+ * import { getDictionary as getIntlayer } from 'intlayer';
113
+ *
114
+ * const content1 = useIntlayer(_dicHash_dyn, 'app');
115
+ * const content2 = getIntlayer(_dicHash);
116
+ * ```
117
+ *
118
+ * ### Live Mode (`importMode = "live"`)
119
+ *
120
+ * Uses live-based dictionary loading for remote dictionaries:
121
+ *
122
+ * **Output if `dictionaryModeMap` includes the key with "live" value:**
123
+ * ```ts
124
+ * import _dicHash from '../../.intlayer/dictionaries/app.json' with { type: 'json' };
125
+ * import _dicHash_fetch from '../../.intlayer/fetch_dictionaries/app.mjs';
126
+ * import { useDictionaryDynamic as useIntlayer } from 'react-intlayer';
127
+ * import { getDictionary as getIntlayer } from 'intlayer';
128
+ *
129
+ * const content1 = useIntlayer(_dicHash_fetch, "app");
130
+ * const content2 = getIntlayer(_dicHash);
131
+ * ```
132
+ *
133
+ * > If `dictionaryModeMap` does not include the key with "live" value, the plugin will fallback to the dynamic impor
134
+ *
135
+ * ```ts
136
+ * import _dicHash from '../../.intlayer/dictionaries/app.json' with { type: 'json' };
137
+ * import _dicHash_dyn from '../../.intlayer/dynamic_dictionaries/app.mjs';
138
+ * import { useDictionaryDynamic as useIntlayer } from 'react-intlayer';
139
+ * import { getDictionary as getIntlayer } from 'intlayer';
140
+ *
141
+ * const content1 = useIntlayer(_dicHash_dyn, 'app');
142
+ * const content2 = getIntlayer(_dicHash);
143
+ * ```
144
+ */
145
+ const intlayerOptimizeBabelPlugin = (babel) => {
146
+ const { types: t } = babel;
147
+ return {
148
+ name: "babel-plugin-intlayer-transform",
149
+ pre() {
150
+ this._newStaticImports = /* @__PURE__ */ new Map();
151
+ this._newDynamicImports = /* @__PURE__ */ new Map();
152
+ this._callerMap = /* @__PURE__ */ new Map();
153
+ this._isIncluded = true;
154
+ this._hasValidImport = false;
155
+ this._isDictEntry = false;
156
+ this._useDynamicHelpers = false;
157
+ if (this.opts.optimize === false) {
158
+ this._isIncluded = false;
159
+ return;
160
+ }
161
+ const filename = this.file.opts.filename;
162
+ if (this.opts.filesList && filename) {
163
+ if (!this.opts.filesList.includes(filename)) {
164
+ this._isIncluded = false;
165
+ return;
166
+ }
167
+ }
168
+ },
169
+ visitor: { Program: {
170
+ enter(programPath, state) {
171
+ const filename = state.file.opts.filename;
172
+ if (state.opts.replaceDictionaryEntry && filename === state.opts.dictionariesEntryPath) {
173
+ state._isDictEntry = true;
174
+ programPath.traverse({
175
+ ImportDeclaration(path) {
176
+ path.remove();
177
+ },
178
+ VariableDeclarator(path) {
179
+ if (t.isObjectExpression(path.node.init)) path.node.init.properties = [];
180
+ }
181
+ });
182
+ }
183
+ },
184
+ exit(programPath, state) {
185
+ if (state._isDictEntry) return;
186
+ if (!state._isIncluded) return;
187
+ let fileHasDynamicCall = false;
188
+ programPath.traverse({ CallExpression(path) {
189
+ const callee = path.node.callee;
190
+ if (!t.isIdentifier(callee)) return;
191
+ if (state._callerMap?.get(callee.name) !== "useIntlayer") return;
192
+ const arg = path.node.arguments[0];
193
+ let key;
194
+ if (arg && t.isStringLiteral(arg)) key = arg.value;
195
+ else if (arg && t.isTemplateLiteral(arg) && arg.expressions.length === 0 && arg.quasis.length === 1) key = arg.quasis[0].value.cooked ?? arg.quasis[0].value.raw;
196
+ if (!key) return;
197
+ const dictionaryOverrideMode = state.opts.dictionaryModeMap?.[key];
198
+ if (dictionaryOverrideMode === "dynamic" || dictionaryOverrideMode === "fetch") fileHasDynamicCall = true;
199
+ } });
200
+ programPath.traverse({
201
+ ImportDeclaration(path) {
202
+ const src = path.node.source.value;
203
+ if (!PACKAGE_LIST.includes(src)) return;
204
+ state._hasValidImport = true;
205
+ for (const spec of path.node.specifiers) {
206
+ if (!t.isImportSpecifier(spec)) continue;
207
+ const importedName = t.isIdentifier(spec.imported) ? spec.imported.name : spec.imported.value;
208
+ if (CALLER_LIST.includes(importedName)) state._callerMap?.set(spec.local.name, importedName);
209
+ const importMode = state.opts.importMode;
210
+ const shouldUseDynamicHelpers = (importMode === "dynamic" || importMode === "fetch" || fileHasDynamicCall) && PACKAGE_LIST_DYNAMIC.includes(src);
211
+ if (shouldUseDynamicHelpers) state._useDynamicHelpers = true;
212
+ let helperMap;
213
+ if (shouldUseDynamicHelpers) helperMap = {
214
+ ...STATIC_IMPORT_FUNCTION,
215
+ ...DYNAMIC_IMPORT_FUNCTION
216
+ };
217
+ else helperMap = STATIC_IMPORT_FUNCTION;
218
+ const newIdentifier = helperMap[importedName];
219
+ if (newIdentifier) spec.imported = t.identifier(newIdentifier);
220
+ }
221
+ },
222
+ CallExpression(path) {
223
+ const callee = path.node.callee;
224
+ if (!t.isIdentifier(callee)) return;
225
+ const originalImportedName = state._callerMap?.get(callee.name);
226
+ if (!originalImportedName) return;
227
+ state._hasValidImport = true;
228
+ const arg = path.node.arguments[0];
229
+ let key;
230
+ if (arg && t.isStringLiteral(arg)) key = arg.value;
231
+ else if (arg && t.isTemplateLiteral(arg) && arg.expressions.length === 0 && arg.quasis.length === 1) key = arg.quasis[0].value.cooked ?? arg.quasis[0].value.raw;
232
+ if (!key) return;
233
+ const importMode = state.opts.importMode;
234
+ const isUseIntlayer = originalImportedName === "useIntlayer";
235
+ const useDynamicHelpers = Boolean(state._useDynamicHelpers);
236
+ let perCallMode = "static";
237
+ const dictionaryOverrideMode = state.opts.dictionaryModeMap?.[key];
238
+ if (isUseIntlayer && useDynamicHelpers) {
239
+ if (dictionaryOverrideMode) perCallMode = dictionaryOverrideMode;
240
+ else if (importMode === "dynamic") perCallMode = "dynamic";
241
+ else if (importMode === "fetch") perCallMode = "fetch";
242
+ } else if (isUseIntlayer && !useDynamicHelpers) {
243
+ if (dictionaryOverrideMode === "dynamic" || dictionaryOverrideMode === "fetch") perCallMode = dictionaryOverrideMode;
244
+ }
245
+ let ident;
246
+ if (perCallMode === "fetch") {
247
+ let dynamicIdent = state._newDynamicImports?.get(key);
248
+ if (!dynamicIdent) {
249
+ const hash = (0, _intlayer_chokidar_utils.getPathHash)(key);
250
+ dynamicIdent = t.identifier(`_${hash}_fetch`);
251
+ state._newDynamicImports?.set(key, dynamicIdent);
252
+ }
253
+ ident = dynamicIdent;
254
+ path.node.arguments = [t.identifier(ident.name), ...path.node.arguments];
255
+ } else if (perCallMode === "dynamic") {
256
+ let dynamicIdent = state._newDynamicImports?.get(key);
257
+ if (!dynamicIdent) {
258
+ const hash = (0, _intlayer_chokidar_utils.getPathHash)(key);
259
+ dynamicIdent = t.identifier(`_${hash}_dyn`);
260
+ state._newDynamicImports?.set(key, dynamicIdent);
261
+ }
262
+ ident = dynamicIdent;
263
+ path.node.arguments = [t.identifier(ident.name), ...path.node.arguments];
264
+ } else {
265
+ let staticIdent = state._newStaticImports?.get(key);
266
+ if (!staticIdent) {
267
+ staticIdent = makeIdent(key, t);
268
+ state._newStaticImports?.set(key, staticIdent);
269
+ }
270
+ ident = staticIdent;
271
+ path.node.arguments[0] = t.identifier(ident.name);
272
+ }
273
+ }
274
+ });
275
+ if (!state._hasValidImport) return;
276
+ const file = state.file.opts.filename;
277
+ const dictionariesDir = state.opts.dictionariesDir;
278
+ const dynamicDictionariesDir = state.opts.dynamicDictionariesDir;
279
+ const fetchDictionariesDir = state.opts.fetchDictionariesDir;
280
+ const imports = [];
281
+ for (const [key, ident] of state._newStaticImports) {
282
+ const rel = computeImport(file, dictionariesDir, dynamicDictionariesDir, fetchDictionariesDir, key, "static");
283
+ const importDeclarationNode = t.importDeclaration([t.importDefaultSpecifier(t.identifier(ident.name))], t.stringLiteral(rel));
284
+ importDeclarationNode.attributes = [t.importAttribute(t.identifier("type"), t.stringLiteral("json"))];
285
+ imports.push(importDeclarationNode);
286
+ }
287
+ for (const [key, ident] of state._newDynamicImports) {
288
+ const rel = computeImport(file, dictionariesDir, dynamicDictionariesDir, fetchDictionariesDir, key, ident.name.endsWith("_fetch") ? "fetch" : "dynamic");
289
+ imports.push(t.importDeclaration([t.importDefaultSpecifier(t.identifier(ident.name))], t.stringLiteral(rel)));
290
+ }
291
+ if (!imports.length) return;
292
+ const bodyPaths = programPath.get("body");
293
+ let insertPos = 0;
294
+ for (const stmtPath of bodyPaths) {
295
+ const stmt = stmtPath.node;
296
+ if (t.isExpressionStatement(stmt) && t.isStringLiteral(stmt.expression) && !stmt.expression.value.startsWith("import") && !stmt.expression.value.startsWith("require")) insertPos += 1;
297
+ else break;
298
+ }
299
+ programPath.node.body.splice(insertPos, 0, ...imports);
300
+ }
301
+ } }
302
+ };
303
+ };
304
+
305
+ //#endregion
306
+ exports.intlayerOptimizeBabelPlugin = intlayerOptimizeBabelPlugin;
2
307
  //# sourceMappingURL=babel-plugin-intlayer-optimize.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"babel-plugin-intlayer-optimize.cjs","names":[],"sources":["../../src/babel-plugin-intlayer-optimize.ts"],"sourcesContent":["import { dirname, join, relative } from 'node:path';\nimport type { NodePath, PluginObj, PluginPass } from '@babel/core';\nimport type * as BabelTypes from '@babel/types';\nimport { getPathHash } from '@intlayer/chokidar/utils';\nimport { normalizePath } from '@intlayer/config/utils';\n\nconst PACKAGE_LIST = [\n 'intlayer',\n '@intlayer/core',\n 'react-intlayer',\n 'react-intlayer/client',\n 'react-intlayer/server',\n 'next-intlayer',\n 'next-intlayer/client',\n 'next-intlayer/server',\n 'svelte-intlayer',\n 'vue-intlayer',\n 'angular-intlayer',\n 'preact-intlayer',\n 'solid-intlayer',\n];\n\nconst CALLER_LIST = ['useIntlayer', 'getIntlayer'] as const;\n\n/**\n * Packages that support dynamic import\n */\nconst PACKAGE_LIST_DYNAMIC = [\n 'react-intlayer',\n 'react-intlayer/client',\n 'react-intlayer/server',\n 'next-intlayer',\n 'next-intlayer/client',\n 'next-intlayer/server',\n 'preact-intlayer',\n 'vue-intlayer',\n 'solid-intlayer',\n 'svelte-intlayer',\n 'angular-intlayer',\n] as const;\n\nconst STATIC_IMPORT_FUNCTION = {\n getIntlayer: 'getDictionary',\n useIntlayer: 'useDictionary',\n} as const;\n\nconst DYNAMIC_IMPORT_FUNCTION = {\n useIntlayer: 'useDictionaryDynamic',\n} as const;\n\n/**\n * Options for the optimization Babel plugin\n */\nexport type OptimizePluginOptions = {\n /**\n * If false, the plugin will not apply any transformation.\n */\n optimize?: boolean;\n /**\n * The path to the dictionaries directory.\n */\n dictionariesDir: string;\n /**\n * The path to the dictionaries entry file.\n */\n dictionariesEntryPath: string;\n /**\n * The path to the unmerged dictionaries entry file.\n */\n unmergedDictionariesEntryPath: string;\n /**\n * The path to the unmerged dictionaries directory.\n */\n unmergedDictionariesDir: string;\n /**\n * The path to the dictionaries directory.\n */\n dynamicDictionariesDir: string;\n /**\n * The path to the dynamic dictionaries entry file.\n */\n dynamicDictionariesEntryPath: string;\n /**\n * The path to the fetch dictionaries directory.\n */\n fetchDictionariesDir: string;\n /**\n * The path to the fetch dictionaries entry file.\n */\n fetchDictionariesEntryPath: string;\n /**\n * If true, the plugin will replace the dictionary entry file with `export default {}`.\n */\n replaceDictionaryEntry: boolean;\n /**\n * If true, the plugin will activate the dynamic import of the dictionaries. It will rely on Suspense to load the dictionaries.\n */\n importMode: 'static' | 'dynamic' | 'fetch' | undefined;\n /**\n * Map of dictionary keys to their specific import mode.\n */\n dictionaryModeMap?: Record<\n string,\n 'static' | 'dynamic' | 'fetch' | undefined\n >;\n /**\n * Files list to traverse.\n */\n filesList: string[];\n};\n\ntype State = PluginPass & {\n opts: OptimizePluginOptions;\n /** map key → generated ident (per-file) for static imports */\n _newStaticImports?: Map<string, BabelTypes.Identifier>;\n /** map key → generated ident (per-file) for dynamic imports */\n _newDynamicImports?: Map<string, BabelTypes.Identifier>;\n /** whether the current file imported *any* intlayer package */\n _hasValidImport?: boolean;\n /** map from local identifier name to the imported intlayer func name ('useIntlayer' | 'getIntlayer') */\n _callerMap?: Map<string, (typeof CALLER_LIST)[number]>;\n /** whether the current file *is* the dictionaries entry file */\n _isDictEntry?: boolean;\n /** whether dynamic helpers are active for this file */\n _useDynamicHelpers?: boolean;\n /** whether the current file is included in the filesList */\n _isIncluded?: boolean;\n};\n\n/**\n * Replicates the xxHash64 → Base-62 algorithm used by the SWC version\n * and prefixes an underscore so the generated identifiers never collide\n * with user-defined ones.\n */\nconst makeIdent = (\n key: string,\n t: typeof BabelTypes\n): BabelTypes.Identifier => {\n const hash = getPathHash(key);\n return t.identifier(`_${hash}`);\n};\n\nconst computeImport = (\n fromFile: string,\n dictionariesDir: string,\n dynamicDictionariesDir: string,\n fetchDictionariesDir: string,\n key: string,\n importMode: 'static' | 'dynamic' | 'fetch'\n): string => {\n let relativePath = join(dictionariesDir, `${key}.json`);\n\n if (importMode === 'fetch') {\n relativePath = join(fetchDictionariesDir, `${key}.mjs`);\n }\n\n if (importMode === 'dynamic') {\n relativePath = join(dynamicDictionariesDir, `${key}.mjs`);\n }\n\n let rel = relative(dirname(fromFile), relativePath);\n\n // Fix windows path\n rel = normalizePath(rel);\n\n // Fix relative path\n if (!rel.startsWith('./') && !rel.startsWith('../')) {\n rel = `./${rel}`;\n }\n\n return rel;\n};\n\n/**\n * Babel plugin that transforms Intlayer function calls and auto-imports dictionaries.\n *\n * This plugin transforms calls to `useIntlayer()` and `getIntlayer()` from various Intlayer\n * packages into optimized dictionary access patterns, automatically importing the required\n * dictionary files based on the configured import mode.\n *\n * ## Supported Input Patterns\n *\n * The plugin recognizes these function calls:\n *\n * ```ts\n * // useIntlayer\n * import { useIntlayer } from 'react-intlayer';\n * import { useIntlayer } from 'next-intlayer';\n *\n * // getIntlayer\n * import { getIntlayer } from 'intlayer';\n *\n * // Usage\n * const content = useIntlayer('app');\n * const content = getIntlayer('app');\n * ```\n *\n * ## Transformation Modes\n *\n * ### Static Mode (default: `importMode = \"static\"`)\n *\n * Imports JSON dictionaries directly and replaces function calls with dictionary access:\n *\n * **Output:**\n * ```ts\n * import _dicHash from '../../.intlayer/dictionaries/app.json' with { type: 'json' };\n * import { useDictionary as useIntlayer } from 'react-intlayer';\n * import { getDictionary as getIntlayer } from 'intlayer';\n *\n * const content1 = useIntlayer(_dicHash);\n * const content2 = getIntlayer(_dicHash);\n * ```\n *\n * ### Dynamic Mode (`importMode = \"dynamic\"`)\n *\n * Uses dynamic dictionary loading with Suspense support:\n *\n * **Output:**\n * ```ts\n * import _dicHash from '../../.intlayer/dictionaries/app.json' with { type: 'json' };\n * import _dicHash_dyn from '../../.intlayer/dynamic_dictionaries/app.mjs';\n * import { useDictionaryDynamic as useIntlayer } from 'react-intlayer';\n * import { getDictionary as getIntlayer } from 'intlayer';\n *\n * const content1 = useIntlayer(_dicHash_dyn, 'app');\n * const content2 = getIntlayer(_dicHash);\n * ```\n *\n * ### Live Mode (`importMode = \"live\"`)\n *\n * Uses live-based dictionary loading for remote dictionaries:\n *\n * **Output if `dictionaryModeMap` includes the key with \"live\" value:**\n * ```ts\n * import _dicHash from '../../.intlayer/dictionaries/app.json' with { type: 'json' };\n * import _dicHash_fetch from '../../.intlayer/fetch_dictionaries/app.mjs';\n * import { useDictionaryDynamic as useIntlayer } from 'react-intlayer';\n * import { getDictionary as getIntlayer } from 'intlayer';\n *\n * const content1 = useIntlayer(_dicHash_fetch, \"app\");\n * const content2 = getIntlayer(_dicHash);\n * ```\n *\n * > If `dictionaryModeMap` does not include the key with \"live\" value, the plugin will fallback to the dynamic impor\n *\n * ```ts\n * import _dicHash from '../../.intlayer/dictionaries/app.json' with { type: 'json' };\n * import _dicHash_dyn from '../../.intlayer/dynamic_dictionaries/app.mjs';\n * import { useDictionaryDynamic as useIntlayer } from 'react-intlayer';\n * import { getDictionary as getIntlayer } from 'intlayer';\n *\n * const content1 = useIntlayer(_dicHash_dyn, 'app');\n * const content2 = getIntlayer(_dicHash);\n * ```\n */\nexport const intlayerOptimizeBabelPlugin = (babel: {\n types: typeof BabelTypes;\n}): PluginObj<State> => {\n const { types: t } = babel;\n\n return {\n name: 'babel-plugin-intlayer-transform',\n\n pre() {\n this._newStaticImports = new Map();\n this._newDynamicImports = new Map();\n this._callerMap = new Map();\n this._isIncluded = true;\n this._hasValidImport = false;\n this._isDictEntry = false;\n this._useDynamicHelpers = false;\n\n // If optimize is false, skip processing entirely\n if (this.opts.optimize === false) {\n this._isIncluded = false;\n return;\n }\n\n // If filesList is provided, check if current file is included\n const filename = this.file.opts.filename;\n if (this.opts.filesList && filename) {\n const isIncluded = this.opts.filesList.includes(filename);\n\n if (!isIncluded) {\n // Force _isIncluded to false to skip processing\n this._isIncluded = false;\n return;\n }\n }\n },\n\n visitor: {\n /* If this file *is* the dictionaries entry, short-circuit: export {} */\n Program: {\n enter(programPath, state) {\n // Safe access to filename\n const filename = state.file.opts.filename;\n\n // Check if this is the correct file to transform\n\n if (\n state.opts.replaceDictionaryEntry &&\n filename === state.opts.dictionariesEntryPath\n ) {\n state._isDictEntry = true;\n\n // Traverse the program to surgically remove/edit specific parts\n programPath.traverse({\n // Remove all import statements (cleaning up 'sssss.json')\n ImportDeclaration(path) {\n path.remove();\n },\n\n // Find the variable definition and empty the object\n VariableDeclarator(path) {\n // We look for: const x = { ... }\n\n if (t.isObjectExpression(path.node.init)) {\n // Set the object properties to an empty array: {}\n path.node.init.properties = [];\n }\n },\n });\n\n // (Optional) Stop other plugins from processing this file further if needed\n // programPath.stop();\n }\n },\n\n /**\n * After full traversal, process imports and call expressions, then inject the JSON dictionary imports.\n *\n * We do the transformation in Program.exit (via a manual traverse) rather than using\n * top-level ImportDeclaration/CallExpression visitors. This ensures that if another plugin\n * (like babel-plugin-intlayer-extract) adds new useIntlayer calls in its Program.exit,\n * we will see and transform them here because our Program.exit runs after theirs.\n */\n exit(programPath, state) {\n if (state._isDictEntry) return; // nothing else to do – already replaced\n\n if (!state._isIncluded) return; // early-out if file is not included\n\n // Manual traversal to process imports and call expressions\n // This runs AFTER all other plugins' visitors have completed\n\n // Pre-pass to determine if we should use dynamic helpers\n let fileHasDynamicCall = false;\n programPath.traverse({\n CallExpression(path) {\n const callee = path.node.callee;\n\n if (!t.isIdentifier(callee)) return;\n\n const originalImportedName = state._callerMap?.get(callee.name);\n if (originalImportedName !== 'useIntlayer') return;\n\n const arg = path.node.arguments[0];\n\n let key: string | undefined;\n\n if (arg && t.isStringLiteral(arg)) {\n key = arg.value;\n } else if (\n arg &&\n t.isTemplateLiteral(arg) &&\n arg.expressions.length === 0 &&\n arg.quasis.length === 1\n ) {\n // If the bundler output is `breadcrumb` instead of 'breadcrumb'\n key = arg.quasis[0].value.cooked ?? arg.quasis[0].value.raw;\n }\n\n if (!key) return;\n const dictionaryOverrideMode =\n state.opts.dictionaryModeMap?.[key];\n\n if (\n dictionaryOverrideMode === 'dynamic' ||\n dictionaryOverrideMode === 'fetch'\n ) {\n fileHasDynamicCall = true;\n }\n },\n });\n\n programPath.traverse({\n /* Inspect every intlayer import */\n ImportDeclaration(path) {\n const src = path.node.source.value;\n\n if (!PACKAGE_LIST.includes(src)) return;\n\n // Mark that we do import from an intlayer package in this file\n state._hasValidImport = true;\n\n for (const spec of path.node.specifiers) {\n if (!t.isImportSpecifier(spec)) continue;\n\n const importedName = t.isIdentifier(spec.imported)\n ? spec.imported.name\n : (spec.imported as BabelTypes.StringLiteral).value;\n\n if (CALLER_LIST.includes(importedName as any)) {\n state._callerMap?.set(\n spec.local.name,\n importedName as (typeof CALLER_LIST)[number]\n );\n }\n\n const importMode = state.opts.importMode;\n // Determine whether this import should use the dynamic helpers.\n const shouldUseDynamicHelpers =\n (importMode === 'dynamic' ||\n importMode === 'fetch' ||\n fileHasDynamicCall) &&\n PACKAGE_LIST_DYNAMIC.includes(src as any);\n\n // Remember for later (CallExpression) whether we are using the dynamic helpers\n\n if (shouldUseDynamicHelpers) {\n state._useDynamicHelpers = true;\n }\n\n let helperMap: Record<string, string>;\n\n if (shouldUseDynamicHelpers) {\n // Use dynamic helpers for useIntlayer when dynamic mode is enabled\n helperMap = {\n ...STATIC_IMPORT_FUNCTION,\n ...DYNAMIC_IMPORT_FUNCTION,\n } as Record<string, string>;\n } else {\n // Use static helpers by default\n helperMap = STATIC_IMPORT_FUNCTION as Record<string, string>;\n }\n\n const newIdentifier = helperMap[importedName];\n\n // Only rewrite when we actually have a mapping for the imported\n // specifier (ignore unrelated named imports).\n\n if (newIdentifier) {\n // Keep the local alias intact (so calls remain `useIntlayer` /\n // `getIntlayer`), but rewrite the imported identifier so it\n // points to our helper implementation.\n spec.imported = t.identifier(newIdentifier);\n }\n }\n },\n\n /* Replace calls: useIntlayer(\"foo\") → useDictionary(_hash) or useDictionaryDynamic(_hash, \"foo\") */\n CallExpression(path) {\n const callee = path.node.callee;\n\n if (!t.isIdentifier(callee)) return;\n\n const originalImportedName = state._callerMap?.get(callee.name);\n if (!originalImportedName) return;\n\n // Ensure we ultimately emit helper imports for files that *invoke*\n // the hooks, even if they didn't import them directly (edge cases with\n // re-exports).\n state._hasValidImport = true;\n\n const arg = path.node.arguments[0];\n\n let key: string | undefined;\n\n if (arg && t.isStringLiteral(arg)) {\n key = arg.value;\n } else if (\n arg &&\n t.isTemplateLiteral(arg) &&\n arg.expressions.length === 0 &&\n arg.quasis.length === 1\n ) {\n // If the bundler output is `breadcrumb` instead of 'breadcrumb'\n key = arg.quasis[0].value.cooked ?? arg.quasis[0].value.raw;\n }\n\n if (!key) return; // must be a static literal\n const importMode = state.opts.importMode;\n const isUseIntlayer = originalImportedName === 'useIntlayer';\n const useDynamicHelpers = Boolean(state._useDynamicHelpers);\n\n // Decide per-call mode: 'static' | 'dynamic' | 'fetch'\n let perCallMode: 'static' | 'dynamic' | 'fetch' = 'static';\n\n const dictionaryOverrideMode =\n state.opts.dictionaryModeMap?.[key];\n\n if (isUseIntlayer && useDynamicHelpers) {\n if (dictionaryOverrideMode) {\n perCallMode = dictionaryOverrideMode;\n } else if (importMode === 'dynamic') {\n perCallMode = 'dynamic';\n } else if (importMode === 'fetch') {\n perCallMode = 'fetch';\n }\n } else if (isUseIntlayer && !useDynamicHelpers) {\n // If dynamic helpers are NOT active (global mode is static),\n // we STILL might want to force dynamic/live for this specific call\n\n if (\n dictionaryOverrideMode === 'dynamic' ||\n dictionaryOverrideMode === 'fetch'\n ) {\n perCallMode = dictionaryOverrideMode;\n }\n }\n\n let ident: BabelTypes.Identifier;\n\n if (perCallMode === 'fetch') {\n // Use fetch dictionaries entry (live mode for selected keys)\n let dynamicIdent = state._newDynamicImports?.get(key);\n\n if (!dynamicIdent) {\n const hash = getPathHash(key);\n dynamicIdent = t.identifier(`_${hash}_fetch`);\n state._newDynamicImports?.set(key, dynamicIdent);\n }\n ident = dynamicIdent;\n\n // Helper: first argument is the dictionary entry, second is the key\n path.node.arguments = [\n t.identifier(ident.name),\n ...path.node.arguments,\n ];\n } else if (perCallMode === 'dynamic') {\n // Use dynamic dictionaries entry\n let dynamicIdent = state._newDynamicImports?.get(key);\n\n if (!dynamicIdent) {\n // Create a unique identifier for dynamic imports by appending a suffix\n const hash = getPathHash(key);\n dynamicIdent = t.identifier(`_${hash}_dyn`);\n state._newDynamicImports?.set(key, dynamicIdent);\n }\n ident = dynamicIdent;\n\n // Dynamic helper: first argument is the dictionary, second is the key.\n path.node.arguments = [\n t.identifier(ident.name),\n ...path.node.arguments,\n ];\n } else {\n // Use static imports for getIntlayer or useIntlayer when not using dynamic helpers\n let staticIdent = state._newStaticImports?.get(key);\n\n if (!staticIdent) {\n staticIdent = makeIdent(key, t);\n state._newStaticImports?.set(key, staticIdent);\n }\n ident = staticIdent;\n\n // Static helper (useDictionary / getDictionary): replace key with iden\n path.node.arguments[0] = t.identifier(ident.name);\n }\n },\n });\n\n // Early-out if we touched nothing\n\n if (!state._hasValidImport) return;\n\n const file = state.file.opts.filename!;\n const dictionariesDir = state.opts.dictionariesDir;\n const dynamicDictionariesDir = state.opts.dynamicDictionariesDir;\n const fetchDictionariesDir = state.opts.fetchDictionariesDir;\n const imports: BabelTypes.ImportDeclaration[] = [];\n\n // Generate static JSON imports (getIntlayer always uses JSON dictionaries)\n for (const [key, ident] of state._newStaticImports!) {\n const rel = computeImport(\n file,\n dictionariesDir,\n dynamicDictionariesDir,\n fetchDictionariesDir,\n key,\n 'static'\n );\n\n const importDeclarationNode = t.importDeclaration(\n [t.importDefaultSpecifier(t.identifier(ident.name))],\n t.stringLiteral(rel)\n );\n\n // Add 'type: json' attribute for JSON files\n importDeclarationNode.attributes = [\n t.importAttribute(t.identifier('type'), t.stringLiteral('json')),\n ];\n\n imports.push(importDeclarationNode);\n }\n\n // Generate dynamic/fetch imports (for useIntlayer when using dynamic/live helpers)\n for (const [key, ident] of state._newDynamicImports!) {\n const modeForThisIdent: 'dynamic' | 'fetch' = ident.name.endsWith(\n '_fetch'\n )\n ? 'fetch'\n : 'dynamic';\n\n const rel = computeImport(\n file,\n dictionariesDir,\n dynamicDictionariesDir,\n fetchDictionariesDir,\n key,\n modeForThisIdent\n );\n imports.push(\n t.importDeclaration(\n [t.importDefaultSpecifier(t.identifier(ident.name))],\n t.stringLiteral(rel)\n )\n );\n }\n\n if (!imports.length) return;\n\n /* Keep \"use client\" / \"use server\" directives at the very top. */\n const bodyPaths = programPath.get(\n 'body'\n ) as NodePath<BabelTypes.Statement>[];\n let insertPos = 0;\n for (const stmtPath of bodyPaths) {\n const stmt = stmtPath.node;\n\n if (\n t.isExpressionStatement(stmt) &&\n t.isStringLiteral(stmt.expression) &&\n !stmt.expression.value.startsWith('import') &&\n !stmt.expression.value.startsWith('require')\n ) {\n insertPos += 1;\n } else {\n break;\n }\n }\n\n programPath.node.body.splice(insertPos, 0, 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AED,EAAQ,KAAK,EAAsB,CAIrC,IAAK,GAAM,CAAC,EAAK,KAAU,EAAM,mBAAqB,CAOpD,IAAM,EAAM,EACV,EACA,EACA,EACA,EACA,EAX4C,EAAM,KAAK,SACvD,SACD,CACG,QACA,UASH,CACD,EAAQ,KACN,EAAE,kBACA,CAAC,EAAE,uBAAuB,EAAE,WAAW,EAAM,KAAK,CAAC,CAAC,CACpD,EAAE,cAAc,EAAI,CACrB,CACF,CAGH,GAAI,CAAC,EAAQ,OAAQ,OAGrB,IAAM,EAAY,EAAY,IAC5B,OACD,CACG,EAAY,EAChB,IAAK,IAAM,KAAY,EAAW,CAChC,IAAM,EAAO,EAAS,KAEtB,GACE,EAAE,sBAAsB,EAAK,EAC7B,EAAE,gBAAgB,EAAK,WAAW,EAClC,CAAC,EAAK,WAAW,MAAM,WAAW,SAAS,EAC3C,CAAC,EAAK,WAAW,MAAM,WAAW,UAAU,CAE5C,GAAa,OAEb,MAIJ,EAAY,KAAK,KAAK,OAAO,EAAW,EAAG,GAAG,EAAQ,EAEzD,CACF,CACF"}
1
+ {"version":3,"file":"babel-plugin-intlayer-optimize.cjs","names":[],"sources":["../../src/babel-plugin-intlayer-optimize.ts"],"sourcesContent":["import { dirname, join, relative } from 'node:path';\nimport type { NodePath, PluginObj, PluginPass } from '@babel/core';\nimport type * as BabelTypes from '@babel/types';\nimport { getPathHash } from '@intlayer/chokidar/utils';\nimport { normalizePath } from '@intlayer/config/utils';\n\nconst PACKAGE_LIST = [\n 'intlayer',\n '@intlayer/core',\n 'react-intlayer',\n 'react-intlayer/client',\n 'react-intlayer/server',\n 'next-intlayer',\n 'next-intlayer/client',\n 'next-intlayer/server',\n 'svelte-intlayer',\n 'vue-intlayer',\n 'angular-intlayer',\n 'preact-intlayer',\n 'solid-intlayer',\n];\n\nconst CALLER_LIST = ['useIntlayer', 'getIntlayer'] as const;\n\n/**\n * Packages that support dynamic import\n */\nconst PACKAGE_LIST_DYNAMIC = [\n 'react-intlayer',\n 'react-intlayer/client',\n 'react-intlayer/server',\n 'next-intlayer',\n 'next-intlayer/client',\n 'next-intlayer/server',\n 'preact-intlayer',\n 'vue-intlayer',\n 'solid-intlayer',\n 'svelte-intlayer',\n 'angular-intlayer',\n] as const;\n\nconst STATIC_IMPORT_FUNCTION = {\n getIntlayer: 'getDictionary',\n useIntlayer: 'useDictionary',\n} as const;\n\nconst DYNAMIC_IMPORT_FUNCTION = {\n useIntlayer: 'useDictionaryDynamic',\n} as const;\n\n/**\n * Options for the optimization Babel plugin\n */\nexport type OptimizePluginOptions = {\n /**\n * If false, the plugin will not apply any transformation.\n */\n optimize?: boolean;\n /**\n * The path to the dictionaries directory.\n */\n dictionariesDir: string;\n /**\n * The path to the dictionaries entry file.\n */\n dictionariesEntryPath: string;\n /**\n * The path to the unmerged dictionaries entry file.\n */\n unmergedDictionariesEntryPath: string;\n /**\n * The path to the unmerged dictionaries directory.\n */\n unmergedDictionariesDir: string;\n /**\n * The path to the dictionaries directory.\n */\n dynamicDictionariesDir: string;\n /**\n * The path to the dynamic dictionaries entry file.\n */\n dynamicDictionariesEntryPath: string;\n /**\n * The path to the fetch dictionaries directory.\n */\n fetchDictionariesDir: string;\n /**\n * The path to the fetch dictionaries entry file.\n */\n fetchDictionariesEntryPath: string;\n /**\n * If true, the plugin will replace the dictionary entry file with `export default {}`.\n */\n replaceDictionaryEntry: boolean;\n /**\n * If true, the plugin will activate the dynamic import of the dictionaries. It will rely on Suspense to load the dictionaries.\n */\n importMode: 'static' | 'dynamic' | 'fetch' | undefined;\n /**\n * Map of dictionary keys to their specific import mode.\n */\n dictionaryModeMap?: Record<\n string,\n 'static' | 'dynamic' | 'fetch' | undefined\n >;\n /**\n * Files list to traverse.\n */\n filesList: string[];\n};\n\ntype State = PluginPass & {\n opts: OptimizePluginOptions;\n /** map key → generated ident (per-file) for static imports */\n _newStaticImports?: Map<string, BabelTypes.Identifier>;\n /** map key → generated ident (per-file) for dynamic imports */\n _newDynamicImports?: Map<string, BabelTypes.Identifier>;\n /** whether the current file imported *any* intlayer package */\n _hasValidImport?: boolean;\n /** map from local identifier name to the imported intlayer func name ('useIntlayer' | 'getIntlayer') */\n _callerMap?: Map<string, (typeof CALLER_LIST)[number]>;\n /** whether the current file *is* the dictionaries entry file */\n _isDictEntry?: boolean;\n /** whether dynamic helpers are active for this file */\n _useDynamicHelpers?: boolean;\n /** whether the current file is included in the filesList */\n _isIncluded?: boolean;\n};\n\n/**\n * Replicates the xxHash64 → Base-62 algorithm used by the SWC version\n * and prefixes an underscore so the generated identifiers never collide\n * with user-defined ones.\n */\nconst makeIdent = (\n key: string,\n t: typeof BabelTypes\n): BabelTypes.Identifier => {\n const hash = getPathHash(key);\n return t.identifier(`_${hash}`);\n};\n\nconst computeImport = (\n fromFile: string,\n dictionariesDir: string,\n dynamicDictionariesDir: string,\n fetchDictionariesDir: string,\n key: string,\n importMode: 'static' | 'dynamic' | 'fetch'\n): string => {\n let relativePath = join(dictionariesDir, `${key}.json`);\n\n if (importMode === 'fetch') {\n relativePath = join(fetchDictionariesDir, `${key}.mjs`);\n }\n\n if (importMode === 'dynamic') {\n relativePath = join(dynamicDictionariesDir, `${key}.mjs`);\n }\n\n let rel = relative(dirname(fromFile), relativePath);\n\n // Fix windows path\n rel = normalizePath(rel);\n\n // Fix relative path\n if (!rel.startsWith('./') && !rel.startsWith('../')) {\n rel = `./${rel}`;\n }\n\n return rel;\n};\n\n/**\n * Babel plugin that transforms Intlayer function calls and auto-imports dictionaries.\n *\n * This plugin transforms calls to `useIntlayer()` and `getIntlayer()` from various Intlayer\n * packages into optimized dictionary access patterns, automatically importing the required\n * dictionary files based on the configured import mode.\n *\n * ## Supported Input Patterns\n *\n * The plugin recognizes these function calls:\n *\n * ```ts\n * // useIntlayer\n * import { useIntlayer } from 'react-intlayer';\n * import { useIntlayer } from 'next-intlayer';\n *\n * // getIntlayer\n * import { getIntlayer } from 'intlayer';\n *\n * // Usage\n * const content = useIntlayer('app');\n * const content = getIntlayer('app');\n * ```\n *\n * ## Transformation Modes\n *\n * ### Static Mode (default: `importMode = \"static\"`)\n *\n * Imports JSON dictionaries directly and replaces function calls with dictionary access:\n *\n * **Output:**\n * ```ts\n * import _dicHash from '../../.intlayer/dictionaries/app.json' with { type: 'json' };\n * import { useDictionary as useIntlayer } from 'react-intlayer';\n * import { getDictionary as getIntlayer } from 'intlayer';\n *\n * const content1 = useIntlayer(_dicHash);\n * const content2 = getIntlayer(_dicHash);\n * ```\n *\n * ### Dynamic Mode (`importMode = \"dynamic\"`)\n *\n * Uses dynamic dictionary loading with Suspense support:\n *\n * **Output:**\n * ```ts\n * import _dicHash from '../../.intlayer/dictionaries/app.json' with { type: 'json' };\n * import _dicHash_dyn from '../../.intlayer/dynamic_dictionaries/app.mjs';\n * import { useDictionaryDynamic as useIntlayer } from 'react-intlayer';\n * import { getDictionary as getIntlayer } from 'intlayer';\n *\n * const content1 = useIntlayer(_dicHash_dyn, 'app');\n * const content2 = getIntlayer(_dicHash);\n * ```\n *\n * ### Live Mode (`importMode = \"live\"`)\n *\n * Uses live-based dictionary loading for remote dictionaries:\n *\n * **Output if `dictionaryModeMap` includes the key with \"live\" value:**\n * ```ts\n * import _dicHash from '../../.intlayer/dictionaries/app.json' with { type: 'json' };\n * import _dicHash_fetch from '../../.intlayer/fetch_dictionaries/app.mjs';\n * import { useDictionaryDynamic as useIntlayer } from 'react-intlayer';\n * import { getDictionary as getIntlayer } from 'intlayer';\n *\n * const content1 = useIntlayer(_dicHash_fetch, \"app\");\n * const content2 = getIntlayer(_dicHash);\n * ```\n *\n * > If `dictionaryModeMap` does not include the key with \"live\" value, the plugin will fallback to the dynamic impor\n *\n * ```ts\n * import _dicHash from '../../.intlayer/dictionaries/app.json' with { type: 'json' };\n * import _dicHash_dyn from '../../.intlayer/dynamic_dictionaries/app.mjs';\n * import { useDictionaryDynamic as useIntlayer } from 'react-intlayer';\n * import { getDictionary as getIntlayer } from 'intlayer';\n *\n * const content1 = useIntlayer(_dicHash_dyn, 'app');\n * const content2 = getIntlayer(_dicHash);\n * ```\n */\nexport const intlayerOptimizeBabelPlugin = (babel: {\n types: typeof BabelTypes;\n}): PluginObj<State> => {\n const { types: t } = babel;\n\n return {\n name: 'babel-plugin-intlayer-transform',\n\n pre() {\n this._newStaticImports = new Map();\n this._newDynamicImports = new Map();\n this._callerMap = new Map();\n this._isIncluded = true;\n this._hasValidImport = false;\n this._isDictEntry = false;\n this._useDynamicHelpers = false;\n\n // If optimize is false, skip processing entirely\n if (this.opts.optimize === false) {\n this._isIncluded = false;\n return;\n }\n\n // If filesList is provided, check if current file is included\n const filename = this.file.opts.filename;\n if (this.opts.filesList && filename) {\n const isIncluded = this.opts.filesList.includes(filename);\n\n if (!isIncluded) {\n // Force _isIncluded to false to skip processing\n this._isIncluded = false;\n return;\n }\n }\n },\n\n visitor: {\n /* If this file *is* the dictionaries entry, short-circuit: export {} */\n Program: {\n enter(programPath, state) {\n // Safe access to filename\n const filename = state.file.opts.filename;\n\n // Check if this is the correct file to transform\n\n if (\n state.opts.replaceDictionaryEntry &&\n filename === state.opts.dictionariesEntryPath\n ) {\n state._isDictEntry = true;\n\n // Traverse the program to surgically remove/edit specific parts\n programPath.traverse({\n // Remove all import statements (cleaning up 'sssss.json')\n ImportDeclaration(path) {\n path.remove();\n },\n\n // Find the variable definition and empty the object\n VariableDeclarator(path) {\n // We look for: const x = { ... }\n\n if (t.isObjectExpression(path.node.init)) {\n // Set the object properties to an empty array: {}\n path.node.init.properties = [];\n }\n },\n });\n\n // (Optional) Stop other plugins from processing this file further if needed\n // programPath.stop();\n }\n },\n\n /**\n * After full traversal, process imports and call expressions, then inject the JSON dictionary imports.\n *\n * We do the transformation in Program.exit (via a manual traverse) rather than using\n * top-level ImportDeclaration/CallExpression visitors. This ensures that if another plugin\n * (like babel-plugin-intlayer-extract) adds new useIntlayer calls in its Program.exit,\n * we will see and transform them here because our Program.exit runs after theirs.\n */\n exit(programPath, state) {\n if (state._isDictEntry) return; // nothing else to do – already replaced\n\n if (!state._isIncluded) return; // early-out if file is not included\n\n // Manual traversal to process imports and call expressions\n // This runs AFTER all other plugins' visitors have completed\n\n // Pre-pass to determine if we should use dynamic helpers\n let fileHasDynamicCall = false;\n programPath.traverse({\n CallExpression(path) {\n const callee = path.node.callee;\n\n if (!t.isIdentifier(callee)) return;\n\n const originalImportedName = state._callerMap?.get(callee.name);\n if (originalImportedName !== 'useIntlayer') return;\n\n const arg = path.node.arguments[0];\n\n let key: string | undefined;\n\n if (arg && t.isStringLiteral(arg)) {\n key = arg.value;\n } else if (\n arg &&\n t.isTemplateLiteral(arg) &&\n arg.expressions.length === 0 &&\n arg.quasis.length === 1\n ) {\n // If the bundler output is `breadcrumb` instead of 'breadcrumb'\n key = arg.quasis[0].value.cooked ?? arg.quasis[0].value.raw;\n }\n\n if (!key) return;\n const dictionaryOverrideMode =\n state.opts.dictionaryModeMap?.[key];\n\n if (\n dictionaryOverrideMode === 'dynamic' ||\n dictionaryOverrideMode === 'fetch'\n ) {\n fileHasDynamicCall = true;\n }\n },\n });\n\n programPath.traverse({\n /* Inspect every intlayer import */\n ImportDeclaration(path) {\n const src = path.node.source.value;\n\n if (!PACKAGE_LIST.includes(src)) return;\n\n // Mark that we do import from an intlayer package in this file\n state._hasValidImport = true;\n\n for (const spec of path.node.specifiers) {\n if (!t.isImportSpecifier(spec)) continue;\n\n const importedName = t.isIdentifier(spec.imported)\n ? spec.imported.name\n : (spec.imported as BabelTypes.StringLiteral).value;\n\n if (CALLER_LIST.includes(importedName as any)) {\n state._callerMap?.set(\n spec.local.name,\n importedName as (typeof CALLER_LIST)[number]\n );\n }\n\n const importMode = state.opts.importMode;\n // Determine whether this import should use the dynamic helpers.\n const shouldUseDynamicHelpers =\n (importMode === 'dynamic' ||\n importMode === 'fetch' ||\n fileHasDynamicCall) &&\n PACKAGE_LIST_DYNAMIC.includes(src as any);\n\n // Remember for later (CallExpression) whether we are using the dynamic helpers\n\n if (shouldUseDynamicHelpers) {\n state._useDynamicHelpers = true;\n }\n\n let helperMap: Record<string, string>;\n\n if (shouldUseDynamicHelpers) {\n // Use dynamic helpers for useIntlayer when dynamic mode is enabled\n helperMap = {\n ...STATIC_IMPORT_FUNCTION,\n ...DYNAMIC_IMPORT_FUNCTION,\n } as Record<string, string>;\n } else {\n // Use static helpers by default\n helperMap = STATIC_IMPORT_FUNCTION as Record<string, string>;\n }\n\n const newIdentifier = helperMap[importedName];\n\n // Only rewrite when we actually have a mapping for the imported\n // specifier (ignore unrelated named imports).\n\n if (newIdentifier) {\n // Keep the local alias intact (so calls remain `useIntlayer` /\n // `getIntlayer`), but rewrite the imported identifier so it\n // points to our helper implementation.\n spec.imported = t.identifier(newIdentifier);\n }\n }\n },\n\n /* Replace calls: useIntlayer(\"foo\") → useDictionary(_hash) or useDictionaryDynamic(_hash, \"foo\") */\n CallExpression(path) {\n const callee = path.node.callee;\n\n if (!t.isIdentifier(callee)) return;\n\n const originalImportedName = state._callerMap?.get(callee.name);\n if (!originalImportedName) return;\n\n // Ensure we ultimately emit helper imports for files that *invoke*\n // the hooks, even if they didn't import them directly (edge cases with\n // re-exports).\n state._hasValidImport = true;\n\n const arg = path.node.arguments[0];\n\n let key: string | undefined;\n\n if (arg && t.isStringLiteral(arg)) {\n key = arg.value;\n } else if (\n arg &&\n t.isTemplateLiteral(arg) &&\n arg.expressions.length === 0 &&\n arg.quasis.length === 1\n ) {\n // If the bundler output is `breadcrumb` instead of 'breadcrumb'\n key = arg.quasis[0].value.cooked ?? arg.quasis[0].value.raw;\n }\n\n if (!key) return; // must be a static literal\n const importMode = state.opts.importMode;\n const isUseIntlayer = originalImportedName === 'useIntlayer';\n const useDynamicHelpers = Boolean(state._useDynamicHelpers);\n\n // Decide per-call mode: 'static' | 'dynamic' | 'fetch'\n let perCallMode: 'static' | 'dynamic' | 'fetch' = 'static';\n\n const dictionaryOverrideMode =\n state.opts.dictionaryModeMap?.[key];\n\n if (isUseIntlayer && useDynamicHelpers) {\n if (dictionaryOverrideMode) {\n perCallMode = dictionaryOverrideMode;\n } else if (importMode === 'dynamic') {\n perCallMode = 'dynamic';\n } else if (importMode === 'fetch') {\n perCallMode = 'fetch';\n }\n } else if (isUseIntlayer && !useDynamicHelpers) {\n // If dynamic helpers are NOT active (global mode is static),\n // we STILL might want to force dynamic/live for this specific call\n\n if (\n dictionaryOverrideMode === 'dynamic' ||\n dictionaryOverrideMode === 'fetch'\n ) {\n perCallMode = dictionaryOverrideMode;\n }\n }\n\n let ident: BabelTypes.Identifier;\n\n if (perCallMode === 'fetch') {\n // Use fetch dictionaries entry (live mode for selected keys)\n let dynamicIdent = state._newDynamicImports?.get(key);\n\n if (!dynamicIdent) {\n const hash = getPathHash(key);\n dynamicIdent = t.identifier(`_${hash}_fetch`);\n state._newDynamicImports?.set(key, dynamicIdent);\n }\n ident = dynamicIdent;\n\n // Helper: first argument is the dictionary entry, second is the key\n path.node.arguments = [\n t.identifier(ident.name),\n ...path.node.arguments,\n ];\n } else if (perCallMode === 'dynamic') {\n // Use dynamic dictionaries entry\n let dynamicIdent = state._newDynamicImports?.get(key);\n\n if (!dynamicIdent) {\n // Create a unique identifier for dynamic imports by appending a suffix\n const hash = getPathHash(key);\n dynamicIdent = t.identifier(`_${hash}_dyn`);\n state._newDynamicImports?.set(key, dynamicIdent);\n }\n ident = dynamicIdent;\n\n // Dynamic helper: first argument is the dictionary, second is the key.\n path.node.arguments = [\n t.identifier(ident.name),\n ...path.node.arguments,\n ];\n } else {\n // Use static imports for getIntlayer or useIntlayer when not using dynamic helpers\n let staticIdent = state._newStaticImports?.get(key);\n\n if (!staticIdent) {\n staticIdent = makeIdent(key, t);\n state._newStaticImports?.set(key, staticIdent);\n }\n ident = staticIdent;\n\n // Static helper (useDictionary / getDictionary): replace key with iden\n path.node.arguments[0] = t.identifier(ident.name);\n }\n },\n });\n\n // Early-out if we touched nothing\n\n if (!state._hasValidImport) return;\n\n const file = state.file.opts.filename!;\n const dictionariesDir = state.opts.dictionariesDir;\n const dynamicDictionariesDir = state.opts.dynamicDictionariesDir;\n const fetchDictionariesDir = state.opts.fetchDictionariesDir;\n const imports: BabelTypes.ImportDeclaration[] = [];\n\n // Generate static JSON imports (getIntlayer always uses JSON dictionaries)\n for (const [key, ident] of state._newStaticImports!) {\n const rel = computeImport(\n file,\n dictionariesDir,\n dynamicDictionariesDir,\n fetchDictionariesDir,\n key,\n 'static'\n );\n\n const importDeclarationNode = t.importDeclaration(\n [t.importDefaultSpecifier(t.identifier(ident.name))],\n t.stringLiteral(rel)\n );\n\n // Add 'type: json' attribute for JSON files\n importDeclarationNode.attributes = [\n t.importAttribute(t.identifier('type'), t.stringLiteral('json')),\n ];\n\n imports.push(importDeclarationNode);\n }\n\n // Generate dynamic/fetch imports (for useIntlayer when using dynamic/live helpers)\n for (const [key, ident] of state._newDynamicImports!) {\n const modeForThisIdent: 'dynamic' | 'fetch' = ident.name.endsWith(\n '_fetch'\n )\n ? 'fetch'\n : 'dynamic';\n\n const rel = computeImport(\n file,\n dictionariesDir,\n dynamicDictionariesDir,\n fetchDictionariesDir,\n key,\n modeForThisIdent\n );\n imports.push(\n t.importDeclaration(\n [t.importDefaultSpecifier(t.identifier(ident.name))],\n t.stringLiteral(rel)\n )\n );\n }\n\n if (!imports.length) return;\n\n /* Keep \"use client\" / \"use server\" directives at the very top. */\n const bodyPaths = programPath.get(\n 'body'\n ) as NodePath<BabelTypes.Statement>[];\n let insertPos = 0;\n for (const stmtPath of bodyPaths) {\n const stmt = stmtPath.node;\n\n if (\n t.isExpressionStatement(stmt) &&\n t.isStringLiteral(stmt.expression) &&\n !stmt.expression.value.startsWith('import') &&\n !stmt.expression.value.startsWith('require')\n ) {\n insertPos += 1;\n } else {\n break;\n }\n }\n\n programPath.node.body.splice(insertPos, 0, ...imports);\n },\n },\n },\n };\n};\n"],"mappings":";;;;;;;AAMA,MAAM,eAAe;CACnB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD;AAED,MAAM,cAAc,CAAC,eAAe,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