@intlayer/babel 5.5.2 → 5.5.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -28,156 +28,197 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
28
28
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
29
  var babel_plugin_intlayer_exports = {};
30
30
  __export(babel_plugin_intlayer_exports, {
31
- babelPluginIntlayer: () => babelPluginIntlayer
31
+ intlayerBabelPlugin: () => intlayerBabelPlugin
32
32
  });
33
33
  module.exports = __toCommonJS(babel_plugin_intlayer_exports);
34
- var import_parser = require("@babel/parser");
35
34
  var t = __toESM(require("@babel/types"));
36
35
  var import_chokidar = require("@intlayer/chokidar");
37
- var import_config = require("@intlayer/config");
38
- var import_path = require("path");
36
+ var import_node_path = require("node:path");
39
37
  const PACKAGE_LIST = [
38
+ "intlayer",
39
+ "@intlayer/core",
40
40
  "react-intlayer",
41
41
  "react-intlayer/client",
42
42
  "react-intlayer/server",
43
43
  "next-intlayer",
44
- "next-intlayer/server",
45
44
  "next-intlayer/client",
45
+ "next-intlayer/server",
46
46
  "svelte-intlayer",
47
47
  "vue-intlayer",
48
48
  "angular-intlayer",
49
49
  "preact-intlayer",
50
- "solid-inltayer"
50
+ "solid-intlayer"
51
51
  ];
52
52
  const CALLER_LIST = ["useIntlayer", "getIntlayer"];
