@docusaurus/babel 3.5.2 → 3.6.0-canary-6134

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) Facebook, Inc. and its affiliates.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Copyright (c) Facebook, Inc. and its affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ */
7
+ import { type TransformOptions } from '@babel/core';
8
+ import type { TranslationFileContent } from '@docusaurus/types';
9
+ export type SourceCodeFileTranslations = {
10
+ sourceCodeFilePath: string;
11
+ translations: TranslationFileContent;
12
+ warnings: string[];
13
+ };
14
+ export declare function extractAllSourceCodeFileTranslations(sourceCodeFilePaths: string[], babelOptions: TransformOptions): Promise<SourceCodeFileTranslations[]>;
15
+ export declare function extractSourceCodeFileTranslations(sourceCodeFilePath: string, babelOptions: TransformOptions): Promise<SourceCodeFileTranslations>;
16
+ //# sourceMappingURL=babelTranslationsExtractor.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"babelTranslationsExtractor.d.ts","sourceRoot":"","sources":["../src/babelTranslationsExtractor.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAMH,OAAO,EAIL,KAAK,gBAAgB,EACtB,MAAM,aAAa,CAAC;AACrB,OAAO,KAAK,EAAC,sBAAsB,EAAC,MAAM,mBAAmB,CAAC;AAE9D,MAAM,MAAM,0BAA0B,GAAG;IACvC,kBAAkB,EAAE,MAAM,CAAC;IAC3B,YAAY,EAAE,sBAAsB,CAAC;IACrC,QAAQ,EAAE,MAAM,EAAE,CAAC;CACpB,CAAC;AAEF,wBAAsB,oCAAoC,CACxD,mBAAmB,EAAE,MAAM,EAAE,EAC7B,YAAY,EAAE,gBAAgB,GAC7B,OAAO,CAAC,0BAA0B,EAAE,CAAC,CAMvC;AAED,wBAAsB,iCAAiC,CACrD,kBAAkB,EAAE,MAAM,EAC1B,YAAY,EAAE,gBAAgB,GAC7B,OAAO,CAAC,0BAA0B,CAAC,CAsBrC"}
@@ -0,0 +1,184 @@
1
+ "use strict";
2
+ /**
3
+ * Copyright (c) Facebook, Inc. and its affiliates.
4
+ *
5
+ * This source code is licensed under the MIT license found in the
6
+ * LICENSE file in the root directory of this source tree.
7
+ */
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.extractAllSourceCodeFileTranslations = extractAllSourceCodeFileTranslations;
10
+ exports.extractSourceCodeFileTranslations = extractSourceCodeFileTranslations;
11
+ const tslib_1 = require("tslib");
12
+ const fs_extra_1 = tslib_1.__importDefault(require("fs-extra"));
13
+ const logger_1 = tslib_1.__importDefault(require("@docusaurus/logger"));
14
+ const traverse_1 = tslib_1.__importDefault(require("@babel/traverse"));
15
+ const generator_1 = tslib_1.__importDefault(require("@babel/generator"));
16
+ const core_1 = require("@babel/core");
17
+ async function extractAllSourceCodeFileTranslations(sourceCodeFilePaths, babelOptions) {
18
+ return Promise.all(sourceCodeFilePaths.flatMap((sourceFilePath) => extractSourceCodeFileTranslations(sourceFilePath, babelOptions)));
19
+ }
20
+ async function extractSourceCodeFileTranslations(sourceCodeFilePath, babelOptions) {
21
+ try {
22
+ const code = await fs_extra_1.default.readFile(sourceCodeFilePath, 'utf8');
23
+ const ast = (0, core_1.parse)(code, {
24
+ ...babelOptions,
25
+ ast: true,
26
+ // filename is important, because babel does not process the same files
27
+ // according to their js/ts extensions.
28
+ // See https://x.com/NicoloRibaudo/status/1321130735605002243
29
+ filename: sourceCodeFilePath,
30
+ });
31
+ const translations = extractSourceCodeAstTranslations(ast, sourceCodeFilePath);
32
+ return translations;
33
+ }
34
+ catch (err) {
35
+ logger_1.default.error `Error while attempting to extract Docusaurus translations from source code file at path=${sourceCodeFilePath}.`;
36
+ throw err;
37
+ }
38
+ }
39
+ /*
40
+ Need help understanding this?
41
+
42
+ Useful resources:
43
+ https://github.com/jamiebuilds/babel-handbook/blob/master/translations/en/plugin-handbook.md
44
+ https://github.com/formatjs/formatjs/blob/main/packages/babel-plugin-formatjs/index.ts
45
+ https://github.com/pugjs/babel-walk
46
+ */
47
+ function extractSourceCodeAstTranslations(ast, sourceCodeFilePath) {
48
+ function sourceWarningPart(node) {
49
+ return `File: ${sourceCodeFilePath} at line ${node.loc?.start.line ?? '?'}
50
+ Full code: ${(0, generator_1.default)(node).code}`;
51
+ }
52
+ const translations = {};
53
+ const warnings = [];
54
+ let translateComponentName;
55
+ let translateFunctionName;
56
+ // First pass: find import declarations of Translate / translate.
57
+ // If not found, don't process the rest to avoid false positives
58
+ (0, traverse_1.default)(ast, {
59
+ ImportDeclaration(path) {
60
+ if (path.node.importKind === 'type' ||
61
+ path.get('source').node.value !== '@docusaurus/Translate') {
62
+ return;
63
+ }
64
+ const importSpecifiers = path.get('specifiers');
65
+ const defaultImport = importSpecifiers.find((specifier) => specifier.node.type === 'ImportDefaultSpecifier');
66
+ const callbackImport = importSpecifiers.find((specifier) => specifier.node.type === 'ImportSpecifier' &&
67
+ (specifier.get('imported')
68
+ .node.name === 'translate' ||
69
+ specifier.get('imported')
70
+ .node.value === 'translate'));
71
+ translateComponentName = defaultImport?.get('local').node.name;
72
+ translateFunctionName = callbackImport?.get('local').node.name;
73
+ },
74
+ });
75
+ (0, traverse_1.default)(ast, {
76
+ ...(translateComponentName && {
77
+ JSXElement(path) {
78
+ if (!path
79
+ .get('openingElement')
80
+ .get('name')
81
+ .isJSXIdentifier({ name: translateComponentName })) {
82
+ return;
83
+ }
84
+ function evaluateJSXProp(propName) {
85
+ const attributePath = path
86
+ .get('openingElement.attributes')
87
+ .find((attr) => attr.isJSXAttribute() &&
88
+ attr.get('name').isJSXIdentifier({ name: propName }));
89
+ if (attributePath) {
90
+ const attributeValue = attributePath.get('value');
91
+ const attributeValueEvaluated = attributeValue.isJSXExpressionContainer()
92
+ ? attributeValue.get('expression').evaluate()
93
+ : attributeValue.evaluate();
94
+ if (attributeValueEvaluated.confident &&
95
+ typeof attributeValueEvaluated.value === 'string') {
96
+ return attributeValueEvaluated.value;
97
+ }
98
+ warnings.push(`<Translate> prop=${propName} should be a statically evaluable object.
99
+ Example: <Translate id="optional id" description="optional description">Message</Translate>
100
+ Dynamically constructed values are not allowed, because they prevent translations to be extracted.
101
+ ${sourceWarningPart(path.node)}`);
102
+ }
103
+ return undefined;
104
+ }
105
+ const id = evaluateJSXProp('id');
106
+ const description = evaluateJSXProp('description');
107
+ let message;
108
+ const childrenPath = path.get('children');
109
+ // Handle empty content
110
+ if (!childrenPath.length) {
111
+ if (!id) {
112
+ warnings.push(`<Translate> without children must have id prop.
113
+ Example: <Translate id="my-id" />
114
+ ${sourceWarningPart(path.node)}`);
115
+ }
116
+ else {
117
+ translations[id] = {
118
+ message: id,
119
+ ...(description && { description }),
120
+ };
121
+ }
122
+ return;
123
+ }
124
+ // Handle single non-empty content
125
+ const singleChildren = childrenPath
126
+ // Remove empty/useless text nodes that might be around our
127
+ // translation! Makes the translation system more reliable to JSX
128
+ // formatting issues
129
+ .filter((children) => !(children.isJSXText() &&
130
+ children.node.value.replace('\n', '').trim() === ''))
131
+ .pop();
132
+ const isJSXText = singleChildren?.isJSXText();
133
+ const isJSXExpressionContainer = singleChildren?.isJSXExpressionContainer() &&
134
+ singleChildren.get('expression').evaluate().confident;
135
+ if (isJSXText || isJSXExpressionContainer) {
136
+ message = isJSXText
137
+ ? singleChildren.node.value.trim().replace(/\s+/g, ' ')
138
+ : String(singleChildren.get('expression').evaluate().value);
139
+ translations[id ?? message] = {
140
+ message,
141
+ ...(description && { description }),
142
+ };
143
+ }
144
+ else {
145
+ warnings.push(`Translate content could not be extracted. It has to be a static string and use optional but static props, like <Translate id="my-id" description="my-description">text</Translate>.
146
+ ${sourceWarningPart(path.node)}`);
147
+ }
148
+ },
149
+ }),
150
+ ...(translateFunctionName && {
151
+ CallExpression(path) {
152
+ if (!path.get('callee').isIdentifier({ name: translateFunctionName })) {
153
+ return;
154
+ }
155
+ const args = path.get('arguments');
156
+ if (args.length === 1 || args.length === 2) {
157
+ const firstArgPath = args[0];
158
+ // translate("x" + "y"); => translate("xy");
159
+ const firstArgEvaluated = firstArgPath.evaluate();
160
+ if (firstArgEvaluated.confident &&
161
+ typeof firstArgEvaluated.value === 'object') {
162
+ const { message, id, description } = firstArgEvaluated.value;
163
+ translations[String(id ?? message)] = {
164
+ message: String(message ?? id),
165
+ ...(Boolean(description) && { description: String(description) }),
166
+ };
167
+ }
168
+ else {
169
+ warnings.push(`translate() first arg should be a statically evaluable object.
170
+ Example: translate({message: "text",id: "optional.id",description: "optional description"}
171
+ Dynamically constructed values are not allowed, because they prevent translations to be extracted.
172
+ ${sourceWarningPart(path.node)}`);
173
+ }
174
+ }
175
+ else {
176
+ warnings.push(`translate() function only takes 1 or 2 args
177
+ ${sourceWarningPart(path.node)}`);
178
+ }
179
+ },
180
+ }),
181
+ });
182
+ return { sourceCodeFilePath, translations, warnings };
183
+ }
184
+ //# sourceMappingURL=babelTranslationsExtractor.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"babelTranslationsExtractor.js","sourceRoot":"","sources":["../src/babelTranslationsExtractor.ts"],"names":[],"mappings":";AAAA;;;;;GAKG;;AAoBH,oFASC;AAED,8EAyBC;;AAtDD,gEAA0B;AAC1B,wEAAwC;AACxC,uEAAoD;AACpD,yEAAwC;AACxC,sCAKqB;AASd,KAAK,UAAU,oCAAoC,CACxD,mBAA6B,EAC7B,YAA8B;IAE9B,OAAO,OAAO,CAAC,GAAG,CAChB,mBAAmB,CAAC,OAAO,CAAC,CAAC,cAAc,EAAE,EAAE,CAC7C,iCAAiC,CAAC,cAAc,EAAE,YAAY,CAAC,CAChE,CACF,CAAC;AACJ,CAAC;AAEM,KAAK,UAAU,iCAAiC,CACrD,kBAA0B,EAC1B,YAA8B;IAE9B,IAAI,CAAC;QACH,MAAM,IAAI,GAAG,MAAM,kBAAE,CAAC,QAAQ,CAAC,kBAAkB,EAAE,MAAM,CAAC,CAAC;QAE3D,MAAM,GAAG,GAAG,IAAA,YAAK,EAAC,IAAI,EAAE;YACtB,GAAG,YAAY;YACf,GAAG,EAAE,IAAI;YACT,uEAAuE;YACvE,uCAAuC;YACvC,6DAA6D;YAC7D,QAAQ,EAAE,kBAAkB;SAC7B,CAAS,CAAC;QAEX,MAAM,YAAY,GAAG,gCAAgC,CACnD,GAAG,EACH,kBAAkB,CACnB,CAAC;QACF,OAAO,YAAY,CAAC;IACtB,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACb,gBAAM,CAAC,KAAK,CAAA,2FAA2F,kBAAkB,GAAG,CAAC;QAC7H,MAAM,GAAG,CAAC;IACZ,CAAC;AACH,CAAC;AAED;;;;;;;GAOG;AACH,SAAS,gCAAgC,CACvC,GAAS,EACT,kBAA0B;IAE1B,SAAS,iBAAiB,CAAC,IAAU;QACnC,OAAO,SAAS,kBAAkB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AAC,IAAI,EAAC,WAAW,EAAE,MAAM,CAAC,WAAW,CAAC,EAAC,CAAC;yBAChE,CAAC;oBACJ,CAAC;yBAAM,CAAC;wBACN,QAAQ,CAAC,IAAI,CACX;;;EAGZ,iBAAiB,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CACnB,CAAC;oBACJ,CAAC;gBACH,CAAC;qBAAM,CAAC;oBACN,QAAQ,CAAC,IAAI,CACX;EACV,iBAAiB,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CACrB,CAAC;gBACJ,CAAC;YACH,CAAC;SACF,CAAC;KACH,CAAC,CAAC;IAEH,OAAO,EAAC,kBAAkB,EAAE,YAAY,EAAE,QAAQ,EAAC,CAAC;AACtD,CAAC"}
package/lib/index.d.ts CHANGED
@@ -5,4 +5,5 @@
5
5
  * LICENSE file in the root directory of this source tree.
