gtx-cli 2.4.14 → 2.5.0-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/CHANGELOG.md +0 -7
  2. package/dist/console/colors.d.ts +1 -0
  3. package/dist/console/colors.js +3 -0
  4. package/dist/console/index.d.ts +6 -0
  5. package/dist/console/index.js +13 -2
  6. package/dist/react/jsx/evaluateJsx.d.ts +5 -6
  7. package/dist/react/jsx/evaluateJsx.js +32 -4
  8. package/dist/react/jsx/utils/buildImportMap.d.ts +9 -0
  9. package/dist/react/jsx/utils/buildImportMap.js +30 -0
  10. package/dist/react/jsx/utils/constants.d.ts +2 -0
  11. package/dist/react/jsx/utils/constants.js +11 -2
  12. package/dist/react/jsx/utils/getPathsAndAliases.d.ts +17 -0
  13. package/dist/react/jsx/utils/getPathsAndAliases.js +89 -0
  14. package/dist/react/{data-_gt → jsx/utils/jsxParsing}/addGTIdentifierToSyntaxTree.d.ts +2 -1
  15. package/dist/react/{data-_gt → jsx/utils/jsxParsing}/addGTIdentifierToSyntaxTree.js +30 -6
  16. package/dist/react/jsx/utils/jsxParsing/handleChildrenWhitespace.d.ts +6 -0
  17. package/dist/react/jsx/utils/jsxParsing/handleChildrenWhitespace.js +199 -0
  18. package/dist/react/jsx/utils/jsxParsing/multiplication/findMultiplicationNode.d.ts +13 -0
  19. package/dist/react/jsx/utils/jsxParsing/multiplication/findMultiplicationNode.js +42 -0
  20. package/dist/react/jsx/utils/jsxParsing/multiplication/multiplyJsxTree.d.ts +5 -0
  21. package/dist/react/jsx/utils/jsxParsing/multiplication/multiplyJsxTree.js +69 -0
  22. package/dist/react/jsx/utils/jsxParsing/parseJsx.d.ts +60 -0
  23. package/dist/react/jsx/utils/jsxParsing/parseJsx.js +949 -0
  24. package/dist/react/jsx/utils/jsxParsing/parseTProps.d.ts +8 -0
  25. package/dist/react/jsx/utils/jsxParsing/parseTProps.js +47 -0
  26. package/dist/react/jsx/utils/jsxParsing/types.d.ts +48 -0
  27. package/dist/react/jsx/utils/jsxParsing/types.js +34 -0
  28. package/dist/react/jsx/utils/parseStringFunction.js +4 -141
  29. package/dist/react/jsx/utils/resolveImportPath.d.ts +11 -0
  30. package/dist/react/jsx/utils/resolveImportPath.js +111 -0
  31. package/dist/react/parse/createInlineUpdates.js +19 -70
  32. package/package.json +2 -2
  33. package/dist/react/jsx/trimJsxStringChildren.d.ts +0 -7
  34. package/dist/react/jsx/trimJsxStringChildren.js +0 -122
  35. package/dist/react/jsx/utils/parseJsx.d.ts +0 -21
  36. package/dist/react/jsx/utils/parseJsx.js +0 -259