53
- const globalUsedKeys = /* @__PURE__ */ new Set();
54
- let isThreeShakable = true;
55
- const isFileInContentDir = (filePath, contentDirs) => {
56
- return contentDirs.some((dir) => {
57
- const normalizedDir = dir.replace(/[/\\]+$/, "");
58
- return filePath.startsWith(normalizedDir);
59
- });
53
+ const PACKAGE_LIST_DYNAMIC = [
54
+ "react-intlayer",
55
+ "react-intlayer/client",
56
+ "react-intlayer/server",
57
+ "next-intlayer",
58
+ "next-intlayer/client",
59
+ "next-intlayer/server"
60
+ ];
61
+ const STATIC_IMPORT_FUNCTION = {
62
+ getIntlayer: "getDictionary",
63
+ useIntlayer: "useDictionary"
64
+ };
65
+ const DYNAMIC_IMPORT_FUNCTION = {
66
+ useIntlayer: "useDictionaryDynamic"
60
67
  };
61
- const isValidIntlayerImport = (source) => {
62
- return PACKAGE_LIST.includes(source);
68
+ const makeIdent = (key) => {
69
+ const hash = (0, import_chokidar.getFileHash)(key);
70
+ return t.identifier(`_${hash}`);
63
71
  };
64
- const babelPluginIntlayer = () => {
65
- const configuration = (0, import_config.getConfiguration)();
66
- const dictionariesRoot = configuration.content.mainDir.replace(
67
- /[/\\]+$/,
68
- ""
69
- );
70
- const contentDir = configuration.content.contentDir;
71
- const appLogger = (0, import_config.getAppLogger)(configuration);
72
+ const computeRelativeImport = (fromFile, dictionariesDir, dynamicDictionariesDir, key, isDynamic = false) => {
73
+ const jsonPath = isDynamic ? (0, import_node_path.join)(dynamicDictionariesDir, `${key}.mjs`) : (0, import_node_path.join)(dictionariesDir, `${key}.json`);
74
+ let rel = (0, import_node_path.relative)((0, import_node_path.dirname)(fromFile), jsonPath).replace(/\\/g, "/");
75
+ if (!rel.startsWith("./") && !rel.startsWith("../")) rel = `./${rel}`;
76
+ return rel;
77
+ };
78
+ const intlayerBabelPlugin = () => {
72
79
  return {
73
- name: "babel-plugin-intlayer-prune",
80
+ name: "babel-plugin-intlayer-transform",
81
+ pre() {
82
+ this._newStaticImports = /* @__PURE__ */ new Map();
83
+ this._newDynamicImports = /* @__PURE__ */ new Map();
84
+ this._isIncluded = true;
85
+ this._hasValidImport = false;
86
+ this._isDictEntry = false;
87
+ this._useDynamicHelpers = false;
88
+ const filename = this.file.opts.filename;
89
+ if (this.opts.filesList && filename) {
90
+ const isIncluded = this.opts.filesList.includes(filename);
91
+ if (!isIncluded) {
92
+ this._isIncluded = false;
93
+ return;
94
+ }
95
+ }
96
+ },
74
97
  visitor: {
98
+ /* 0. If this file *is* the dictionaries entry, short-circuit: export {} */
75
99
  Program: {
76
- enter(_programPath, state) {
77
- state.importedPackages = /* @__PURE__ */ new Set();
78
- state.hasValidIntlayerImport = false;
79
- const filePath = state.file.opts.filename ?? "";
80
- if (!isFileInContentDir(filePath, contentDir)) {
81
- return;
100
+ enter(programPath, state) {
101
+ const filename = state.file.opts.filename;
102
+ if (filename === state.opts.dictionariesEntryPath) {
103
+ state._isDictEntry = true;
104
+ programPath.node.body = [
105
+ t.exportDefaultDeclaration(t.objectExpression([]))
106
+ ];
107
+ programPath.stop();
82
108
  }
83
109
  },
84
- /*
85
- * After the whole file has been walked, decide if THIS file is the
86
- * dictionary entry-point. If it is, swap its body for the generated
87
- * code that imports only the used dictionaries.
88
- */
110
+ /* 3. After full traversal, inject the JSON dictionary imports. */
89
111
  exit(programPath, state) {
90
- const filePath = state.file.opts.filename ?? "";
91
- if (!isFileInContentDir(filePath, contentDir)) return;
92
- if (!isThreeShakable) return;
93
- if (!filePath.startsWith(dictionariesRoot)) return;
94
- const keys = Array.from(globalUsedKeys);
95
- if (!keys.length) return;
96
- const extension = (0, import_path.extname)(filePath);
97
- const format = extension === ".cjs" ? "cjs" : "esm";
98
- const dictionaries = (0, import_chokidar.getBuiltDictionariesPath)(configuration).filter(
99
- (p) => keys.some((k) => p.endsWith(`${import_path.sep}${k}.json`))
100
- );
101
- const generatedSrc = (0, import_chokidar.generateDictionaryListContent)(
102
- dictionaries,
103
- format,
104
- configuration
105
- );
106
- if (!generatedSrc) return;
107
- const newAst = (0, import_parser.parse)(generatedSrc, {
108
- sourceType: format === "cjs" ? "script" : "module",
109
- plugins: ["importMeta"]
110
- });
111
- appLogger("Unused dictionaries pruned to reduce bundle size", {
112
- level: "info"
113
- });
114
- programPath.node.body = [];
115
- programPath.pushContainer("body", newAst.program.body);
116
- state.file.metadata = {
117
- ...state.file.metadata,
118
- intlayerPruned: true
119
- };
112
+ if (state._isDictEntry) return;
113
+ if (!state._hasValidImport) return;
114
+ if (!state._isIncluded) return;
115
+ const file = state.file.opts.filename;
116
+ const dictionariesDir = state.opts.dictionariesDir;
117
+ const dynamicDictionariesDir = state.opts.dynamicDictionariesDir;
118
+ const imports = [];
119
+ for (const [key, ident] of state._newStaticImports) {
120
+ const rel = computeRelativeImport(
121
+ file,
122
+ dictionariesDir,
123
+ dynamicDictionariesDir,
124
+ key,
125
+ false
126
+ // Always static
127
+ );
128
+ imports.push(
129
+ t.importDeclaration(
130
+ [t.importDefaultSpecifier(t.identifier(ident.name))],
131
+ t.stringLiteral(rel)
132
+ )
133
+ );
134
+ }
135
+ for (const [key, ident] of state._newDynamicImports) {
136
+ const rel = computeRelativeImport(
137
+ file,
138
+ dictionariesDir,
139
+ dynamicDictionariesDir,
140
+ key,
141
+ true
142
+ // Always dynamic
143
+ );
144
+ imports.push(
145
+ t.importDeclaration(
146
+ [t.importDefaultSpecifier(t.identifier(ident.name))],
147
+ t.stringLiteral(rel)
148
+ )
149
+ );
150
+ }
151
+ if (!imports.length) return;
152
+ const bodyPaths = programPath.get("body");
153
+ let insertPos = 0;
154
+ for (const stmtPath of bodyPaths) {
155
+ const stmt = stmtPath.node;
156
+ if (t.isExpressionStatement(stmt) && t.isStringLiteral(stmt.expression) && !stmt.expression.value.startsWith("import") && !stmt.expression.value.startsWith("require")) {
157
+ insertPos += 1;
158
+ } else {
159
+ break;
160
+ }
161
+ }
162
+ programPath.node.body.splice(insertPos, 0, ...imports);
120
163
  }
121
164
  },
165
+ /* 1. Inspect *every* intlayer import. */
122
166
  ImportDeclaration(path, state) {
123
- const filePath = state.file.opts.filename ?? "";
124
- if (!isFileInContentDir(filePath, contentDir)) {
125
- return;
126
- }
127
- const source = path.node.source.value;
128
- state.importedPackages?.add(source);
129
- if (isValidIntlayerImport(source)) {
130
- const hasIntlayerFunction = path.node.specifiers.some((specifier) => {
131
- if (t.isImportSpecifier(specifier) && t.isIdentifier(specifier.imported)) {
132
- return CALLER_LIST.includes(specifier.imported.name);
133
- }
134
- return false;
135
- });
136
- if (hasIntlayerFunction) {
137
- state.hasValidIntlayerImport = true;
167
+ if (state._isDictEntry) return;
168
+ const src = path.node.source.value;
169
+ if (!PACKAGE_LIST.includes(src)) return;
170
+ state._hasValidImport = true;
171
+ for (const spec of path.node.specifiers) {
172
+ if (!t.isImportSpecifier(spec)) continue;
173
+ const importedName = t.isIdentifier(spec.imported) ? spec.imported.name : spec.imported.value;
174
+ const activateDynamicImport = state.opts.activateDynamicImport;
175
+ const shouldUseDynamicHelpers = activateDynamicImport && PACKAGE_LIST_DYNAMIC.includes(src);
176
+ if (shouldUseDynamicHelpers) {
177
+ state._useDynamicHelpers = true;
178
+ }
179
+ const helperMap = shouldUseDynamicHelpers ? {
180
+ ...STATIC_IMPORT_FUNCTION,
181
+ ...DYNAMIC_IMPORT_FUNCTION
182
+ } : STATIC_IMPORT_FUNCTION;
183
+ const newIdentifier = helperMap[importedName];
184
+ if (newIdentifier) {
185
+ spec.imported = t.identifier(newIdentifier);
138
186
  }
139
187
  }
140
188
  },
189
+ /* 2. Replace calls: useIntlayer("foo") → useDictionary(_hash) or useDictionaryDynamic(_hash, "foo") */
141
190
  CallExpression(path, state) {
142
- const filePath = state.file.opts.filename ?? "";
143
- if (!isFileInContentDir(filePath, contentDir)) return;
144
- if (!isThreeShakable) return;
145
- const { node } = path;
146
- const renderError = (message) => {
147
- const filePath2 = state.file.opts.filename ?? "";
148
- const codeFrame = path.buildCodeFrameError("").message;
149
- console.info("");
150
- appLogger(message, {
151
- level: "error"
152
- });
153
- appLogger(`At ${(0, import_path.relative)(process.cwd(), filePath2)}`, {
154
- level: "error"
155
- });
156
- appLogger(codeFrame.split("\n").slice(1).join("\n"), {
157
- level: "error"
158
- });
159
- };
160
- if (t.isIdentifier(node.callee) && CALLER_LIST.includes(node.callee.name)) {
161
- if (!state.hasValidIntlayerImport) {
162
- isThreeShakable = false;
163
- renderError(
164
- `For dictionary optimization to work, ${node.callee.name} must be imported from one of these packages: ${PACKAGE_LIST.join(", ")}`
165
- );
166
- return;
167
- }
168
- if (!node.arguments.length) {
169
- isThreeShakable = false;
170
- renderError(`${node.callee.name} requires at least one argument`);
171
- return;
191
+ if (state._isDictEntry) return;
192
+ const callee = path.node.callee;
193
+ if (!t.isIdentifier(callee)) return;
194
+ if (!CALLER_LIST.includes(callee.name)) return;
195
+ state._hasValidImport = true;
196
+ const arg = path.node.arguments[0];
197
+ if (!arg || !t.isStringLiteral(arg)) return;
198
+ const key = arg.value;
199
+ const useDynamic = Boolean(state._useDynamicHelpers);
200
+ const shouldUseDynamicForThisCall = callee.name === "useIntlayer" && useDynamic;
201
+ let ident;
202
+ if (shouldUseDynamicForThisCall) {
203
+ let dynamicIdent = state._newDynamicImports.get(key);
204
+ if (!dynamicIdent) {
205
+ const hash = (0, import_chokidar.getFileHash)(key);
206
+ dynamicIdent = t.identifier(`_${hash}_dyn`);
207
+ state._newDynamicImports.set(key, dynamicIdent);
172
208
  }
173
- if (!t.isStringLiteral(node.arguments[0])) {
174
- isThreeShakable = false;
175
- renderError(
176
- `For dictionary optimization to work, ${node.callee.name} key must be a literal string, otherwise tree shaking cannot be performed properly`
177
- );
178
- return;
209
+ ident = dynamicIdent;
210
+ path.node.arguments = [
211
+ t.identifier(ident.name),
212
+ ...path.node.arguments
213
+ ];
214
+ } else {
215
+ let staticIdent = state._newStaticImports.get(key);
216
+ if (!staticIdent) {
217
+ staticIdent = makeIdent(key);
218
+ state._newStaticImports.set(key, staticIdent);
179
219
  }
180
- globalUsedKeys.add(node.arguments[0].value);
220
+ ident = staticIdent;
221
+ path.node.arguments[0] = t.identifier(ident.name);
181
222
  }
182
223
  }
183
224
  }
@@ -185,6 +226,6 @@ const babelPluginIntlayer = () => {
185
226
  };
186
227
  // Annotate the CommonJS export names for ESM import in node:
187
228
  0 && (module.exports = {
188
- babelPluginIntlayer
229
+ intlayerBabelPlugin
189
230
  });
190
231
  //# sourceMappingURL=babel-plugin-intlayer.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/babel-plugin-intlayer.ts"],"sourcesContent":["import type { PluginObj, PluginPass } from '@babel/core';\nimport { parse } from '@babel/parser';\nimport type { NodePath } from '@babel/traverse';\nimport * as t from '@babel/types';\nimport {\n generateDictionaryListContent,\n getBuiltDictionariesPath,\n} from '@intlayer/chokidar';\nimport { getAppLogger, getConfiguration } from '@intlayer/config';\nimport { extname, relative, sep } from 'path';\n\ntype PluginState = PluginPass & {\n opts: {\n enableTransform?: boolean;\n };\n // Add tracking for imports per file\n importedPackages?: Set<string>;\n hasValidIntlayerImport?: boolean;\n};\n\n// ────────────────────────────────────────────────────────────\n// shared state across ALL files (1 build = 1 Node process)\nconst PACKAGE_LIST = [\n 'react-intlayer',\n 'react-intlayer/client',\n 'react-intlayer/server',\n 'next-intlayer',\n 'next-intlayer/server',\n 'next-intlayer/client',\n 'svelte-intlayer',\n 'vue-intlayer',\n 'angular-intlayer',\n 'preact-intlayer',\n 'solid-inltayer',\n];\nconst CALLER_LIST = ['useIntlayer', 'getIntlayer'];\nconst globalUsedKeys = new Set<string>();\nlet isThreeShakable = true;\n// ────────────────────────────────────────────────────────────\n\n// Helper function to check if file is in contentDir\nconst isFileInContentDir = (\n filePath: string,\n contentDirs: string[]\n): boolean => {\n return contentDirs.some((dir) => {\n const normalizedDir = dir.replace(/[/\\\\]+$/, '');\n return filePath.startsWith(normalizedDir);\n });\n};\n\n// Helper function to check if import is from valid package\nconst isValidIntlayerImport = (source: string): boolean => {\n return PACKAGE_LIST.includes(source);\n};\n\nexport const babelPluginIntlayer = (): PluginObj<PluginState> => {\n const configuration = getConfiguration();\n const dictionariesRoot: string = configuration.content.mainDir.replace(\n /[/\\\\]+$/,\n ''\n );\n const contentDir: string[] = configuration.content.contentDir;\n const appLogger = getAppLogger(configuration);\n\n return {\n name: 'babel-plugin-intlayer-prune',\n\n visitor: {\n Program: {\n enter(_programPath, state: PluginState) {\n // Initialize per-file state\n state.importedPackages = new Set<string>();\n state.hasValidIntlayerImport = false;\n\n const filePath: string = state.file.opts.filename ?? '';\n\n // Skip files that are not in contentDir\n if (!isFileInContentDir(filePath, contentDir)) {\n return;\n }\n },\n\n /*\n * After the whole file has been walked, decide if THIS file is the\n * dictionary entry-point. If it is, swap its body for the generated\n * code that imports only the used dictionaries.\n */\n exit(programPath, state: PluginState) {\n const filePath: string = state.file.opts.filename ?? '';\n\n // Skip files that are not in contentDir\n if (!isFileInContentDir(filePath, contentDir)) return;\n\n // Skip files is bundle is not three-shakable\n if (!isThreeShakable) return;\n\n // Is this *the* entry-point we want to shrink?\n if (!filePath.startsWith(dictionariesRoot)) return;\n\n const keys = Array.from(globalUsedKeys);\n if (!keys.length) return; // nothing collected yet – leave the file untouched\n\n const extension = extname(filePath); // .js / .mjs / .cjs\n const format = extension === '.cjs' ? 'cjs' : 'esm';\n\n // Pick only the dictionaries whose basename matches a collected key\n const dictionaries = getBuiltDictionariesPath(configuration).filter(\n (p) => keys.some((k) => p.endsWith(`${sep}${k}.json`))\n );\n\n const generatedSrc = generateDictionaryListContent(\n dictionaries,\n format,\n configuration\n );\n if (!generatedSrc) return;\n\n // Replace the current AST with the new one\n const newAst = parse(generatedSrc, {\n sourceType: format === 'cjs' ? 'script' : 'module',\n plugins: ['importMeta'],\n });\n\n appLogger('Unused dictionaries pruned to reduce bundle size', {\n level: 'info',\n });\n\n // Clear and inject\n programPath.node.body = [];\n programPath.pushContainer('body', newAst.program.body);\n\n // Optional: mark the file as \"transformed\" for other tooling\n state.file.metadata = {\n ...state.file.metadata,\n intlayerPruned: true,\n };\n },\n },\n\n ImportDeclaration(\n path: NodePath<t.ImportDeclaration>,\n state: PluginState\n ) {\n const filePath: string = state.file.opts.filename ?? '';\n\n // Skip files that are not in contentDir\n if (!isFileInContentDir(filePath, contentDir)) {\n return;\n }\n\n const source = path.node.source.value;\n state.importedPackages?.add(source);\n\n // Check if this import is from a valid intlayer package\n if (isValidIntlayerImport(source)) {\n // Check if any of the imported specifiers include useIntlayer or getIntlayer\n const hasIntlayerFunction = path.node.specifiers.some((specifier) => {\n if (\n t.isImportSpecifier(specifier) &&\n t.isIdentifier(specifier.imported)\n ) {\n return CALLER_LIST.includes(specifier.imported.name);\n }\n return false;\n });\n\n if (hasIntlayerFunction) {\n state.hasValidIntlayerImport = true;\n }\n }\n },\n\n CallExpression(path: NodePath<t.CallExpression>, state: PluginState) {\n const filePath: string = state.file.opts.filename ?? '';\n\n // Skip files that are not in contentDir\n if (!isFileInContentDir(filePath, contentDir)) return;\n if (!isThreeShakable) return;\n\n const { node } = path;\n\n const renderError = (message: string) => {\n const filePath: string = state.file.opts.filename ?? '';\n\n // Generate code frame to show the error context\n const codeFrame = path.buildCodeFrameError('').message;\n\n console.info(''); // For formating\n appLogger(message, {\n level: 'error',\n });\n appLogger(`At ${relative(process.cwd(), filePath)}`, {\n level: 'error',\n });\n appLogger(codeFrame.split('\\n').slice(1).join('\\n'), {\n level: 'error',\n });\n };\n\n if (\n t.isIdentifier(node.callee) &&\n CALLER_LIST.includes(node.callee.name)\n ) {\n // Check if the function is imported from a valid package\n if (!state.hasValidIntlayerImport) {\n isThreeShakable = false;\n\n renderError(\n `For dictionary optimization to work, ${node.callee.name} must be imported from one of these packages: ${PACKAGE_LIST.join(', ')}`\n );\n return;\n }\n\n // Check if arguments exist\n if (!node.arguments.length) {\n isThreeShakable = false;\n\n renderError(`${node.callee.name} requires at least one argument`);\n\n return;\n }\n\n // Check if the first argument is a string literal\n if (!t.isStringLiteral(node.arguments[0])) {\n isThreeShakable = false;\n\n renderError(\n `For dictionary optimization to work, ${node.callee.name} key must be a literal string, otherwise tree shaking cannot be performed properly`\n );\n return;\n }\n\n globalUsedKeys.add(node.arguments[0].value);\n }\n },\n },\n };\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,oBAAsB;AAEtB,QAAmB;AACnB,sBAGO;AACP,oBAA+C;AAC/C,kBAAuC;AAavC,MAAM,eAAe;AAAA,EACnB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,E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I,CAAC,gBAAiB;AAEtB,cAAM,EAAE,KAAK,IAAI;AAEjB,cAAM,cAAc,CAAC,YAAoB;AACvC,gBAAMA,YAAmB,MAAM,KAAK,KAAK,YAAY;AAGrD,gBAAM,YAAY,KAAK,oBAAoB,EAAE,EAAE;AAE/C,kBAAQ,KAAK,EAAE;AACf,oBAAU,SAAS;AAAA,YACjB,OAAO;AAAA,UACT,CAAC;AACD,oBAAU,UAAM,sBAAS,QAAQ,IAAI,GAAGA,SAAQ,CAAC,IAAI;AAAA,YACnD,OAAO;AAAA,UACT,CAAC;AACD,oBAAU,UAAU,MAAM,IAAI,EAAE,MAAM,CAAC,EAAE,KAAK,IAAI,GAAG;AAAA,YACnD,OAAO;AAAA,UACT,CAAC;AAAA,QACH;AAEA,YACE,EAAE,aAAa,KAAK,MAAM,KAC1B,YAAY,SAAS,KAAK,OAAO,IAAI,GACrC;AAEA,cAAI,CAAC,MAAM,wBAAwB;AACjC,8BAAkB;AAElB;AAAA,cACE,wCAAwC,KAAK,OAAO,IAAI,iDAAiD,aAAa,KAAK,IAAI,CAAC;AAAA,YAClI;AACA;AAAA,UACF;AAGA,cAAI,CAAC,KAAK,UAAU,QAAQ;AAC1B,8BAAkB;AAElB,wBAAY,GAAG,KAAK,OAAO,IAAI,iCAAiC;AAEhE;AAAA,UACF;AAGA,cAAI,CAAC,EAAE,gBAAgB,KAAK,UAAU,CAAC,CAAC,GAAG;AACzC,8BAAkB;AAElB;AAAA,cACE,wCAAwC,KAAK,OAAO,IAAI;AAAA,YAC1D;AACA;AAAA,UACF;AAEA,yBAAe,IAAI,KAAK,UAAU,CAAC,EAAE,KAAK;AAAA,QAC5C;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;","names":["filePath"]}
1
+ {"version":3,"sources":["../../src/babel-plugin-intlayer.ts"],"sourcesContent":["import type { NodePath, PluginObj, PluginPass } from '@babel/core';\nimport * as t from '@babel/types';\nimport { getFileHash } from '@intlayer/chokidar';\nimport { dirname, join, relative } from 'node:path';\n\n/* ────────────────────────────────────────── constants ───────────────────── */\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] 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/* ────────────────────────────────────────── types ───────────────────────── */\n\ntype State = PluginPass & {\n opts: {\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 dictionaries directory.\n */\n dynamicDictionariesDir: string;\n /**\n * The path to the dynamic dictionaries entry file.\n */\n dynamicDictionariesEntryPath: string;\n /**\n * If true, the plugin will activate the dynamic import of the dictionaries.\n */\n activateDynamicImport?: boolean;\n /**\n * Files list to traverse.\n */\n filesList?: string[];\n };\n /** map key → generated ident (per-file) for static imports */\n _newStaticImports?: Map<string, t.Identifier>;\n /** map key → generated ident (per-file) for dynamic imports */\n _newDynamicImports?: Map<string, t.Identifier>;\n /** whether the current file imported *any* intlayer package */\n _hasValidImport?: boolean;\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};\n\n/* ────────────────────────────────────────── helpers ─────────────────────── */\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 = (key: string): t.Identifier => {\n const hash = getFileHash(key);\n return t.identifier(`_${hash}`);\n};\n\nconst computeRelativeImport = (\n fromFile: string,\n dictionariesDir: string,\n dynamicDictionariesDir: string,\n key: string,\n isDynamic = false\n): string => {\n const jsonPath = isDynamic\n ? join(dynamicDictionariesDir, `${key}.mjs`)\n : join(dictionariesDir, `${key}.json`);\n\n let rel = relative(dirname(fromFile), jsonPath).replace(/\\\\/g, '/'); // win →\n if (!rel.startsWith('./') && !rel.startsWith('../')) rel = `./${rel}`;\n return rel;\n};\n\n/* ────────────────────────────────────────── plugin ──────────────────────── */\n\n/**\n * Babel plugin that transforms `useIntlayer/getIntlayer` calls into\n * `useDictionary/getDictionary` and auto-imports the required JSON dictionaries.\n *\n *\n * This means cases like:\n *\n * ```ts\n * import { getIntlayer } from 'intlayer';\n * import { useIntlayer } from 'react-intlayer';\n *\n * // ...\n *\n * const content1 = getIntlayer('app');\n * const content2 = useIntlayer('app');\n * ```\n *\n * will be transformed into:\n *\n * ```ts\n * import _dicHash from '../../.intlayer/dictionaries/app.mjs';\n * import { getDictionary as getIntlayer } from 'intlayer';\n * import { useDictionaryDynamic as useIntlayer } from 'react-intlayer';\n *\n * // ...\n *\n * const content1 = getIntlayer(_dicHash);\n * const content2 = useIntlayer(_dicHash)\n * ```\n *\n * Or if the `activateDynamicImport` option is enabled:\n *\n * ```ts\n * import _dicHash from '../../.intlayer/dynamic_dictionaries/app.mjs';\n * import _dicHash_dyn from '../../.intlayer/dictionaries/app.mjs';\n *\n * import { useDictionary as getIntlayer } from 'intlayer';\n * import { useDictionaryDynamic as useIntlayer } from 'react-intlayer';\n *\n * // ...\n *\n * const content1 = getIntlayer(_dicHash);\n * const content2 = useIntlayer(_dicHash_dyn, 'app');\n * ```\n */\nexport const intlayerBabelPlugin = (): PluginObj<State> => {\n return {\n name: 'babel-plugin-intlayer-transform',\n\n pre() {\n this._newStaticImports = new Map();\n this._newDynamicImports = new Map();\n this._isIncluded = true;\n this._hasValidImport = false;\n this._isDictEntry = false;\n this._useDynamicHelpers = false;\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 /* 0. If this file *is* the dictionaries entry, short-circuit: export {} */\n Program: {\n enter(programPath, state) {\n const filename = state.file.opts.filename!;\n if (filename === state.opts.dictionariesEntryPath) {\n state._isDictEntry = true;\n // Replace all existing statements with: export default {}\n programPath.node.body = [\n t.exportDefaultDeclaration(t.objectExpression([])),\n ];\n // Stop further traversal for this plugin – nothing else to transform\n programPath.stop();\n }\n },\n\n /* 3. After full traversal, inject the JSON dictionary imports. */\n exit(programPath, state) {\n if (state._isDictEntry) return; // nothing else to do – already replaced\n if (!state._hasValidImport) return; // early-out if we touched nothing\n if (!state._isIncluded) return; // early-out if file is not included\n\n const file = state.file.opts.filename!;\n const dictionariesDir = state.opts.dictionariesDir;\n const dynamicDictionariesDir = state.opts.dynamicDictionariesDir;\n const imports: t.ImportDeclaration[] = [];\n\n // Generate static imports (for getIntlayer and useIntlayer when not using dynamic)\n for (const [key, ident] of state._newStaticImports!) {\n const rel = computeRelativeImport(\n file,\n dictionariesDir,\n dynamicDictionariesDir,\n key,\n false // Always static\n );\n imports.push(\n t.importDeclaration(\n [t.importDefaultSpecifier(t.identifier(ident.name))],\n t.stringLiteral(rel)\n )\n );\n }\n\n // Generate dynamic imports (for useIntlayer when using dynamic helpers)\n for (const [key, ident] of state._newDynamicImports!) {\n const rel = computeRelativeImport(\n file,\n dictionariesDir,\n dynamicDictionariesDir,\n key,\n true // Always dynamic\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('body') as NodePath<t.Statement>[];\n let insertPos = 0;\n for (const stmtPath of bodyPaths) {\n const stmt = stmtPath.node;\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 /* 1. Inspect *every* intlayer import. */\n ImportDeclaration(path, state) {\n if (state._isDictEntry) return; // skip if entry file – already handled\n\n const src = path.node.source.value;\n if (!PACKAGE_LIST.includes(src)) return;\n\n // Mark that we do import from an intlayer package in this file; this is\n // enough to know that we *might* need to inject runtime helpers later.\n state._hasValidImport = true;\n\n for (const spec of path.node.specifiers) {\n if (!t.isImportSpecifier(spec)) continue;\n\n // ⚠️ We now key off *imported* name, *not* local name.\n const importedName = t.isIdentifier(spec.imported)\n ? spec.imported.name\n : (spec.imported as t.StringLiteral).value;\n\n const activateDynamicImport = state.opts.activateDynamicImport;\n // Determine whether this import should use the dynamic helpers. We\n // only switch to the dynamic helpers when (1) the option is turned\n // on AND (2) the package we are importing from supports the dynamic\n // helpers.\n const shouldUseDynamicHelpers =\n activateDynamicImport && PACKAGE_LIST_DYNAMIC.includes(src as any);\n\n // Remember for later (CallExpression) whether we are using the dynamic helpers\n if (shouldUseDynamicHelpers) {\n state._useDynamicHelpers = true;\n }\n\n const helperMap = shouldUseDynamicHelpers\n ? ({\n ...STATIC_IMPORT_FUNCTION,\n ...DYNAMIC_IMPORT_FUNCTION,\n } as Record<string, string>)\n : (STATIC_IMPORT_FUNCTION as Record<string, string>);\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 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 /* 2. Replace calls: useIntlayer(\"foo\") → useDictionary(_hash) or useDictionaryDynamic(_hash, \"foo\") */\n CallExpression(path, state) {\n if (state._isDictEntry) return; // skip if entry file – already handled\n\n const callee = path.node.callee;\n if (!t.isIdentifier(callee)) return;\n if (!CALLER_LIST.includes(callee.name as any)) 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 if (!arg || !t.isStringLiteral(arg)) return; // must be literal\n\n const key = arg.value;\n const useDynamic = Boolean(state._useDynamicHelpers);\n\n // Determine if this specific call should use dynamic imports\n const shouldUseDynamicForThisCall =\n callee.name === 'useIntlayer' && useDynamic;\n\n let ident: t.Identifier;\n\n if (shouldUseDynamicForThisCall) {\n // Use dynamic imports for useIntlayer when dynamic helpers are enabled\n let dynamicIdent = state._newDynamicImports!.get(key);\n if (!dynamicIdent) {\n // Create a unique identifier for dynamic imports by appending a suffix\n const hash = getFileHash(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 if (!staticIdent) {\n staticIdent = makeIdent(key);\n state._newStaticImports!.set(key, staticIdent);\n }\n ident = staticIdent;\n\n // Static helper (useDictionary / getDictionary): replace key with ident.\n path.node.arguments[0] = t.identifier(ident.name);\n }\n },\n },\n };\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,QAAmB;AACnB,sBAA4B;AAC5B,uBAAwC;AAIxC,MAAM,eAAe;A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C,YAAY,SAAS,OAAO,IAAW,EAAG;AAK/C,cAAM,kBAAkB;AAExB,cAAM,MAAM,KAAK,KAAK,UAAU,CAAC;AACjC,YAAI,CAAC,OAAO,CAAC,EAAE,gBAAgB,GAAG,EAAG;AAErC,cAAM,MAAM,IAAI;AAChB,cAAM,aAAa,QAAQ,MAAM,kBAAkB;AAGnD,cAAM,8BACJ,OAAO,SAAS,iBAAiB;AAEnC,YAAI;AAEJ,YAAI,6BAA6B;AAE/B,cAAI,eAAe,MAAM,mBAAoB,IAAI,GAAG;AACpD,cAAI,CAAC,cAAc;AAEjB,kBAAM,WAAO,6BAAY,GAAG;AAC5B,2BAAe,EAAE,WAAW,IAAI,IAAI,MAAM;AAC1C,kBAAM,mBAAoB,IAAI,KAAK,YAAY;AAAA,UACjD;AACA,kBAAQ;AAGR,eAAK,KAAK,YAAY;AAAA,YACpB,EAAE,WAAW,MAAM,IAAI;AAAA,YACvB,GAAG,KAAK,KAAK;AAAA,UACf;AAAA,QACF,OAAO;AAEL,cAAI,cAAc,MAAM,kBAAmB,IAAI,GAAG;AAClD,cAAI,CAAC,aAAa;AAChB,0BAAc,UAAU,GAAG;AAC3B,kBAAM,kBAAmB,IAAI,KAAK,WAAW;AAAA,UAC/C;AACA,kBAAQ;AAGR,eAAK,KAAK,UAAU,CAAC,IAAI,EAAE,WAAW,MAAM,IAAI;AAAA,QAClD;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
@@ -1,159 +1,197 @@
1
- import { parse } from "@babel/parser";
2
1
  import * as t from "@babel/types";
3
- import {
4
- generateDictionaryListContent,
5
- getBuiltDictionariesPath
6
- } from "@intlayer/chokidar";
7
- import { getAppLogger, getConfiguration } from "@intlayer/config";
8
- import { extname, relative, sep } from "path";
2
+ import { getFileHash } from "@intlayer/chokidar";
3
+ import { dirname, join, relative } from "node:path";
9
4
  const PACKAGE_LIST = [
5
+ "intlayer",
6
+ "@intlayer/core",
10
7
  "react-intlayer",
11
8
  "react-intlayer/client",
12
9
  "react-intlayer/server",
13
10
  "next-intlayer",
14
- "next-intlayer/server",
15
11
  "next-intlayer/client",
12
+ "next-intlayer/server",
16
13
  "svelte-intlayer",
17
14
  "vue-intlayer",
18
15
  "angular-intlayer",
19
16
  "preact-intlayer",
20
- "solid-inltayer"
17
+ "solid-intlayer"
21
18
  ];
22
19
  const CALLER_LIST = ["useIntlayer", "getIntlayer"];
23
- const globalUsedKeys = /* @__PURE__ */ new Set();
24
- let isThreeShakable = true;
25
- const isFileInContentDir = (filePath, contentDirs) => {
26
- return contentDirs.some((dir) => {
27
- const normalizedDir = dir.replace(/[/\\]+$/, "");
28
- return filePath.startsWith(normalizedDir);
29
- });
20
+ const PACKAGE_LIST_DYNAMIC = [
21
+ "react-intlayer",
22
+ "react-intlayer/client",
23
+ "react-intlayer/server",
24
+ "next-intlayer",
25
+ "next-intlayer/client",
26
+ "next-intlayer/server"
27
+ ];
28
+ const STATIC_IMPORT_FUNCTION = {
29
+ getIntlayer: "getDictionary",
30
+ useIntlayer: "useDictionary"
31
+ };
32
+ const DYNAMIC_IMPORT_FUNCTION = {
33
+ useIntlayer: "useDictionaryDynamic"
30
34
  };
31
- const isValidIntlayerImport = (source) => {
32
- return PACKAGE_LIST.includes(source);
35
+ const makeIdent = (key) => {
36
+ const hash = getFileHash(key);
37
+ return t.identifier(`_${hash}`);
33
38
  };
34
- const babelPluginIntlayer = () => {
35
- const configuration = getConfiguration();
36
- const dictionariesRoot = configuration.content.mainDir.replace(
37
- /[/\\]+$/,
38
- ""
39
- );
40
- const contentDir = configuration.content.contentDir;
41
- const appLogger = getAppLogger(configuration);
39
+ const computeRelativeImport = (fromFile, dictionariesDir, dynamicDictionariesDir, key, isDynamic = false) => {
40
+ const jsonPath = isDynamic ? join(dynamicDictionariesDir, `${key}.mjs`) : join(dictionariesDir, `${key}.json`);
41
+ let rel = relative(dirname(fromFile), jsonPath).replace(/\\/g, "/");
42
+ if (!rel.startsWith("./") && !rel.startsWith("../")) rel = `./${rel}`;
43
+ return rel;
44
+ };
45
+ const intlayerBabelPlugin = () => {
42
46
  return {
43
- name: "babel-plugin-intlayer-prune",
47
+ name: "babel-plugin-intlayer-transform",
48
+ pre() {
49
+ this._newStaticImports = /* @__PURE__ */ new Map();
50
+ this._newDynamicImports = /* @__PURE__ */ new Map();
51
+ this._isIncluded = true;
52
+ this._hasValidImport = false;
53
+ this._isDictEntry = false;
54
+ this._useDynamicHelpers = false;
55
+ const filename = this.file.opts.filename;
56
+ if (this.opts.filesList && filename) {
57
+ const isIncluded = this.opts.filesList.includes(filename);
58
+ if (!isIncluded) {
59
+ this._isIncluded = false;
60
+ return;
61
+ }
62
+ }
63
+ },
44
64
  visitor: {
65
+ /* 0. If this file *is* the dictionaries entry, short-circuit: export {} */
45
66
  Program: {
46
- enter(_programPath, state) {
47
- state.importedPackages = /* @__PURE__ */ new Set();
48
- state.hasValidIntlayerImport = false;
49
- const filePath = state.file.opts.filename ?? "";
50
- if (!isFileInContentDir(filePath, contentDir)) {
51
- return;
67
+ enter(programPath, state) {
68
+ const filename = state.file.opts.filename;
69
+ if (filename === state.opts.dictionariesEntryPath) {
70
+ state._isDictEntry = true;
71
+ programPath.node.body = [
72
+ t.exportDefaultDeclaration(t.objectExpression([]))
73
+ ];
74
+ programPath.stop();
52
75
  }
53
76
  },
54
- /*
55
- * After the whole file has been walked, decide if THIS file is the
56
- * dictionary entry-point. If it is, swap its body for the generated
57
- * code that imports only the used dictionaries.
58
- */
77
+ /* 3. After full traversal, inject the JSON dictionary imports. */
59
78
  exit(programPath, state) {
60
- const filePath = state.file.opts.filename ?? "";
61
- if (!isFileInContentDir(filePath, contentDir)) return;
62
- if (!isThreeShakable) return;
63
- if (!filePath.startsWith(dictionariesRoot)) return;
64
- const keys = Array.from(globalUsedKeys);
65
- if (!keys.length) return;
66
- const extension = extname(filePath);
67
- const format = extension === ".cjs" ? "cjs" : "esm";
68
- const dictionaries = getBuiltDictionariesPath(configuration).filter(
69
- (p) => keys.some((k) => p.endsWith(`${sep}${k}.json`))
70
- );
71
- const generatedSrc = generateDictionaryListContent(
72
- dictionaries,
73
- format,
74
- configuration
75
- );
76
- if (!generatedSrc) return;
77
- const newAst = parse(generatedSrc, {
78
- sourceType: format === "cjs" ? "script" : "module",
79
- plugins: ["importMeta"]
80
- });
81
- appLogger("Unused dictionaries pruned to reduce bundle size", {
82
- level: "info"
83
- });
84
- programPath.node.body = [];
85
- programPath.pushContainer("body", newAst.program.body);
86
- state.file.metadata = {
87
- ...state.file.metadata,
88
- intlayerPruned: true
89
- };
79
+ if (state._isDictEntry) return;
80
+ if (!state._hasValidImport) return;
81
+ if (!state._isIncluded) return;
82
+ const file = state.file.opts.filename;
83
+ const dictionariesDir = state.opts.dictionariesDir;
84
+ const dynamicDictionariesDir = state.opts.dynamicDictionariesDir;
85
+ const imports = [];
86
+ for (const [key, ident] of state._newStaticImports) {
87
+ const rel = computeRelativeImport(
88
+ file,
89
+ dictionariesDir,
90
+ dynamicDictionariesDir,
91
+ key,
92
+ false
93
+ // Always static
94
+ );
95
+ imports.push(
96
+ t.importDeclaration(
97
+ [t.importDefaultSpecifier(t.identifier(ident.name))],
98
+ t.stringLiteral(rel)
99
+ )
100
+ );
101
+ }
102
+ for (const [key, ident] of state._newDynamicImports) {
103
+ const rel = computeRelativeImport(
104
+ file,
105
+ dictionariesDir,
106
+ dynamicDictionariesDir,
107
+ key,
108
+ true
109
+ // Always dynamic
110
+ );
111
+ imports.push(
112
+ t.importDeclaration(
113
+ [t.importDefaultSpecifier(t.identifier(ident.name))],
114
+ t.stringLiteral(rel)
115
+ )
116
+ );
117
+ }
118
+ if (!imports.length) return;
119
+ const bodyPaths = programPath.get("body");
120
+ let insertPos = 0;
121
+ for (const stmtPath of bodyPaths) {
122
+ const stmt = stmtPath.node;
123
+ if (t.isExpressionStatement(stmt) && t.isStringLiteral(stmt.expression) && !stmt.expression.value.startsWith("import") && !stmt.expression.value.startsWith("require")) {
124
+ insertPos += 1;
125
+ } else {
126
+ break;
127
+ }
128
+ }
129
+ programPath.node.body.splice(insertPos, 0, ...imports);
90
130
  }
91
131
  },
132
+ /* 1. Inspect *every* intlayer import. */
92
133
  ImportDeclaration(path, state) {
93
- const filePath = state.file.opts.filename ?? "";
94
- if (!isFileInContentDir(filePath, contentDir)) {
95
- return;
96
- }
97
- const source = path.node.source.value;
98
- state.importedPackages?.add(source);
99
- if (isValidIntlayerImport(source)) {
100
- const hasIntlayerFunction = path.node.specifiers.some((specifier) => {
101
- if (t.isImportSpecifier(specifier) && t.isIdentifier(specifier.imported)) {
102
- return CALLER_LIST.includes(specifier.imported.name);
103
- }
104
- return false;
105
- });
106
- if (hasIntlayerFunction) {
107
- state.hasValidIntlayerImport = true;
134
+ if (state._isDictEntry) return;
135
+ const src = path.node.source.value;
136
+ if (!PACKAGE_LIST.includes(src)) return;
137
+ state._hasValidImport = true;
138
+ for (const spec of path.node.specifiers) {
139
+ if (!t.isImportSpecifier(spec)) continue;
140
+ const importedName = t.isIdentifier(spec.imported) ? spec.imported.name : spec.imported.value;
141
+ const activateDynamicImport = state.opts.activateDynamicImport;
142
+ const shouldUseDynamicHelpers = activateDynamicImport && PACKAGE_LIST_DYNAMIC.includes(src);
143
+ if (shouldUseDynamicHelpers) {
144
+ state._useDynamicHelpers = true;
145
+ }
146
+ const helperMap = shouldUseDynamicHelpers ? {
147
+ ...STATIC_IMPORT_FUNCTION,
148
+ ...DYNAMIC_IMPORT_FUNCTION
149
+ } : STATIC_IMPORT_FUNCTION;
150
+ const newIdentifier = helperMap[importedName];
151
+ if (newIdentifier) {
152
+ spec.imported = t.identifier(newIdentifier);
108
153
  }
109
154
  }
110
155
  },
156
+ /* 2. Replace calls: useIntlayer("foo") → useDictionary(_hash) or useDictionaryDynamic(_hash, "foo") */
111
157
  CallExpression(path, state) {
112
- const filePath = state.file.opts.filename ?? "";
113
- if (!isFileInContentDir(filePath, contentDir)) return;
114
- if (!isThreeShakable) return;
115
- const { node } = path;
116
- const renderError = (message) => {
117
- const filePath2 = state.file.opts.filename ?? "";
118
- const codeFrame = path.buildCodeFrameError("").message;
119
- console.info("");
120
- appLogger(message, {
121
- level: "error"
122
- });
123
- appLogger(`At ${relative(process.cwd(), filePath2)}`, {
124
- level: "error"
125
- });
126
- appLogger(codeFrame.split("\n").slice(1).join("\n"), {
127
- level: "error"
128
- });
129
- };
130
- if (t.isIdentifier(node.callee) && CALLER_LIST.includes(node.callee.name)) {
131
- if (!state.hasValidIntlayerImport) {
132
- isThreeShakable = false;
133
- renderError(
134
- `For dictionary optimization to work, ${node.callee.name} must be imported from one of these packages: ${PACKAGE_LIST.join(", ")}`
135
- );
136
- return;
137
- }
138
- if (!node.arguments.length) {
139
- isThreeShakable = false;
140
- renderError(`${node.callee.name} requires at least one argument`);
141
- return;
158
+ if (state._isDictEntry) return;
159
+ const callee = path.node.callee;
160
+ if (!t.isIdentifier(callee)) return;
161
+ if (!CALLER_LIST.includes(callee.name)) return;
162
+ state._hasValidImport = true;
163
+ const arg = path.node.arguments[0];
164
+ if (!arg || !t.isStringLiteral(arg)) return;
165
+ const key = arg.value;
166
+ const useDynamic = Boolean(state._useDynamicHelpers);
167
+ const shouldUseDynamicForThisCall = callee.name === "useIntlayer" && useDynamic;
168
+ let ident;
169
+ if (shouldUseDynamicForThisCall) {
170
+ let dynamicIdent = state._newDynamicImports.get(key);
171
+ if (!dynamicIdent) {
172
+ const hash = getFileHash(key);
173
+ dynamicIdent = t.identifier(`_${hash}_dyn`);
174
+ state._newDynamicImports.set(key, dynamicIdent);
142
175
  }
143
- if (!t.isStringLiteral(node.arguments[0])) {
144
- isThreeShakable = false;
145
- renderError(
146
- `For dictionary optimization to work, ${node.callee.name} key must be a literal string, otherwise tree shaking cannot be performed properly`
147
- );
148
- return;
176
+ ident = dynamicIdent;
177
+ path.node.arguments = [
178
+ t.identifier(ident.name),
179
+ ...path.node.arguments
180
+ ];
181
+ } else {
182
+ let staticIdent = state._newStaticImports.get(key);
183
+ if (!staticIdent) {
184
+ staticIdent = makeIdent(key);
185
+ state._newStaticImports.set(key, staticIdent);
149
186
  }
150
- globalUsedKeys.add(node.arguments[0].value);
187
+ ident = staticIdent;
188
+ path.node.arguments[0] = t.identifier(ident.name);
151
189
  }
152
190
  }
153
191
  }
154
192
  };
155
193
  };
156
194
  export {
157
- babelPluginIntlayer
195
+ intlayerBabelPlugin
158
196
  };
159
197
  //# sourceMappingURL=babel-plugin-intlayer.mjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/babel-plugin-intlayer.ts"],"sourcesContent":["import type { PluginObj, PluginPass } from '@babel/core';\nimport { parse } from '@babel/parser';\nimport type { NodePath } from '@babel/traverse';\nimport * as t from '@babel/types';\nimport {\n generateDictionaryListContent,\n getBuiltDictionariesPath,\n} from '@intlayer/chokidar';\nimport { getAppLogger, getConfiguration } from '@intlayer/config';\nimport { extname, relative, sep } from 'path';\n\ntype PluginState = PluginPass & {\n opts: {\n enableTransform?: boolean;\n };\n // Add tracking for imports per file\n importedPackages?: Set<string>;\n hasValidIntlayerImport?: boolean;\n};\n\n// ────────────────────────────────────────────────────────────\n// shared state across ALL files (1 build = 1 Node process)\nconst PACKAGE_LIST = [\n 'react-intlayer',\n 'react-intlayer/client',\n 'react-intlayer/server',\n 'next-intlayer',\n 'next-intlayer/server',\n 'next-intlayer/client',\n 'svelte-intlayer',\n 'vue-intlayer',\n 'angular-intlayer',\n 'preact-intlayer',\n 'solid-inltayer',\n];\nconst CALLER_LIST = ['useIntlayer', 'getIntlayer'];\nconst globalUsedKeys = new Set<string>();\nlet isThreeShakable = true;\n// ────────────────────────────────────────────────────────────\n\n// Helper function to check if file is in contentDir\nconst isFileInContentDir = (\n filePath: string,\n contentDirs: string[]\n): boolean => {\n return contentDirs.some((dir) => {\n const normalizedDir = dir.replace(/[/\\\\]+$/, '');\n return filePath.startsWith(normalizedDir);\n });\n};\n\n// Helper function to check if import is from valid package\nconst isValidIntlayerImport = (source: string): boolean => {\n return PACKAGE_LIST.includes(source);\n};\n\nexport const babelPluginIntlayer = (): PluginObj<PluginState> => {\n const configuration = getConfiguration();\n const dictionariesRoot: string = configuration.content.mainDir.replace(\n /[/\\\\]+$/,\n ''\n );\n const contentDir: string[] = configuration.content.contentDir;\n const appLogger = getAppLogger(configuration);\n\n return {\n name: 'babel-plugin-intlayer-prune',\n\n visitor: {\n Program: {\n enter(_programPath, state: PluginState) {\n // Initialize per-file state\n state.importedPackages = new Set<string>();\n state.hasValidIntlayerImport = false;\n\n const filePath: string = state.file.opts.filename ?? '';\n\n // Skip files that are not in contentDir\n if (!isFileInContentDir(filePath, contentDir)) {\n return;\n }\n },\n\n /*\n * After the whole file has been walked, decide if THIS file is the\n * dictionary entry-point. If it is, swap its body for the generated\n * code that imports only the used dictionaries.\n */\n exit(programPath, state: PluginState) {\n const filePath: string = state.file.opts.filename ?? '';\n\n // Skip files that are not in contentDir\n if (!isFileInContentDir(filePath, contentDir)) return;\n\n // Skip files is bundle is not three-shakable\n if (!isThreeShakable) return;\n\n // Is this *the* entry-point we want to shrink?\n if (!filePath.startsWith(dictionariesRoot)) return;\n\n const keys = Array.from(globalUsedKeys);\n if (!keys.length) return; // nothing collected yet – leave the file untouched\n\n const extension = extname(filePath); // .js / .mjs / .cjs\n const format = extension === '.cjs' ? 'cjs' : 'esm';\n\n // Pick only the dictionaries whose basename matches a collected key\n const dictionaries = getBuiltDictionariesPath(configuration).filter(\n (p) => keys.some((k) => p.endsWith(`${sep}${k}.json`))\n );\n\n const generatedSrc = generateDictionaryListContent(\n dictionaries,\n format,\n configuration\n );\n if (!generatedSrc) return;\n\n // Replace the current AST with the new one\n const newAst = parse(generatedSrc, {\n sourceType: format === 'cjs' ? 'script' : 'module',\n plugins: ['importMeta'],\n });\n\n appLogger('Unused dictionaries pruned to reduce bundle size', {\n level: 'info',\n });\n\n // Clear and inject\n programPath.node.body = [];\n programPath.pushContainer('body', newAst.program.body);\n\n // Optional: mark the file as \"transformed\" for other tooling\n state.file.metadata = {\n ...state.file.metadata,\n intlayerPruned: true,\n };\n },\n },\n\n ImportDeclaration(\n path: NodePath<t.ImportDeclaration>,\n state: PluginState\n ) {\n const filePath: string = state.file.opts.filename ?? '';\n\n // Skip files that are not in contentDir\n if (!isFileInContentDir(filePath, contentDir)) {\n return;\n }\n\n const source = path.node.source.value;\n state.importedPackages?.add(source);\n\n // Check if this import is from a valid intlayer package\n if (isValidIntlayerImport(source)) {\n // Check if any of the imported specifiers include useIntlayer or getIntlayer\n const hasIntlayerFunction = path.node.specifiers.some((specifier) => {\n if (\n t.isImportSpecifier(specifier) &&\n t.isIdentifier(specifier.imported)\n ) {\n return CALLER_LIST.includes(specifier.imported.name);\n }\n return false;\n });\n\n if (hasIntlayerFunction) {\n state.hasValidIntlayerImport = true;\n }\n }\n },\n\n CallExpression(path: NodePath<t.CallExpression>, state: PluginState) {\n const filePath: string = state.file.opts.filename ?? '';\n\n // Skip files that are not in contentDir\n if (!isFileInContentDir(filePath, contentDir)) return;\n if (!isThreeShakable) return;\n\n const { node } = path;\n\n const renderError = (message: string) => {\n const filePath: string = state.file.opts.filename ?? '';\n\n // Generate code frame to show the error context\n const codeFrame = path.buildCodeFrameError('').message;\n\n console.info(''); // For formating\n appLogger(message, {\n level: 'error',\n });\n appLogger(`At ${relative(process.cwd(), filePath)}`, {\n level: 'error',\n });\n appLogger(codeFrame.split('\\n').slice(1).join('\\n'), {\n level: 'error',\n });\n };\n\n if (\n t.isIdentifier(node.callee) &&\n CALLER_LIST.includes(node.callee.name)\n ) {\n // Check if the function is imported from a valid package\n if (!state.hasValidIntlayerImport) {\n isThreeShakable = false;\n\n renderError(\n `For dictionary optimization to work, ${node.callee.name} must be imported from one of these packages: ${PACKAGE_LIST.join(', ')}`\n );\n return;\n }\n\n // Check if arguments exist\n if (!node.arguments.length) {\n isThreeShakable = false;\n\n renderError(`${node.callee.name} requires at least one argument`);\n\n return;\n }\n\n // Check if the first argument is a string literal\n if (!t.isStringLiteral(node.arguments[0])) {\n isThreeShakable = false;\n\n renderError(\n `For dictionary optimization to work, ${node.callee.name} key must be a literal string, otherwise tree shaking cannot be performed properly`\n );\n return;\n }\n\n globalUsedKeys.add(node.arguments[0].value);\n }\n },\n },\n };\n};\n"],"mappings":"AACA,SAAS,aAAa;AAEtB,YAAY,OAAO;AACnB;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,cAAc,wBAAwB;AAC/C,SAAS,SAAS,UAAU,WAAW;AAavC,MAAM,eAAe;AAAA,EACnB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AACA,MAAM,cAAc,CAAC,eAAe,aAAa;AACjD,MAAM,iBAAiB,oBAAI,IAAY;AACvC,IAAI,kBAAkB;AAItB,MAAM,qBAAqB,CACzB,UACA,gBACY;AACZ,SAAO,YAAY,KAAK,CAAC,QAAQ;AAC/B,UAAM,gBAAgB,IAAI,QAAQ,WAAW,EAAE;AAC/C,WAAO,SAAS,WAAW,aAAa;AAAA,EAC1C,CAAC;AACH;AAGA,MAAM,wBAAwB,CAAC,WAA4B;AACzD,SAAO,aAAa,SAAS,MAAM;AACrC;AAEO,MAAM,sBAAsB,MAA8B;AAC/D,QAAM,gBAAgB,iBAAiB;AACvC,QAAM,mBAA2B,cAAc,QAAQ,QAAQ;AAAA,IAC7D;AAAA,IACA;AAAA,EACF;AACA,QAAM,aAAuB,cAAc,QAAQ;AACnD,QAAM,YAAY,aAAa,aAAa;AAE5C,SAAO;AAAA,IACL,MAAM;AAAA,IAEN,SAAS;AAAA,MACP,SAAS;AAAA,QACP,MAAM,cAAc,OAAoB;AAEtC,gBAAM,mBAAmB,oBAAI,IAAY;AACzC,gBAAM,yBAAyB;AAE/B,gBAAM,WAAmB,MAAM,KAAK,KAAK,YAAY;AAGrD,cAAI,CAAC,mBAAmB,UAAU,UAAU,GAAG;AAC7C;AAAA,UACF;AAAA,QACF;AAAA;AAAA;AAAA;AAAA;AAA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C,GAAG;AACzC,8BAAkB;AAElB;AAAA,cACE,wCAAwC,KAAK,OAAO,IAAI;AAAA,YAC1D;AACA;AAAA,UACF;AAEA,yBAAe,IAAI,KAAK,UAAU,CAAC,EAAE,KAAK;AAAA,QAC5C;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;","names":["filePath"]}
1
+ {"version":3,"sources":["../../src/babel-plugin-intlayer.ts"],"sourcesContent":["import type { NodePath, PluginObj, PluginPass } from '@babel/core';\nimport * as t from '@babel/types';\nimport { getFileHash } from '@intlayer/chokidar';\nimport { dirname, join, relative } from 'node:path';\n\n/* ────────────────────────────────────────── constants ───────────────────── */\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] 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/* ────────────────────────────────────────── types ───────────────────────── */\n\ntype State = PluginPass & {\n opts: {\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 dictionaries directory.\n */\n dynamicDictionariesDir: string;\n /**\n * The path to the dynamic dictionaries entry file.\n */\n dynamicDictionariesEntryPath: string;\n /**\n * If true, the plugin will activate the dynamic import of the dictionaries.\n */\n activateDynamicImport?: boolean;\n /**\n * Files list to traverse.\n */\n filesList?: string[];\n };\n /** map key → generated ident (per-file) for static imports */\n _newStaticImports?: Map<string, t.Identifier>;\n /** map key → generated ident (per-file) for dynamic imports */\n _newDynamicImports?: Map<string, t.Identifier>;\n /** whether the current file imported *any* intlayer package */\n _hasValidImport?: boolean;\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};\n\n/* ────────────────────────────────────────── helpers ─────────────────────── */\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 = (key: string): t.Identifier => {\n const hash = getFileHash(key);\n return t.identifier(`_${hash}`);\n};\n\nconst computeRelativeImport = (\n fromFile: string,\n dictionariesDir: string,\n dynamicDictionariesDir: string,\n key: string,\n isDynamic = false\n): string => {\n const jsonPath = isDynamic\n ? join(dynamicDictionariesDir, `${key}.mjs`)\n : join(dictionariesDir, `${key}.json`);\n\n let rel = relative(dirname(fromFile), jsonPath).replace(/\\\\/g, '/'); // win →\n if (!rel.startsWith('./') && !rel.startsWith('../')) rel = `./${rel}`;\n return rel;\n};\n\n/* ────────────────────────────────────────── plugin ──────────────────────── */\n\n/**\n * Babel plugin that transforms `useIntlayer/getIntlayer` calls into\n * `useDictionary/getDictionary` and auto-imports the required JSON dictionaries.\n *\n *\n * This means cases like:\n *\n * ```ts\n * import { getIntlayer } from 'intlayer';\n * import { useIntlayer } from 'react-intlayer';\n *\n * // ...\n *\n * const content1 = getIntlayer('app');\n * const content2 = useIntlayer('app');\n * ```\n *\n * will be transformed into:\n *\n * ```ts\n * import _dicHash from '../../.intlayer/dictionaries/app.mjs';\n * import { getDictionary as getIntlayer } from 'intlayer';\n * import { useDictionaryDynamic as useIntlayer } from 'react-intlayer';\n *\n * // ...\n *\n * const content1 = getIntlayer(_dicHash);\n * const content2 = useIntlayer(_dicHash)\n * ```\n *\n * Or if the `activateDynamicImport` option is enabled:\n *\n * ```ts\n * import _dicHash from '../../.intlayer/dynamic_dictionaries/app.mjs';\n * import _dicHash_dyn from '../../.intlayer/dictionaries/app.mjs';\n *\n * import { useDictionary as getIntlayer } from 'intlayer';\n * import { useDictionaryDynamic as useIntlayer } from 'react-intlayer';\n *\n * // ...\n *\n * const content1 = getIntlayer(_dicHash);\n * const content2 = useIntlayer(_dicHash_dyn, 'app');\n * ```\n */\nexport const intlayerBabelPlugin = (): PluginObj<State> => {\n return {\n name: 'babel-plugin-intlayer-transform',\n\n pre() {\n this._newStaticImports = new Map();\n this._newDynamicImports = new Map();\n this._isIncluded = true;\n this._hasValidImport = false;\n this._isDictEntry = false;\n this._useDynamicHelpers = false;\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 /* 0. If this file *is* the dictionaries entry, short-circuit: export {} */\n Program: {\n enter(programPath, state) {\n const filename = state.file.opts.filename!;\n if (filename === state.opts.dictionariesEntryPath) {\n state._isDictEntry = true;\n // Replace all existing statements with: export default {}\n programPath.node.body = [\n t.exportDefaultDeclaration(t.objectExpression([])),\n ];\n // Stop further traversal for this plugin – nothing else to transform\n programPath.stop();\n }\n },\n\n /* 3. After full traversal, inject the JSON dictionary imports. */\n exit(programPath, state) {\n if (state._isDictEntry) return; // nothing else to do – already replaced\n if (!state._hasValidImport) return; // early-out if we touched nothing\n if (!state._isIncluded) return; // early-out if file is not included\n\n const file = state.file.opts.filename!;\n const dictionariesDir = state.opts.dictionariesDir;\n const dynamicDictionariesDir = state.opts.dynamicDictionariesDir;\n const imports: t.ImportDeclaration[] = [];\n\n // Generate static imports (for getIntlayer and useIntlayer when not using dynamic)\n for (const [key, ident] of state._newStaticImports!) {\n const rel = computeRelativeImport(\n file,\n dictionariesDir,\n dynamicDictionariesDir,\n key,\n false // Always static\n );\n imports.push(\n t.importDeclaration(\n [t.importDefaultSpecifier(t.identifier(ident.name))],\n t.stringLiteral(rel)\n )\n );\n }\n\n // Generate dynamic imports (for useIntlayer when using dynamic helpers)\n for (const [key, ident] of state._newDynamicImports!) {\n const rel = computeRelativeImport(\n file,\n dictionariesDir,\n dynamicDictionariesDir,\n key,\n true // Always dynamic\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('body') as NodePath<t.Statement>[];\n let insertPos = 0;\n for (const stmtPath of bodyPaths) {\n const stmt = stmtPath.node;\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 /* 1. Inspect *every* intlayer import. */\n ImportDeclaration(path, state) {\n if (state._isDictEntry) return; // skip if entry file – already handled\n\n const src = path.node.source.value;\n if (!PACKAGE_LIST.includes(src)) return;\n\n // Mark that we do import from an intlayer package in this file; this is\n // enough to know that we *might* need to inject runtime helpers later.\n state._hasValidImport = true;\n\n for (const spec of path.node.specifiers) {\n if (!t.isImportSpecifier(spec)) continue;\n\n // ⚠️ We now key off *imported* name, *not* local name.\n const importedName = t.isIdentifier(spec.imported)\n ? spec.imported.name\n : (spec.imported as t.StringLiteral).value;\n\n const activateDynamicImport = state.opts.activateDynamicImport;\n // Determine whether this import should use the dynamic helpers. We\n // only switch to the dynamic helpers when (1) the option is turned\n // on AND (2) the package we are importing from supports the dynamic\n // helpers.\n const shouldUseDynamicHelpers =\n activateDynamicImport && PACKAGE_LIST_DYNAMIC.includes(src as any);\n\n // Remember for later (CallExpression) whether we are using the dynamic helpers\n if (shouldUseDynamicHelpers) {\n state._useDynamicHelpers = true;\n }\n\n const helperMap = shouldUseDynamicHelpers\n ? ({\n ...STATIC_IMPORT_FUNCTION,\n ...DYNAMIC_IMPORT_FUNCTION,\n } as Record<string, string>)\n : (STATIC_IMPORT_FUNCTION as Record<string, string>);\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 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 /* 2. Replace calls: useIntlayer(\"foo\") → useDictionary(_hash) or useDictionaryDynamic(_hash, \"foo\") */\n CallExpression(path, state) {\n if (state._isDictEntry) return; // skip if entry file – already handled\n\n const callee = path.node.callee;\n if (!t.isIdentifier(callee)) return;\n if (!CALLER_LIST.includes(callee.name as any)) 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 if (!arg || !t.isStringLiteral(arg)) return; // must be literal\n\n const key = arg.value;\n const useDynamic = Boolean(state._useDynamicHelpers);\n\n // Determine if this specific call should use dynamic imports\n const shouldUseDynamicForThisCall =\n callee.name === 'useIntlayer' && useDynamic;\n\n let ident: t.Identifier;\n\n if (shouldUseDynamicForThisCall) {\n // Use dynamic imports for useIntlayer when dynamic helpers are enabled\n let dynamicIdent = state._newDynamicImports!.get(key);\n if (!dynamicIdent) {\n // Create a unique identifier for dynamic imports by appending a suffix\n const hash = getFileHash(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 if (!staticIdent) {\n staticIdent = makeIdent(key);\n state._newStaticImports!.set(key, staticIdent);\n }\n ident = staticIdent;\n\n // Static helper (useDictionary / getDictionary): replace key with ident.\n path.node.arguments[0] = t.identifier(ident.name);\n }\n },\n },\n };\n};\n"],"mappings":"AACA,YAAY,OAAO;AACnB,SAAS,mBAAmB;AAC5B,SAAS,SAAS,MAAM,gBAAgB;AAIxC,MAAM,eAAe;AAAA,EACnB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEA,MAAM,cAAc,CAAC,eAAe,aAAa;AAKjD,MAAM,uBAAuB;AAAA,EAC3B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEA,MAAM,yBAAyB;AAAA,EAC7B,aAAa;AAAA,EACb,aAAa;AACf;AAEA,MAAM,0BAA0B;AAAA,EAC9B,aAAa;AACf;AAkDA,MAAM,YAAY,CAAC,QAA8B;AAC/C,QAAM,OAAO,YAAY,GAAG;AAC5B,SAAO,EAAE,WAAW,IAAI,IAAI,EAAE;AAChC;AAEA,MAAM,wBAAwB,CAC5B,UACA,iBACA,wBACA,KACA,YAAY,UACD;AACX,QAAM,WAAW,YACb,KAAK,wBAAwB,GAAG,GAAG,MAAM,IACzC,KAAK,iBAAiB,GAAG,GAAG,OAAO;AAEvC,MAAI,MAAM,SAAS,QAAQ,QAAQ,GAAG,QAAQ,EAAE,QAAQ,OAAO,GAAG;AAClE,MAAI,CAAC,IAAI,WAAW,IAAI,KAAK,CAAC,IAAI,WAAW,KAAK,EAAG,OAAM,KAAK,GAAG;AACnE,SAAO;AACT;AAiDO,MAAM,sBAAsB,MAAwB;AACzD,SAAO;AAAA,IACL,MAAM;AAAA,IAEN,MA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+1,88 @@
1
1
  import type { PluginObj, PluginPass } from '@babel/core';
2
- type PluginState = PluginPass & {
2
+ import * as t from '@babel/types';
3
+ type State = PluginPass & {
3
4
  opts: {
4
- enableTransform?: boolean;
5
+ /**
6
+ * The path to the dictionaries directory.
7
+ */
8
+ dictionariesDir: string;
9
+ /**
10
+ * The path to the dictionaries entry file.
11
+ */
12
+ dictionariesEntryPath: string;
13
+ /**
14
+ * The path to the dictionaries directory.
15
+ */
16
+ dynamicDictionariesDir: string;
17
+ /**
18
+ * The path to the dynamic dictionaries entry file.
19
+ */
20
+ dynamicDictionariesEntryPath: string;
21
+ /**
22
+ * If true, the plugin will activate the dynamic import of the dictionaries.
23
+ */
24
+ activateDynamicImport?: boolean;
25
+ /**
26
+ * Files list to traverse.
27
+ */
28
+ filesList?: string[];
5
29
  };
6
- importedPackages?: Set<string>;
7
- hasValidIntlayerImport?: boolean;
30
+ /** map key → generated ident (per-file) for static imports */
31
+ _newStaticImports?: Map<string, t.Identifier>;
32
+ /** map key → generated ident (per-file) for dynamic imports */
33
+ _newDynamicImports?: Map<string, t.Identifier>;
34
+ /** whether the current file imported *any* intlayer package */
35
+ _hasValidImport?: boolean;
36
+ /** whether the current file *is* the dictionaries entry file */
37
+ _isDictEntry?: boolean;
38
+ /** whether dynamic helpers are active for this file */
39
+ _useDynamicHelpers?: boolean;
8
40
  };
9
- export declare const babelPluginIntlayer: () => PluginObj<PluginState>;
41
+ /**
42
+ * Babel plugin that transforms `useIntlayer/getIntlayer` calls into
43
+ * `useDictionary/getDictionary` and auto-imports the required JSON dictionaries.
44
+ *
45
+ *
46
+ * This means cases like:
47
+ *
48
+ * ```ts
49
+ * import { getIntlayer } from 'intlayer';
50
+ * import { useIntlayer } from 'react-intlayer';
51
+ *
52
+ * // ...
53
+ *
54
+ * const content1 = getIntlayer('app');
55
+ * const content2 = useIntlayer('app');
56
+ * ```
57
+ *
58
+ * will be transformed into:
59
+ *
60
+ * ```ts
61
+ * import _dicHash from '../../.intlayer/dictionaries/app.mjs';
62
+ * import { getDictionary as getIntlayer } from 'intlayer';
63
+ * import { useDictionaryDynamic as useIntlayer } from 'react-intlayer';
64
+ *
65
+ * // ...
66
+ *
67
+ * const content1 = getIntlayer(_dicHash);
68
+ * const content2 = useIntlayer(_dicHash)
69
+ * ```
70
+ *
71
+ * Or if the `activateDynamicImport` option is enabled:
72
+ *
73
+ * ```ts
74
+ * import _dicHash from '../../.intlayer/dynamic_dictionaries/app.mjs';
75
+ * import _dicHash_dyn from '../../.intlayer/dictionaries/app.mjs';
76
+ *
77
+ * import { useDictionary as getIntlayer } from 'intlayer';
78
+ * import { useDictionaryDynamic as useIntlayer } from 'react-intlayer';
79
+ *
80
+ * // ...
81
+ *
82
+ * const content1 = getIntlayer(_dicHash);
83
+ * const content2 = useIntlayer(_dicHash_dyn, 'app');
84
+ * ```
85
+ */
86
+ export declare const intlayerBabelPlugin: () => PluginObj<State>;
10
87
  export {};
11
88
  //# sourceMappingURL=babel-plugin-intlayer.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"babel-plugin-intlayer.d.ts","sourceRoot":"","sources":["../../src/babel-plugin-intlayer.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAWzD,KAAK,WAAW,GAAG,UAAU,GAAG;IAC9B,IAAI,EAAE;QACJ,eAAe,CAAC,EAAE,OAAO,CAAC;KAC3B,CAAC;IAEF,gBAAgB,CAAC,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;IAC/B,sBAAsB,CAAC,EAAE,OAAO,CAAC;CAClC,CAAC;AAsCF,eAAO,MAAM,mBAAmB,QAAO,SAAS,CAAC,WAAW,CAsL3D,CAAC"}
1
+ {"version":3,"file":"babel-plugin-intlayer.d.ts","sourceRoot":"","sources":["../../src/babel-plugin-intlayer.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAY,SAAS,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACnE,OAAO,KAAK,CAAC,MAAM,cAAc,CAAC;AA+ClC,KAAK,KAAK,GAAG,UAAU,GAAG;IACxB,IAAI,EAAE;QACJ;;WAEG;QACH,eAAe,EAAE,MAAM,CAAC;QACxB;;WAEG;QACH,qBAAqB,EAAE,MAAM,CAAC;QAC9B;;WAEG;QACH,sBAAsB,EAAE,MAAM,CAAC;QAC/B;;WAEG;QACH,4BAA4B,EAAE,MAAM,CAAC;QACrC;;WAEG;QACH,qBAAqB,CAAC,EAAE,OAAO,CAAC;QAChC;;WAEG;QACH,SAAS,CAAC,EAAE,MAAM,EAAE,CAAC;KACtB,CAAC;IACF,8DAA8D;IAC9D,iBAAiB,CAAC,EAAE,GAAG,CAAC,MAAM,EAAE,CAAC,CAAC,UAAU,CAAC,CAAC;IAC9C,+DAA+D;IAC/D,kBAAkB,CAAC,EAAE,GAAG,CAAC,MAAM,EAAE,CAAC,CAAC,UAAU,CAAC,CAAC;IAC/C,+DAA+D;IAC/D,eAAe,CAAC,EAAE,OAAO,CAAC;IAC1B,gEAAgE;IAChE,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,uDAAuD;IACvD,kBAAkB,CAAC,EAAE,OAAO,CAAC;CAC9B,CAAC;AAgCF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4CG;AACH,eAAO,MAAM,mBAAmB,QAAO,SAAS,CAAC,KAAK,CAyNrD,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@intlayer/babel",
3
- "version": "5.5.2",
3
+ "version": "5.5.4",
4
4
  "private": false,
5
5
  "description": "A Babel plugin for Intlayer that transforms declaration files and provides internationalization features during the build process according to the Intlayer configuration.",
6
6
  "keywords": [
@@ -62,8 +62,8 @@
62
62
  "@babel/generator": "^7.27.1",
63
63
  "@babel/parser": "^7.27.2",
64
64
  "@babel/traverse": "^7.27.1",
65
- "@intlayer/config": "5.5.2",
66
- "@intlayer/chokidar": "5.5.2"
65
+ "@intlayer/chokidar": "5.5.4",
66
+ "@intlayer/config": "5.5.4"
67
67
  },
68
68
  "devDependencies": {
69
69
  "@babel/types": "^7.27.1",
@@ -83,13 +83,13 @@
83
83
  "tsup": "^8.4.0",
84
84
  "typescript": "^5.8.2",
85
85
  "@utils/eslint-config": "1.0.4",
86
+ "@utils/ts-config": "1.0.4",
86
87
  "@utils/ts-config-types": "1.0.4",
87
- "@utils/tsup-config": "1.0.4",
88
- "@utils/ts-config": "1.0.4"
88
+ "@utils/tsup-config": "1.0.4"
89
89
  },
90
90
  "peerDependencies": {
91
- "@intlayer/chokidar": "5.5.2",
92
- "@intlayer/config": "5.5.2"
91
+ "@intlayer/config": "5.5.4",
92
+ "@intlayer/chokidar": "5.5.4"
93
93
  },
94
94
  "engines": {
95
95
  "node": ">=14.18"