6
6
  */
7
7
  export { getCustomBabelConfigFilePath, getBabelOptions } from './utils';
8
+ export { extractAllSourceCodeFileTranslations } from './babelTranslationsExtractor';
8
9
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAC,4BAA4B,EAAE,eAAe,EAAC,MAAM,SAAS,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAC,4BAA4B,EAAE,eAAe,EAAC,MAAM,SAAS,CAAC;AAEtE,OAAO,EAAC,oCAAoC,EAAC,MAAM,8BAA8B,CAAC"}
package/lib/index.js CHANGED
@@ -6,8 +6,10 @@
6
6
  * LICENSE file in the root directory of this source tree.
7
7
  */
8
8
  Object.defineProperty(exports, "__esModule", { value: true });
9
- exports.getBabelOptions = exports.getCustomBabelConfigFilePath = void 0;
9
+ exports.extractAllSourceCodeFileTranslations = exports.getBabelOptions = exports.getCustomBabelConfigFilePath = void 0;
10
10
  var utils_1 = require("./utils");
11
11
  Object.defineProperty(exports, "getCustomBabelConfigFilePath", { enumerable: true, get: function () { return utils_1.getCustomBabelConfigFilePath; } });
12
12
  Object.defineProperty(exports, "getBabelOptions", { enumerable: true, get: function () { return utils_1.getBabelOptions; } });