@@ -0,0 +1,949 @@
1
+ import generateModule from '@babel/generator';
2
+ // Handle CommonJS/ESM interop
3
+ const generate = generateModule.default || generateModule;
4
+ import * as t from '@babel/types';
5
+ import fs from 'node:fs';
6
+ import { parse } from '@babel/parser';
7
+ import addGTIdentifierToSyntaxTree from './addGTIdentifierToSyntaxTree.js';
8
+ import { warnHasUnwrappedExpressionSync, warnNestedTComponent, warnInvalidStaticChildSync, warnInvalidReturnSync as warnInvalidReturnExpressionSync, warnFunctionNotFoundSync, warnMissingReturnSync, warnDuplicateFunctionDefinitionSync, warnInvalidStaticInitSync, } from '../../../../console/index.js';
9
+ import { isAcceptedPluralForm } from 'generaltranslation/internal';
10
+ import { isStaticExpression } from '../../evaluateJsx.js';
11
+ import { STATIC_COMPONENT, TRANSLATION_COMPONENT, VARIABLE_COMPONENTS, } from '../constants.js';
12
+ import { HTML_CONTENT_PROPS } from 'generaltranslation/types';
13
+ import { resolveImportPath } from '../resolveImportPath.js';
14
+ import traverseModule from '@babel/traverse';
15
+ import { buildImportMap } from '../buildImportMap.js';
16
+ import { getPathsAndAliases } from '../getPathsAndAliases.js';
17
+ import { parseTProps } from './parseTProps.js';
18
+ import { handleChildrenWhitespace } from './handleChildrenWhitespace.js';
19
+ import { isElementNode, } from './types.js';
20
+ import { multiplyJsxTree } from './multiplication/multiplyJsxTree.js';
21
+ // Handle CommonJS/ESM interop
22
+ const traverse = traverseModule.default || traverseModule;
23
+ // TODO: currently we cover VariableDeclaration and FunctionDeclaration nodes, but are there others we should cover as well?
24
+ /**
25
+ * Cache for resolved import paths to avoid redundant I/O operations.
26
+ * Key: `${currentFile}::${importPath}`
27
+ * Value: resolved absolute path or null
28
+ */
29
+ const resolveImportPathCache = new Map();
30
+ /**
31
+ * Cache for processed functions to avoid re-parsing the same files.
32
+ * Key: `${filePath}::${functionName}::${argIndex}`
33
+ * Value: boolean indicating whether the function was found and processed
34
+ */
35
+ const processFunctionCache = new Map();
36
+ /**
37
+ * Entry point for JSX parsing
38
+ */
39
+ export function parseTranslationComponent({ originalName, importAliases, localName, path, updates, errors, warnings, file, parsingOptions, pkg, }) {
40
+ // First, collect all imports in this file to track cross-file function calls
41
+ const importedFunctionsMap = buildImportMap(path.scope.getProgramParent().path);
42
+ const referencePaths = path.scope.bindings[localName]?.referencePaths || [];
43
+ for (const refPath of referencePaths) {
44
+ // Only start at opening tag
45
+ if (!t.isJSXOpeningElement(refPath.parent) ||
46
+ !refPath.parentPath?.parentPath) {
47
+ continue;
48
+ }
49
+ // Get the JSX element NodePath
50
+ const jsxElementPath = refPath.parentPath
51
+ ?.parentPath;
52
+ // Parse <T> component
53
+ parseJSXElement({
54
+ scopeNode: jsxElementPath,
55
+ node: jsxElementPath.node,
56
+ pkg,
57
+ originalName,
58
+ importAliases,
59
+ updates,
60
+ errors,
61
+ warnings,
62
+ file,
63
+ parsingOptions,
64
+ importedFunctionsMap,
65
+ });
66
+ }
67
+ }
68
+ /**
69
+ * Builds a JSX tree from a given node, recursively handling children.
70
+ * @param node - The node to build the tree from
71
+ * @param unwrappedExpressions - An array to store unwrapped expressions
72
+ * @param updates - The updates array
73
+ * @param errors - The errors array
74
+ * @param file - The file name
75
+ * @param insideT - Whether the current node is inside a <T> component
76
+ * @returns The built JSX tree
77
+ */
78
+ export function buildJSXTree({ importAliases, node, unwrappedExpressions, visited, updates, errors, warnings, file, insideT, parsingOptions, scopeNode, importedFunctionsMap, pkg, }) {
79
+ if (t.isJSXExpressionContainer(node)) {
80
+ // Skip JSX comments
81
+ if (t.isJSXEmptyExpression(node.expression)) {
82
+ return null;
83
+ }
84
+ const expr = node.expression;
85
+ if (t.isJSXElement(expr)) {
86
+ return buildJSXTree({
87
+ importAliases,
88
+ node: expr,
89
+ unwrappedExpressions,
90
+ visited,
91
+ updates,
92
+ errors: errors,
93
+ warnings: warnings,
94
+ file,
95
+ insideT,
96
+ parsingOptions,
97
+ scopeNode,
98
+ importedFunctionsMap,
99
+ pkg,
100
+ });
101
+ }
102
+ const staticAnalysis = isStaticExpression(expr, true);
103
+ if (staticAnalysis.isStatic && staticAnalysis.value !== undefined) {
104
+ // Preserve the exact whitespace for static string expressions
105
+ return {
106
+ nodeType: 'expression',
107
+ result: staticAnalysis.value,
108
+ };
109
+ }
110
+ // Keep existing behavior for non-static expressions
111
+ const code = generate(node).code;
112
+ unwrappedExpressions.push(code); // Keep track of unwrapped expressions for error reporting
113
+ return code;
114
+ }
115
+ else if (t.isJSXText(node)) {
116
+ // Updated JSX Text handling
117
+ // JSX Text handling following React's rules
118
+ const text = node.value;
119
+ return text;
120
+ }
121
+ else if (t.isJSXElement(node)) {
122
+ const element = node;
123
+ const elementName = element.openingElement.name;
124
+ let typeName;
125
+ if (t.isJSXIdentifier(elementName)) {
126
+ typeName = elementName.name;
127
+ }
128
+ else if (t.isJSXMemberExpression(elementName)) {
129
+ typeName = generate(elementName).code;
130
+ }
131
+ else {
132
+ typeName = null;
133
+ }
134
+ // Convert from alias to original name
135
+ const componentType = importAliases[typeName ?? ''];
136
+ if (componentType === TRANSLATION_COMPONENT && insideT) {
137
+ // Add warning: Nested <T> components are allowed, but they are advised against
138
+ warnings.add(warnNestedTComponent(file, `${element.loc?.start?.line}:${element.loc?.start?.column}`));
139
+ }
140
+ // If this JSXElement is one of the recognized variable components,
141
+ const elementIsVariable = VARIABLE_COMPONENTS.includes(componentType);
142
+ const props = {};
143
+ const elementIsPlural = componentType === 'Plural';
144
+ const elementIsBranch = componentType === 'Branch';
145
+ element.openingElement.attributes.forEach((attr) => {
146
+ if (t.isJSXAttribute(attr)) {
147
+ const attrName = attr.name.name;
148
+ let attrValue = null;
149
+ if (attr.value) {
150
+ if (t.isStringLiteral(attr.value)) {
151
+ attrValue = attr.value.value;
152
+ }
153
+ else if (t.isJSXExpressionContainer(attr.value)) {
154
+ // Check if this is an HTML content prop (title, placeholder, alt, etc.)
155
+ const isHtmlContentProp = Object.values(HTML_CONTENT_PROPS).includes(attrName);
156
+ if (isHtmlContentProp) {
157
+ // For HTML content props, only accept static string expressions
158
+ const staticAnalysis = isStaticExpression(attr.value.expression, true);
159
+ if (staticAnalysis.isStatic &&
160
+ staticAnalysis.value !== undefined) {
161
+ attrValue = staticAnalysis.value;
162
+ }
163
+ // Otherwise attrValue stays null and won't be included
164
+ }
165
+ else {
166
+ // For non-HTML-content props, validate plural/branch then build tree
167
+ if ((elementIsPlural && isAcceptedPluralForm(attrName)) ||
168
+ (elementIsBranch && attrName !== 'branch')) {
169
+ // Make sure that variable strings like {`I have ${count} book`} are invalid!
170
+ if (t.isTemplateLiteral(attr.value.expression) &&
171
+ !isStaticExpression(attr.value.expression, true).isStatic) {
172
+ unwrappedExpressions.push(generate(attr.value).code);
173
+ }
174
+ // If it's an array, flag as an unwrapped expression
175
+ if (t.isArrayExpression(attr.value.expression)) {
176
+ unwrappedExpressions.push(generate(attr.value.expression).code);
177
+ }
178
+ }
179
+ attrValue = buildJSXTree({
180
+ importAliases,
181
+ node: attr.value.expression,
182
+ unwrappedExpressions,
183
+ visited,
184
+ updates,
185
+ errors: errors,
186
+ warnings: warnings,
187
+ file: file,
188
+ insideT: true,
189
+ parsingOptions,
190
+ scopeNode,
191
+ importedFunctionsMap,
192
+ pkg,
193
+ });
194
+ }
195
+ }
196
+ }
197
+ props[attrName] = attrValue;
198
+ }
199
+ });
200
+ if (elementIsVariable) {
201
+ if (componentType === STATIC_COMPONENT) {
202
+ return resolveStaticComponentChildren({
203
+ importAliases,
204
+ scopeNode,
205
+ children: element.children,
206
+ unwrappedExpressions,
207
+ visited,
208
+ updates,
209
+ errors,
210
+ warnings,
211
+ file,
212
+ parsingOptions,
213
+ importedFunctionsMap,
214
+ pkg,
215
+ props,
216
+ });
217
+ }
218
+ // I do not see why this is being called, i am disabling this for now:
219
+ // parseJSXElement({
220
+ // importAliases,
221
+ // node: element,
222
+ // updates,
223
+ // errors,
224
+ // warnings,
225
+ // file,
226
+ // parsingOptions,
227
+ // });
228
+ return {
229
+ nodeType: 'element',
230
+ // if componentType is undefined, use typeName
231
+ // Basically, if componentType is not a GT component, use typeName such as <div>
232
+ type: componentType ?? typeName ?? '',
233
+ props,
234
+ };
235
+ }
236
+ const children = element.children
237
+ .map((child) => buildJSXTree({
238
+ importAliases,
239
+ node: child,
240
+ unwrappedExpressions,
241
+ visited,
242
+ updates,
243
+ errors,
244
+ warnings,
245
+ file,
246
+ insideT: true,
247
+ parsingOptions,
248
+ scopeNode,
249
+ importedFunctionsMap,
250
+ pkg,
251
+ }))
252
+ .filter((child) => child !== null && child !== '');
253
+ if (children.length === 1) {
254
+ props.children = children[0];
255
+ }
256
+ else if (children.length > 1) {
257
+ props.children = children;
258
+ }
259
+ return {
260
+ nodeType: 'element',
261
+ // if componentType is undefined, use typeName
262
+ // Basically, if componentType is not a GT component, use typeName such as <div>
263
+ type: componentType ?? typeName,
264
+ props,
265
+ };
266
+ }
267
+ // If it's a JSX fragment
268
+ else if (t.isJSXFragment(node)) {
269
+ const children = node.children
270
+ .map((child) => buildJSXTree({
271
+ importAliases,
272
+ node: child,
273
+ unwrappedExpressions,
274
+ visited,
275
+ updates,
276
+ errors,
277
+ warnings,
278
+ file,
279
+ insideT: true,
280
+ parsingOptions,
281
+ scopeNode,
282
+ importedFunctionsMap,
283
+ pkg,
284
+ }))
285
+ .filter((child) => child !== null && child !== '');
286
+ const props = {};
287
+ if (children.length === 1) {
288
+ props.children = children[0];
289
+ }
290
+ else if (children.length > 1) {
291
+ props.children = children;
292
+ }
293
+ return {
294
+ nodeType: 'element',
295
+ type: '',
296
+ props,
297
+ };
298
+ }
299
+ // If it's a string literal (standalone)
300
+ else if (t.isStringLiteral(node)) {
301
+ return node.value;
302
+ }
303
+ // If it's a template literal
304
+ else if (t.isTemplateLiteral(node)) {
305
+ // We've already checked that it's static, and and added a warning if it's not, this check is just for fallback behavior
306
+ if (!isStaticExpression(node, true).isStatic ||
307
+ node.quasis[0].value.cooked === undefined) {
308
+ return generate(node).code;
309
+ }
310
+ return node.quasis[0].value.cooked;
311
+ }
312
+ else if (t.isNullLiteral(node)) {
313
+ // If it's null, return null
314
+ return null;
315
+ }
316
+ else if (t.isBooleanLiteral(node)) {
317
+ // If it's a boolean, return the boolean
318
+ return node.value;
319
+ }
320
+ else if (t.isNumericLiteral(node)) {
321
+ // If it's a number, return the number
322
+ return node.value.toString();
323
+ }
324
+ // Negative
325
+ else if (t.isUnaryExpression(node)) {
326
+ // If it's a unary expression, return the expression
327
+ const staticAnalysis = isStaticExpression(node, true);
328
+ if (staticAnalysis.isStatic && staticAnalysis.value !== undefined) {
329
+ return staticAnalysis.value;
330
+ }
331
+ return generate(node).code;
332
+ }
333
+ // If it's some other JS expression
334
+ else if (t.isIdentifier(node) ||
335
+ t.isMemberExpression(node) ||
336
+ t.isCallExpression(node) ||
337
+ t.isBinaryExpression(node) ||
338
+ t.isLogicalExpression(node) ||
339
+ t.isConditionalExpression(node)) {
340
+ return generate(node).code;
341
+ }
342
+ else {
343
+ return generate(node).code;
344
+ }
345
+ }
346
+ // end buildJSXTree
347
+ // Parses a JSX element and adds it to the updates array
348
+ export function parseJSXElement({ importAliases, node, originalName, pkg, updates, errors, warnings, file, parsingOptions, scopeNode, importedFunctionsMap, }) {
349
+ const openingElement = node.openingElement;
350
+ const name = openingElement.name;
351
+ // Only proceed if it's <T> ...
352
+ // TODO: i don't think this condition is needed anymore
353
+ if (!(name.type === 'JSXIdentifier' && originalName === TRANSLATION_COMPONENT)) {
354
+ return;
355
+ }
356
+ const componentErrors = [];
357
+ const componentWarnings = new Set();
358
+ const metadata = {};
359
+ // We'll track this flag to know if any unwrapped {variable} is found in children
360
+ const unwrappedExpressions = [];
361
+ // Gather <T>'s props
362
+ parseTProps({
363
+ openingElement,
364
+ metadata,
365
+ componentErrors,
366
+ file,
367
+ });
368
+ // Build the JSX tree for this component
369
+ const treeResult = buildJSXTree({
370
+ importAliases,
371
+ node,
372
+ scopeNode,
373
+ visited: new Set(),
374
+ pkg,
375
+ unwrappedExpressions,
376
+ updates,
377
+ errors: componentErrors,
378
+ warnings: componentWarnings,
379
+ file,
380
+ insideT: false,
381
+ parsingOptions,
382
+ importedFunctionsMap,
383
+ });
384
+ // Strip the outer <T> component if necessary
385
+ const jsxTree = isElementNode(treeResult) && treeResult.props?.children
386
+ ? // We know this b/c the direct children of <T> will never be a multiplication node
387
+ treeResult.props.children
388
+ : treeResult;
389
+ // Update warnings
390
+ if (componentWarnings.size > 0) {
391
+ componentWarnings.forEach((warning) => warnings.add(warning));
392
+ }
393
+ // Update errors
394
+ if (componentErrors.length > 0) {
395
+ errors.push(...componentErrors);
396
+ return;
397
+ }
398
+ // Handle whitespace in children
399
+ const whitespaceHandledTree = handleChildrenWhitespace(jsxTree);
400
+ // Multiply the tree
401
+ const multipliedTrees = multiplyJsxTree(whitespaceHandledTree);
402
+ // Add GT identifiers to the tree
403
+ // TODO: do this in parallel
404
+ const minifiedTress = [];
405
+ for (const multipliedTree of multipliedTrees) {
406
+ const minifiedTree = addGTIdentifierToSyntaxTree(multipliedTree);
407
+ minifiedTress.push(Array.isArray(minifiedTree) && minifiedTree.length === 1
408
+ ? minifiedTree[0]
409
+ : minifiedTree);
410
+ }
411
+ // If we found an unwrapped expression, skip
412
+ if (unwrappedExpressions.length > 0) {
413
+ errors.push(warnHasUnwrappedExpressionSync(file, unwrappedExpressions, metadata.id, `${node.loc?.start?.line}:${node.loc?.start?.column}`));
414
+ return;
415
+ }
416
+ // <T> is valid here
417
+ for (const minifiedTree of minifiedTress) {
418
+ updates.push({
419
+ dataFormat: 'JSX',
420
+ source: minifiedTree,
421
+ // eslint-disable-next-line no-undef
422
+ metadata: { ...structuredClone(metadata) },
423
+ });
424
+ }
425
+ }
426
+ /**
427
+ * Resolves an invocation inside of a <Static> component. It will resolve the function, and build
428
+ * a jsx tree for each return inside of the function definition.
429
+ *
430
+ * function getOtherSubject() {
431
+ * return <div>Jane</div>;
432
+ * }
433
+ *
434
+ * function getSubject() {
435
+ * if (condition) return getOtherSubject();
436
+ * return <div>John</div>;
437
+ * }
438
+ * ...
439
+ * <Static>
440
+ * {getSubject()}
441
+ * </Static>
442
+ */
443
+ function resolveStaticComponentChildren({ importAliases, scopeNode, children, unwrappedExpressions, visited, updates, errors, warnings, file, parsingOptions, importedFunctionsMap, pkg, props, }) {
444
+ const result = {
445
+ nodeType: 'element',
446
+ type: STATIC_COMPONENT,
447
+ props,
448
+ };
449
+ let found = false;
450
+ // Create children array if necessary
451
+ if (children.length) {
452
+ result.props.children = [];
453
+ }
454
+ for (const child of children) {
455
+ // Ignore whitespace outside of jsx container
456
+ if (t.isJSXText(child) && child.value.trim() === '') {
457
+ result.props.children.push(child.value);
458
+ continue;
459
+ }
460
+ // Must be an expression container with a function invocation
461
+ if (!t.isJSXExpressionContainer(child) ||
462
+ !((t.isCallExpression(child.expression) &&
463
+ t.isIdentifier(child.expression.callee)) ||
464
+ (t.isAwaitExpression(child.expression) &&
465
+ t.isCallExpression(child.expression.argument) &&
466
+ t.isIdentifier(child.expression.argument.callee))) ||
467
+ found // There can only be one invocation inside of a <Static> component
468
+ ) {
469
+ errors.push(warnInvalidStaticChildSync(file, `${child.loc?.start?.line}:${child.loc?.start?.column}`));
470
+ continue;
471
+ }
472
+ // Set found to true
473
+ found = true;
474
+ // Get callee and binding from scope
475
+ const callee = (t.isAwaitExpression(child.expression)
476
+ ? child.expression.argument.callee
477
+ : child.expression.callee);
478
+ const calleeBinding = scopeNode.scope.getBinding(callee.name);
479
+ if (!calleeBinding) {
480
+ warnFunctionNotFoundSync(file, callee.name, `${callee.loc?.start?.line}:${callee.loc?.start?.column}`);
481
+ continue;
482
+ }
483
+ // Function is found locally, return wrapped in an expression
484
+ const staticFunctionInvocation = resolveStaticFunctionInvocationFromBinding({
485
+ importAliases,
486
+ calleeBinding,
487
+ callee,
488
+ visited,
489
+ file,
490
+ updates,
491
+ errors,
492
+ warnings,
493
+ unwrappedExpressions,
494
+ pkg,
495
+ parsingOptions,
496
+ importedFunctionsMap,
497
+ });
498
+ result.props.children.push({
499
+ nodeType: 'expression',
500
+ result: staticFunctionInvocation,
501
+ });
502
+ }
503
+ return result;
504
+ }
505
+ function resolveStaticFunctionInvocationFromBinding({ importAliases, calleeBinding, callee, unwrappedExpressions, visited, file, updates, errors, warnings, parsingOptions, importedFunctionsMap, pkg, }) {
506
+ if (calleeBinding.path.isFunctionDeclaration()) {
507
+ // Handle function declarations: function getSubject() { ... }
508
+ return processFunctionDeclarationNodePath({
509
+ importAliases,
510
+ functionName: callee.name,
511
+ path: calleeBinding.path,
512
+ unwrappedExpressions,
513
+ updates,
514
+ errors,
515
+ warnings,
516
+ visited,
517
+ file,
518
+ parsingOptions,
519
+ importedFunctionsMap,
520
+ pkg,
521
+ });
522
+ }
523
+ else if (calleeBinding.path.isVariableDeclarator() &&
524
+ calleeBinding.path.node.init &&
525
+ (t.isArrowFunctionExpression(calleeBinding.path.node.init) ||
526
+ t.isFunctionExpression(calleeBinding.path.node.init))) {
527
+ // Handle arrow functions assigned to variables: const getData = (t) => {...}
528
+ return processVariableDeclarationNodePath({
529
+ importAliases,
530
+ functionName: callee.name,
531
+ path: calleeBinding.path,
532
+ unwrappedExpressions,
533
+ updates,
534
+ pkg,
535
+ errors,
536
+ visited,
537
+ warnings,
538
+ file,
539
+ parsingOptions,
540
+ importedFunctionsMap,
541
+ });
542
+ }
543
+ else if (importedFunctionsMap.has(callee.name)) {
544
+ // Function is being imported
545
+ const importPath = importedFunctionsMap.get(callee.name);
546
+ const resolvedPath = resolveImportPath(file, importPath, parsingOptions, resolveImportPathCache);
547
+ if (resolvedPath) {
548
+ return processFunctionInFile({
549
+ filePath: resolvedPath,
550
+ functionName: callee.name,
551
+ visited,
552
+ unwrappedExpressions,
553
+ updates,
554
+ errors,
555
+ warnings,
556
+ file,
557
+ parsingOptions,
558
+ pkg,
559
+ });
560
+ }
561
+ }
562
+ warnings.add(warnFunctionNotFoundSync(file, callee.name, `${callee.loc?.start?.line}:${callee.loc?.start?.column}`));
563
+ return null;
564
+ }
565
+ /**
566
+ * Searches for a specific user-defined function in a file.
567
+ * This is the resolution logic
568
+ *
569
+ * Handles multiple function declaration patterns:
570
+ * - function getInfo() { ... }
571
+ * - export function getInfo() { ... }
572
+ * - const getInfo = () => { ... }
573
+ *
574
+ * If the function is not found in the file, follows re-exports (export * from './other')
575
+ */
576
+ function processFunctionInFile({ filePath, functionName, visited, parsingOptions, updates, errors, warnings, file, unwrappedExpressions, pkg, }) {
577
+ // Check cache first to avoid redundant parsing
578
+ const cacheKey = `${filePath}::${functionName}`;
579
+ if (processFunctionCache.has(cacheKey)) {
580
+ return null;
581
+ }
582
+ // Prevent infinite loops from circular re-exports
583
+ if (visited.has(filePath))
584
+ return null;
585
+ visited.add(filePath);
586
+ let result = undefined;
587
+ try {
588
+ const code = fs.readFileSync(filePath, 'utf8');
589
+ const ast = parse(code, {
590
+ sourceType: 'module',
591
+ plugins: ['jsx', 'typescript'],
592
+ });
593
+ const { importAliases } = getPathsAndAliases(ast, pkg);
594
+ // Collect all imports in this file to track cross-file function calls
595
+ let importedFunctionsMap;
596
+ traverse(ast, {
597
+ Program(path) {
598
+ importedFunctionsMap = buildImportMap(path);
599
+ },
600
+ });
601
+ const reExports = [];
602
+ const warnDuplicateFuncDef = (path) => {
603
+ warnings.add(warnDuplicateFunctionDefinitionSync(file, functionName, `${path.node.loc?.start?.line}:${path.node.loc?.start?.column}`));
604
+ };
605
+ traverse(ast, {
606
+ // Handle function declarations: function getInfo() { ... }
607
+ FunctionDeclaration(path) {
608
+ if (path.node.id?.name === functionName) {
609
+ if (result !== undefined)
610
+ return warnDuplicateFuncDef(path);
611
+ result = processFunctionDeclarationNodePath({
612
+ importAliases,
613
+ functionName,
614
+ path,
615
+ unwrappedExpressions,
616
+ visited,
617
+ pkg,
618
+ updates,
619
+ errors,
620
+ warnings,
621
+ file,
622
+ parsingOptions,
623
+ importedFunctionsMap,
624
+ });
625
+ }
626
+ },
627
+ // Handle variable declarations: const getInfo = () => { ... }
628
+ VariableDeclarator(path) {
629
+ if (t.isIdentifier(path.node.id) &&
630
+ path.node.id.name === functionName &&
631
+ path.node.init &&
632
+ (t.isArrowFunctionExpression(path.node.init) ||
633
+ t.isFunctionExpression(path.node.init))) {
634
+ if (result !== undefined)
635
+ return warnDuplicateFuncDef(path);
636
+ result = processVariableDeclarationNodePath({
637
+ importAliases,
638
+ functionName,
639
+ path,
640
+ pkg,
641
+ updates,
642
+ errors,
643
+ warnings,
644
+ visited,
645
+ unwrappedExpressions,
646
+ file,
647
+ parsingOptions,
648
+ importedFunctionsMap,
649
+ });
650
+ }
651
+ },
652
+ // Collect re-exports: export * from './other'
653
+ ExportAllDeclaration(path) {
654
+ if (t.isStringLiteral(path.node.source)) {
655
+ reExports.push(path.node.source.value);
656
+ }
657
+ },
658
+ // Collect named re-exports: export { foo } from './other'
659
+ ExportNamedDeclaration(path) {
660
+ if (path.node.source && t.isStringLiteral(path.node.source)) {
661
+ // Check if this export includes our function
662
+ const exportsFunction = path.node.specifiers.some((spec) => {
663
+ if (t.isExportSpecifier(spec)) {
664
+ const exportedName = t.isIdentifier(spec.exported)
665
+ ? spec.exported.name
666
+ : spec.exported.value;
667
+ return exportedName === functionName;
668
+ }
669
+ return false;
670
+ });
671
+ if (exportsFunction) {
672
+ reExports.push(path.node.source.value);
673
+ }
674
+ }
675
+ },
676
+ });
677
+ // If function not found, follow re-exports
678
+ if (result === undefined && reExports.length > 0) {
679
+ for (const reExportPath of reExports) {
680
+ const resolvedPath = resolveImportPath(filePath, reExportPath, parsingOptions, resolveImportPathCache);
681
+ if (resolvedPath) {
682
+ result = processFunctionInFile({
683
+ filePath: resolvedPath,
684
+ functionName,
685
+ unwrappedExpressions,
686
+ visited,
687
+ parsingOptions,
688
+ updates,
689
+ errors,
690
+ warnings,
691
+ file,
692
+ pkg,
693
+ });
694
+ }
695
+ }
696
+ }
697
+ // Mark this function search as processed in the cache
698
+ processFunctionCache.set(cacheKey, result !== undefined);
699
+ }
700
+ catch {
701
+ // Silently skip files that can't be parsed or accessed
702
+ // Still mark as processed to avoid retrying failed parses
703
+ processFunctionCache.set(cacheKey, false);
704
+ }
705
+ return result !== undefined ? result : null;
706
+ }
707
+ /**
708
+ * Process a function declaration
709
+ * function getInfo() { ... }
710
+ */
711
+ function processFunctionDeclarationNodePath({ functionName, path, importAliases, unwrappedExpressions, visited, updates, errors, warnings, file, parsingOptions, importedFunctionsMap, pkg, }) {
712
+ const result = {
713
+ nodeType: 'multiplication',
714
+ branches: [],
715
+ };
716
+ path.traverse({
717
+ Function(path) {
718
+ path.skip();
719
+ },
720
+ ReturnStatement(returnPath) {
721
+ const returnNodePath = returnPath.get('argument');
722
+ if (!returnNodePath.isExpression()) {
723
+ return;
724
+ }
725
+ result.branches.push(processReturnExpression({
726
+ unwrappedExpressions,
727
+ functionName,
728
+ pkg,
729
+ scopeNode: returnNodePath,
730
+ expressionNodePath: returnNodePath,
731
+ importAliases,
732
+ visited,
733
+ updates,
734
+ errors,
735
+ warnings,
736
+ file,
737
+ parsingOptions,
738
+ importedFunctionsMap,
739
+ }));
740
+ },
741
+ });
742
+ if (result.branches.length === 0) {
743
+ return null;
744
+ }
745
+ return result;
746
+ }
747
+ /**
748
+ * Process a variable declaration of a function
749
+ * const getInfo = () => { ... }
750
+ *
751
+ * IMPORTANT: the RHand value must be the function definition, or this will fail
752
+ */
753
+ function processVariableDeclarationNodePath({ functionName, path, importAliases, unwrappedExpressions, visited, updates, errors, warnings, file, parsingOptions, importedFunctionsMap, pkg, }) {
754
+ const result = {
755
+ nodeType: 'multiplication',
756
+ branches: [],
757
+ };
758
+ // Enforce the Rhand is a function definition
759
+ const arrowFunctionPath = path.get('init');
760
+ if (!arrowFunctionPath.isArrowFunctionExpression()) {
761
+ errors.push(warnInvalidStaticInitSync(file, functionName, `${path.node.loc?.start?.line}:${path.node.loc?.start?.column}`));
762
+ return null;
763
+ }
764
+ const bodyNodePath = arrowFunctionPath.get('body');
765
+ if (bodyNodePath.isExpression()) {
766
+ // process expression return
767
+ result.branches.push(processReturnExpression({
768
+ unwrappedExpressions,
769
+ functionName,
770
+ pkg,
771
+ scopeNode: arrowFunctionPath,
772
+ expressionNodePath: bodyNodePath,
773
+ importAliases,
774
+ visited,
775
+ updates,
776
+ errors,
777
+ warnings,
778
+ file,
779
+ parsingOptions,
780
+ importedFunctionsMap,
781
+ }));
782
+ }
783
+ else {
784
+ // search for a return statement
785
+ bodyNodePath.traverse({
786
+ Function(path) {
787
+ path.skip();
788
+ },
789
+ ReturnStatement(returnPath) {
790
+ const returnNodePath = returnPath.get('argument');
791
+ if (!returnNodePath.isExpression()) {
792
+ return;
793
+ }
794
+ result.branches.push(processReturnExpression({
795
+ unwrappedExpressions,
796
+ functionName,
797
+ pkg,
798
+ scopeNode: returnPath,
799
+ expressionNodePath: returnNodePath,
800
+ importAliases,
801
+ visited,
802
+ updates,
803
+ errors,
804
+ warnings,
805
+ file,
806
+ parsingOptions,
807
+ importedFunctionsMap,
808
+ }));
809
+ },
810
+ });
811
+ }
812
+ if (result.branches.length === 0) {
813
+ errors.push(warnMissingReturnSync(file, functionName, `${path.node.loc?.start?.line}:${path.node.loc?.start?.column}`));
814
+ return null;
815
+ }
816
+ return result;
817
+ }
818
+ /**
819
+ * Process a expression being returned from a function
820
+ */
821
+ function processReturnExpression({ unwrappedExpressions, scopeNode, expressionNodePath, importAliases, visited, updates, errors, warnings, file, parsingOptions, importedFunctionsMap, functionName, pkg, }) {
822
+ // // If the node is null, return
823
+ // if (expressionNodePath == null) return null;
824
+ // Remove parentheses if they exist
825
+ if (t.isParenthesizedExpression(expressionNodePath.node)) {
826
+ // ex: return (value)
827
+ return processReturnExpression({
828
+ unwrappedExpressions,
829
+ importAliases,
830
+ scopeNode,
831
+ expressionNodePath: expressionNodePath.get('expression'),
832
+ visited,
833
+ updates,
834
+ errors,
835
+ warnings,
836
+ file,
837
+ parsingOptions,
838
+ functionName,
839
+ importedFunctionsMap,
840
+ pkg,
841
+ });
842
+ }
843
+ else if (t.isCallExpression(expressionNodePath.node) &&
844
+ t.isIdentifier(expressionNodePath.node.callee)) {
845
+ // ex: return someFunc()
846
+ const callee = expressionNodePath.node.callee;
847
+ const calleeBinding = scopeNode.scope.getBinding(callee.name);
848
+ if (!calleeBinding) {
849
+ warnFunctionNotFoundSync(file, callee.name, `${callee.loc?.start?.line}:${callee.loc?.start?.column}`);
850
+ return null;
851
+ }
852
+ // Function is found locally
853
+ return resolveStaticFunctionInvocationFromBinding({
854
+ importAliases,
855
+ calleeBinding,
856
+ callee,
857
+ unwrappedExpressions,
858
+ visited,
859
+ file,
860
+ updates,
861
+ errors,
862
+ warnings,
863
+ pkg,
864
+ parsingOptions,
865
+ importedFunctionsMap,
866
+ });
867
+ }
868
+ else if (t.isAwaitExpression(expressionNodePath.node) &&
869
+ t.isCallExpression(expressionNodePath.node.argument) &&
870
+ t.isIdentifier(expressionNodePath.node.argument.callee)) {
871
+ // ex: return await someFunc()
872
+ const callee = expressionNodePath.node.argument.callee;
873
+ const calleeBinding = scopeNode.scope.getBinding(callee.name);
874
+ if (!calleeBinding) {
875
+ warnFunctionNotFoundSync(file, callee.name, `${callee.loc?.start?.line}:${callee.loc?.start?.column}`);
876
+ return null;
877
+ }
878
+ // Function is found locally
879
+ return resolveStaticFunctionInvocationFromBinding({
880
+ importAliases,
881
+ calleeBinding,
882
+ callee,
883
+ unwrappedExpressions,
884
+ visited,
885
+ file,
886
+ updates,
887
+ errors,
888
+ warnings,
889
+ pkg,
890
+ parsingOptions,
891
+ importedFunctionsMap,
892
+ });
893
+ }
894
+ else if (t.isJSXElement(expressionNodePath.node) ||
895
+ t.isJSXFragment(expressionNodePath.node)) {
896
+ // ex: return <div>Jsx content</div>
897
+ return buildJSXTree({
898
+ importAliases,
899
+ node: expressionNodePath.node,
900
+ unwrappedExpressions,
901
+ visited,
902
+ updates,
903
+ errors,
904
+ warnings,
905
+ file,
906
+ insideT: true,
907
+ parsingOptions,
908
+ scopeNode,
909
+ importedFunctionsMap,
910
+ pkg,
911
+ });
912
+ }
913
+ else if (t.isConditionalExpression(expressionNodePath.node)) {
914
+ // ex: return condition ? <div>Jsx content</div> : <div>Jsx content</div>
915
+ // since two options here we must construct a new multiplication node
916
+ const consequentNodePath = expressionNodePath.get('consequent');
917
+ const alternateNodePath = expressionNodePath.get('alternate');
918
+ const result = {
919
+ nodeType: 'multiplication',
920
+ branches: [consequentNodePath, alternateNodePath].map((expressionNodePath) => processReturnExpression({
921
+ unwrappedExpressions,
922
+ importAliases,
923
+ scopeNode,
924
+ expressionNodePath,
925
+ visited,
926
+ updates,
927
+ errors,
928
+ warnings,
929
+ file,
930
+ parsingOptions,
931
+ functionName,
932
+ importedFunctionsMap,
933
+ pkg,
934
+ })),
935
+ };
936
+ return result;
937
+ }
938
+ else {
939
+ // Handle static expressions (e.g. return 'static string')
940
+ const staticAnalysis = isStaticExpression(expressionNodePath.node);
941
+ if (staticAnalysis.isStatic && staticAnalysis.value !== undefined) {
942
+ // Preserve the exact whitespace for static string expressions
943
+ return staticAnalysis.value;
944
+ }
945
+ // reject
946
+ errors.push(warnInvalidReturnExpressionSync(file, functionName, generate(expressionNodePath.node).code, `${scopeNode.node.loc?.start?.line}:${scopeNode.node.loc?.start?.column}`));
947
+ return null;
948
+ }
949
+ }