@intlayer/babel 8.4.3 → 8.4.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/_virtual/_rolldown/runtime.cjs +29 -0
- package/dist/cjs/babel-plugin-intlayer-extract.cjs +75 -1
- package/dist/cjs/babel-plugin-intlayer-extract.cjs.map +1 -1
- package/dist/cjs/babel-plugin-intlayer-optimize.cjs +306 -1
- package/dist/cjs/babel-plugin-intlayer-optimize.cjs.map +1 -1
- package/dist/cjs/extractContent/babelProcessor.cjs +261 -1
- package/dist/cjs/extractContent/babelProcessor.cjs.map +1 -1
- package/dist/cjs/extractContent/contentWriter.cjs +134 -1
- package/dist/cjs/extractContent/contentWriter.cjs.map +1 -1
- package/dist/cjs/extractContent/extractContent.cjs +184 -1
- package/dist/cjs/extractContent/extractContent.cjs.map +1 -1
- package/dist/cjs/extractContent/index.cjs +26 -1
- package/dist/cjs/extractContent/processTsxFile.cjs +263 -5
- package/dist/cjs/extractContent/processTsxFile.cjs.map +1 -1
- package/dist/cjs/extractContent/utils/constants.cjs +42 -1
- package/dist/cjs/extractContent/utils/constants.cjs.map +1 -1
- package/dist/cjs/extractContent/utils/detectPackageName.cjs +26 -1
- package/dist/cjs/extractContent/utils/detectPackageName.cjs.map +1 -1
- package/dist/cjs/extractContent/utils/extractDictionaryInfo.cjs +77 -1
- package/dist/cjs/extractContent/utils/extractDictionaryInfo.cjs.map +1 -1
- package/dist/cjs/extractContent/utils/extractDictionaryKey.cjs +29 -1
- package/dist/cjs/extractContent/utils/extractDictionaryKey.cjs.map +1 -1
- package/dist/cjs/extractContent/utils/generateKey.cjs +16 -1
- package/dist/cjs/extractContent/utils/generateKey.cjs.map +1 -1
- package/dist/cjs/extractContent/utils/getComponentName.cjs +18 -1
- package/dist/cjs/extractContent/utils/getComponentName.cjs.map +1 -1
- package/dist/cjs/extractContent/utils/getExistingIntlayerInfo.cjs +50 -1
- package/dist/cjs/extractContent/utils/getExistingIntlayerInfo.cjs.map +1 -1
- package/dist/cjs/extractContent/utils/getOrGenerateKey.cjs +19 -1
- package/dist/cjs/extractContent/utils/getOrGenerateKey.cjs.map +1 -1
- package/dist/cjs/extractContent/utils/index.cjs +27 -1
- package/dist/cjs/extractContent/utils/resolveDictionaryKey.cjs +34 -1
- package/dist/cjs/extractContent/utils/resolveDictionaryKey.cjs.map +1 -1
- package/dist/cjs/extractContent/utils/shouldExtract.cjs +23 -1
- package/dist/cjs/extractContent/utils/shouldExtract.cjs.map +1 -1
- package/dist/cjs/getExtractPluginOptions.cjs +41 -1
- package/dist/cjs/getExtractPluginOptions.cjs.map +1 -1
- package/dist/cjs/getOptimizePluginOptions.cjs +63 -1
- package/dist/cjs/getOptimizePluginOptions.cjs.map +1 -1
- package/dist/cjs/index.cjs +34 -1
- package/dist/esm/_virtual/_rolldown/runtime.mjs +8 -0
- package/dist/esm/babel-plugin-intlayer-extract.mjs +72 -1
- package/dist/esm/babel-plugin-intlayer-extract.mjs.map +1 -1
- package/dist/esm/babel-plugin-intlayer-optimize.mjs +304 -1
- package/dist/esm/babel-plugin-intlayer-optimize.mjs.map +1 -1
- package/dist/esm/extractContent/babelProcessor.mjs +255 -1
- package/dist/esm/extractContent/babelProcessor.mjs.map +1 -1
- package/dist/esm/extractContent/contentWriter.mjs +129 -1
- package/dist/esm/extractContent/contentWriter.mjs.map +1 -1
- package/dist/esm/extractContent/extractContent.mjs +180 -1
- package/dist/esm/extractContent/extractContent.mjs.map +1 -1
- package/dist/esm/extractContent/index.mjs +10 -1
- package/dist/esm/extractContent/processTsxFile.mjs +259 -5
- package/dist/esm/extractContent/processTsxFile.mjs.map +1 -1
- package/dist/esm/extractContent/utils/constants.mjs +38 -1
- package/dist/esm/extractContent/utils/constants.mjs.map +1 -1
- package/dist/esm/extractContent/utils/detectPackageName.mjs +24 -1
- package/dist/esm/extractContent/utils/detectPackageName.mjs.map +1 -1
- package/dist/esm/extractContent/utils/extractDictionaryInfo.mjs +72 -1
- package/dist/esm/extractContent/utils/extractDictionaryInfo.mjs.map +1 -1
- package/dist/esm/extractContent/utils/extractDictionaryKey.mjs +26 -1
- package/dist/esm/extractContent/utils/extractDictionaryKey.mjs.map +1 -1
- package/dist/esm/extractContent/utils/generateKey.mjs +14 -1
- package/dist/esm/extractContent/utils/generateKey.mjs.map +1 -1
- package/dist/esm/extractContent/utils/getComponentName.mjs +15 -1
- package/dist/esm/extractContent/utils/getComponentName.mjs.map +1 -1
- package/dist/esm/extractContent/utils/getExistingIntlayerInfo.mjs +47 -1
- package/dist/esm/extractContent/utils/getExistingIntlayerInfo.mjs.map +1 -1
- package/dist/esm/extractContent/utils/getOrGenerateKey.mjs +18 -1
- package/dist/esm/extractContent/utils/getOrGenerateKey.mjs.map +1 -1
- package/dist/esm/extractContent/utils/index.mjs +12 -1
- package/dist/esm/extractContent/utils/resolveDictionaryKey.mjs +32 -1
- package/dist/esm/extractContent/utils/resolveDictionaryKey.mjs.map +1 -1
- package/dist/esm/extractContent/utils/shouldExtract.mjs +21 -1
- package/dist/esm/extractContent/utils/shouldExtract.mjs.map +1 -1
- package/dist/esm/getExtractPluginOptions.mjs +38 -1
- package/dist/esm/getExtractPluginOptions.mjs.map +1 -1
- package/dist/esm/getOptimizePluginOptions.mjs +63 -1
- package/dist/esm/getOptimizePluginOptions.mjs.map +1 -0
- package/dist/esm/index.mjs +14 -1
- package/dist/types/babel-plugin-intlayer-extract.d.ts +1 -1
- package/dist/types/extractContent/contentWriter.d.ts +36 -2
- package/dist/types/extractContent/contentWriter.d.ts.map +1 -0
- package/dist/types/extractContent/extractContent.d.ts +37 -2
- package/dist/types/extractContent/extractContent.d.ts.map +1 -0
- package/dist/types/extractContent/index.d.ts +8 -8
- package/dist/types/extractContent/processTsxFile.d.ts +1 -1
- package/dist/types/extractContent/processTsxFile.d.ts.map +1 -1
- package/dist/types/extractContent/utils/constants.d.ts +20 -2
- package/dist/types/extractContent/utils/constants.d.ts.map +1 -0
- package/dist/types/extractContent/utils/detectPackageName.d.ts +10 -2
- package/dist/types/extractContent/utils/detectPackageName.d.ts.map +1 -0
- package/dist/types/extractContent/utils/extractDictionaryInfo.d.ts +28 -2
- package/dist/types/extractContent/utils/extractDictionaryInfo.d.ts.map +1 -0
- package/dist/types/extractContent/utils/extractDictionaryKey.d.ts +11 -2
- package/dist/types/extractContent/utils/extractDictionaryKey.d.ts.map +1 -0
- package/dist/types/extractContent/utils/generateKey.d.ts +5 -2
- package/dist/types/extractContent/utils/generateKey.d.ts.map +1 -0
- package/dist/types/extractContent/utils/getComponentName.d.ts +10 -2
- package/dist/types/extractContent/utils/getComponentName.d.ts.map +1 -0
- package/dist/types/extractContent/utils/getExistingIntlayerInfo.d.ts +19 -2
- package/dist/types/extractContent/utils/getExistingIntlayerInfo.d.ts.map +1 -0
- package/dist/types/extractContent/utils/getOrGenerateKey.d.ts +8 -2
- package/dist/types/extractContent/utils/getOrGenerateKey.d.ts.map +1 -0
- package/dist/types/extractContent/utils/index.d.ts +10 -10
- package/dist/types/extractContent/utils/resolveDictionaryKey.d.ts +12 -2
- package/dist/types/extractContent/utils/resolveDictionaryKey.d.ts.map +1 -0
- package/dist/types/extractContent/utils/shouldExtract.d.ts +14 -2
- package/dist/types/extractContent/utils/shouldExtract.d.ts.map +1 -0
- package/dist/types/index.d.ts +8 -8
- package/package.json +9 -9
- package/dist/cjs/chunk-Bmb41Sf3.cjs +0 -1
- package/dist/esm/getOptimizePluginOptions-BAFPfVq5.mjs +0 -2
- package/dist/esm/getOptimizePluginOptions-BAFPfVq5.mjs.map +0 -1
- package/dist/types/constants-BLArAqsA.d.ts +0 -20
- package/dist/types/constants-BLArAqsA.d.ts.map +0 -1
- package/dist/types/contentWriter-I2Ch5yQY.d.ts +0 -36
- package/dist/types/contentWriter-I2Ch5yQY.d.ts.map +0 -1
- package/dist/types/detectPackageName-C0TfbHa3.d.ts +0 -10
- package/dist/types/detectPackageName-C0TfbHa3.d.ts.map +0 -1
- package/dist/types/extractContent-AFk68B7L.d.ts +0 -37
- package/dist/types/extractContent-AFk68B7L.d.ts.map +0 -1
- package/dist/types/extractDictionaryInfo-5GLZsA_I.d.ts +0 -28
- package/dist/types/extractDictionaryInfo-5GLZsA_I.d.ts.map +0 -1
- package/dist/types/extractDictionaryKey-CHgfwRo6.d.ts +0 -11
- package/dist/types/extractDictionaryKey-CHgfwRo6.d.ts.map +0 -1
- package/dist/types/generateKey-Cgdh6seq.d.ts +0 -5
- package/dist/types/generateKey-Cgdh6seq.d.ts.map +0 -1
- package/dist/types/getComponentName-DGlmJa-F.d.ts +0 -10
- package/dist/types/getComponentName-DGlmJa-F.d.ts.map +0 -1
- package/dist/types/getExistingIntlayerInfo-Cy6Vpcfb.d.ts +0 -19
- package/dist/types/getExistingIntlayerInfo-Cy6Vpcfb.d.ts.map +0 -1
- package/dist/types/getOrGenerateKey-DtIR0WeU.d.ts +0 -8
- package/dist/types/getOrGenerateKey-DtIR0WeU.d.ts.map +0 -1
- package/dist/types/index-DK_kKFOF.d.ts +0 -1
- package/dist/types/resolveDictionaryKey-CcbieIfX.d.ts +0 -12
- package/dist/types/resolveDictionaryKey-CcbieIfX.d.ts.map +0 -1
- package/dist/types/shouldExtract-BRaeB9eg.d.ts +0 -14
- package/dist/types/shouldExtract-BRaeB9eg.d.ts.map +0 -1
|
@@ -1,2 +1,256 @@
|
|
|
1
|
-
import
|
|
1
|
+
import { ATTRIBUTES_TO_EXTRACT } from "./utils/constants.mjs";
|
|
2
|
+
import { getComponentName } from "./utils/getComponentName.mjs";
|
|
3
|
+
import { getExistingIntlayerInfo } from "./utils/getExistingIntlayerInfo.mjs";
|
|
4
|
+
import { getOrGenerateKey } from "./utils/getOrGenerateKey.mjs";
|
|
5
|
+
import { resolveDictionaryKey } from "./utils/resolveDictionaryKey.mjs";
|
|
6
|
+
import { shouldExtract } from "./utils/shouldExtract.mjs";
|
|
7
|
+
import _traverse from "@babel/traverse";
|
|
8
|
+
import * as t from "@babel/types";
|
|
9
|
+
|
|
10
|
+
//#region src/extractContent/babelProcessor.ts
|
|
11
|
+
const traverse = typeof _traverse === "function" ? _traverse : _traverse.default;
|
|
12
|
+
/**
|
|
13
|
+
* Handles JSX insertions (elements with multiple children, including expressions).
|
|
14
|
+
* Replaces complex JSX structures with variable-based translations.
|
|
15
|
+
*/
|
|
16
|
+
const handleJsxInsertionBabel = (path, fileCode, existingKeys, getComponentKeyForPath, extractedContent, replacements, handledNodes) => {
|
|
17
|
+
const children = path.node.children;
|
|
18
|
+
if (children.length <= 1) return false;
|
|
19
|
+
const parts = [];
|
|
20
|
+
let hasSignificantText = false;
|
|
21
|
+
let hasVariables = false;
|
|
22
|
+
for (const child of children) if (t.isJSXText(child)) {
|
|
23
|
+
const text = child.value;
|
|
24
|
+
if (text.trim().length > 0) hasSignificantText = true;
|
|
25
|
+
parts.push({
|
|
26
|
+
type: "text",
|
|
27
|
+
value: text
|
|
28
|
+
});
|
|
29
|
+
} else if (t.isJSXExpressionContainer(child)) if (t.isJSXEmptyExpression(child.expression)) parts.push({
|
|
30
|
+
type: "text",
|
|
31
|
+
value: ""
|
|
32
|
+
});
|
|
33
|
+
else {
|
|
34
|
+
const expr = child.expression;
|
|
35
|
+
if (t.isIdentifier(expr)) {
|
|
36
|
+
parts.push({
|
|
37
|
+
type: "var",
|
|
38
|
+
value: expr.name,
|
|
39
|
+
originalExpr: expr.name
|
|
40
|
+
});
|
|
41
|
+
hasVariables = true;
|
|
42
|
+
} else if (t.isMemberExpression(expr)) {
|
|
43
|
+
const code = fileCode.substring(expr.start, expr.end);
|
|
44
|
+
const varName = t.isIdentifier(expr.property) ? expr.property.name : "var";
|
|
45
|
+
parts.push({
|
|
46
|
+
type: "var",
|
|
47
|
+
value: varName,
|
|
48
|
+
originalExpr: code
|
|
49
|
+
});
|
|
50
|
+
hasVariables = true;
|
|
51
|
+
} else return false;
|
|
52
|
+
}
|
|
53
|
+
else return false;
|
|
54
|
+
if (!hasSignificantText) return false;
|
|
55
|
+
let combinedString = "";
|
|
56
|
+
for (const part of parts) if (part.type === "var") combinedString += `{{${part.value}}}`;
|
|
57
|
+
else combinedString += part.value;
|
|
58
|
+
const cleanString = combinedString.replace(/\s+/g, " ").trim();
|
|
59
|
+
if (shouldExtract(cleanString)) {
|
|
60
|
+
const componentKey = getComponentKeyForPath(path);
|
|
61
|
+
const key = getOrGenerateKey(cleanString, componentKey, existingKeys, extractedContent);
|
|
62
|
+
const varMap = parts.filter((part) => part.type === "var").map((part) => `${part.value}: ${part.originalExpr}`);
|
|
63
|
+
const uniqueVars = Array.from(new Set(varMap));
|
|
64
|
+
if (hasVariables) replacements.push({
|
|
65
|
+
path,
|
|
66
|
+
key,
|
|
67
|
+
type: "jsx-insertion",
|
|
68
|
+
componentKey,
|
|
69
|
+
childrenToReplace: children,
|
|
70
|
+
variables: uniqueVars
|
|
71
|
+
});
|
|
72
|
+
else replacements.push({
|
|
73
|
+
path,
|
|
74
|
+
key,
|
|
75
|
+
type: "jsx-text-combined",
|
|
76
|
+
componentKey,
|
|
77
|
+
childrenToReplace: children
|
|
78
|
+
});
|
|
79
|
+
children.forEach((child) => {
|
|
80
|
+
handledNodes.add(child);
|
|
81
|
+
});
|
|
82
|
+
return true;
|
|
83
|
+
}
|
|
84
|
+
return false;
|
|
85
|
+
};
|
|
86
|
+
/**
|
|
87
|
+
* Traverses the AST to identify components and extract content.
|
|
88
|
+
* Returns extraction results and metadata about which components need Intlayer hooks.
|
|
89
|
+
*/
|
|
90
|
+
const extractBabelContentForComponents = (ast, fileCode, existingKeys, defaultKey = "default", configuration, filePath, unmergedDictionaries = {}) => {
|
|
91
|
+
const extractedContent = {};
|
|
92
|
+
const replacements = [];
|
|
93
|
+
const handledNodes = /* @__PURE__ */ new Set();
|
|
94
|
+
const componentKeyMap = /* @__PURE__ */ new Map();
|
|
95
|
+
const hookMap = /* @__PURE__ */ new Map();
|
|
96
|
+
const usedKeysInFile = /* @__PURE__ */ new Set();
|
|
97
|
+
let globalFileKey;
|
|
98
|
+
const componentPaths = [];
|
|
99
|
+
traverse(ast, {
|
|
100
|
+
FunctionDeclaration(path) {
|
|
101
|
+
componentPaths.push(path);
|
|
102
|
+
},
|
|
103
|
+
ArrowFunctionExpression(path) {
|
|
104
|
+
componentPaths.push(path);
|
|
105
|
+
},
|
|
106
|
+
FunctionExpression(path) {
|
|
107
|
+
componentPaths.push(path);
|
|
108
|
+
}
|
|
109
|
+
});
|
|
110
|
+
for (const path of componentPaths) {
|
|
111
|
+
const existingInfo = getExistingIntlayerInfo(path);
|
|
112
|
+
if (existingInfo) {
|
|
113
|
+
componentKeyMap.set(path.node, existingInfo.key);
|
|
114
|
+
usedKeysInFile.add(existingInfo.key);
|
|
115
|
+
hookMap.set(path.node, existingInfo.hook);
|
|
116
|
+
} else {
|
|
117
|
+
if (!globalFileKey) {
|
|
118
|
+
globalFileKey = resolveDictionaryKey(defaultKey, filePath, configuration, unmergedDictionaries, usedKeysInFile);
|
|
119
|
+
usedKeysInFile.add(globalFileKey);
|
|
120
|
+
}
|
|
121
|
+
componentKeyMap.set(path.node, globalFileKey);
|
|
122
|
+
const compName = getComponentName(path);
|
|
123
|
+
const isComponent = compName ? /^[A-Z]/.test(compName) : false;
|
|
124
|
+
hookMap.set(path.node, isComponent ? "useIntlayer" : "getIntlayer");
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
const getComponentKeyForPath = (path) => {
|
|
128
|
+
let current = path;
|
|
129
|
+
while (current) {
|
|
130
|
+
if (componentKeyMap.has(current.node)) return componentKeyMap.get(current.node);
|
|
131
|
+
current = current.parentPath;
|
|
132
|
+
}
|
|
133
|
+
return globalFileKey || defaultKey;
|
|
134
|
+
};
|
|
135
|
+
traverse(ast, {
|
|
136
|
+
JSXElement(path) {
|
|
137
|
+
if (handledNodes.has(path.node)) return;
|
|
138
|
+
handleJsxInsertionBabel(path, fileCode, existingKeys, getComponentKeyForPath, extractedContent, replacements, handledNodes);
|
|
139
|
+
},
|
|
140
|
+
JSXFragment(path) {
|
|
141
|
+
if (handledNodes.has(path.node)) return;
|
|
142
|
+
handleJsxInsertionBabel(path, fileCode, existingKeys, getComponentKeyForPath, extractedContent, replacements, handledNodes);
|
|
143
|
+
},
|
|
144
|
+
JSXText(path) {
|
|
145
|
+
if (handledNodes.has(path.node)) return;
|
|
146
|
+
const text = path.node.value;
|
|
147
|
+
if (shouldExtract(text)) {
|
|
148
|
+
const componentKey = getComponentKeyForPath(path);
|
|
149
|
+
const key = getOrGenerateKey(text.replace(/\s+/g, " ").trim(), componentKey, existingKeys, extractedContent);
|
|
150
|
+
replacements.push({
|
|
151
|
+
path,
|
|
152
|
+
key,
|
|
153
|
+
type: "jsx-text",
|
|
154
|
+
componentKey
|
|
155
|
+
});
|
|
156
|
+
}
|
|
157
|
+
},
|
|
158
|
+
JSXAttribute(path) {
|
|
159
|
+
if (handledNodes.has(path.node)) return;
|
|
160
|
+
const name = path.node.name.name;
|
|
161
|
+
if (typeof name !== "string" || !ATTRIBUTES_TO_EXTRACT.includes(name)) return;
|
|
162
|
+
const value = path.node.value;
|
|
163
|
+
if (t.isStringLiteral(value) && shouldExtract(value.value)) {
|
|
164
|
+
const componentKey = getComponentKeyForPath(path);
|
|
165
|
+
const key = getOrGenerateKey(value.value.trim(), componentKey, existingKeys, extractedContent);
|
|
166
|
+
replacements.push({
|
|
167
|
+
path,
|
|
168
|
+
key,
|
|
169
|
+
type: "jsx-attribute",
|
|
170
|
+
componentKey
|
|
171
|
+
});
|
|
172
|
+
}
|
|
173
|
+
},
|
|
174
|
+
StringLiteral(path) {
|
|
175
|
+
if (handledNodes.has(path.node)) return;
|
|
176
|
+
const text = path.node.value;
|
|
177
|
+
if (!shouldExtract(text)) return;
|
|
178
|
+
const parent = path.parentPath;
|
|
179
|
+
if (parent.isImportDeclaration() || parent.isImportSpecifier() || parent.isExportDeclaration()) return;
|
|
180
|
+
if (parent.isJSXAttribute()) return;
|
|
181
|
+
if (parent.isCallExpression() && t.isMemberExpression(parent.node.callee)) {
|
|
182
|
+
if (t.isIdentifier(parent.node.callee.object) && parent.node.callee.object.name === "console" && t.isIdentifier(parent.node.callee.property) && parent.node.callee.property.name === "log") return;
|
|
183
|
+
}
|
|
184
|
+
if (parent.isObjectProperty() && parent.node.key === path.node) return;
|
|
185
|
+
if (parent.isMemberExpression() && parent.node.property === path.node) return;
|
|
186
|
+
const componentKey = getComponentKeyForPath(path);
|
|
187
|
+
const key = getOrGenerateKey(text.trim(), componentKey, existingKeys, extractedContent);
|
|
188
|
+
replacements.push({
|
|
189
|
+
path,
|
|
190
|
+
key,
|
|
191
|
+
type: "string-literal",
|
|
192
|
+
componentKey
|
|
193
|
+
});
|
|
194
|
+
}
|
|
195
|
+
});
|
|
196
|
+
const componentsNeedingHooks = /* @__PURE__ */ new Set();
|
|
197
|
+
for (const componentPath of componentPaths) if (replacements.some((replacement) => {
|
|
198
|
+
let current = replacement.path;
|
|
199
|
+
while (current) {
|
|
200
|
+
if (current.node === componentPath.node) return true;
|
|
201
|
+
current = current.parentPath;
|
|
202
|
+
}
|
|
203
|
+
return false;
|
|
204
|
+
})) {
|
|
205
|
+
const key = componentKeyMap.get(componentPath.node);
|
|
206
|
+
let ancestorProvidesKey = false;
|
|
207
|
+
let currentPath = componentPath.parentPath;
|
|
208
|
+
while (currentPath) {
|
|
209
|
+
const ancestorPath = componentPaths.find((path) => path.node === currentPath?.node);
|
|
210
|
+
if (ancestorPath) {
|
|
211
|
+
if (componentKeyMap.get(ancestorPath.node) === key) {
|
|
212
|
+
const ancestorHasReplacements = replacements.some((replacement) => {
|
|
213
|
+
let rPath = replacement.path;
|
|
214
|
+
while (rPath) {
|
|
215
|
+
if (rPath.node === ancestorPath.node) return true;
|
|
216
|
+
rPath = rPath.parentPath;
|
|
217
|
+
}
|
|
218
|
+
return false;
|
|
219
|
+
});
|
|
220
|
+
const existingInfo = getExistingIntlayerInfo(ancestorPath);
|
|
221
|
+
if (ancestorHasReplacements || existingInfo) {
|
|
222
|
+
ancestorProvidesKey = true;
|
|
223
|
+
break;
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
currentPath = currentPath.parentPath;
|
|
228
|
+
}
|
|
229
|
+
if (!ancestorProvidesKey) componentsNeedingHooks.add(componentPath);
|
|
230
|
+
}
|
|
231
|
+
return {
|
|
232
|
+
extractedContent,
|
|
233
|
+
replacements,
|
|
234
|
+
componentsNeedingHooks,
|
|
235
|
+
componentKeyMap,
|
|
236
|
+
componentPaths,
|
|
237
|
+
hookMap,
|
|
238
|
+
isSolid: false
|
|
239
|
+
};
|
|
240
|
+
};
|
|
241
|
+
/**
|
|
242
|
+
* High-level function to extract content from TS/JS/JSX/TSX AST.
|
|
243
|
+
*/
|
|
244
|
+
const extractTsContent = (ast, fileCode, existingKeys, configuration, filePath, unmergedDictionaries = {}) => {
|
|
245
|
+
const { extractedContent, replacements } = extractBabelContentForComponents(ast, fileCode, existingKeys, "default", configuration, filePath, unmergedDictionaries);
|
|
246
|
+
const flatContent = {};
|
|
247
|
+
for (const group of Object.values(extractedContent)) Object.assign(flatContent, group);
|
|
248
|
+
return {
|
|
249
|
+
extractedContent: flatContent,
|
|
250
|
+
replacements
|
|
251
|
+
};
|
|
252
|
+
};
|
|
253
|
+
|
|
254
|
+
//#endregion
|
|
255
|
+
export { extractBabelContentForComponents, extractTsContent, handleJsxInsertionBabel };
|
|
2
256
|
//# sourceMappingURL=babelProcessor.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"babelProcessor.mjs","names":[],"sources":["../../../src/extractContent/babelProcessor.ts"],"sourcesContent":["import _traverse, { type NodePath } from '@babel/traverse';\nimport * as t from '@babel/types';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport { resolveDictionaryKey } from '../extractContent/utils';\nimport {\n ATTRIBUTES_TO_EXTRACT,\n getComponentName,\n getExistingIntlayerInfo,\n getOrGenerateKey,\n shouldExtract,\n} from './utils';\n\nexport type BabelReplacement = {\n path: NodePath;\n key: string;\n type:\n | 'jsx-text'\n | 'jsx-attribute'\n | 'string-literal'\n | 'jsx-insertion'\n | 'jsx-text-combined';\n componentKey: string;\n childrenToReplace?: t.Node[];\n variables?: string[];\n};\n\n// CJS/ESM interop: @babel/traverse exports its function as `.default` in CJS bundles\nconst traverse = (\n typeof _traverse === 'function' ? _traverse : (_traverse as any).default\n) as typeof _traverse;\n\n/**\n * Handles JSX insertions (elements with multiple children, including expressions).\n * Replaces complex JSX structures with variable-based translations.\n */\nexport const handleJsxInsertionBabel = (\n path: NodePath<t.JSXElement | t.JSXFragment>,\n fileCode: string,\n existingKeys: Set<string>,\n getComponentKeyForPath: (path: NodePath) => string,\n extractedContent: Record<string, Record<string, string>>,\n replacements: BabelReplacement[],\n handledNodes: Set<t.Node>\n): boolean => {\n const children = path.node.children;\n\n if (children.length <= 1) return false;\n\n const parts: {\n type: 'text' | 'var';\n value: string;\n originalExpr?: string;\n }[] = [];\n let hasSignificantText = false;\n let hasVariables = false;\n\n for (const child of children) {\n if (t.isJSXText(child)) {\n const text = child.value;\n\n if (text.trim().length > 0) hasSignificantText = true;\n\n parts.push({ type: 'text', value: text });\n } else if (t.isJSXExpressionContainer(child)) {\n if (t.isJSXEmptyExpression(child.expression)) {\n parts.push({ type: 'text', value: '' });\n } else {\n const expr = child.expression;\n\n if (t.isIdentifier(expr)) {\n parts.push({\n type: 'var',\n value: expr.name,\n originalExpr: expr.name,\n });\n hasVariables = true;\n } else if (t.isMemberExpression(expr)) {\n const code = fileCode.substring(expr.start!, expr.end!);\n\n const varName = t.isIdentifier(expr.property)\n ? expr.property.name\n : 'var';\n\n parts.push({ type: 'var', value: varName, originalExpr: code });\n\n hasVariables = true;\n } else {\n return false;\n }\n }\n } else {\n return false;\n }\n }\n\n if (!hasSignificantText) return false;\n\n let combinedString = '';\n for (const part of parts) {\n if (part.type === 'var') combinedString += `{{${part.value}}}`;\n else combinedString += part.value;\n }\n\n const cleanString = combinedString.replace(/\\s+/g, ' ').trim();\n\n if (shouldExtract(cleanString)) {\n const componentKey = getComponentKeyForPath(path);\n const key = getOrGenerateKey(\n cleanString,\n componentKey,\n existingKeys,\n extractedContent\n );\n\n const varMap = parts\n .filter((part) => part.type === 'var')\n .map((part) => `${part.value}: ${part.originalExpr}`);\n const uniqueVars = Array.from(new Set(varMap));\n\n if (hasVariables) {\n replacements.push({\n path,\n key,\n type: 'jsx-insertion',\n componentKey,\n childrenToReplace: children,\n variables: uniqueVars,\n });\n } else {\n replacements.push({\n path,\n key,\n type: 'jsx-text-combined',\n componentKey,\n childrenToReplace: children,\n });\n }\n\n children.forEach((child) => {\n handledNodes.add(child);\n });\n return true;\n }\n\n return false;\n};\n\n/**\n * Traverses the AST to identify components and extract content.\n * Returns extraction results and metadata about which components need Intlayer hooks.\n */\nexport const extractBabelContentForComponents = (\n ast: t.File,\n fileCode: string,\n existingKeys: Set<string>,\n defaultKey: string = 'default',\n configuration: IntlayerConfig,\n filePath: string,\n unmergedDictionaries: Record<string, unknown> = {}\n): {\n extractedContent: Record<string, Record<string, string>>;\n replacements: BabelReplacement[];\n componentsNeedingHooks: Set<NodePath>;\n componentKeyMap: Map<t.Node, string>;\n componentPaths: NodePath[];\n hookMap: Map<t.Node, 'useIntlayer' | 'getIntlayer'>;\n isSolid: boolean;\n} => {\n const extractedContent: Record<string, Record<string, string>> = {};\n const replacements: BabelReplacement[] = [];\n const handledNodes = new Set<t.Node>();\n const componentKeyMap = new Map<t.Node, string>();\n const hookMap = new Map<t.Node, 'useIntlayer' | 'getIntlayer'>();\n const usedKeysInFile = new Set<string>();\n let globalFileKey: string | undefined;\n\n const componentPaths: NodePath[] = [];\n\n traverse(ast, {\n FunctionDeclaration(path) {\n componentPaths.push(path);\n },\n ArrowFunctionExpression(path) {\n componentPaths.push(path);\n },\n FunctionExpression(path) {\n componentPaths.push(path);\n },\n });\n\n for (const path of componentPaths) {\n const existingInfo = getExistingIntlayerInfo(path);\n\n if (existingInfo) {\n componentKeyMap.set(path.node, existingInfo.key);\n usedKeysInFile.add(existingInfo.key);\n hookMap.set(path.node, existingInfo.hook);\n } else {\n if (!globalFileKey) {\n globalFileKey = resolveDictionaryKey(\n defaultKey,\n filePath,\n configuration,\n unmergedDictionaries,\n usedKeysInFile\n );\n usedKeysInFile.add(globalFileKey);\n }\n componentKeyMap.set(path.node, globalFileKey);\n\n const compName = getComponentName(path);\n const isComponent = compName ? /^[A-Z]/.test(compName) : false;\n hookMap.set(path.node, isComponent ? 'useIntlayer' : 'getIntlayer');\n }\n }\n\n const getComponentKeyForPath = (path: NodePath): string => {\n let current: NodePath | null = path;\n while (current) {\n if (componentKeyMap.has(current.node)) {\n return componentKeyMap.get(current.node)!;\n }\n current = current.parentPath;\n }\n return globalFileKey || defaultKey;\n };\n\n traverse(ast, {\n JSXElement(path) {\n if (handledNodes.has(path.node)) return;\n\n handleJsxInsertionBabel(\n path,\n fileCode,\n existingKeys,\n getComponentKeyForPath,\n extractedContent,\n replacements,\n handledNodes\n );\n },\n JSXFragment(path) {\n if (handledNodes.has(path.node)) return;\n\n handleJsxInsertionBabel(\n path,\n fileCode,\n existingKeys,\n getComponentKeyForPath,\n extractedContent,\n replacements,\n handledNodes\n );\n },\n JSXText(path) {\n if (handledNodes.has(path.node)) return;\n\n const text = path.node.value;\n\n if (shouldExtract(text)) {\n const componentKey = getComponentKeyForPath(path);\n const key = getOrGenerateKey(\n text.replace(/\\s+/g, ' ').trim(),\n componentKey,\n existingKeys,\n extractedContent\n );\n replacements.push({ path, key, type: 'jsx-text', componentKey });\n }\n },\n JSXAttribute(path) {\n if (handledNodes.has(path.node)) return;\n\n const name = path.node.name.name;\n\n if (\n typeof name !== 'string' ||\n !ATTRIBUTES_TO_EXTRACT.includes(name as any)\n )\n return;\n const value = path.node.value;\n\n if (t.isStringLiteral(value) && shouldExtract(value.value)) {\n const componentKey = getComponentKeyForPath(path);\n const key = getOrGenerateKey(\n value.value.trim(),\n componentKey,\n existingKeys,\n extractedContent\n );\n replacements.push({ path, key, type: 'jsx-attribute', componentKey });\n }\n },\n StringLiteral(path) {\n if (handledNodes.has(path.node)) return;\n\n const text = path.node.value;\n\n if (!shouldExtract(text)) return;\n\n const parent = path.parentPath;\n\n if (\n parent.isImportDeclaration() ||\n parent.isImportSpecifier() ||\n parent.isExportDeclaration()\n )\n return;\n\n if (parent.isJSXAttribute()) return;\n\n if (\n parent.isCallExpression() &&\n t.isMemberExpression(parent.node.callee)\n ) {\n if (\n t.isIdentifier(parent.node.callee.object) &&\n parent.node.callee.object.name === 'console' &&\n t.isIdentifier(parent.node.callee.property) &&\n parent.node.callee.property.name === 'log'\n ) {\n return;\n }\n }\n\n if (parent.isObjectProperty() && parent.node.key === path.node) return;\n\n if (parent.isMemberExpression() && parent.node.property === path.node)\n return;\n\n const componentKey = getComponentKeyForPath(path);\n const key = getOrGenerateKey(\n text.trim(),\n componentKey,\n existingKeys,\n extractedContent\n );\n replacements.push({ path, key, type: 'string-literal', componentKey });\n },\n });\n\n const componentsNeedingHooks = new Set<NodePath>();\n for (const componentPath of componentPaths) {\n const hasReplacements = replacements.some((replacement) => {\n let current: NodePath | null = replacement.path;\n while (current) {\n if (current.node === componentPath.node) return true;\n\n current = current.parentPath;\n }\n return false;\n });\n\n if (hasReplacements) {\n const key = componentKeyMap.get(componentPath.node)!;\n let ancestorProvidesKey = false;\n let currentPath: NodePath | null = componentPath.parentPath;\n while (currentPath) {\n const ancestorPath = componentPaths.find(\n (path) => path.node === currentPath?.node\n );\n\n if (ancestorPath) {\n const ancestorKey = componentKeyMap.get(ancestorPath.node);\n\n if (ancestorKey === key) {\n const ancestorHasReplacements = replacements.some((replacement) => {\n let rPath: NodePath | null = replacement.path;\n while (rPath) {\n if (rPath.node === ancestorPath.node) return true;\n\n rPath = rPath.parentPath;\n }\n return false;\n });\n const existingInfo = getExistingIntlayerInfo(ancestorPath);\n\n if (ancestorHasReplacements || existingInfo) {\n ancestorProvidesKey = true;\n break;\n }\n }\n }\n currentPath = currentPath.parentPath;\n }\n\n if (!ancestorProvidesKey) {\n componentsNeedingHooks.add(componentPath);\n }\n }\n }\n\n return {\n extractedContent,\n replacements,\n componentsNeedingHooks,\n componentKeyMap,\n componentPaths,\n hookMap,\n isSolid: false,\n };\n};\n\n/**\n * High-level function to extract content from TS/JS/JSX/TSX AST.\n */\nexport const extractTsContent = (\n ast: t.File,\n fileCode: string,\n existingKeys: Set<string>,\n configuration: IntlayerConfig,\n filePath: string,\n unmergedDictionaries: Record<string, unknown> = {}\n): {\n extractedContent: Record<string, string>;\n replacements: BabelReplacement[];\n} => {\n const { extractedContent, replacements } = extractBabelContentForComponents(\n ast,\n fileCode,\n existingKeys,\n 'default',\n configuration,\n filePath,\n unmergedDictionaries\n );\n\n const flatContent: Record<string, string> = {};\n for (const group of Object.values(extractedContent)) {\n Object.assign(flatContent, group);\n }\n\n return { extractedContent: flatContent, replacements };\n};\n"],"mappings":"4cA2BA,MAAM,EACJ,OAAO,GAAc,WAAa,EAAa,EAAkB,QAOtD,GACX,EACA,EACA,EACA,EACA,EACA,EACA,IACY,CACZ,IAAM,EAAW,EAAK,KAAK,SAE3B,GAAI,EAAS,QAAU,EAAG,MAAO,GAEjC,IAAM,EAIA,EAAE,CACJ,EAAqB,GACrB,EAAe,GAEnB,IAAK,IAAM,KAAS,EAClB,GAAI,EAAE,UAAU,EAAM,CAAE,CACtB,IAAM,EAAO,EAAM,MAEf,EAAK,MAAM,CAAC,OAAS,IAAG,EAAqB,IAEjD,EAAM,KAAK,CAAE,KAAM,OAAQ,MAAO,EAAM,CAAC,SAChC,EAAE,yBAAyB,EAAM,CAC1C,GAAI,EAAE,qBAAqB,EAAM,WAAW,CAC1C,EAAM,KAAK,CAAE,KAAM,OAAQ,MAAO,GAAI,CAAC,KAClC,CACL,IAAM,EAAO,EAAM,WAEnB,GAAI,EAAE,aAAa,EAAK,CACtB,EAAM,KAAK,CACT,KAAM,MACN,MAAO,EAAK,KACZ,aAAc,EAAK,KACpB,CAAC,CACF,EAAe,WACN,EAAE,mBAAmB,EAAK,CAAE,CACrC,IAAM,E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M,MAAO,GAEhD,EAAU,EAAQ,WAEpB,MAAO,IACP,CAEmB,CACnB,IAAM,EAAM,EAAgB,IAAI,EAAc,KAAK,CAC/C,EAAsB,GACtB,EAA+B,EAAc,WACjD,KAAO,GAAa,CAClB,IAAM,EAAe,EAAe,KACjC,GAAS,EAAK,OAAS,GAAa,KACtC,CAED,GAAI,GACkB,EAAgB,IAAI,EAAa,KAAK,GAEtC,EAAK,CACvB,IAAM,EAA0B,EAAa,KAAM,GAAgB,CACjE,IAAI,EAAyB,EAAY,KACzC,KAAO,GAAO,CACZ,GAAI,EAAM,OAAS,EAAa,KAAM,MAAO,GAE7C,EAAQ,EAAM,WAEhB,MAAO,IACP,CACI,EAAe,EAAwB,EAAa,CAE1D,GAAI,GAA2B,EAAc,CAC3C,EAAsB,GACtB,OAIN,EAAc,EAAY,WAGvB,GACH,EAAuB,IAAI,EAAc,CAK/C,MAAO,CACL,mBACA,eACA,yBACA,kBACA,iBACA,UACA,QAAS,GACV,EAMU,GACX,EACA,EACA,EACA,EACA,EACA,EAAgD,EAAE,GAI/C,CACH,GAAM,CAAE,mBAAkB,gBAAiB,EACzC,EACA,EACA,EACA,UACA,EACA,EACA,EACD,CAEK,EAAsC,EAAE,CAC9C,IAAK,IAAM,KAAS,OAAO,OAAO,EAAiB,CACjD,OAAO,OAAO,EAAa,EAAM,CAGnC,MAAO,CAAE,iBAAkB,EAAa,eAAc"}
|
|
1
|
+
{"version":3,"file":"babelProcessor.mjs","names":[],"sources":["../../../src/extractContent/babelProcessor.ts"],"sourcesContent":["import _traverse, { type NodePath } from '@babel/traverse';\nimport * as t from '@babel/types';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport { resolveDictionaryKey } from '../extractContent/utils';\nimport {\n ATTRIBUTES_TO_EXTRACT,\n getComponentName,\n getExistingIntlayerInfo,\n getOrGenerateKey,\n shouldExtract,\n} from './utils';\n\nexport type BabelReplacement = {\n path: NodePath;\n key: string;\n type:\n | 'jsx-text'\n | 'jsx-attribute'\n | 'string-literal'\n | 'jsx-insertion'\n | 'jsx-text-combined';\n componentKey: string;\n childrenToReplace?: t.Node[];\n variables?: string[];\n};\n\n// CJS/ESM interop: @babel/traverse exports its function as `.default` in CJS bundles\nconst traverse = (\n typeof _traverse === 'function' ? _traverse : (_traverse as any).default\n) as typeof _traverse;\n\n/**\n * Handles JSX insertions (elements with multiple children, including expressions).\n * Replaces complex JSX structures with variable-based translations.\n */\nexport const handleJsxInsertionBabel = (\n path: NodePath<t.JSXElement | t.JSXFragment>,\n fileCode: string,\n existingKeys: Set<string>,\n getComponentKeyForPath: (path: NodePath) => string,\n extractedContent: Record<string, Record<string, string>>,\n replacements: BabelReplacement[],\n handledNodes: Set<t.Node>\n): boolean => {\n const children = path.node.children;\n\n if (children.length <= 1) return false;\n\n const parts: {\n type: 'text' | 'var';\n value: string;\n originalExpr?: string;\n }[] = [];\n let hasSignificantText = false;\n let hasVariables = false;\n\n for (const child of children) {\n if (t.isJSXText(child)) {\n const text = child.value;\n\n if (text.trim().length > 0) hasSignificantText = true;\n\n parts.push({ type: 'text', value: text });\n } else if (t.isJSXExpressionContainer(child)) {\n if (t.isJSXEmptyExpression(child.expression)) {\n parts.push({ type: 'text', value: '' });\n } else {\n const expr = child.expression;\n\n if (t.isIdentifier(expr)) {\n parts.push({\n type: 'var',\n value: expr.name,\n originalExpr: expr.name,\n });\n hasVariables = true;\n } else if (t.isMemberExpression(expr)) {\n const code = fileCode.substring(expr.start!, expr.end!);\n\n const varName = t.isIdentifier(expr.property)\n ? expr.property.name\n : 'var';\n\n parts.push({ type: 'var', value: varName, originalExpr: code });\n\n hasVariables = true;\n } else {\n return false;\n }\n }\n } else {\n return false;\n }\n }\n\n if (!hasSignificantText) return false;\n\n let combinedString = '';\n for (const part of parts) {\n if (part.type === 'var') combinedString += `{{${part.value}}}`;\n else combinedString += part.value;\n }\n\n const cleanString = combinedString.replace(/\\s+/g, ' ').trim();\n\n if (shouldExtract(cleanString)) {\n const componentKey = getComponentKeyForPath(path);\n const key = getOrGenerateKey(\n cleanString,\n componentKey,\n existingKeys,\n extractedContent\n );\n\n const varMap = parts\n .filter((part) => part.type === 'var')\n .map((part) => `${part.value}: ${part.originalExpr}`);\n const uniqueVars = Array.from(new Set(varMap));\n\n if (hasVariables) {\n replacements.push({\n path,\n key,\n type: 'jsx-insertion',\n componentKey,\n childrenToReplace: children,\n variables: uniqueVars,\n });\n } else {\n replacements.push({\n path,\n key,\n type: 'jsx-text-combined',\n componentKey,\n childrenToReplace: children,\n });\n }\n\n children.forEach((child) => {\n handledNodes.add(child);\n });\n return true;\n }\n\n return false;\n};\n\n/**\n * Traverses the AST to identify components and extract content.\n * Returns extraction results and metadata about which components need Intlayer hooks.\n */\nexport const extractBabelContentForComponents = (\n ast: t.File,\n fileCode: string,\n existingKeys: Set<string>,\n defaultKey: string = 'default',\n configuration: IntlayerConfig,\n filePath: string,\n unmergedDictionaries: Record<string, unknown> = {}\n): {\n extractedContent: Record<string, Record<string, string>>;\n replacements: BabelReplacement[];\n componentsNeedingHooks: Set<NodePath>;\n componentKeyMap: Map<t.Node, string>;\n componentPaths: NodePath[];\n hookMap: Map<t.Node, 'useIntlayer' | 'getIntlayer'>;\n isSolid: boolean;\n} => {\n const extractedContent: Record<string, Record<string, string>> = {};\n const replacements: BabelReplacement[] = [];\n const handledNodes = new Set<t.Node>();\n const componentKeyMap = new Map<t.Node, string>();\n const hookMap = new Map<t.Node, 'useIntlayer' | 'getIntlayer'>();\n const usedKeysInFile = new Set<string>();\n let globalFileKey: string | undefined;\n\n const componentPaths: NodePath[] = [];\n\n traverse(ast, {\n FunctionDeclaration(path) {\n componentPaths.push(path);\n },\n ArrowFunctionExpression(path) {\n componentPaths.push(path);\n },\n FunctionExpression(path) {\n componentPaths.push(path);\n },\n });\n\n for (const path of componentPaths) {\n const existingInfo = getExistingIntlayerInfo(path);\n\n if (existingInfo) {\n componentKeyMap.set(path.node, existingInfo.key);\n usedKeysInFile.add(existingInfo.key);\n hookMap.set(path.node, existingInfo.hook);\n } else {\n if (!globalFileKey) {\n globalFileKey = resolveDictionaryKey(\n defaultKey,\n filePath,\n configuration,\n unmergedDictionaries,\n usedKeysInFile\n );\n usedKeysInFile.add(globalFileKey);\n }\n componentKeyMap.set(path.node, globalFileKey);\n\n const compName = getComponentName(path);\n const isComponent = compName ? /^[A-Z]/.test(compName) : false;\n hookMap.set(path.node, isComponent ? 'useIntlayer' : 'getIntlayer');\n }\n }\n\n const getComponentKeyForPath = (path: NodePath): string => {\n let current: NodePath | null = path;\n while (current) {\n if (componentKeyMap.has(current.node)) {\n return componentKeyMap.get(current.node)!;\n }\n current = current.parentPath;\n }\n return globalFileKey || defaultKey;\n };\n\n traverse(ast, {\n JSXElement(path) {\n if (handledNodes.has(path.node)) return;\n\n handleJsxInsertionBabel(\n path,\n fileCode,\n existingKeys,\n getComponentKeyForPath,\n extractedContent,\n replacements,\n handledNodes\n );\n },\n JSXFragment(path) {\n if (handledNodes.has(path.node)) return;\n\n handleJsxInsertionBabel(\n path,\n fileCode,\n existingKeys,\n getComponentKeyForPath,\n extractedContent,\n replacements,\n handledNodes\n );\n },\n JSXText(path) {\n if (handledNodes.has(path.node)) return;\n\n const text = path.node.value;\n\n if (shouldExtract(text)) {\n const componentKey = getComponentKeyForPath(path);\n const key = getOrGenerateKey(\n text.replace(/\\s+/g, ' ').trim(),\n componentKey,\n existingKeys,\n extractedContent\n );\n replacements.push({ path, key, type: 'jsx-text', componentKey });\n }\n },\n JSXAttribute(path) {\n if (handledNodes.has(path.node)) return;\n\n const name = path.node.name.name;\n\n if (\n typeof name !== 'string' ||\n !ATTRIBUTES_TO_EXTRACT.includes(name as any)\n )\n return;\n const value = path.node.value;\n\n if (t.isStringLiteral(value) && shouldExtract(value.value)) {\n const componentKey = getComponentKeyForPath(path);\n const key = getOrGenerateKey(\n value.value.trim(),\n componentKey,\n existingKeys,\n extractedContent\n );\n replacements.push({ path, key, type: 'jsx-attribute', componentKey });\n }\n },\n StringLiteral(path) {\n if (handledNodes.has(path.node)) return;\n\n const text = path.node.value;\n\n if (!shouldExtract(text)) return;\n\n const parent = path.parentPath;\n\n if (\n parent.isImportDeclaration() ||\n parent.isImportSpecifier() ||\n parent.isExportDeclaration()\n )\n return;\n\n if (parent.isJSXAttribute()) return;\n\n if (\n parent.isCallExpression() &&\n t.isMemberExpression(parent.node.callee)\n ) {\n if (\n t.isIdentifier(parent.node.callee.object) &&\n parent.node.callee.object.name === 'console' &&\n t.isIdentifier(parent.node.callee.property) &&\n parent.node.callee.property.name === 'log'\n ) {\n return;\n }\n }\n\n if (parent.isObjectProperty() && parent.node.key === path.node) return;\n\n if (parent.isMemberExpression() && parent.node.property === path.node)\n return;\n\n const componentKey = getComponentKeyForPath(path);\n const key = getOrGenerateKey(\n text.trim(),\n componentKey,\n existingKeys,\n extractedContent\n );\n replacements.push({ path, key, type: 'string-literal', componentKey });\n },\n });\n\n const componentsNeedingHooks = new Set<NodePath>();\n for (const componentPath of componentPaths) {\n const hasReplacements = replacements.some((replacement) => {\n let current: NodePath | null = replacement.path;\n while (current) {\n if (current.node === componentPath.node) return true;\n\n current = current.parentPath;\n }\n return false;\n });\n\n if (hasReplacements) {\n const key = componentKeyMap.get(componentPath.node)!;\n let ancestorProvidesKey = false;\n let currentPath: NodePath | null = componentPath.parentPath;\n while (currentPath) {\n const ancestorPath = componentPaths.find(\n (path) => path.node === currentPath?.node\n );\n\n if (ancestorPath) {\n const ancestorKey = componentKeyMap.get(ancestorPath.node);\n\n if (ancestorKey === key) {\n const ancestorHasReplacements = replacements.some((replacement) => {\n let rPath: NodePath | null = replacement.path;\n while (rPath) {\n if (rPath.node === ancestorPath.node) return true;\n\n rPath = rPath.parentPath;\n }\n return false;\n });\n const existingInfo = getExistingIntlayerInfo(ancestorPath);\n\n if (ancestorHasReplacements || existingInfo) {\n ancestorProvidesKey = true;\n break;\n }\n }\n }\n currentPath = currentPath.parentPath;\n }\n\n if (!ancestorProvidesKey) {\n componentsNeedingHooks.add(componentPath);\n }\n }\n }\n\n return {\n extractedContent,\n replacements,\n componentsNeedingHooks,\n componentKeyMap,\n componentPaths,\n hookMap,\n isSolid: false,\n };\n};\n\n/**\n * High-level function to extract content from TS/JS/JSX/TSX AST.\n */\nexport const extractTsContent = (\n ast: t.File,\n fileCode: string,\n existingKeys: Set<string>,\n configuration: IntlayerConfig,\n filePath: string,\n unmergedDictionaries: Record<string, unknown> = {}\n): {\n extractedContent: Record<string, string>;\n replacements: BabelReplacement[];\n} => {\n const { extractedContent, replacements } = extractBabelContentForComponents(\n ast,\n fileCode,\n existingKeys,\n 'default',\n configuration,\n filePath,\n unmergedDictionaries\n );\n\n const flatContent: Record<string, string> = {};\n for (const group of Object.values(extractedContent)) {\n Object.assign(flatContent, group);\n }\n\n return { extractedContent: flatContent, replacements };\n};\n"],"mappings":";;;;;;;;;;AA2BA,MAAM,WACJ,OAAO,cAAc,aAAa,YAAa,UAAkB;;;;;AAOnE,MAAa,2BACX,MACA,UACA,cACA,wBACA,kBACA,cACA,iBACY;CACZ,MAAM,WAAW,KAAK,KAAK;AAE3B,KAAI,SAAS,UAAU,EAAG,QAAO;CAEjC,MAAM,QAIA,EAAE;CACR,IAAI,qBAAqB;CACzB,IAAI,eAAe;AAEnB,MAAK,MAAM,SAAS,SAClB,KAAI,EAAE,UAAU,MAAM,EAAE;EACtB,MAAM,OAAO,MAAM;AAEnB,MAAI,KAAK,MAAM,CAAC,SAAS,EAAG,sBAAqB;AAEjD,QAAM,KAAK;GAAE,MAAM;GAAQ,OAAO;GAAM,CAAC;YAChC,EAAE,yBAAyB,MAAM,CAC1C,KAAI,EAAE,qBAAqB,MAAM,WAAW,CAC1C,OAAM,KAAK;EAAE,MAAM;EAAQ,OAAO;EAAI,CAAC;MAClC;EACL,MAAM,OAAO,MAAM;AAEnB,MAAI,EAAE,aAAa,KAAK,EAAE;AACxB,SAAM,KAAK;IACT,MAAM;IACN,OAAO,KAAK;IACZ,cAAc,KAAK;IACpB,CAAC;AACF,kBAAe;a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OAAO,iBAAiB,CACjD,QAAO,OAAO,aAAa,MAAM;AAGnC,QAAO;EAAE,kBAAkB;EAAa;EAAc"}
|
|
@@ -1,2 +1,130 @@
|
|
|
1
|
-
import{resolveContentFilePaths
|
|
1
|
+
import { resolveContentFilePaths } from "./utils/extractDictionaryInfo.mjs";
|
|
2
|
+
import { existsSync } from "node:fs";
|
|
3
|
+
import { mkdir } from "node:fs/promises";
|
|
4
|
+
import { dirname, relative } from "node:path";
|
|
5
|
+
import { buildDictionary, ensureIntlayerBundle, loadContentDeclaration, writeContentDeclaration } from "@intlayer/chokidar/build";
|
|
6
|
+
import { insertContentInDictionary } from "@intlayer/core/plugins";
|
|
7
|
+
import * as NodeTypes from "@intlayer/types/nodeType";
|
|
8
|
+
|
|
9
|
+
//#region src/extractContent/contentWriter.ts
|
|
10
|
+
const hasInsertionVars = (str) => /\{\{[^}]+\}\}/.test(str);
|
|
11
|
+
const getInsertionFields = (template) => {
|
|
12
|
+
const fields = [];
|
|
13
|
+
const regex = /\{\{([^}]+)\}\}/g;
|
|
14
|
+
let match;
|
|
15
|
+
for (let result = regex.exec(template); result !== null; result = regex.exec(template)) {
|
|
16
|
+
match = result;
|
|
17
|
+
const field = match[1].trim();
|
|
18
|
+
if (!fields.includes(field)) fields.push(field);
|
|
19
|
+
}
|
|
20
|
+
return fields;
|
|
21
|
+
};
|
|
22
|
+
/**
|
|
23
|
+
* Cached bundle file path to optimize performance
|
|
24
|
+
*/
|
|
25
|
+
let cachedBundleFilePath;
|
|
26
|
+
/**
|
|
27
|
+
* Merge extracted content with existing dictionary for multilingual format.
|
|
28
|
+
* - Keys in extracted but not in existing: added with default locale only
|
|
29
|
+
* - Keys in both: preserve existing translations, update default locale value
|
|
30
|
+
* - Keys in existing but not in extracted: removed (no longer in source)
|
|
31
|
+
*/
|
|
32
|
+
const mergeWithExistingMultilingualDictionary = (extractedContent, existingDictionary, defaultLocale) => {
|
|
33
|
+
const mergedContent = insertContentInDictionary(existingDictionary ?? {
|
|
34
|
+
key: "",
|
|
35
|
+
content: {},
|
|
36
|
+
filePath: ""
|
|
37
|
+
}, extractedContent, defaultLocale).content;
|
|
38
|
+
const finalContent = {};
|
|
39
|
+
for (const key in extractedContent) finalContent[key] = mergedContent[key];
|
|
40
|
+
for (const key in extractedContent) {
|
|
41
|
+
const rawValue = extractedContent[key];
|
|
42
|
+
if (typeof rawValue === "string" && hasInsertionVars(rawValue)) {
|
|
43
|
+
const node = finalContent[key];
|
|
44
|
+
if (node && node.nodeType === NodeTypes.TRANSLATION) finalContent[key] = {
|
|
45
|
+
nodeType: NodeTypes.INSERTION,
|
|
46
|
+
[NodeTypes.INSERTION]: node,
|
|
47
|
+
fields: getInsertionFields(rawValue)
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
return finalContent;
|
|
52
|
+
};
|
|
53
|
+
/**
|
|
54
|
+
* Merge extracted content with existing dictionary for per-locale format.
|
|
55
|
+
* - Keys in extracted but not in existing: added
|
|
56
|
+
* - Keys in both: update value
|
|
57
|
+
* - Keys in existing but not in extracted: removed (no longer in source)
|
|
58
|
+
*/
|
|
59
|
+
const mergeWithExistingPerLocaleDictionary = (extractedContent, existingDictionary) => {
|
|
60
|
+
const mergedContent = insertContentInDictionary(existingDictionary ?? {
|
|
61
|
+
key: "",
|
|
62
|
+
content: {},
|
|
63
|
+
filePath: ""
|
|
64
|
+
}, extractedContent).content;
|
|
65
|
+
const finalContent = {};
|
|
66
|
+
for (const key in extractedContent) finalContent[key] = mergedContent[key];
|
|
67
|
+
for (const key in extractedContent) {
|
|
68
|
+
const rawValue = extractedContent[key];
|
|
69
|
+
if (typeof rawValue === "string" && hasInsertionVars(rawValue)) {
|
|
70
|
+
const currentVal = finalContent[key];
|
|
71
|
+
if (typeof currentVal === "string") finalContent[key] = {
|
|
72
|
+
nodeType: NodeTypes.INSERTION,
|
|
73
|
+
[NodeTypes.INSERTION]: currentVal,
|
|
74
|
+
fields: getInsertionFields(rawValue)
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
return finalContent;
|
|
79
|
+
};
|
|
80
|
+
/**
|
|
81
|
+
* Helper to write extracted content to dictionary file(s).
|
|
82
|
+
*/
|
|
83
|
+
const writeContentHelper = async (extractedContent, dictionaryKey, filePath, configuration) => {
|
|
84
|
+
const { absolutePath, isPerLocale } = await resolveContentFilePaths(filePath, dictionaryKey, configuration);
|
|
85
|
+
const { defaultLocale } = configuration.internationalization;
|
|
86
|
+
const { baseDir } = configuration.system;
|
|
87
|
+
if (!cachedBundleFilePath) cachedBundleFilePath = await ensureIntlayerBundle(configuration);
|
|
88
|
+
const outputDir = dirname(absolutePath);
|
|
89
|
+
await mkdir(outputDir, { recursive: true });
|
|
90
|
+
let existingDictionary = null;
|
|
91
|
+
if (existsSync(absolutePath)) try {
|
|
92
|
+
existingDictionary = await loadContentDeclaration(absolutePath, configuration, cachedBundleFilePath) ?? null;
|
|
93
|
+
} catch (error) {
|
|
94
|
+
console.error(error);
|
|
95
|
+
}
|
|
96
|
+
const relativeContentFilePath = relative(baseDir, absolutePath);
|
|
97
|
+
let mergedDictionary;
|
|
98
|
+
if (isPerLocale) {
|
|
99
|
+
const mergedContent = mergeWithExistingPerLocaleDictionary(extractedContent, existingDictionary);
|
|
100
|
+
mergedDictionary = {
|
|
101
|
+
...existingDictionary,
|
|
102
|
+
key: dictionaryKey,
|
|
103
|
+
content: mergedContent,
|
|
104
|
+
locale: defaultLocale,
|
|
105
|
+
filePath: relativeContentFilePath
|
|
106
|
+
};
|
|
107
|
+
} else {
|
|
108
|
+
const mergedContent = mergeWithExistingMultilingualDictionary(extractedContent, existingDictionary, defaultLocale);
|
|
109
|
+
mergedDictionary = {
|
|
110
|
+
...existingDictionary,
|
|
111
|
+
key: dictionaryKey,
|
|
112
|
+
content: mergedContent,
|
|
113
|
+
filePath: relativeContentFilePath
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
const relativeDir = relative(baseDir, outputDir);
|
|
117
|
+
const writeResult = await writeContentDeclaration(mergedDictionary, configuration, {
|
|
118
|
+
newDictionariesPath: relativeDir,
|
|
119
|
+
localeList: [defaultLocale]
|
|
120
|
+
});
|
|
121
|
+
await buildDictionary([{
|
|
122
|
+
...mergedDictionary,
|
|
123
|
+
filePath: relative(baseDir, writeResult?.path ?? absolutePath)
|
|
124
|
+
}], configuration);
|
|
125
|
+
return absolutePath;
|
|
126
|
+
};
|
|
127
|
+
|
|
128
|
+
//#endregion
|
|
129
|
+
export { mergeWithExistingMultilingualDictionary, mergeWithExistingPerLocaleDictionary, writeContentHelper };
|
|
2
130
|
//# sourceMappingURL=contentWriter.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"contentWriter.mjs","names":[],"sources":["../../../src/extractContent/contentWriter.ts"],"sourcesContent":["import { existsSync } from 'node:fs';\nimport { mkdir } from 'node:fs/promises';\nimport { dirname, relative } from 'node:path';\nimport {\n buildDictionary,\n ensureIntlayerBundle,\n loadContentDeclaration,\n writeContentDeclaration,\n} from '@intlayer/chokidar/build';\nimport { insertContentInDictionary } from '@intlayer/core/plugins';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary, DictionaryKey } from '@intlayer/types/dictionary';\nimport
|
|
1
|
+
{"version":3,"file":"contentWriter.mjs","names":[],"sources":["../../../src/extractContent/contentWriter.ts"],"sourcesContent":["import { existsSync } from 'node:fs';\nimport { mkdir } from 'node:fs/promises';\nimport { dirname, relative } from 'node:path';\nimport {\n buildDictionary,\n ensureIntlayerBundle,\n loadContentDeclaration,\n writeContentDeclaration,\n} from '@intlayer/chokidar/build';\nimport { insertContentInDictionary } from '@intlayer/core/plugins';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary, DictionaryKey } from '@intlayer/types/dictionary';\nimport * as NodeTypes from '@intlayer/types/nodeType';\nimport { resolveContentFilePaths } from './utils/extractDictionaryInfo';\n\nconst hasInsertionVars = (str: string): boolean => /\\{\\{[^}]+\\}\\}/.test(str);\n\nconst getInsertionFields = (template: string): string[] => {\n const fields: string[] = [];\n const regex = /\\{\\{([^}]+)\\}\\}/g;\n let match: RegExpExecArray | null;\n for (\n let result = regex.exec(template);\n result !== null;\n result = regex.exec(template)\n ) {\n match = result;\n const field = match[1].trim();\n if (!fields.includes(field)) fields.push(field);\n }\n return fields;\n};\n\n/**\n * Translation node structure used in dictionaries\n */\ntype TranslationNode = {\n nodeType: 'translation';\n translation: Record<string, string>;\n};\n\n/**\n * Dictionary content structure - map of keys to translation nodes\n */\ntype DictionaryContentMap = Record<string, TranslationNode>;\n\n/**\n * Cached bundle file path to optimize performance\n */\nlet cachedBundleFilePath: string | undefined;\n\n/**\n * Merge extracted content with existing dictionary for multilingual format.\n * - Keys in extracted but not in existing: added with default locale only\n * - Keys in both: preserve existing translations, update default locale value\n * - Keys in existing but not in extracted: removed (no longer in source)\n */\nexport const mergeWithExistingMultilingualDictionary = (\n extractedContent: Record<string, string>,\n existingDictionary: Dictionary | null,\n defaultLocale: string\n): DictionaryContentMap => {\n const dictionary: Dictionary =\n existingDictionary ??\n ({\n key: '',\n content: {},\n filePath: '',\n } as Dictionary);\n\n const mergedDictionary = insertContentInDictionary(\n dictionary,\n extractedContent,\n defaultLocale as Locale\n );\n\n const mergedContent = mergedDictionary.content as DictionaryContentMap;\n\n // Pruning: remove keys not in extractedContent\n const finalContent: DictionaryContentMap = {};\n for (const key in extractedContent) {\n finalContent[key] = mergedContent[key];\n }\n\n // Promote any key whose source text contains {{vars}} to an insertion node\n for (const key in extractedContent) {\n const rawValue = extractedContent[key];\n if (typeof rawValue === 'string' && hasInsertionVars(rawValue)) {\n const node = finalContent[key] as any;\n if (node && node.nodeType === NodeTypes.TRANSLATION) {\n (finalContent as any)[key] = {\n nodeType: NodeTypes.INSERTION,\n [NodeTypes.INSERTION]: node,\n fields: getInsertionFields(rawValue),\n };\n }\n }\n }\n\n return finalContent;\n};\n\n/**\n * Merge extracted content with existing dictionary for per-locale format.\n * - Keys in extracted but not in existing: added\n * - Keys in both: update value\n * - Keys in existing but not in extracted: removed (no longer in source)\n */\nexport const mergeWithExistingPerLocaleDictionary = (\n extractedContent: Record<string, string>,\n existingDictionary: Dictionary | null\n): Record<string, string> => {\n const dictionary: Dictionary =\n existingDictionary ??\n ({\n key: '',\n content: {},\n filePath: '',\n } as Dictionary);\n\n const mergedDictionary = insertContentInDictionary(\n dictionary,\n extractedContent\n );\n\n const mergedContent = mergedDictionary.content as Record<string, string>;\n\n // Pruning: remove keys not in extractedContent\n const finalContent: Record<string, string> = {};\n for (const key in extractedContent) {\n finalContent[key] = mergedContent[key];\n }\n\n // Promote any key whose source text contains {{vars}} to an insertion node\n for (const key in extractedContent) {\n const rawValue = extractedContent[key];\n if (typeof rawValue === 'string' && hasInsertionVars(rawValue)) {\n const currentVal = finalContent[key];\n if (typeof currentVal === 'string') {\n (finalContent as any)[key] = {\n nodeType: NodeTypes.INSERTION,\n [NodeTypes.INSERTION]: currentVal,\n fields: getInsertionFields(rawValue),\n };\n }\n }\n }\n\n return finalContent;\n};\n\n/**\n * Helper to write extracted content to dictionary file(s).\n */\nexport const writeContentHelper = async (\n extractedContent: Record<string, string>,\n dictionaryKey: DictionaryKey,\n filePath: string,\n configuration: IntlayerConfig\n): Promise<string> => {\n const { absolutePath, isPerLocale } = await resolveContentFilePaths(\n filePath,\n dictionaryKey,\n configuration\n );\n\n const { defaultLocale } = configuration.internationalization;\n const { baseDir } = configuration.system;\n\n if (!cachedBundleFilePath) {\n cachedBundleFilePath = await ensureIntlayerBundle(configuration);\n }\n\n const outputDir = dirname(absolutePath);\n\n // Ensure output directory exists\n await mkdir(outputDir, { recursive: true });\n\n // Read existing dictionary to preserve translations and metadata\n let existingDictionary: Dictionary | null = null;\n\n if (existsSync(absolutePath)) {\n try {\n const dictionary = await loadContentDeclaration(\n absolutePath,\n configuration,\n cachedBundleFilePath\n );\n\n existingDictionary = dictionary ?? null;\n } catch (error) {\n console.error(error);\n }\n }\n\n const relativeContentFilePath = relative(baseDir, absolutePath);\n\n let mergedDictionary: Dictionary;\n\n if (isPerLocale) {\n // Per-locale format: simple string content for a single locale\n const mergedContent = mergeWithExistingPerLocaleDictionary(\n extractedContent,\n existingDictionary\n );\n\n mergedDictionary = {\n // Preserve existing metadata\n ...existingDictionary,\n key: dictionaryKey,\n content: mergedContent,\n locale: defaultLocale,\n filePath: relativeContentFilePath,\n };\n } else {\n // Multilingual format: content wrapped in translation nodes for multiple locales\n const mergedContent = mergeWithExistingMultilingualDictionary(\n extractedContent,\n existingDictionary,\n defaultLocale\n );\n\n mergedDictionary = {\n // Preserve existing metadata\n ...existingDictionary,\n key: dictionaryKey,\n content: mergedContent,\n filePath: relativeContentFilePath,\n };\n }\n\n const relativeDir = relative(baseDir, outputDir);\n\n const writeResult = await writeContentDeclaration(\n mergedDictionary,\n configuration,\n {\n newDictionariesPath: relativeDir,\n localeList: [defaultLocale],\n }\n );\n\n // Build the dictionary immediately\n const dictionaryToBuild: Dictionary = {\n ...mergedDictionary,\n filePath: relative(baseDir, writeResult?.path ?? absolutePath),\n };\n\n await buildDictionary([dictionaryToBuild], configuration);\n\n return absolutePath;\n};\n"],"mappings":";;;;;;;;;AAgBA,MAAM,oBAAoB,QAAyB,gBAAgB,KAAK,IAAI;AAE5E,MAAM,sBAAsB,aAA+B;CACzD,MAAM,SAAmB,EAAE;CAC3B,MAAM,QAAQ;CACd,IAAI;AACJ,MACE,IAAI,SAAS,MAAM,KAAK,SAAS,EACjC,WAAW,MACX,SAAS,MAAM,KAAK,SAAS,EAC7B;AACA,UAAQ;EACR,MAAM,QAAQ,MAAM,GAAG,MAAM;AAC7B,MAAI,CAAC,OAAO,SAAS,MAAM,CAAE,QAAO,KAAK,MAAM;;AAEjD,QAAO;;;;;AAmBT,IAAI;;;;;;;AAQJ,MAAa,2CACX,kBACA,oBACA,kBACyB;CAezB,MAAM,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