13
+ var babelTranslationsExtractor_1 = require("./babelTranslationsExtractor");
14
+ Object.defineProperty(exports, "extractAllSourceCodeFileTranslations", { enumerable: true, get: function () { return babelTranslationsExtractor_1.extractAllSourceCodeFileTranslations; } });
13
15
  //# sourceMappingURL=index.js.map
package/lib/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AAAA;;;;;GAKG;;;AAEH,iCAAsE;AAA9D,qHAAA,4BAA4B,OAAA;AAAE,wGAAA,eAAe,OAAA"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AAAA;;;;;GAKG;;;AAEH,iCAAsE;AAA9D,qHAAA,4BAA4B,OAAA;AAAE,wGAAA,eAAe,OAAA;AAErD,2EAAkF;AAA1E,kJAAA,oCAAoC,OAAA"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@docusaurus/babel",
3
- "version": "3.5.2",
3
+ "version": "3.6.0-canary-6134",
4
4
  "description": "Docusaurus package for Babel-related utils.",
5
5
  "main": "./lib/index.js",
6
6
  "types": "./lib/index.d.ts",
@@ -28,20 +28,24 @@
28
28
  },
29
29
  "license": "MIT",
30
30
  "dependencies": {
31
- "@babel/core": "^7.23.3",
31
+ "@babel/core": "^7.25.9",
32
+ "@babel/generator": "^7.25.9",
32
33
  "@babel/plugin-syntax-dynamic-import": "^7.8.3",
33
- "@babel/plugin-transform-runtime": "^7.22.9",
34
- "@babel/preset-env": "^7.22.9",
35
- "@babel/preset-react": "^7.22.5",
36
- "@babel/preset-typescript": "^7.22.5",
37
- "@babel/runtime": "^7.22.6",
38
- "@babel/runtime-corejs3": "^7.22.6",
39
- "@docusaurus/utils": "3.5.2",
40
- "babel-loader": "^9.1.3",
34
+ "@babel/plugin-transform-runtime": "^7.25.9",
35
+ "@babel/preset-env": "^7.25.9",
36
+ "@babel/preset-react": "^7.25.9",
37
+ "@babel/preset-typescript": "^7.25.9",
38
+ "@babel/runtime": "^7.25.9",
39
+ "@babel/runtime-corejs3": "^7.25.9",
40
+ "@babel/traverse": "^7.25.9",
41
+ "@docusaurus/logger": "3.6.0-canary-6134",
42
+ "@docusaurus/utils": "3.6.0-canary-6134",
41
43
  "babel-plugin-dynamic-import-node": "^2.3.3",
42
- "fs-extra": "^11.1.1"
44
+ "fs-extra": "^11.1.1",
45
+ "tslib": "^2.6.0"
43
46
  },
