gt 2.28.5 → 2.28.7
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/CHANGELOG.md +23 -0
- package/dist/api/collectUserEditDiffs.js.map +1 -1
- package/dist/formats/files/aggregateFiles.js +25 -3
- package/dist/formats/files/aggregateFiles.js.map +1 -1
- package/dist/formats/files/supportedFiles.d.ts +10 -1
- package/dist/formats/files/supportedFiles.js +27 -3
- package/dist/formats/files/supportedFiles.js.map +1 -1
- package/dist/formats/files/transformFormat.d.ts +14 -0
- package/dist/formats/files/transformFormat.js +24 -3
- package/dist/formats/files/transformFormat.js.map +1 -1
- package/dist/fs/findFilepath.d.ts +1 -1
- package/dist/fs/findFilepath.js +1 -1
- package/dist/fs/findFilepath.js.map +1 -1
- package/dist/generated/version.d.ts +1 -1
- package/dist/generated/version.js +1 -1
- package/dist/generated/version.js.map +1 -1
- package/dist/next/parse/wrapContent.js +1 -1
- package/dist/react/jsx/utils/getPathsAndAliases.d.ts +11 -0
- package/dist/react/jsx/utils/getPathsAndAliases.js +62 -21
- package/dist/react/jsx/utils/getPathsAndAliases.js.map +1 -1
- package/dist/react/jsx/utils/parseStringFunction.js +16 -2
- package/dist/react/jsx/utils/parseStringFunction.js.map +1 -1
- package/dist/react/parse/createInlineUpdates.d.ts +15 -0
- package/dist/react/parse/createInlineUpdates.js +31 -111
- package/dist/react/parse/createInlineUpdates.js.map +1 -1
- package/dist/react/parse/scanFiles.d.ts +22 -0
- package/dist/react/parse/scanFiles.js +125 -0
- package/dist/react/parse/scanFiles.js.map +1 -0
- package/dist/react/parse/scanPool.d.ts +28 -0
- package/dist/react/parse/scanPool.js +122 -0
- package/dist/react/parse/scanPool.js.map +1 -0
- package/dist/react/parse/scanWorker.d.ts +1 -0
- package/dist/react/parse/scanWorker.js +19 -0
- package/dist/react/parse/scanWorker.js.map +1 -0
- package/dist/react/parse/wrapContent.js +1 -1
- package/dist/translation/stage.js +2 -2
- package/dist/translation/stage.js.map +1 -1
- package/dist/types/index.d.ts +1 -0
- package/dist/types/index.js.map +1 -1
- package/dist/utils/hash.d.ts +2 -0
- package/dist/utils/hash.js +5 -1
- package/dist/utils/hash.js.map +1 -1
- package/dist/utils/localizeStaticUrls.js +1 -1
- package/dist/utils/sharedStaticAssets.js +22 -4
- package/dist/utils/sharedStaticAssets.js.map +1 -1
- package/package.json +6 -6
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const PACKAGE_VERSION = "2.28.
|
|
1
|
+
export declare const PACKAGE_VERSION = "2.28.7";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"version.js","names":[],"sources":["../../src/generated/version.ts"],"sourcesContent":["// This file is auto-generated. Do not edit manually.\nexport const PACKAGE_VERSION = '2.28.
|
|
1
|
+
{"version":3,"file":"version.js","names":[],"sources":["../../src/generated/version.ts"],"sourcesContent":["// This file is auto-generated. Do not edit manually.\nexport const PACKAGE_VERSION = '2.28.7';\n"],"mappings":";AACA,MAAa,kBAAkB"}
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import "../../types/libraries.js";
|
|
2
2
|
import { getRelativePath } from "../../fs/findFilepath.js";
|
|
3
3
|
import { isMeaningful } from "../../react/jsx/evaluateJsx.js";
|
|
4
|
-
import { createImports, generateImportMap } from "../../react/jsx/utils/parseAst.js";
|
|
5
4
|
import { matchFiles } from "../../fs/matchFiles.js";
|
|
6
5
|
import { DEFAULT_SRC_PATTERNS } from "../../config/generateSettings.js";
|
|
6
|
+
import { createImports, generateImportMap } from "../../react/jsx/utils/parseAst.js";
|
|
7
7
|
import { handleJsxElement } from "../../react/jsx/wrapJsx.js";
|
|
8
8
|
import { addDynamicLangAttribute, hasGTProviderChild, isBodyElement, isHtmlElement, makeParentFunctionAsync } from "../jsx/utils.js";
|
|
9
9
|
import fs from "node:fs";
|
|
@@ -1,6 +1,17 @@
|
|
|
1
1
|
import { NodePath } from '@babel/traverse';
|
|
2
2
|
import { GTLibrary } from '../../../types/libraries.js';
|
|
3
3
|
import * as t from '@babel/types';
|
|
4
|
+
/**
|
|
5
|
+
* Text check before parsing: false only for a file that names no GT package
|
|
6
|
+
* and, when global tags are extracted, never uses the global tag's name,
|
|
7
|
+
* where hasTranslationEntryPoints finds nothing to extract either.
|
|
8
|
+
*/
|
|
9
|
+
export declare function mayHaveTranslationEntryPoints(code: string, pkgs: GTLibrary[], includeGlobalTag: boolean): boolean;
|
|
10
|
+
/**
|
|
11
|
+
* Whether getPathsAndAliases could find anything in this file, decided by the
|
|
12
|
+
* same node checks its visitor uses but without building paths or scopes.
|
|
13
|
+
*/
|
|
14
|
+
export declare function hasTranslationEntryPoints(ast: t.Node, pkgs: GTLibrary[]): boolean;
|
|
4
15
|
/**
|
|
5
16
|
* Constructs tracking for gt related variables of interest
|
|
6
17
|
* inlineTranslationPaths: these are string-related translation functions
|
|
@@ -4,6 +4,50 @@ import * as t from "@babel/types";
|
|
|
4
4
|
import traverseModule from "@babel/traverse";
|
|
5
5
|
//#region src/react/jsx/utils/getPathsAndAliases.ts
|
|
6
6
|
const traverse = traverseModule.default || traverseModule;
|
|
7
|
+
function isGtSource(source, pkgs) {
|
|
8
|
+
return pkgs.some((pkg) => source.startsWith(pkg));
|
|
9
|
+
}
|
|
10
|
+
function isGtImport(node, pkgs) {
|
|
11
|
+
return t.isImportDeclaration(node) && isGtSource(node.source.value, pkgs);
|
|
12
|
+
}
|
|
13
|
+
function isGtRequire(node, pkgs) {
|
|
14
|
+
if (!t.isVariableDeclarator(node)) return false;
|
|
15
|
+
const init = node.init;
|
|
16
|
+
if (!t.isCallExpression(init)) return false;
|
|
17
|
+
if (!t.isIdentifier(init.callee, { name: "require" })) return false;
|
|
18
|
+
const args = init.arguments;
|
|
19
|
+
return args.length === 1 && t.isStringLiteral(args[0]) && isGtSource(args[0].value, pkgs);
|
|
20
|
+
}
|
|
21
|
+
function isGlobalTagCandidate(node) {
|
|
22
|
+
return t.isTaggedTemplateExpression(node) && t.isIdentifier(node.tag, { name: "t" });
|
|
23
|
+
}
|
|
24
|
+
const GLOBAL_TAG_NAME = new RegExp(`(?<![\\w$])t(?![\\w$])`);
|
|
25
|
+
/**
|
|
26
|
+
* Text check before parsing: false only for a file that names no GT package
|
|
27
|
+
* and, when global tags are extracted, never uses the global tag's name,
|
|
28
|
+
* where hasTranslationEntryPoints finds nothing to extract either.
|
|
29
|
+
*/
|
|
30
|
+
function mayHaveTranslationEntryPoints(code, pkgs, includeGlobalTag) {
|
|
31
|
+
return pkgs.some((pkg) => code.includes(pkg)) || includeGlobalTag && GLOBAL_TAG_NAME.test(code);
|
|
32
|
+
}
|
|
33
|
+
function someNode(node, test) {
|
|
34
|
+
if (test(node)) return true;
|
|
35
|
+
const children = node;
|
|
36
|
+
for (const key of t.VISITOR_KEYS[node.type] ?? []) {
|
|
37
|
+
const child = children[key];
|
|
38
|
+
if (Array.isArray(child)) {
|
|
39
|
+
for (const item of child) if (item && someNode(item, test)) return true;
|
|
40
|
+
} else if (child && someNode(child, test)) return true;
|
|
41
|
+
}
|
|
42
|
+
return false;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Whether getPathsAndAliases could find anything in this file, decided by the
|
|
46
|
+
* same node checks its visitor uses but without building paths or scopes.
|
|
47
|
+
*/
|
|
48
|
+
function hasTranslationEntryPoints(ast, pkgs) {
|
|
49
|
+
return someNode(ast, (node) => isGtImport(node, pkgs) || isGtRequire(node, pkgs) || isGlobalTagCandidate(node));
|
|
50
|
+
}
|
|
7
51
|
/**
|
|
8
52
|
* Constructs tracking for gt related variables of interest
|
|
9
53
|
* inlineTranslationPaths: these are string-related translation functions
|
|
@@ -16,14 +60,14 @@ function getPathsAndAliases(ast, pkgs) {
|
|
|
16
60
|
const translationComponentPaths = [];
|
|
17
61
|
traverse(ast, {
|
|
18
62
|
TaggedTemplateExpression(path) {
|
|
19
|
-
if (
|
|
63
|
+
if (isGlobalTagCandidate(path.node) && !path.scope.hasBinding("t")) inlineTranslationPaths.push({
|
|
20
64
|
localName: "t",
|
|
21
65
|
path: path.get("tag"),
|
|
22
66
|
originalName: T_GLOBAL_REGISTRATION_FUNCTION_MARKER
|
|
23
67
|
});
|
|
24
68
|
},
|
|
25
69
|
ImportDeclaration(path) {
|
|
26
|
-
if (
|
|
70
|
+
if (isGtImport(path.node, pkgs)) {
|
|
27
71
|
const importName = extractImportName(path.node, pkgs, GT_TRANSLATION_FUNCS);
|
|
28
72
|
for (const name of importName) if (name.original === "useGT" || name.original === "getGT" || name.original === "useMessages" || name.original === "getMessages" || name.original === "msg" || name.original === "t") inlineTranslationPaths.push({
|
|
29
73
|
localName: name.local,
|
|
@@ -39,24 +83,21 @@ function getPathsAndAliases(ast, pkgs) {
|
|
|
39
83
|
}
|
|
40
84
|
},
|
|
41
85
|
VariableDeclarator(path) {
|
|
42
|
-
if (path.node
|
|
43
|
-
const
|
|
44
|
-
if (
|
|
45
|
-
const
|
|
46
|
-
if (
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
});
|
|
58
|
-
else importAliases[name.local] = name.original;
|
|
59
|
-
}
|
|
86
|
+
if (isGtRequire(path.node, pkgs)) {
|
|
87
|
+
const parentPath = path.parentPath;
|
|
88
|
+
if (parentPath.isVariableDeclaration()) {
|
|
89
|
+
const importName = extractImportName(parentPath.node, pkgs, GT_TRANSLATION_FUNCS);
|
|
90
|
+
for (const name of importName) if (name.original === "useGT" || name.original === "getGT" || name.original === "useMessages" || name.original === "getMessages") inlineTranslationPaths.push({
|
|
91
|
+
localName: name.local,
|
|
92
|
+
path: parentPath,
|
|
93
|
+
originalName: name.original
|
|
94
|
+
});
|
|
95
|
+
else if (name.original === "T" || name.original === "GtInternalTranslateJsx") translationComponentPaths.push({
|
|
96
|
+
localName: name.local,
|
|
97
|
+
path: parentPath,
|
|
98
|
+
originalName: name.original
|
|
99
|
+
});
|
|
100
|
+
else importAliases[name.local] = name.original;
|
|
60
101
|
}
|
|
61
102
|
}
|
|
62
103
|
}
|
|
@@ -68,6 +109,6 @@ function getPathsAndAliases(ast, pkgs) {
|
|
|
68
109
|
};
|
|
69
110
|
}
|
|
70
111
|
//#endregion
|
|
71
|
-
export { getPathsAndAliases };
|
|
112
|
+
export { getPathsAndAliases, hasTranslationEntryPoints, mayHaveTranslationEntryPoints };
|
|
72
113
|
|
|
73
114
|
//# sourceMappingURL=getPathsAndAliases.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getPathsAndAliases.js","names":[],"sources":["../../../../src/react/jsx/utils/getPathsAndAliases.ts"],"sourcesContent":["import traverseModule from '@babel/traverse';\nimport { NodePath } from '@babel/traverse';\nimport {\n GT_TRANSLATION_FUNCS,\n INLINE_TRANSLATION_HOOK,\n INLINE_TRANSLATION_HOOK_ASYNC,\n INLINE_MESSAGE_HOOK,\n INLINE_MESSAGE_HOOK_ASYNC,\n MSG_REGISTRATION_FUNCTION,\n T_REGISTRATION_FUNCTION,\n TRANSLATION_COMPONENT,\n INTERNAL_TRANSLATION_COMPONENT,\n T_GLOBAL_REGISTRATION_FUNCTION,\n T_GLOBAL_REGISTRATION_FUNCTION_MARKER,\n} from '../../jsx/utils/constants.js';\nimport { GTLibrary } from '../../../types/libraries.js';\nimport { extractImportName } from './parseAst.js';\nimport * as t from '@babel/types';\n\n// Handle CommonJS/ESM interop\nconst traverse = traverseModule.default || traverseModule;\n\n/**\n * Constructs tracking for gt related variables of interest\n * inlineTranslationPaths: these are string-related translation functions\n * translationComponentPaths: these are just <T> components\n * importAliases: any other GT related imports\n */\nexport function getPathsAndAliases(\n ast: t.Node,\n pkgs: GTLibrary[]\n): {\n importAliases: Record<string, string>;\n inlineTranslationPaths: Array<{\n localName: string;\n path: NodePath;\n originalName: string;\n }>;\n translationComponentPaths: Array<{\n localName: string;\n path: NodePath;\n originalName: string;\n }>;\n} {\n // First pass: collect imports and process translation functions\n const importAliases: Record<string, string> = {};\n const inlineTranslationPaths: Array<{\n localName: string;\n path: NodePath;\n originalName: string;\n }> = [];\n\n const translationComponentPaths: Array<{\n localName: string;\n path: NodePath;\n originalName: string;\n }> = [];\n\n traverse(ast, {\n // extract global t tagged template\n TaggedTemplateExpression(path) {\n if (\n
|
|
1
|
+
{"version":3,"file":"getPathsAndAliases.js","names":[],"sources":["../../../../src/react/jsx/utils/getPathsAndAliases.ts"],"sourcesContent":["import traverseModule from '@babel/traverse';\nimport { NodePath } from '@babel/traverse';\nimport {\n GT_TRANSLATION_FUNCS,\n INLINE_TRANSLATION_HOOK,\n INLINE_TRANSLATION_HOOK_ASYNC,\n INLINE_MESSAGE_HOOK,\n INLINE_MESSAGE_HOOK_ASYNC,\n MSG_REGISTRATION_FUNCTION,\n T_REGISTRATION_FUNCTION,\n TRANSLATION_COMPONENT,\n INTERNAL_TRANSLATION_COMPONENT,\n T_GLOBAL_REGISTRATION_FUNCTION,\n T_GLOBAL_REGISTRATION_FUNCTION_MARKER,\n} from '../../jsx/utils/constants.js';\nimport { GTLibrary } from '../../../types/libraries.js';\nimport { extractImportName } from './parseAst.js';\nimport * as t from '@babel/types';\n\n// Handle CommonJS/ESM interop\nconst traverse = traverseModule.default || traverseModule;\n\nfunction isGtSource(source: string, pkgs: GTLibrary[]): boolean {\n return pkgs.some((pkg) => source.startsWith(pkg));\n}\n\nfunction isGtImport(\n node: t.Node,\n pkgs: GTLibrary[]\n): node is t.ImportDeclaration {\n return t.isImportDeclaration(node) && isGtSource(node.source.value, pkgs);\n}\n\nfunction isGtRequire(\n node: t.Node,\n pkgs: GTLibrary[]\n): node is t.VariableDeclarator {\n if (!t.isVariableDeclarator(node)) return false;\n const init = node.init;\n if (!t.isCallExpression(init)) return false;\n if (!t.isIdentifier(init.callee, { name: 'require' })) return false;\n const args = init.arguments;\n return (\n args.length === 1 &&\n t.isStringLiteral(args[0]) &&\n isGtSource(args[0].value, pkgs)\n );\n}\n\nfunction isGlobalTagCandidate(\n node: t.Node\n): node is t.TaggedTemplateExpression {\n return (\n t.isTaggedTemplateExpression(node) &&\n t.isIdentifier(node.tag, { name: T_GLOBAL_REGISTRATION_FUNCTION })\n );\n}\n\nconst GLOBAL_TAG_NAME = new RegExp(\n `(?<![\\\\w$])${T_GLOBAL_REGISTRATION_FUNCTION}(?![\\\\w$])`\n);\n\n/**\n * Text check before parsing: false only for a file that names no GT package\n * and, when global tags are extracted, never uses the global tag's name,\n * where hasTranslationEntryPoints finds nothing to extract either.\n */\nexport function mayHaveTranslationEntryPoints(\n code: string,\n pkgs: GTLibrary[],\n includeGlobalTag: boolean\n): boolean {\n return (\n pkgs.some((pkg) => code.includes(pkg)) ||\n (includeGlobalTag && GLOBAL_TAG_NAME.test(code))\n );\n}\n\nfunction someNode(node: t.Node, test: (node: t.Node) => boolean): boolean {\n if (test(node)) return true;\n const children = node as unknown as Record<\n string,\n t.Node | (t.Node | null)[] | null | undefined\n >;\n for (const key of t.VISITOR_KEYS[node.type] ?? []) {\n const child = children[key];\n if (Array.isArray(child)) {\n for (const item of child) {\n if (item && someNode(item, test)) return true;\n }\n } else if (child && someNode(child, test)) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Whether getPathsAndAliases could find anything in this file, decided by the\n * same node checks its visitor uses but without building paths or scopes.\n */\nexport function hasTranslationEntryPoints(\n ast: t.Node,\n pkgs: GTLibrary[]\n): boolean {\n return someNode(\n ast,\n (node) =>\n isGtImport(node, pkgs) ||\n isGtRequire(node, pkgs) ||\n isGlobalTagCandidate(node)\n );\n}\n\n/**\n * Constructs tracking for gt related variables of interest\n * inlineTranslationPaths: these are string-related translation functions\n * translationComponentPaths: these are just <T> components\n * importAliases: any other GT related imports\n */\nexport function getPathsAndAliases(\n ast: t.Node,\n pkgs: GTLibrary[]\n): {\n importAliases: Record<string, string>;\n inlineTranslationPaths: Array<{\n localName: string;\n path: NodePath;\n originalName: string;\n }>;\n translationComponentPaths: Array<{\n localName: string;\n path: NodePath;\n originalName: string;\n }>;\n} {\n // First pass: collect imports and process translation functions\n const importAliases: Record<string, string> = {};\n const inlineTranslationPaths: Array<{\n localName: string;\n path: NodePath;\n originalName: string;\n }> = [];\n\n const translationComponentPaths: Array<{\n localName: string;\n path: NodePath;\n originalName: string;\n }> = [];\n\n traverse(ast, {\n // extract global t tagged template\n TaggedTemplateExpression(path) {\n if (\n isGlobalTagCandidate(path.node) &&\n !path.scope.hasBinding(T_GLOBAL_REGISTRATION_FUNCTION)\n ) {\n inlineTranslationPaths.push({\n localName: T_GLOBAL_REGISTRATION_FUNCTION,\n path: path.get('tag') as NodePath,\n originalName: T_GLOBAL_REGISTRATION_FUNCTION_MARKER,\n });\n }\n },\n ImportDeclaration(path) {\n if (isGtImport(path.node, pkgs)) {\n const importName = extractImportName(\n path.node,\n pkgs,\n GT_TRANSLATION_FUNCS\n );\n for (const name of importName) {\n if (\n name.original === INLINE_TRANSLATION_HOOK ||\n name.original === INLINE_TRANSLATION_HOOK_ASYNC ||\n name.original === INLINE_MESSAGE_HOOK ||\n name.original === INLINE_MESSAGE_HOOK_ASYNC ||\n name.original === MSG_REGISTRATION_FUNCTION ||\n name.original === T_REGISTRATION_FUNCTION\n ) {\n inlineTranslationPaths.push({\n localName: name.local,\n path,\n originalName: name.original,\n });\n } else if (\n name.original === TRANSLATION_COMPONENT ||\n name.original === INTERNAL_TRANSLATION_COMPONENT\n ) {\n translationComponentPaths.push({\n localName: name.local,\n path,\n originalName: name.original,\n });\n } else {\n importAliases[name.local] = name.original;\n }\n }\n }\n },\n VariableDeclarator(path) {\n if (isGtRequire(path.node, pkgs)) {\n const parentPath = path.parentPath;\n if (parentPath.isVariableDeclaration()) {\n const importName = extractImportName(\n parentPath.node,\n pkgs,\n GT_TRANSLATION_FUNCS\n );\n for (const name of importName) {\n if (\n name.original === INLINE_TRANSLATION_HOOK ||\n name.original === INLINE_TRANSLATION_HOOK_ASYNC ||\n name.original === INLINE_MESSAGE_HOOK ||\n name.original === INLINE_MESSAGE_HOOK_ASYNC\n ) {\n inlineTranslationPaths.push({\n localName: name.local,\n path: parentPath,\n originalName: name.original,\n });\n } else if (\n name.original === TRANSLATION_COMPONENT ||\n name.original === INTERNAL_TRANSLATION_COMPONENT\n ) {\n translationComponentPaths.push({\n localName: name.local,\n path: parentPath,\n originalName: name.original,\n });\n } else {\n importAliases[name.local] = name.original;\n }\n }\n }\n }\n },\n });\n return {\n importAliases,\n inlineTranslationPaths,\n translationComponentPaths,\n };\n}\n"],"mappings":";;;;;AAoBA,MAAM,WAAW,eAAe,WAAW;AAE3C,SAAS,WAAW,QAAgB,MAA4B;AAC9D,QAAO,KAAK,MAAM,QAAQ,OAAO,WAAW,IAAI,CAAC;;AAGnD,SAAS,WACP,MACA,MAC6B;AAC7B,QAAO,EAAE,oBAAoB,KAAK,IAAI,WAAW,KAAK,OAAO,OAAO,KAAK;;AAG3E,SAAS,YACP,MACA,MAC8B;AAC9B,KAAI,CAAC,EAAE,qBAAqB,KAAK,CAAE,QAAO;CAC1C,MAAM,OAAO,KAAK;AAClB,KAAI,CAAC,EAAE,iBAAiB,KAAK,CAAE,QAAO;AACtC,KAAI,CAAC,EAAE,aAAa,KAAK,QAAQ,EAAE,MAAM,WAAW,CAAC,CAAE,QAAO;CAC9D,MAAM,OAAO,KAAK;AAClB,QACE,KAAK,WAAW,KAChB,EAAE,gBAAgB,KAAK,GAAG,IAC1B,WAAW,KAAK,GAAG,OAAO,KAAK;;AAInC,SAAS,qBACP,MACoC;AACpC,QACE,EAAE,2BAA2B,KAAK,IAClC,EAAE,aAAa,KAAK,KAAK,EAAE,MAAA,KAAsC,CAAC;;AAItE,MAAM,kBAAkB,IAAI,OAC1B,yBACD;;;;;;AAOD,SAAgB,8BACd,MACA,MACA,kBACS;AACT,QACE,KAAK,MAAM,QAAQ,KAAK,SAAS,IAAI,CAAC,IACrC,oBAAoB,gBAAgB,KAAK,KAAK;;AAInD,SAAS,SAAS,MAAc,MAA0C;AACxE,KAAI,KAAK,KAAK,C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AAE;IAChC,MAAM,aAAa,KAAK;AACxB,QAAI,WAAW,uBAAuB,EAAE;KACtC,MAAM,aAAa,kBACjB,WAAW,MACX,MACA,qBACD;AACD,UAAK,MAAM,QAAQ,WACjB,KACE,KAAK,aAAA,WACL,KAAK,aAAA,WACL,KAAK,aAAA,iBACL,KAAK,aAAA,cAEL,wBAAuB,KAAK;MAC1B,WAAW,KAAK;MAChB,MAAM;MACN,cAAc,KAAK;MACpB,CAAC;cAEF,KAAK,aAAA,OACL,KAAK,aAAA,yBAEL,2BAA0B,KAAK;MAC7B,WAAW,KAAK;MAChB,MAAM;MACN,cAAc,KAAK;MACpB,CAAC;SAEF,eAAc,KAAK,SAAS,KAAK;;;;EAM5C,CAAC;AACF,QAAO;EACL;EACA;EACA;EACD"}
|
|
@@ -18,7 +18,7 @@ const traverse = traverseModule.default || traverseModule;
|
|
|
18
18
|
const resolveImportPathCache = /* @__PURE__ */ new Map();
|
|
19
19
|
/**
|
|
20
20
|
* Cache for processed functions to avoid re-parsing the same files.
|
|
21
|
-
* Key: `${filePath}::${functionName}::${argIndex}`
|
|
21
|
+
* Key: `${filePath}::${functionName}::${argIndex}::${settingsKey(config)}`
|
|
22
22
|
* Value: boolean indicating whether the function was found and processed
|
|
23
23
|
*/
|
|
24
24
|
const processFunctionCache = /* @__PURE__ */ new Map();
|
|
@@ -129,6 +129,20 @@ function findFunctionParameterUsage(functionPath, parameterName, config, output,
|
|
|
129
129
|
}
|
|
130
130
|
}
|
|
131
131
|
/**
|
|
132
|
+
* The settings that change what a function's translation callback yields, so
|
|
133
|
+
* callers with different ones, e.g. useGT and useMessages, are each processed.
|
|
134
|
+
*/
|
|
135
|
+
function settingsKey(config) {
|
|
136
|
+
return [
|
|
137
|
+
config.ignoreInlineMetadata,
|
|
138
|
+
config.ignoreDynamicContent,
|
|
139
|
+
config.ignoreInvalidIcu,
|
|
140
|
+
config.ignoreInlineListContent,
|
|
141
|
+
config.ignoreTaggedTemplates,
|
|
142
|
+
config.autoderiveMethod
|
|
143
|
+
].join(",");
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
132
146
|
* Searches for a specific user-defined function in a file and analyzes how a translation callback
|
|
133
147
|
* parameter (at argIndex position) is used within that function.
|
|
134
148
|
*
|
|
@@ -140,7 +154,7 @@ function findFunctionParameterUsage(functionPath, parameterName, config, output,
|
|
|
140
154
|
* If the function is not found in the file, follows re-exports (export * from './other')
|
|
141
155
|
*/
|
|
142
156
|
function processFunctionInFile(filePath, functionName, argIndex, config, state, output) {
|
|
143
|
-
const cacheKey = `${filePath}::${functionName}::${argIndex}`;
|
|
157
|
+
const cacheKey = `${filePath}::${functionName}::${argIndex}::${settingsKey(config)}`;
|
|
144
158
|
if (processFunctionCache.has(cacheKey)) return;
|
|
145
159
|
if (state.visited.has(filePath)) return;
|
|
146
160
|
state.visited.add(filePath);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"parseStringFunction.js","names":[],"sources":["../../../../src/react/jsx/utils/parseStringFunction.ts"],"sourcesContent":["import { NodePath, Scope, Binding } from '@babel/traverse';\nimport * as t from '@babel/types';\nimport {\n INLINE_TRANSLATION_HOOK,\n INLINE_TRANSLATION_HOOK_ASYNC,\n INLINE_MESSAGE_HOOK,\n INLINE_MESSAGE_HOOK_ASYNC,\n STRING_REGISTRATION_FUNCS,\n T_GLOBAL_REGISTRATION_FUNCTION_MARKER,\n} from './constants.js';\nimport {\n warnAsyncUseGT,\n warnSyncGetGT,\n warnUnresolvedImportSync,\n} from '../../../console/index.js';\n\nimport traverseModule from '@babel/traverse';\n// Handle CommonJS/ESM interop\nconst traverse = traverseModule.default || traverseModule;\n\nimport fs from 'node:fs';\nimport { parse } from '@babel/parser';\nimport type {\n ParsingConfig,\n ParsingState,\n ParsingOutput,\n} from './stringParsing/types.js';\nimport { resolveImportPath } from './resolveImportPath.js';\nimport { buildImportMap } from './buildImportMap.js';\nimport { processTranslationCall } from './stringParsing/processTranslationCall/index.js';\nimport { processTaggedTemplateCall } from './stringParsing/processTaggedTemplateCall/index.js';\n\n/**\n * Cache for resolved import paths to avoid redundant I/O operations.\n * Key: `${currentFile}::${importPath}`\n * Value: resolved absolute path or null\n */\nconst resolveImportPathCache = new Map<string, string | null>();\n\n/**\n * Cache for processed functions to avoid re-parsing the same files.\n * Key: `${filePath}::${functionName}::${argIndex}`\n * Value: boolean indicating whether the function was found and processed\n */\nconst processFunctionCache = new Map<string, boolean>();\n\n/**\n * Clears all caches. Useful for testing or when file system changes.\n */\nexport function clearParsingCaches(): void {\n resolveImportPathCache.clear();\n processFunctionCache.clear();\n}\n\n/**\n * Extracts the parameter name from a function parameter node, handling TypeScript annotations and default values.\n */\nfunction extractParameterName(param: t.Node): string | null {\n if (t.isIdentifier(param)) {\n return param.name;\n }\n // Handle parameters with default values: (gt = () => {})\n if (t.isAssignmentPattern(param) && t.isIdentifier(param.left)) {\n return param.left.name;\n }\n return null;\n}\n\n/**\n * Recursively resolves variable assignments to find all aliases of a translation callback parameter.\n * Handles cases like: const t = translate; const a = translate; const b = a; const c = b;\n *\n * @param scope The scope to search within\n * @param variableName The variable name to resolve\n * @param visited Set to track already visited variables to prevent infinite loops\n * @returns Array of all variable names that reference the original translation callback\n */\nexport function resolveVariableAliases(\n scope: Scope,\n variableName: string,\n visited: Set<string> = new Set()\n): string[] {\n if (visited.has(variableName)) {\n return []; // Prevent infinite loops\n }\n visited.add(variableName);\n\n const aliases = [variableName];\n const binding = scope.bindings[variableName];\n\n if (binding) {\n // Look for variable declarations that assign this variable to another name\n // Example: const t = translate; or const a = t;\n for (const [otherVarName, otherBinding] of Object.entries(scope.bindings)) {\n if (otherVarName === variableName || visited.has(otherVarName)) continue;\n\n const otherBindingTyped = otherBinding as Binding;\n if (\n otherBindingTyped.path &&\n otherBindingTyped.path.isVariableDeclarator() &&\n otherBindingTyped.path.node.init &&\n t.isIdentifier(otherBindingTyped.path.node.init) &&\n otherBindingTyped.path.node.init.name === variableName\n ) {\n // Found an alias: const otherVarName = variableName;\n const nestedAliases = resolveVariableAliases(\n scope,\n otherVarName,\n visited\n );\n aliases.push(...nestedAliases);\n }\n }\n }\n\n return aliases;\n}\n\n/**\n * Handles how translation callbacks are used within code.\n * This covers both direct translation calls (gt('hello')) and prop drilling\n * where the translation callback is passed to other functions (getData(gt)).\n */\nfunction handleFunctionCall(\n tPath: NodePath,\n config: ParsingConfig,\n state: ParsingState,\n output: ParsingOutput,\n visitedFunctions: Set<t.Node>\n): void {\n if (\n tPath.parent.type === 'CallExpression' &&\n tPath.parent.callee === tPath.node\n ) {\n // Direct translation call: t('hello')\n processTranslationCall(tPath, config, output);\n } else if (\n !config.ignoreTaggedTemplates &&\n tPath.parent.type === 'TaggedTemplateExpression' &&\n tPath.parent.tag === tPath.node\n ) {\n // Tagged template: t`hello ${name}`\n processTaggedTemplateCall(tPath, config, output);\n } else if (\n tPath.parent.type === 'CallExpression' &&\n t.isExpression(tPath.node) &&\n tPath.parent.arguments.includes(tPath.node)\n ) {\n // Parameter passed to another function: getData(t)\n const argIndex = tPath.parent.arguments.indexOf(tPath.node);\n const callee = tPath.parent.callee;\n\n if (t.isIdentifier(callee)) {\n const calleeBinding = tPath.scope.getBinding(callee.name);\n\n if (calleeBinding && calleeBinding.path.isFunction()) {\n const functionPath = calleeBinding.path;\n processFunctionIfMatches(\n callee.name,\n argIndex,\n functionPath.node,\n functionPath,\n config,\n output,\n visitedFunctions\n );\n }\n // Handle arrow functions assigned to variables: const getData = (t) => {...}\n else if (\n calleeBinding &&\n calleeBinding.path.isVariableDeclarator() &&\n calleeBinding.path.node.init &&\n (t.isArrowFunctionExpression(calleeBinding.path.node.init) ||\n t.isFunctionExpression(calleeBinding.path.node.init))\n ) {\n const initPath = calleeBinding.path.get('init') as NodePath;\n processFunctionIfMatches(\n callee.name,\n argIndex,\n calleeBinding.path.node.init,\n initPath,\n config,\n output,\n visitedFunctions\n );\n }\n // If not found locally, check if it's an imported function\n else if (state.importMap.has(callee.name)) {\n const importPath = state.importMap.get(callee.name)!;\n const resolvedPath = resolveImportPath(\n config.file,\n importPath,\n config.parsingOptions,\n resolveImportPathCache\n );\n\n if (resolvedPath) {\n processFunctionInFile(\n resolvedPath,\n callee.name,\n argIndex,\n config,\n state,\n output\n );\n } else {\n output.warnings.add(\n warnUnresolvedImportSync(\n config.file,\n callee.name,\n importPath,\n tPath.node.loc\n ? `${tPath.node.loc.start.line}:${tPath.node.loc.start.column}`\n : undefined\n )\n );\n }\n }\n }\n }\n}\n\n/**\n * Processes a user-defined function that receives a translation callback as a parameter.\n * Validates the function has enough parameters and traces how the translation callback\n * is used within that function's body.\n */\nfunction processFunctionIfMatches(\n _functionName: string,\n argIndex: number,\n functionNode: t.Function,\n functionPath: NodePath,\n config: ParsingConfig,\n output: ParsingOutput,\n visitedFunctions: Set<t.Node>\n): void {\n if (visitedFunctions.has(functionNode)) return;\n visitedFunctions.add(functionNode);\n\n if (functionNode.params.length > argIndex) {\n const param = functionNode.params[argIndex];\n const paramName = extractParameterName(param);\n\n if (paramName) {\n findFunctionParameterUsage(\n functionPath,\n paramName,\n config,\n output,\n visitedFunctions\n );\n }\n }\n\n visitedFunctions.delete(functionNode);\n}\n\n/**\n * Finds all usages of a translation callback parameter within a user-defined function's scope.\n * Processes both direct translation calls and cases where the translation callback is passed\n * to other functions (prop drilling).\n *\n * Example: In function getInfo(t) { return t('hello'); }, this finds the t('hello') call.\n * Example: In function getData(t) { return getFooter(t); }, this finds and traces into getFooter.\n */\nfunction findFunctionParameterUsage(\n functionPath: NodePath,\n parameterName: string,\n config: ParsingConfig,\n output: ParsingOutput,\n visitedFunctions: Set<t.Node>\n): void {\n // Look for the function body and find all usages of the parameter\n if (functionPath.isFunction()) {\n const functionScope = functionPath.scope;\n\n // Resolve all aliases of the translation callback parameter\n // Example: translate -> [translate, t, a, b] for const t = translate; const a = t; const b = a;\n const allParameterNames = resolveVariableAliases(\n functionScope,\n parameterName\n );\n\n // Build import map for this function's scope to handle cross-file calls\n const programPath = functionPath.scope.getProgramParent().path;\n const importMap = buildImportMap(programPath);\n\n // Process references for all parameter names and their aliases\n allParameterNames.forEach((name) => {\n const binding = functionScope.bindings[name];\n if (binding) {\n binding.referencePaths.forEach((refPath) => {\n handleFunctionCall(\n refPath,\n config,\n { visited: new Set(), importMap },\n output,\n visitedFunctions\n );\n });\n }\n });\n }\n}\n\n/**\n * Searches for a specific user-defined function in a file and analyzes how a translation callback\n * parameter (at argIndex position) is used within that function.\n *\n * Handles multiple function declaration patterns:\n * - function getInfo(t) { ... }\n * - export function getInfo(t) { ... }\n * - const getInfo = (t) => { ... }\n *\n * If the function is not found in the file, follows re-exports (export * from './other')\n */\nfunction processFunctionInFile(\n filePath: string,\n functionName: string,\n argIndex: number,\n config: ParsingConfig,\n state: ParsingState,\n output: ParsingOutput\n): void {\n // Check cache first to avoid redundant parsing\n const cacheKey = `${filePath}::${functionName}::${argIndex}`;\n if (processFunctionCache.has(cacheKey)) {\n return;\n }\n\n // Prevent infinite loops from circular re-exports\n if (state.visited.has(filePath)) {\n return;\n }\n state.visited.add(filePath);\n\n try {\n const code = fs.readFileSync(filePath, 'utf8');\n const ast = parse(code, {\n sourceType: 'module',\n plugins: ['jsx', 'typescript'],\n });\n\n let found = false;\n const reExports: string[] = [];\n // Fresh set per cross-file parse — node identity is only stable within a single parse.\n // Cross-file cycles are already guarded by processFunctionCache above.\n const visitedFunctions = new Set<t.Node>();\n // Update config.file so relative imports in the target file resolve correctly\n const crossFileConfig: ParsingConfig = { ...config, file: filePath };\n\n traverse(ast, {\n // Handle function declarations: function getInfo(t) { ... }\n FunctionDeclaration(path) {\n if (path.node.id?.name === functionName) {\n found = true;\n processFunctionIfMatches(\n functionName,\n argIndex,\n path.node,\n path,\n crossFileConfig,\n output,\n visitedFunctions\n );\n }\n },\n // Handle variable declarations: const getInfo = (t) => { ... }\n VariableDeclarator(path) {\n if (\n t.isIdentifier(path.node.id) &&\n path.node.id.name === functionName &&\n path.node.init &&\n (t.isArrowFunctionExpression(path.node.init) ||\n t.isFunctionExpression(path.node.init))\n ) {\n found = true;\n const initPath = path.get('init') as NodePath;\n processFunctionIfMatches(\n functionName,\n argIndex,\n path.node.init,\n initPath,\n crossFileConfig,\n output,\n visitedFunctions\n );\n }\n },\n // Collect re-exports: export * from './other'\n ExportAllDeclaration(path) {\n if (t.isStringLiteral(path.node.source)) {\n reExports.push(path.node.source.value);\n }\n },\n // Collect named re-exports: export { foo } from './other'\n ExportNamedDeclaration(path) {\n if (path.node.source && t.isStringLiteral(path.node.source)) {\n // Check if this export includes our function\n const exportsFunction = path.node.specifiers.some((spec) => {\n if (t.isExportSpecifier(spec)) {\n const exportedName = t.isIdentifier(spec.exported)\n ? spec.exported.name\n : spec.exported.value;\n return exportedName === functionName;\n }\n return false;\n });\n if (exportsFunction) {\n reExports.push(path.node.source.value);\n }\n }\n },\n });\n\n // If function not found, follow re-exports\n if (!found && reExports.length > 0) {\n for (const reExportPath of reExports) {\n const resolvedPath = resolveImportPath(\n filePath,\n reExportPath,\n config.parsingOptions,\n resolveImportPathCache\n );\n if (resolvedPath) {\n processFunctionInFile(\n resolvedPath,\n functionName,\n argIndex,\n config,\n state,\n output\n );\n }\n }\n }\n\n // Mark this function search as processed in the cache\n processFunctionCache.set(cacheKey, found);\n } catch {\n // Silently skip files that can't be parsed or accessed\n // Still mark as processed to avoid retrying failed parses\n processFunctionCache.set(cacheKey, false);\n }\n}\n\n/**\n * Main entry point for parsing translation strings from useGT() and getGT() calls.\n *\n * Supports complex patterns including:\n * 1. Direct calls: const gt = useGT(); gt('hello');\n * 2. Translation callback prop drilling: const gt = useGT(); getInfo(gt); where getInfo uses gt() internally\n * 3. Cross-file function calls: imported functions that receive the translation callback as a parameter\n *\n * Example flow:\n * - const gt = useGT();\n * - const { home } = getInfo(gt); // getInfo is imported from './constants'\n * - This will parse constants.ts to find translation calls within getInfo function\n */\nexport function parseStrings(\n importName: string,\n originalName: string,\n path: NodePath,\n config: ParsingConfig,\n output: ParsingOutput\n): void {\n // Handle global t macro directly — path is already the tag identifier\n // NOTE: if we decide to add support for a global t() function in addition to the macro,\n // then we need to add support for skipDeriveInvocation here\n if (originalName === T_GLOBAL_REGISTRATION_FUNCTION_MARKER) {\n if (!config.ignoreGlobalTaggedTemplates) {\n processTaggedTemplateCall(\n path,\n {\n ...config,\n autoderiveMethod:\n config.autoderiveMethod === 'AUTO'\n ? 'DISABLED'\n : config.autoderiveMethod,\n },\n output\n );\n }\n return;\n }\n\n // First, collect all imports in this file to track cross-file function calls\n const importMap = buildImportMap(path.scope.getProgramParent().path);\n\n const referencePaths = path.scope.bindings[importName]?.referencePaths || [];\n\n for (const refPath of referencePaths) {\n // Handle msg(), t() calls directly without variable assignment\n if (\n STRING_REGISTRATION_FUNCS.includes(\n originalName as (typeof STRING_REGISTRATION_FUNCS)[number]\n )\n ) {\n const stringRegistrationConfig: ParsingConfig = {\n parsingOptions: config.parsingOptions,\n file: config.file,\n ignoreInlineMetadata: false,\n ignoreDynamicContent: false,\n ignoreInvalidIcu: false,\n ignoreInlineListContent: false,\n includeSourceCodeContext: config.includeSourceCodeContext,\n ignoreTaggedTemplates: false,\n ignoreGlobalTaggedTemplates: false,\n // User configurable, otherwise default to AUTO\n autoderiveMethod:\n config.autoderiveMethod === 'AUTO'\n ? 'DISABLED'\n : config.autoderiveMethod,\n };\n\n // Check if this is a direct call to msg('string') or t('string')\n if (\n refPath.parent.type === 'CallExpression' &&\n refPath.parent.callee === refPath.node\n ) {\n /**\n * CASE: Autoderive t() and msg() function\n * The t() function, will treat variable content as if it was marked for derivation\n * without explicit calls to derive().\n *\n * @example\n * const derivedValue = 'John';\n * const interpolatedValue = \"Ernest\"\n * t(\n * \"Hello, \" + derivedValue + \"! My name is {interpolatedValue}\",\n * { interpolatedValue }\n * );\n * // \"Hello, John! My name is {interpolatedValue}\"\n */\n processTranslationCall(\n refPath,\n config.autoderiveMethod === 'AUTO'\n ? {\n ...stringRegistrationConfig,\n autoderiveMethod: 'ENABLED',\n }\n : stringRegistrationConfig,\n output\n );\n } else if (\n !stringRegistrationConfig.ignoreTaggedTemplates &&\n refPath.parent.type === 'TaggedTemplateExpression' &&\n refPath.parent.tag === refPath.node\n ) {\n // Tagged template: t`hello ${name}`\n processTaggedTemplateCall(refPath, stringRegistrationConfig, output);\n }\n continue;\n }\n\n // Handle useGT(), getGT(), useMessages(), and getMessages() calls that need variable assignment\n const callExpr = refPath.findParent((p) => p.isCallExpression());\n if (callExpr) {\n // Get the parent, handling both await and non-await cases\n const parentPath = callExpr.parentPath;\n\n const parentFunction = refPath.getFunctionParent();\n const asyncScope = parentFunction?.node.async;\n if (\n asyncScope &&\n (originalName === INLINE_TRANSLATION_HOOK ||\n originalName === INLINE_MESSAGE_HOOK)\n ) {\n output.errors.push(\n warnAsyncUseGT(\n config.file,\n `${refPath.node.loc?.start?.line}:${refPath.node.loc?.start?.column}`\n )\n );\n return;\n } else if (\n !asyncScope &&\n (originalName === INLINE_TRANSLATION_HOOK_ASYNC ||\n originalName === INLINE_MESSAGE_HOOK_ASYNC)\n ) {\n output.errors.push(\n warnSyncGetGT(\n config.file,\n `${refPath.node.loc?.start?.line}:${refPath.node.loc?.start?.column}`\n )\n );\n return;\n }\n\n const isMessageHook =\n originalName === INLINE_MESSAGE_HOOK ||\n originalName === INLINE_MESSAGE_HOOK_ASYNC;\n const isInlineGT =\n originalName === INLINE_TRANSLATION_HOOK ||\n originalName === INLINE_TRANSLATION_HOOK_ASYNC;\n const hookConfig: ParsingConfig = {\n parsingOptions: config.parsingOptions,\n file: config.file,\n ignoreInlineMetadata: isMessageHook,\n ignoreDynamicContent: isMessageHook,\n ignoreInvalidIcu: isMessageHook,\n // TODO: when we add support for array content in gt function, this should just always be false\n ignoreInlineListContent: isInlineGT,\n includeSourceCodeContext: config.includeSourceCodeContext,\n ignoreTaggedTemplates: false,\n ignoreGlobalTaggedTemplates: false,\n // User configurable, otherwise default to DISABLED\n autoderiveMethod:\n config.autoderiveMethod === 'AUTO'\n ? isInlineGT\n ? 'ENABLED'\n : 'DISABLED'\n : config.autoderiveMethod,\n };\n\n const effectiveParent =\n parentPath?.node.type === 'AwaitExpression'\n ? parentPath.parentPath\n : parentPath;\n if (\n effectiveParent &&\n effectiveParent.node.type === 'VariableDeclarator' &&\n effectiveParent.node.id.type === 'Identifier'\n ) {\n const tFuncName = effectiveParent.node.id.name;\n // Get the scope from the variable declaration\n const variableScope = effectiveParent.scope;\n\n // Resolve all aliases of the translation function\n // Example: translate -> [translate, t, a, b] for const t = translate; const a = t; const b = a;\n const allTranslationNames = resolveVariableAliases(\n variableScope,\n tFuncName\n );\n\n // Process references for all translation function names and their aliases\n const visitedFunctions = new Set<t.Node>();\n allTranslationNames.forEach((name) => {\n const tReferencePaths =\n variableScope.bindings[name]?.referencePaths || [];\n\n for (const tPath of tReferencePaths) {\n handleFunctionCall(\n tPath,\n hookConfig,\n { visited: new Set(), importMap },\n output,\n visitedFunctions\n );\n }\n });\n }\n }\n }\n}\n"],"mappings":";;;;;;;;;;;AAkBA,MAAM,WAAW,eAAe,WAAW;;;;;;AAmB3C,MAAM,yCAAyB,IAAI,KAA4B;;;;;;AAO/D,MAAM,uCAAuB,IAAI,KAAsB;;;;AAKvD,SAAgB,qBAA2B;AACzC,wBAAuB,OAAO;AAC9B,sBAAqB,OAAO;;;;;AAM9B,SAAS,qBAAqB,OAA8B;AAC1D,KAAI,EAAE,aAAa,MAAM,CACvB,QAAO,MAAM;AAGf,KAAI,EAAE,oBAAoB,MAAM,IAAI,EAAE,aAAa,MAAM,KAAK,CAC5D,QAAO,MAAM,KAAK;AAEpB,QAAO;;;;;;;;;;;AAYT,SAAgB,uBACd,OACA,cACA,0BAAuB,IAAI,KAAK,EACtB;AACV,KAAI,QAAQ,IAAI,aAAa,CAC3B,QAAO,EAAE;AAEX,SAAQ,IAAI,aAAa;CAEzB,MAAM,UAAU,CAAC,aAAa;AAG9B,KAFgB,MAAM,SAAS,cAK7B,MAAK,MAAM,CAAC,cAAc,iBAAiB,OAAO,QAAQ,MAAM,SAAS,EAA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AEZ,MAAM,aAAa,SAAS;GAG5B,MAAM,aADiB,QAAQ,mBACE,EAAE,KAAK;AACxC,OACE,eACC,iBAAA,WACC,iBAAA,gBACF;AACA,WAAO,OAAO,KACZ,eACE,OAAO,MACP,GAAG,QAAQ,KAAK,KAAK,OAAO,KAAK,GAAG,QAAQ,KAAK,KAAK,OAAO,SAC9D,CACF;AACD;cAEA,CAAC,eACA,iBAAA,WACC,iBAAA,gBACF;AACA,WAAO,OAAO,KACZ,cACE,OAAO,MACP,GAAG,QAAQ,KAAK,KAAK,OAAO,KAAK,GAAG,QAAQ,KAAK,KAAK,OAAO,SAC9D,CACF;AACD;;GAGF,MAAM,gBACJ,iBAAA,iBACA,iBAAA;GACF,MAAM,aACJ,iBAAA,WACA,iBAAA;GACF,MAAM,aAA4B;IAChC,gBAAgB,OAAO;IACvB,MAAM,OAAO;IACb,sBAAsB;IACtB,sBAAsB;IACtB,kBAAkB;IAElB,yBAAyB;IACzB,0BAA0B,OAAO;IACjC,uBAAuB;IACvB,6BAA6B;IAE7B,kBACE,OAAO,qBAAqB,SACxB,aACE,YACA,aACF,OAAO;IACd;GAED,MAAM,kBACJ,YAAY,KAAK,SAAS,oBACtB,WAAW,aACX;AACN,OACE,mBACA,gBAAgB,KAAK,SAAS,wBAC9B,gBAAgB,KAAK,GAAG,SAAS,cACjC;IACA,MAAM,YAAY,gBAAgB,KAAK,GAAG;IAE1C,MAAM,gBAAgB,gBAAgB;IAItC,MAAM,sBAAsB,uBAC1B,eACA,UACD;IAGD,MAAM,mCAAmB,IAAI,KAAa;AAC1C,wBAAoB,SAAS,SAAS;KACpC,MAAM,kBACJ,cAAc,SAAS,OAAO,kBAAkB,EAAE;AAEpD,UAAK,MAAM,SAAS,gBAClB,oBACE,OACA,YACA;MAAE,yBAAS,IAAI,KAAK;MAAE;MAAW,EACjC,QACA,iBACD;MAEH"}
|
|
1
|
+
{"version":3,"file":"parseStringFunction.js","names":[],"sources":["../../../../src/react/jsx/utils/parseStringFunction.ts"],"sourcesContent":["import { NodePath, Scope, Binding } from '@babel/traverse';\nimport * as t from '@babel/types';\nimport {\n INLINE_TRANSLATION_HOOK,\n INLINE_TRANSLATION_HOOK_ASYNC,\n INLINE_MESSAGE_HOOK,\n INLINE_MESSAGE_HOOK_ASYNC,\n STRING_REGISTRATION_FUNCS,\n T_GLOBAL_REGISTRATION_FUNCTION_MARKER,\n} from './constants.js';\nimport {\n warnAsyncUseGT,\n warnSyncGetGT,\n warnUnresolvedImportSync,\n} from '../../../console/index.js';\n\nimport traverseModule from '@babel/traverse';\n// Handle CommonJS/ESM interop\nconst traverse = traverseModule.default || traverseModule;\n\nimport fs from 'node:fs';\nimport { parse } from '@babel/parser';\nimport type {\n ParsingConfig,\n ParsingState,\n ParsingOutput,\n} from './stringParsing/types.js';\nimport { resolveImportPath } from './resolveImportPath.js';\nimport { buildImportMap } from './buildImportMap.js';\nimport { processTranslationCall } from './stringParsing/processTranslationCall/index.js';\nimport { processTaggedTemplateCall } from './stringParsing/processTaggedTemplateCall/index.js';\n\n/**\n * Cache for resolved import paths to avoid redundant I/O operations.\n * Key: `${currentFile}::${importPath}`\n * Value: resolved absolute path or null\n */\nconst resolveImportPathCache = new Map<string, string | null>();\n\n/**\n * Cache for processed functions to avoid re-parsing the same files.\n * Key: `${filePath}::${functionName}::${argIndex}::${settingsKey(config)}`\n * Value: boolean indicating whether the function was found and processed\n */\nconst processFunctionCache = new Map<string, boolean>();\n\n/**\n * Clears all caches. Useful for testing or when file system changes.\n */\nexport function clearParsingCaches(): void {\n resolveImportPathCache.clear();\n processFunctionCache.clear();\n}\n\n/**\n * Extracts the parameter name from a function parameter node, handling TypeScript annotations and default values.\n */\nfunction extractParameterName(param: t.Node): string | null {\n if (t.isIdentifier(param)) {\n return param.name;\n }\n // Handle parameters with default values: (gt = () => {})\n if (t.isAssignmentPattern(param) && t.isIdentifier(param.left)) {\n return param.left.name;\n }\n return null;\n}\n\n/**\n * Recursively resolves variable assignments to find all aliases of a translation callback parameter.\n * Handles cases like: const t = translate; const a = translate; const b = a; const c = b;\n *\n * @param scope The scope to search within\n * @param variableName The variable name to resolve\n * @param visited Set to track already visited variables to prevent infinite loops\n * @returns Array of all variable names that reference the original translation callback\n */\nexport function resolveVariableAliases(\n scope: Scope,\n variableName: string,\n visited: Set<string> = new Set()\n): string[] {\n if (visited.has(variableName)) {\n return []; // Prevent infinite loops\n }\n visited.add(variableName);\n\n const aliases = [variableName];\n const binding = scope.bindings[variableName];\n\n if (binding) {\n // Look for variable declarations that assign this variable to another name\n // Example: const t = translate; or const a = t;\n for (const [otherVarName, otherBinding] of Object.entries(scope.bindings)) {\n if (otherVarName === variableName || visited.has(otherVarName)) continue;\n\n const otherBindingTyped = otherBinding as Binding;\n if (\n otherBindingTyped.path &&\n otherBindingTyped.path.isVariableDeclarator() &&\n otherBindingTyped.path.node.init &&\n t.isIdentifier(otherBindingTyped.path.node.init) &&\n otherBindingTyped.path.node.init.name === variableName\n ) {\n // Found an alias: const otherVarName = variableName;\n const nestedAliases = resolveVariableAliases(\n scope,\n otherVarName,\n visited\n );\n aliases.push(...nestedAliases);\n }\n }\n }\n\n return aliases;\n}\n\n/**\n * Handles how translation callbacks are used within code.\n * This covers both direct translation calls (gt('hello')) and prop drilling\n * where the translation callback is passed to other functions (getData(gt)).\n */\nfunction handleFunctionCall(\n tPath: NodePath,\n config: ParsingConfig,\n state: ParsingState,\n output: ParsingOutput,\n visitedFunctions: Set<t.Node>\n): void {\n if (\n tPath.parent.type === 'CallExpression' &&\n tPath.parent.callee === tPath.node\n ) {\n // Direct translation call: t('hello')\n processTranslationCall(tPath, config, output);\n } else if (\n !config.ignoreTaggedTemplates &&\n tPath.parent.type === 'TaggedTemplateExpression' &&\n tPath.parent.tag === tPath.node\n ) {\n // Tagged template: t`hello ${name}`\n processTaggedTemplateCall(tPath, config, output);\n } else if (\n tPath.parent.type === 'CallExpression' &&\n t.isExpression(tPath.node) &&\n tPath.parent.arguments.includes(tPath.node)\n ) {\n // Parameter passed to another function: getData(t)\n const argIndex = tPath.parent.arguments.indexOf(tPath.node);\n const callee = tPath.parent.callee;\n\n if (t.isIdentifier(callee)) {\n const calleeBinding = tPath.scope.getBinding(callee.name);\n\n if (calleeBinding && calleeBinding.path.isFunction()) {\n const functionPath = calleeBinding.path;\n processFunctionIfMatches(\n callee.name,\n argIndex,\n functionPath.node,\n functionPath,\n config,\n output,\n visitedFunctions\n );\n }\n // Handle arrow functions assigned to variables: const getData = (t) => {...}\n else if (\n calleeBinding &&\n calleeBinding.path.isVariableDeclarator() &&\n calleeBinding.path.node.init &&\n (t.isArrowFunctionExpression(calleeBinding.path.node.init) ||\n t.isFunctionExpression(calleeBinding.path.node.init))\n ) {\n const initPath = calleeBinding.path.get('init') as NodePath;\n processFunctionIfMatches(\n callee.name,\n argIndex,\n calleeBinding.path.node.init,\n initPath,\n config,\n output,\n visitedFunctions\n );\n }\n // If not found locally, check if it's an imported function\n else if (state.importMap.has(callee.name)) {\n const importPath = state.importMap.get(callee.name)!;\n const resolvedPath = resolveImportPath(\n config.file,\n importPath,\n config.parsingOptions,\n resolveImportPathCache\n );\n\n if (resolvedPath) {\n processFunctionInFile(\n resolvedPath,\n callee.name,\n argIndex,\n config,\n state,\n output\n );\n } else {\n output.warnings.add(\n warnUnresolvedImportSync(\n config.file,\n callee.name,\n importPath,\n tPath.node.loc\n ? `${tPath.node.loc.start.line}:${tPath.node.loc.start.column}`\n : undefined\n )\n );\n }\n }\n }\n }\n}\n\n/**\n * Processes a user-defined function that receives a translation callback as a parameter.\n * Validates the function has enough parameters and traces how the translation callback\n * is used within that function's body.\n */\nfunction processFunctionIfMatches(\n _functionName: string,\n argIndex: number,\n functionNode: t.Function,\n functionPath: NodePath,\n config: ParsingConfig,\n output: ParsingOutput,\n visitedFunctions: Set<t.Node>\n): void {\n if (visitedFunctions.has(functionNode)) return;\n visitedFunctions.add(functionNode);\n\n if (functionNode.params.length > argIndex) {\n const param = functionNode.params[argIndex];\n const paramName = extractParameterName(param);\n\n if (paramName) {\n findFunctionParameterUsage(\n functionPath,\n paramName,\n config,\n output,\n visitedFunctions\n );\n }\n }\n\n visitedFunctions.delete(functionNode);\n}\n\n/**\n * Finds all usages of a translation callback parameter within a user-defined function's scope.\n * Processes both direct translation calls and cases where the translation callback is passed\n * to other functions (prop drilling).\n *\n * Example: In function getInfo(t) { return t('hello'); }, this finds the t('hello') call.\n * Example: In function getData(t) { return getFooter(t); }, this finds and traces into getFooter.\n */\nfunction findFunctionParameterUsage(\n functionPath: NodePath,\n parameterName: string,\n config: ParsingConfig,\n output: ParsingOutput,\n visitedFunctions: Set<t.Node>\n): void {\n // Look for the function body and find all usages of the parameter\n if (functionPath.isFunction()) {\n const functionScope = functionPath.scope;\n\n // Resolve all aliases of the translation callback parameter\n // Example: translate -> [translate, t, a, b] for const t = translate; const a = t; const b = a;\n const allParameterNames = resolveVariableAliases(\n functionScope,\n parameterName\n );\n\n // Build import map for this function's scope to handle cross-file calls\n const programPath = functionPath.scope.getProgramParent().path;\n const importMap = buildImportMap(programPath);\n\n // Process references for all parameter names and their aliases\n allParameterNames.forEach((name) => {\n const binding = functionScope.bindings[name];\n if (binding) {\n binding.referencePaths.forEach((refPath) => {\n handleFunctionCall(\n refPath,\n config,\n { visited: new Set(), importMap },\n output,\n visitedFunctions\n );\n });\n }\n });\n }\n}\n\n/**\n * The settings that change what a function's translation callback yields, so\n * callers with different ones, e.g. useGT and useMessages, are each processed.\n */\nfunction settingsKey(config: ParsingConfig): string {\n return [\n config.ignoreInlineMetadata,\n config.ignoreDynamicContent,\n config.ignoreInvalidIcu,\n config.ignoreInlineListContent,\n config.ignoreTaggedTemplates,\n config.autoderiveMethod,\n ].join(',');\n}\n\n/**\n * Searches for a specific user-defined function in a file and analyzes how a translation callback\n * parameter (at argIndex position) is used within that function.\n *\n * Handles multiple function declaration patterns:\n * - function getInfo(t) { ... }\n * - export function getInfo(t) { ... }\n * - const getInfo = (t) => { ... }\n *\n * If the function is not found in the file, follows re-exports (export * from './other')\n */\nfunction processFunctionInFile(\n filePath: string,\n functionName: string,\n argIndex: number,\n config: ParsingConfig,\n state: ParsingState,\n output: ParsingOutput\n): void {\n // Check cache first to avoid redundant parsing\n const cacheKey = `${filePath}::${functionName}::${argIndex}::${settingsKey(config)}`;\n if (processFunctionCache.has(cacheKey)) {\n return;\n }\n\n // Prevent infinite loops from circular re-exports\n if (state.visited.has(filePath)) {\n return;\n }\n state.visited.add(filePath);\n\n try {\n const code = fs.readFileSync(filePath, 'utf8');\n const ast = parse(code, {\n sourceType: 'module',\n plugins: ['jsx', 'typescript'],\n });\n\n let found = false;\n const reExports: string[] = [];\n // Fresh set per cross-file parse — node identity is only stable within a single parse.\n // Cross-file cycles are already guarded by processFunctionCache above.\n const visitedFunctions = new Set<t.Node>();\n // Update config.file so relative imports in the target file resolve correctly\n const crossFileConfig: ParsingConfig = { ...config, file: filePath };\n\n traverse(ast, {\n // Handle function declarations: function getInfo(t) { ... }\n FunctionDeclaration(path) {\n if (path.node.id?.name === functionName) {\n found = true;\n processFunctionIfMatches(\n functionName,\n argIndex,\n path.node,\n path,\n crossFileConfig,\n output,\n visitedFunctions\n );\n }\n },\n // Handle variable declarations: const getInfo = (t) => { ... }\n VariableDeclarator(path) {\n if (\n t.isIdentifier(path.node.id) &&\n path.node.id.name === functionName &&\n path.node.init &&\n (t.isArrowFunctionExpression(path.node.init) ||\n t.isFunctionExpression(path.node.init))\n ) {\n found = true;\n const initPath = path.get('init') as NodePath;\n processFunctionIfMatches(\n functionName,\n argIndex,\n path.node.init,\n initPath,\n crossFileConfig,\n output,\n visitedFunctions\n );\n }\n },\n // Collect re-exports: export * from './other'\n ExportAllDeclaration(path) {\n if (t.isStringLiteral(path.node.source)) {\n reExports.push(path.node.source.value);\n }\n },\n // Collect named re-exports: export { foo } from './other'\n ExportNamedDeclaration(path) {\n if (path.node.source && t.isStringLiteral(path.node.source)) {\n // Check if this export includes our function\n const exportsFunction = path.node.specifiers.some((spec) => {\n if (t.isExportSpecifier(spec)) {\n const exportedName = t.isIdentifier(spec.exported)\n ? spec.exported.name\n : spec.exported.value;\n return exportedName === functionName;\n }\n return false;\n });\n if (exportsFunction) {\n reExports.push(path.node.source.value);\n }\n }\n },\n });\n\n // If function not found, follow re-exports\n if (!found && reExports.length > 0) {\n for (const reExportPath of reExports) {\n const resolvedPath = resolveImportPath(\n filePath,\n reExportPath,\n config.parsingOptions,\n resolveImportPathCache\n );\n if (resolvedPath) {\n processFunctionInFile(\n resolvedPath,\n functionName,\n argIndex,\n config,\n state,\n output\n );\n }\n }\n }\n\n // Mark this function search as processed in the cache\n processFunctionCache.set(cacheKey, found);\n } catch {\n // Silently skip files that can't be parsed or accessed\n // Still mark as processed to avoid retrying failed parses\n processFunctionCache.set(cacheKey, false);\n }\n}\n\n/**\n * Main entry point for parsing translation strings from useGT() and getGT() calls.\n *\n * Supports complex patterns including:\n * 1. Direct calls: const gt = useGT(); gt('hello');\n * 2. Translation callback prop drilling: const gt = useGT(); getInfo(gt); where getInfo uses gt() internally\n * 3. Cross-file function calls: imported functions that receive the translation callback as a parameter\n *\n * Example flow:\n * - const gt = useGT();\n * - const { home } = getInfo(gt); // getInfo is imported from './constants'\n * - This will parse constants.ts to find translation calls within getInfo function\n */\nexport function parseStrings(\n importName: string,\n originalName: string,\n path: NodePath,\n config: ParsingConfig,\n output: ParsingOutput\n): void {\n // Handle global t macro directly — path is already the tag identifier\n // NOTE: if we decide to add support for a global t() function in addition to the macro,\n // then we need to add support for skipDeriveInvocation here\n if (originalName === T_GLOBAL_REGISTRATION_FUNCTION_MARKER) {\n if (!config.ignoreGlobalTaggedTemplates) {\n processTaggedTemplateCall(\n path,\n {\n ...config,\n autoderiveMethod:\n config.autoderiveMethod === 'AUTO'\n ? 'DISABLED'\n : config.autoderiveMethod,\n },\n output\n );\n }\n return;\n }\n\n // First, collect all imports in this file to track cross-file function calls\n const importMap = buildImportMap(path.scope.getProgramParent().path);\n\n const referencePaths = path.scope.bindings[importName]?.referencePaths || [];\n\n for (const refPath of referencePaths) {\n // Handle msg(), t() calls directly without variable assignment\n if (\n STRING_REGISTRATION_FUNCS.includes(\n originalName as (typeof STRING_REGISTRATION_FUNCS)[number]\n )\n ) {\n const stringRegistrationConfig: ParsingConfig = {\n parsingOptions: config.parsingOptions,\n file: config.file,\n ignoreInlineMetadata: false,\n ignoreDynamicContent: false,\n ignoreInvalidIcu: false,\n ignoreInlineListContent: false,\n includeSourceCodeContext: config.includeSourceCodeContext,\n ignoreTaggedTemplates: false,\n ignoreGlobalTaggedTemplates: false,\n // User configurable, otherwise default to AUTO\n autoderiveMethod:\n config.autoderiveMethod === 'AUTO'\n ? 'DISABLED'\n : config.autoderiveMethod,\n };\n\n // Check if this is a direct call to msg('string') or t('string')\n if (\n refPath.parent.type === 'CallExpression' &&\n refPath.parent.callee === refPath.node\n ) {\n /**\n * CASE: Autoderive t() and msg() function\n * The t() function, will treat variable content as if it was marked for derivation\n * without explicit calls to derive().\n *\n * @example\n * const derivedValue = 'John';\n * const interpolatedValue = \"Ernest\"\n * t(\n * \"Hello, \" + derivedValue + \"! My name is {interpolatedValue}\",\n * { interpolatedValue }\n * );\n * // \"Hello, John! My name is {interpolatedValue}\"\n */\n processTranslationCall(\n refPath,\n config.autoderiveMethod === 'AUTO'\n ? {\n ...stringRegistrationConfig,\n autoderiveMethod: 'ENABLED',\n }\n : stringRegistrationConfig,\n output\n );\n } else if (\n !stringRegistrationConfig.ignoreTaggedTemplates &&\n refPath.parent.type === 'TaggedTemplateExpression' &&\n refPath.parent.tag === refPath.node\n ) {\n // Tagged template: t`hello ${name}`\n processTaggedTemplateCall(refPath, stringRegistrationConfig, output);\n }\n continue;\n }\n\n // Handle useGT(), getGT(), useMessages(), and getMessages() calls that need variable assignment\n const callExpr = refPath.findParent((p) => p.isCallExpression());\n if (callExpr) {\n // Get the parent, handling both await and non-await cases\n const parentPath = callExpr.parentPath;\n\n const parentFunction = refPath.getFunctionParent();\n const asyncScope = parentFunction?.node.async;\n if (\n asyncScope &&\n (originalName === INLINE_TRANSLATION_HOOK ||\n originalName === INLINE_MESSAGE_HOOK)\n ) {\n output.errors.push(\n warnAsyncUseGT(\n config.file,\n `${refPath.node.loc?.start?.line}:${refPath.node.loc?.start?.column}`\n )\n );\n return;\n } else if (\n !asyncScope &&\n (originalName === INLINE_TRANSLATION_HOOK_ASYNC ||\n originalName === INLINE_MESSAGE_HOOK_ASYNC)\n ) {\n output.errors.push(\n warnSyncGetGT(\n config.file,\n `${refPath.node.loc?.start?.line}:${refPath.node.loc?.start?.column}`\n )\n );\n return;\n }\n\n const isMessageHook =\n originalName === INLINE_MESSAGE_HOOK ||\n originalName === INLINE_MESSAGE_HOOK_ASYNC;\n const isInlineGT =\n originalName === INLINE_TRANSLATION_HOOK ||\n originalName === INLINE_TRANSLATION_HOOK_ASYNC;\n const hookConfig: ParsingConfig = {\n parsingOptions: config.parsingOptions,\n file: config.file,\n ignoreInlineMetadata: isMessageHook,\n ignoreDynamicContent: isMessageHook,\n ignoreInvalidIcu: isMessageHook,\n // TODO: when we add support for array content in gt function, this should just always be false\n ignoreInlineListContent: isInlineGT,\n includeSourceCodeContext: config.includeSourceCodeContext,\n ignoreTaggedTemplates: false,\n ignoreGlobalTaggedTemplates: false,\n // User configurable, otherwise default to DISABLED\n autoderiveMethod:\n config.autoderiveMethod === 'AUTO'\n ? isInlineGT\n ? 'ENABLED'\n : 'DISABLED'\n : config.autoderiveMethod,\n };\n\n const effectiveParent =\n parentPath?.node.type === 'AwaitExpression'\n ? parentPath.parentPath\n : parentPath;\n if (\n effectiveParent &&\n effectiveParent.node.type === 'VariableDeclarator' &&\n effectiveParent.node.id.type === 'Identifier'\n ) {\n const tFuncName = effectiveParent.node.id.name;\n // Get the scope from the variable declaration\n const variableScope = effectiveParent.scope;\n\n // Resolve all aliases of the translation function\n // Example: translate -> [translate, t, a, b] for const t = translate; const a = t; const b = a;\n const allTranslationNames = resolveVariableAliases(\n variableScope,\n tFuncName\n );\n\n // Process references for all translation function names and their aliases\n const visitedFunctions = new Set<t.Node>();\n allTranslationNames.forEach((name) => {\n const tReferencePaths =\n variableScope.bindings[name]?.referencePaths || [];\n\n for (const tPath of tReferencePaths) {\n handleFunctionCall(\n tPath,\n hookConfig,\n { visited: new Set(), importMap },\n output,\n visitedFunctions\n );\n }\n });\n }\n }\n }\n}\n"],"mappings":";;;;;;;;;;;AAkBA,MAAM,WAAW,eAAe,WAAW;;;;;;AAmB3C,MAAM,yCAAyB,IAAI,KAA4B;;;;;;AAO/D,MAAM,uCAAuB,IAAI,KAAsB;;;;AAKvD,SAAgB,qBAA2B;AACzC,wBAAuB,OAAO;AAC9B,sBAAqB,OAAO;;;;;AAM9B,SAAS,qBAAqB,OAA8B;AAC1D,KAAI,EAAE,aAAa,MAAM,CACvB,QAAO,MAAM;AAGf,KAAI,EAAE,oBAAoB,MAAM,IAAI,EAAE,aAAa,MAAM,KAAK,CAC5D,QAAO,MAAM,KAAK;AAEpB,QAAO;;;;;;;;;;;AAYT,SAAgB,uBACd,OACA,cACA,0BAAuB,IAAI,KAAK,EACtB;AACV,KAAI,QAAQ,IAAI,aAAa,CAC3B,QAAO,EAAE;AAEX,SAAQ,IAAI,aAAa;CAEzB,MAAM,UAAU,CAAC,aAAa;AAG9B,KAFgB,MAAM,SAAS,cAK7B,MAAK,MAAM,CAAC,cAAc,iBAAiB,OAAO,QAAQ,MAAM,SAAS,EAAE;AACzE,MAAI,iBAAiB,gBAAgB,QAAQ,IAAI,aAAa,CAAE;EAEhE,MAAM,oBAAoB;AAC1B,MACE,kBAAkB,QAClB,kBAAkB,KAAK,sBAAsB,IAC7C,kBAAkB,KAAK,KAAK,QAC5B,EAAE,aAAa,kBAAkB,KAAK,KAAK,KAAK,IAChD,kBAAkB,KAAK,KAAK,KAAK,SAAS,cAC1C;GAEA,MAAM,gBAAgB,uBACpB,OACA,cACA,QACD;AACD,WAAQ,KAAK,GAAG,cAAc;;;AAKpC,QAAO;;;;;;;AAQT,SAAS,mBACP,OACA,QACA,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O,SAC9D,CACF;AACD;cAEA,CAAC,eACA,iBAAA,WACC,iBAAA,gBACF;AACA,WAAO,OAAO,KACZ,cACE,OAAO,MACP,GAAG,QAAQ,KAAK,KAAK,OAAO,KAAK,GAAG,QAAQ,KAAK,KAAK,OAAO,SAC9D,CACF;AACD;;GAGF,MAAM,gBACJ,iBAAA,iBACA,iBAAA;GACF,MAAM,aACJ,iBAAA,WACA,iBAAA;GACF,MAAM,aAA4B;IAChC,gBAAgB,OAAO;IACvB,MAAM,OAAO;IACb,sBAAsB;IACtB,sBAAsB;IACtB,kBAAkB;IAElB,yBAAyB;IACzB,0BAA0B,OAAO;IACjC,uBAAuB;IACvB,6BAA6B;IAE7B,kBACE,OAAO,qBAAqB,SACxB,aACE,YACA,aACF,OAAO;IACd;GAED,MAAM,kBACJ,YAAY,KAAK,SAAS,oBACtB,WAAW,aACX;AACN,OACE,mBACA,gBAAgB,KAAK,SAAS,wBAC9B,gBAAgB,KAAK,GAAG,SAAS,cACjC;IACA,MAAM,YAAY,gBAAgB,KAAK,GAAG;IAE1C,MAAM,gBAAgB,gBAAgB;IAItC,MAAM,sBAAsB,uBAC1B,eACA,UACD;IAGD,MAAM,mCAAmB,IAAI,KAAa;AAC1C,wBAAoB,SAAS,SAAS;KACpC,MAAM,kBACJ,cAAc,SAAS,OAAO,kBAAkB,EAAE;AAEpD,UAAK,MAAM,SAAS,gBAClB,oBACE,OACA,YACA;MAAE,yBAAS,IAAI,KAAK;MAAE;MAAW,EACjC,QACA,iBACD;MAEH"}
|
|
@@ -2,9 +2,24 @@ import { Updates } from '../../types/index.js';
|
|
|
2
2
|
import type { ParsingConfigOptions, GTParsingFlags } from '../../types/parsing.js';
|
|
3
3
|
import { GTLibrary } from '../../types/libraries.js';
|
|
4
4
|
import { dedupeUpdates } from '../../extraction/postProcess.js';
|
|
5
|
+
import { type ScanResult } from './scanFiles.js';
|
|
5
6
|
export declare function createInlineUpdates(pkg: GTLibrary, validate: boolean, filePatterns: string[] | undefined, parsingFlags: GTParsingFlags, parsingOptions: ParsingConfigOptions): Promise<{
|
|
6
7
|
updates: Updates;
|
|
7
8
|
errors: string[];
|
|
8
9
|
warnings: string[];
|
|
9
10
|
}>;
|
|
11
|
+
/**
|
|
12
|
+
* Joins the results of a scan, given in file order, into what one pass over
|
|
13
|
+
* every file gives.
|
|
14
|
+
*
|
|
15
|
+
* A thread remembers the functions it resolved in other files, so it reports
|
|
16
|
+
* what such a function yields once, at its first caller. Several threads each
|
|
17
|
+
* report it. Everything is therefore kept once, at its first place in file
|
|
18
|
+
* order: errors, warnings and locations here, updates by hash below.
|
|
19
|
+
*/
|
|
20
|
+
export declare function collectScanResults(results: readonly ScanResult[]): Promise<{
|
|
21
|
+
updates: Updates;
|
|
22
|
+
errors: string[];
|
|
23
|
+
warnings: string[];
|
|
24
|
+
}>;
|
|
10
25
|
export { dedupeUpdates as _test_dedupeUpdates };
|
|
@@ -1,132 +1,52 @@
|
|
|
1
1
|
import { logger } from "../../console/logger.js";
|
|
2
|
-
import { GT_LIBRARIES_UPSTREAM, REACT_LIBRARIES } from "../../types/libraries.js";
|
|
3
|
-
import "../jsx/utils/constants.js";
|
|
4
2
|
import { warnDeprecatedTSugarPropsSync } from "../../console/index.js";
|
|
5
|
-
import { getPathsAndAliases } from "../jsx/utils/getPathsAndAliases.js";
|
|
6
|
-
import { autoInsertJsxComponents, ensureTAndVarImported } from "../jsx/utils/jsxParsing/autoInsertion.js";
|
|
7
|
-
import { parseTranslationComponent } from "../jsx/utils/jsxParsing/parseJsx.js";
|
|
8
|
-
import { parseStrings } from "../jsx/utils/parseStringFunction.js";
|
|
9
3
|
import { matchFiles } from "../../fs/matchFiles.js";
|
|
10
4
|
import { DEFAULT_SRC_PATTERNS } from "../../config/generateSettings.js";
|
|
11
|
-
import { resolveAutoderive } from "../../types/parsing.js";
|
|
12
5
|
import { calculateHashes, dedupeUpdates, linkDeriveUpdates } from "../../extraction/postProcess.js";
|
|
13
|
-
import
|
|
14
|
-
import { parse } from "@babel/parser";
|
|
15
|
-
import traverseModule from "@babel/traverse";
|
|
6
|
+
import { scanFilesInMainThread, scanFilesInThreads, scanThreads } from "./scanPool.js";
|
|
16
7
|
//#region src/react/parse/createInlineUpdates.ts
|
|
17
|
-
const traverse = traverseModule.default || traverseModule;
|
|
18
8
|
async function createInlineUpdates(pkg, validate, filePatterns, parsingFlags, parsingOptions) {
|
|
9
|
+
const files = matchFiles(process.cwd(), filePatterns || DEFAULT_SRC_PATTERNS);
|
|
10
|
+
const context = {
|
|
11
|
+
pkg,
|
|
12
|
+
parsingFlags,
|
|
13
|
+
parsingOptions
|
|
14
|
+
};
|
|
15
|
+
const threads = parsingFlags.enableAutoJsxInjection || parsingFlags.includeSourceCodeContext ? 0 : scanThreads(files.length);
|
|
16
|
+
return collectScanResults(threads > 0 ? await scanFilesInThreads(files, context, threads) : await scanFilesInMainThread(files, context));
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Joins the results of a scan, given in file order, into what one pass over
|
|
20
|
+
* every file gives.
|
|
21
|
+
*
|
|
22
|
+
* A thread remembers the functions it resolved in other files, so it reports
|
|
23
|
+
* what such a function yields once, at its first caller. Several threads each
|
|
24
|
+
* report it. Everything is therefore kept once, at its first place in file
|
|
25
|
+
* order: errors, warnings and locations here, updates by hash below.
|
|
26
|
+
*/
|
|
27
|
+
async function collectScanResults(results) {
|
|
19
28
|
const updates = [];
|
|
20
|
-
const errors =
|
|
29
|
+
const errors = /* @__PURE__ */ new Set();
|
|
21
30
|
const warnings = /* @__PURE__ */ new Set();
|
|
22
|
-
const sugarPropLocations =
|
|
23
|
-
const
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
const
|
|
28
|
-
|
|
29
|
-
try {
|
|
30
|
-
ast = parse(code, {
|
|
31
|
-
sourceType: "module",
|
|
32
|
-
plugins: ["jsx", "typescript"]
|
|
33
|
-
});
|
|
34
|
-
} catch (error) {
|
|
35
|
-
logger.error(`Error parsing file ${file}: ${error}`);
|
|
36
|
-
continue;
|
|
37
|
-
}
|
|
38
|
-
const { importAliases, inlineTranslationPaths, translationComponentPaths } = getPathsAndAliases(ast, pkgs);
|
|
39
|
-
for (const { localName: name, originalName, path } of inlineTranslationPaths) parseStrings(name, originalName, path, {
|
|
40
|
-
parsingOptions,
|
|
41
|
-
file,
|
|
42
|
-
ignoreInlineMetadata: false,
|
|
43
|
-
ignoreDynamicContent: false,
|
|
44
|
-
ignoreInvalidIcu: false,
|
|
45
|
-
ignoreInlineListContent: false,
|
|
46
|
-
includeSourceCodeContext: parsingFlags.includeSourceCodeContext,
|
|
47
|
-
ignoreTaggedTemplates: false,
|
|
48
|
-
ignoreGlobalTaggedTemplates: false,
|
|
49
|
-
autoderiveMethod: autoderive.strings ? "AUTO" : "DISABLED"
|
|
50
|
-
}, {
|
|
51
|
-
updates,
|
|
52
|
-
errors,
|
|
53
|
-
warnings
|
|
54
|
-
});
|
|
55
|
-
if (REACT_LIBRARIES.includes(pkg)) {
|
|
56
|
-
for (const { localName, path } of translationComponentPaths) parseTranslationComponent({
|
|
57
|
-
originalName: localName,
|
|
58
|
-
localName,
|
|
59
|
-
path,
|
|
60
|
-
updates,
|
|
61
|
-
config: {
|
|
62
|
-
importAliases,
|
|
63
|
-
parsingOptions,
|
|
64
|
-
pkgs,
|
|
65
|
-
file,
|
|
66
|
-
includeSourceCodeContext: parsingFlags.includeSourceCodeContext,
|
|
67
|
-
autoderive: autoderive.jsx
|
|
68
|
-
},
|
|
69
|
-
output: {
|
|
70
|
-
errors,
|
|
71
|
-
warnings,
|
|
72
|
-
unwrappedExpressions: [],
|
|
73
|
-
sugarPropLocations
|
|
74
|
-
}
|
|
75
|
-
});
|
|
76
|
-
if (parsingFlags.enableAutoJsxInjection) {
|
|
77
|
-
for (const { localName, originalName } of translationComponentPaths) importAliases[localName] = originalName;
|
|
78
|
-
ensureTAndVarImported(ast, importAliases, parsingFlags.legacyGtReactImportSource);
|
|
79
|
-
autoInsertJsxComponents(ast, importAliases);
|
|
80
|
-
traverse(ast, { Program(programPath) {
|
|
81
|
-
programPath.scope.crawl();
|
|
82
|
-
} });
|
|
83
|
-
const refreshed = getPathsAndAliases(ast, pkgs);
|
|
84
|
-
for (const { localName: tLocalName, originalName: tOrigName } of refreshed.translationComponentPaths) refreshed.importAliases[tLocalName] = tOrigName;
|
|
85
|
-
for (const { localName, path, originalName } of refreshed.translationComponentPaths) {
|
|
86
|
-
if (originalName !== "GtInternalTranslateJsx") continue;
|
|
87
|
-
parseTranslationComponent({
|
|
88
|
-
originalName: localName,
|
|
89
|
-
localName,
|
|
90
|
-
path,
|
|
91
|
-
updates,
|
|
92
|
-
config: {
|
|
93
|
-
importAliases: refreshed.importAliases,
|
|
94
|
-
parsingOptions,
|
|
95
|
-
pkgs,
|
|
96
|
-
file,
|
|
97
|
-
includeSourceCodeContext: parsingFlags.includeSourceCodeContext,
|
|
98
|
-
enableAutoJsxInjection: true,
|
|
99
|
-
autoderive: autoderive.jsx
|
|
100
|
-
},
|
|
101
|
-
output: {
|
|
102
|
-
errors,
|
|
103
|
-
warnings,
|
|
104
|
-
unwrappedExpressions: []
|
|
105
|
-
}
|
|
106
|
-
});
|
|
107
|
-
}
|
|
108
|
-
}
|
|
109
|
-
}
|
|
31
|
+
const sugarPropLocations = /* @__PURE__ */ new Set();
|
|
32
|
+
for (const result of results) {
|
|
33
|
+
for (const message of result.parseErrors) logger.error(message);
|
|
34
|
+
for (const update of result.updates) updates.push(update);
|
|
35
|
+
for (const error of result.errors) errors.add(error);
|
|
36
|
+
for (const warning of result.warnings) warnings.add(warning);
|
|
37
|
+
for (const location of result.sugarPropLocations) sugarPropLocations.add(location);
|
|
110
38
|
}
|
|
111
|
-
if (sugarPropLocations.
|
|
39
|
+
if (sugarPropLocations.size > 0) warnings.add(warnDeprecatedTSugarPropsSync([...sugarPropLocations]));
|
|
112
40
|
await calculateHashes(updates);
|
|
113
41
|
dedupeUpdates(updates);
|
|
114
42
|
linkDeriveUpdates(updates);
|
|
115
43
|
return {
|
|
116
44
|
updates,
|
|
117
|
-
errors,
|
|
45
|
+
errors: [...errors],
|
|
118
46
|
warnings: [...warnings]
|
|
119
47
|
};
|
|
120
48
|
}
|
|
121
|
-
/**
|
|
122
|
-
* Given a package name, return the upstream packages that it depends on
|
|
123
|
-
* @param pkg - The package name
|
|
124
|
-
* @returns The upstream packages that the package depends on
|
|
125
|
-
*/
|
|
126
|
-
function getUpstreamPackages(pkg) {
|
|
127
|
-
return GT_LIBRARIES_UPSTREAM[pkg];
|
|
128
|
-
}
|
|
129
49
|
//#endregion
|
|
130
|
-
export { dedupeUpdates as _test_dedupeUpdates, createInlineUpdates };
|
|
50
|
+
export { dedupeUpdates as _test_dedupeUpdates, collectScanResults, createInlineUpdates };
|
|
131
51
|
|
|
132
52
|
//# sourceMappingURL=createInlineUpdates.js.map
|