44
47
  "engines": {
45
48
  "node": ">=18.0"
46
- }
49
+ },
50
+ "gitHead": "706c96c3bdd92c7d3ac61447ec49e4bfa6d0526b"
47
51
  }
@@ -0,0 +1,266 @@
1
+ /**
2
+ * Copyright (c) Facebook, Inc. and its affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ */
7
+
8
+ import fs from 'fs-extra';
9
+ import logger from '@docusaurus/logger';
10
+ import traverse, {type Node} from '@babel/traverse';
11
+ import generate from '@babel/generator';
12
+ import {
13
+ parse,
14
+ type types as t,
15
+ type NodePath,
16
+ type TransformOptions,
17
+ } from '@babel/core';
18
+ import type {TranslationFileContent} from '@docusaurus/types';
19
+
20
+ export type SourceCodeFileTranslations = {
21
+ sourceCodeFilePath: string;
22
+ translations: TranslationFileContent;
23
+ warnings: string[];
24
+ };
25
+
26
+ export async function extractAllSourceCodeFileTranslations(
27
+ sourceCodeFilePaths: string[],
28
+ babelOptions: TransformOptions,
29
+ ): Promise<SourceCodeFileTranslations[]> {
30
+ return Promise.all(
31
+ sourceCodeFilePaths.flatMap((sourceFilePath) =>
32
+ extractSourceCodeFileTranslations(sourceFilePath, babelOptions),
33
+ ),
34
+ );
35
+ }
36
+
37
+ export async function extractSourceCodeFileTranslations(
38
+ sourceCodeFilePath: string,
39
+ babelOptions: TransformOptions,
40
+ ): Promise<SourceCodeFileTranslations> {
41
+ try {
42
+ const code = await fs.readFile(sourceCodeFilePath, 'utf8');
43
+
44
+ const ast = parse(code, {
45
+ ...babelOptions,
46
+ ast: true,
47
+ // filename is important, because babel does not process the same files
48
+ // according to their js/ts extensions.
49
+ // See https://x.com/NicoloRibaudo/status/1321130735605002243
50
+ filename: sourceCodeFilePath,
51
+ }) as Node;
52
+
53
+ const translations = extractSourceCodeAstTranslations(
54
+ ast,
55
+ sourceCodeFilePath,
56
+ );
57
+ return translations;
58
+ } catch (err) {
59
+ logger.error`Error while attempting to extract Docusaurus translations from source code file at path=${sourceCodeFilePath}.`;
60
+ throw err;
61
+ }
62
+ }
63
+
64
+ /*
65
+ Need help understanding this?
66
+
67
+ Useful resources:
68
+ https://github.com/jamiebuilds/babel-handbook/blob/master/translations/en/plugin-handbook.md
69
+ https://github.com/formatjs/formatjs/blob/main/packages/babel-plugin-formatjs/index.ts
70
+ https://github.com/pugjs/babel-walk
71
+ */
72
+ function extractSourceCodeAstTranslations(
73
+ ast: Node,
74
+ sourceCodeFilePath: string,
75
+ ): SourceCodeFileTranslations {
76
+ function sourceWarningPart(node: Node) {
77
+ return `File: ${sourceCodeFilePath} at line ${node.loc?.start.line ?? '?'}
78
+ Full code: ${generate(node).code}`;
79
+ }
80
+
81
+ const translations: TranslationFileContent = {};
82
+ const warnings: string[] = [];
83
+ let translateComponentName: string | undefined;
84
+ let translateFunctionName: string | undefined;
85
+
86
+ // First pass: find import declarations of Translate / translate.
87
+ // If not found, don't process the rest to avoid false positives
88
+ traverse(ast, {
89
+ ImportDeclaration(path) {
90
+ if (
91
+ path.node.importKind === 'type' ||
92
+ path.get('source').node.value !== '@docusaurus/Translate'
93
+ ) {
94
+ return;
95
+ }
96
+ const importSpecifiers = path.get('specifiers');
97
+ const defaultImport = importSpecifiers.find(
98
+ (specifier): specifier is NodePath<t.ImportDefaultSpecifier> =>
99
+ specifier.node.type === 'ImportDefaultSpecifier',
100
+ );
101
+ const callbackImport = importSpecifiers.find(
102
+ (specifier): specifier is NodePath<t.ImportSpecifier> =>
103
+ specifier.node.type === 'ImportSpecifier' &&
104
+ ((
105
+ (specifier as NodePath<t.ImportSpecifier>).get('imported')
106
+ .node as t.Identifier
107
+ ).name === 'translate' ||
108
+ (
109
+ (specifier as NodePath<t.ImportSpecifier>).get('imported')
110
+ .node as t.StringLiteral
111
+ ).value === 'translate'),
112
+ );
113
+
114
+ translateComponentName = defaultImport?.get('local').node.name;
115
+ translateFunctionName = callbackImport?.get('local').node.name;
116
+ },
117
+ });
118
+
119
+ traverse(ast, {
120
+ ...(translateComponentName && {
121
+ JSXElement(path) {
122
+ if (
123
+ !path
124
+ .get('openingElement')
125
+ .get('name')
126
+ .isJSXIdentifier({name: translateComponentName})
127
+ ) {
128
+ return;
129
+ }
130
+ function evaluateJSXProp(propName: string): string | undefined {
131
+ const attributePath = path
132
+ .get('openingElement.attributes')
133
+ .find(
134
+ (attr) =>
135
+ attr.isJSXAttribute() &&
136
+ attr.get('name').isJSXIdentifier({name: propName}),
137
+ );
138
+
139
+ if (attributePath) {
140
+ const attributeValue = attributePath.get('value') as NodePath;
141
+
142
+ const attributeValueEvaluated =
143
+ attributeValue.isJSXExpressionContainer()
144
+ ? (attributeValue.get('expression') as NodePath).evaluate()
145
+ : attributeValue.evaluate();
146
+
147
+ if (
148
+ attributeValueEvaluated.confident &&
149
+ typeof attributeValueEvaluated.value === 'string'
150
+ ) {
151
+ return attributeValueEvaluated.value;
152
+ }
153
+ warnings.push(
154
+ `<Translate> prop=${propName} should be a statically evaluable object.
155
+ Example: <Translate id="optional id" description="optional description">Message</Translate>
156
+ Dynamically constructed values are not allowed, because they prevent translations to be extracted.
157
+ ${sourceWarningPart(path.node)}`,
158
+ );
159
+ }
160
+
161
+ return undefined;
162
+ }
163
+
164
+ const id = evaluateJSXProp('id');
165
+ const description = evaluateJSXProp('description');
166
+ let message: string;
167
+ const childrenPath = path.get('children');
168
+
169
+ // Handle empty content
170
+ if (!childrenPath.length) {
171
+ if (!id) {
172
+ warnings.push(`<Translate> without children must have id prop.
173
+ Example: <Translate id="my-id" />
174
+ ${sourceWarningPart(path.node)}`);
175
+ } else {
176
+ translations[id] = {
177
+ message: id,
178
+ ...(description && {description}),
179
+ };
180
+ }
181
+
182
+ return;
183
+ }
184
+
185
+ // Handle single non-empty content
186
+ const singleChildren = childrenPath
187
+ // Remove empty/useless text nodes that might be around our
188
+ // translation! Makes the translation system more reliable to JSX
189
+ // formatting issues
190
+ .filter(
191
+ (children) =>
192
+ !(
193
+ children.isJSXText() &&
194
+ children.node.value.replace('\n', '').trim() === ''
195
+ ),
196
+ )
197
+ .pop();
198
+ const isJSXText = singleChildren?.isJSXText();
199
+ const isJSXExpressionContainer =
200
+ singleChildren?.isJSXExpressionContainer() &&
201
+ (singleChildren.get('expression') as NodePath).evaluate().confident;
202
+
203
+ if (isJSXText || isJSXExpressionContainer) {
204
+ message = isJSXText
205
+ ? singleChildren.node.value.trim().replace(/\s+/g, ' ')
206
+ : String(
207
+ (singleChildren.get('expression') as NodePath).evaluate().value,
208
+ );
209
+
210
+ translations[id ?? message] = {
211
+ message,
212
+ ...(description && {description}),
213
+ };
214
+ } else {
215
+ warnings.push(
216
+ `Translate content could not be extracted. It has to be a static string and use optional but static props, like <Translate id="my-id" description="my-description">text</Translate>.
217
+ ${sourceWarningPart(path.node)}`,
218
+ );
219
+ }
220
+ },
221
+ }),
222
+
223
+ ...(translateFunctionName && {
224
+ CallExpression(path) {
225
+ if (!path.get('callee').isIdentifier({name: translateFunctionName})) {
226
+ return;
227
+ }
228
+
229
+ const args = path.get('arguments');
230
+ if (args.length === 1 || args.length === 2) {
231
+ const firstArgPath = args[0]!;
232
+
233
+ // translate("x" + "y"); => translate("xy");
234
+ const firstArgEvaluated = firstArgPath.evaluate();
235
+
236
+ if (
237
+ firstArgEvaluated.confident &&
238
+ typeof firstArgEvaluated.value === 'object'
239
+ ) {
240
+ const {message, id, description} = firstArgEvaluated.value as {
241
+ [propName: string]: unknown;
242
+ };
243
+ translations[String(id ?? message)] = {
244
+ message: String(message ?? id),
245
+ ...(Boolean(description) && {description: String(description)}),
246
+ };
247
+ } else {
248
+ warnings.push(
249
+ `translate() first arg should be a statically evaluable object.
250
+ Example: translate({message: "text",id: "optional.id",description: "optional description"}
251
+ Dynamically constructed values are not allowed, because they prevent translations to be extracted.
252
+ ${sourceWarningPart(path.node)}`,
253
+ );
254
+ }
255
+ } else {
256
+ warnings.push(
257
+ `translate() function only takes 1 or 2 args
258
+ ${sourceWarningPart(path.node)}`,
259
+ );
260
+ }
261
+ },
262
+ }),
263
+ });
264
+
265
+ return {sourceCodeFilePath, translations, warnings};
266
+ }
package/src/index.ts CHANGED
@@ -6,3 +6,5 @@
6
6
  */
7
7
 
8
8
  export {getCustomBabelConfigFilePath, getBabelOptions} from './utils';
9
+
10
+ export {extractAllSourceCodeFileTranslations} from './babelTranslationsExtractor';