@codeyam/codeyam-cli 0.1.0-staging.323686 → 0.1.0-staging.483fdc2

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 (171) hide show
  1. package/analyzer-template/.build-info.json +7 -7
  2. package/analyzer-template/log.txt +3 -3
  3. package/analyzer-template/package.json +2 -2
  4. package/analyzer-template/packages/ai/index.ts +6 -1
  5. package/analyzer-template/packages/ai/src/lib/analyzeScope.ts +39 -17
  6. package/analyzer-template/packages/ai/src/lib/astScopes/astScopeAnalyzer.ts +67 -9
  7. package/analyzer-template/packages/ai/src/lib/astScopes/processExpression.ts +308 -50
  8. package/analyzer-template/packages/ai/src/lib/astScopes/types.ts +15 -6
  9. package/analyzer-template/packages/ai/src/lib/dataStructure/ScopeDataStructure.ts +664 -242
  10. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/BatchSchemaProcessor.ts +16 -3
  11. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/ScopeTreeManager.ts +6 -4
  12. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/cleanKnownObjectFunctions.ts +20 -1
  13. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/cleanNonObjectFunctions.ts +35 -13
  14. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/convertTypeAnnotationsToValues.ts +160 -0
  15. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/deduplicateFunctionSchemas.ts +40 -30
  16. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/fillInSchemaGapsAndUnknowns.ts +289 -83
  17. package/analyzer-template/packages/ai/src/lib/generateEntityScenarioData.ts +269 -1
  18. package/analyzer-template/packages/ai/src/lib/generateEntityScenarios.ts +9 -5
  19. package/analyzer-template/packages/ai/src/lib/generateExecutionFlows.ts +11 -3
  20. package/analyzer-template/packages/ai/src/lib/generateExecutionFlowsFromConditionalEffects.ts +1 -1
  21. package/analyzer-template/packages/ai/src/lib/generateExecutionFlowsFromConditionals.ts +297 -7
  22. package/analyzer-template/packages/ai/src/lib/generateExecutionFlowsFromJsxUsages.ts +1 -1
  23. package/analyzer-template/packages/ai/src/lib/mergeStatements.ts +90 -96
  24. package/analyzer-template/packages/ai/src/lib/promptGenerators/gatherAttributesMap.ts +10 -7
  25. package/analyzer-template/packages/ai/src/lib/resolvePathToControllable.ts +25 -13
  26. package/analyzer-template/packages/ai/src/lib/worker/SerializableDataStructure.ts +4 -3
  27. package/analyzer-template/packages/analyze/src/lib/FileAnalyzer.ts +65 -59
  28. package/analyzer-template/packages/analyze/src/lib/ProjectAnalyzer.ts +113 -26
  29. package/analyzer-template/packages/analyze/src/lib/asts/sourceFiles/getAllDeclaredEntityNodes.ts +19 -0
  30. package/analyzer-template/packages/analyze/src/lib/asts/sourceFiles/getAllEntityNodes.ts +19 -0
  31. package/analyzer-template/packages/analyze/src/lib/asts/sourceFiles/getAllExports.ts +11 -0
  32. package/analyzer-template/packages/analyze/src/lib/asts/sourceFiles/getImportsAnalysis.ts +8 -0
  33. package/analyzer-template/packages/analyze/src/lib/asts/sourceFiles/getResolvedModule.ts +49 -1
  34. package/analyzer-template/packages/analyze/src/lib/asts/sourceFiles/getSourceFilesForAllImports.ts +2 -1
  35. package/analyzer-template/packages/analyze/src/lib/files/analyze/analyzeEntities/prepareDataStructures.ts +20 -6
  36. package/analyzer-template/packages/analyze/src/lib/files/analyze/analyzeEntities.ts +14 -4
  37. package/analyzer-template/packages/analyze/src/lib/files/analyze/gatherEntityMap.ts +4 -2
  38. package/analyzer-template/packages/analyze/src/lib/files/analyze/validateDependencyAnalyses.ts +0 -3
  39. package/analyzer-template/packages/analyze/src/lib/files/analyzeRemixRoute.ts +4 -5
  40. package/analyzer-template/packages/analyze/src/lib/files/getImportedExports.ts +14 -12
  41. package/analyzer-template/packages/analyze/src/lib/files/scenarios/enrichArrayTypesFromChildSignatures.ts +57 -13
  42. package/analyzer-template/packages/analyze/src/lib/files/scenarios/gatherDataForMocks.ts +29 -0
  43. package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateDataStructure.ts +35 -4
  44. package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateExecutionFlows.ts +117 -9
  45. package/analyzer-template/packages/analyze/src/lib/files/scenarios/mergeInDependentDataStructure.ts +199 -17
  46. package/analyzer-template/packages/analyze/src/lib/files/scenarios/propagateArrayItemSchemas.ts +474 -0
  47. package/analyzer-template/packages/analyze/src/lib/files/setImportedExports.ts +2 -1
  48. package/analyzer-template/packages/analyze/src/lib/utils/getFileByPath.ts +19 -0
  49. package/analyzer-template/packages/aws/package.json +1 -1
  50. package/analyzer-template/packages/github/dist/types/src/types/ScenariosDataStructure.d.ts +5 -5
  51. package/analyzer-template/packages/github/dist/types/src/types/ScenariosDataStructure.d.ts.map +1 -1
  52. package/analyzer-template/packages/github/dist/types/src/types/ScopeAnalysis.d.ts +6 -1
  53. package/analyzer-template/packages/github/dist/types/src/types/ScopeAnalysis.d.ts.map +1 -1
  54. package/analyzer-template/packages/github/package.json +1 -1
  55. package/analyzer-template/packages/types/src/types/ScenariosDataStructure.ts +6 -5
  56. package/analyzer-template/packages/types/src/types/ScopeAnalysis.ts +6 -1
  57. package/analyzer-template/packages/utils/dist/types/src/types/ScenariosDataStructure.d.ts +5 -5
  58. package/analyzer-template/packages/utils/dist/types/src/types/ScenariosDataStructure.d.ts.map +1 -1
  59. package/analyzer-template/packages/utils/dist/types/src/types/ScopeAnalysis.d.ts +6 -1
  60. package/analyzer-template/packages/utils/dist/types/src/types/ScopeAnalysis.d.ts.map +1 -1
  61. package/analyzer-template/project/constructMockCode.ts +54 -9
  62. package/analyzer-template/project/writeMockDataTsx.ts +73 -2
  63. package/background/src/lib/virtualized/project/constructMockCode.js +45 -3
  64. package/background/src/lib/virtualized/project/constructMockCode.js.map +1 -1
  65. package/background/src/lib/virtualized/project/writeMockDataTsx.js +71 -2
  66. package/background/src/lib/virtualized/project/writeMockDataTsx.js.map +1 -1
  67. package/codeyam-cli/scripts/apply-setup.js +146 -0
  68. package/codeyam-cli/scripts/apply-setup.js.map +1 -1
  69. package/codeyam-cli/src/commands/debug.js +7 -5
  70. package/codeyam-cli/src/commands/debug.js.map +1 -1
  71. package/codeyam-cli/src/utils/install-skills.js +22 -0
  72. package/codeyam-cli/src/utils/install-skills.js.map +1 -1
  73. package/codeyam-cli/src/utils/reviewedRules.js +92 -0
  74. package/codeyam-cli/src/utils/reviewedRules.js.map +1 -0
  75. package/codeyam-cli/src/webserver/build/client/assets/globals-CX9f-5xM.css +1 -0
  76. package/codeyam-cli/src/webserver/build/client/assets/{manifest-7522edd4.js → manifest-bba56ec1.js} +1 -1
  77. package/codeyam-cli/src/webserver/build/client/assets/memory-DuTFSyJ2.js +92 -0
  78. package/codeyam-cli/src/webserver/build/client/assets/{root-eVAaavTS.js → root-DTfSQARG.js} +6 -6
  79. package/codeyam-cli/src/webserver/build/server/assets/{index-DVzYx8PN.js → index-TD1f-DHV.js} +1 -1
  80. package/codeyam-cli/src/webserver/build/server/assets/server-build-BQ-1XyEa.js +258 -0
  81. package/codeyam-cli/src/webserver/build/server/index.js +1 -1
  82. package/codeyam-cli/src/webserver/build-info.json +5 -5
  83. package/codeyam-cli/templates/codeyam:memory.md +174 -233
  84. package/codeyam-cli/templates/codeyam:new-rule.md +41 -2
  85. package/codeyam-cli/templates/rule-reflection-hook.py +161 -0
  86. package/codeyam-cli/templates/rules-instructions.md +126 -0
  87. package/package.json +1 -1
  88. package/packages/ai/index.js +2 -1
  89. package/packages/ai/index.js.map +1 -1
  90. package/packages/ai/src/lib/analyzeScope.js +29 -12
  91. package/packages/ai/src/lib/analyzeScope.js.map +1 -1
  92. package/packages/ai/src/lib/astScopes/astScopeAnalyzer.js +54 -8
  93. package/packages/ai/src/lib/astScopes/astScopeAnalyzer.js.map +1 -1
  94. package/packages/ai/src/lib/astScopes/processExpression.js +239 -43
  95. package/packages/ai/src/lib/astScopes/processExpression.js.map +1 -1
  96. package/packages/ai/src/lib/dataStructure/ScopeDataStructure.js +503 -165
  97. package/packages/ai/src/lib/dataStructure/ScopeDataStructure.js.map +1 -1
  98. package/packages/ai/src/lib/dataStructure/helpers/BatchSchemaProcessor.js +13 -3
  99. package/packages/ai/src/lib/dataStructure/helpers/BatchSchemaProcessor.js.map +1 -1
  100. package/packages/ai/src/lib/dataStructure/helpers/ScopeTreeManager.js +6 -4
  101. package/packages/ai/src/lib/dataStructure/helpers/ScopeTreeManager.js.map +1 -1
  102. package/packages/ai/src/lib/dataStructure/helpers/cleanKnownObjectFunctions.js +22 -1
  103. package/packages/ai/src/lib/dataStructure/helpers/cleanKnownObjectFunctions.js.map +1 -1
  104. package/packages/ai/src/lib/dataStructure/helpers/cleanNonObjectFunctions.js +34 -9
  105. package/packages/ai/src/lib/dataStructure/helpers/cleanNonObjectFunctions.js.map +1 -1
  106. package/packages/ai/src/lib/dataStructure/helpers/convertTypeAnnotationsToValues.js +159 -0
  107. package/packages/ai/src/lib/dataStructure/helpers/convertTypeAnnotationsToValues.js.map +1 -0
  108. package/packages/ai/src/lib/dataStructure/helpers/deduplicateFunctionSchemas.js +37 -20
  109. package/packages/ai/src/lib/dataStructure/helpers/deduplicateFunctionSchemas.js.map +1 -1
  110. package/packages/ai/src/lib/dataStructure/helpers/fillInSchemaGapsAndUnknowns.js +237 -73
  111. package/packages/ai/src/lib/dataStructure/helpers/fillInSchemaGapsAndUnknowns.js.map +1 -1
  112. package/packages/ai/src/lib/generateEntityScenarioData.js +195 -1
  113. package/packages/ai/src/lib/generateEntityScenarioData.js.map +1 -1
  114. package/packages/ai/src/lib/generateEntityScenarios.js +7 -1
  115. package/packages/ai/src/lib/generateEntityScenarios.js.map +1 -1
  116. package/packages/ai/src/lib/generateExecutionFlows.js +10 -2
  117. package/packages/ai/src/lib/generateExecutionFlows.js.map +1 -1
  118. package/packages/ai/src/lib/generateExecutionFlowsFromConditionals.js +209 -3
  119. package/packages/ai/src/lib/generateExecutionFlowsFromConditionals.js.map +1 -1
  120. package/packages/ai/src/lib/mergeStatements.js +70 -51
  121. package/packages/ai/src/lib/mergeStatements.js.map +1 -1
  122. package/packages/ai/src/lib/promptGenerators/gatherAttributesMap.js +10 -4
  123. package/packages/ai/src/lib/promptGenerators/gatherAttributesMap.js.map +1 -1
  124. package/packages/ai/src/lib/resolvePathToControllable.js +24 -14
  125. package/packages/ai/src/lib/resolvePathToControllable.js.map +1 -1
  126. package/packages/ai/src/lib/worker/SerializableDataStructure.js.map +1 -1
  127. package/packages/analyze/src/lib/FileAnalyzer.js +60 -36
  128. package/packages/analyze/src/lib/FileAnalyzer.js.map +1 -1
  129. package/packages/analyze/src/lib/ProjectAnalyzer.js +96 -26
  130. package/packages/analyze/src/lib/ProjectAnalyzer.js.map +1 -1
  131. package/packages/analyze/src/lib/asts/sourceFiles/getAllDeclaredEntityNodes.js +14 -0
  132. package/packages/analyze/src/lib/asts/sourceFiles/getAllDeclaredEntityNodes.js.map +1 -1
  133. package/packages/analyze/src/lib/asts/sourceFiles/getAllEntityNodes.js +14 -0
  134. package/packages/analyze/src/lib/asts/sourceFiles/getAllEntityNodes.js.map +1 -1
  135. package/packages/analyze/src/lib/asts/sourceFiles/getAllExports.js +6 -0
  136. package/packages/analyze/src/lib/asts/sourceFiles/getAllExports.js.map +1 -1
  137. package/packages/analyze/src/lib/asts/sourceFiles/getImportsAnalysis.js +6 -0
  138. package/packages/analyze/src/lib/asts/sourceFiles/getImportsAnalysis.js.map +1 -1
  139. package/packages/analyze/src/lib/asts/sourceFiles/getResolvedModule.js +39 -1
  140. package/packages/analyze/src/lib/asts/sourceFiles/getResolvedModule.js.map +1 -1
  141. package/packages/analyze/src/lib/asts/sourceFiles/getSourceFilesForAllImports.js +2 -1
  142. package/packages/analyze/src/lib/asts/sourceFiles/getSourceFilesForAllImports.js.map +1 -1
  143. package/packages/analyze/src/lib/files/analyze/analyzeEntities/prepareDataStructures.js +13 -5
  144. package/packages/analyze/src/lib/files/analyze/analyzeEntities/prepareDataStructures.js.map +1 -1
  145. package/packages/analyze/src/lib/files/analyze/analyzeEntities.js +14 -4
  146. package/packages/analyze/src/lib/files/analyze/analyzeEntities.js.map +1 -1
  147. package/packages/analyze/src/lib/files/analyze/gatherEntityMap.js +2 -1
  148. package/packages/analyze/src/lib/files/analyze/gatherEntityMap.js.map +1 -1
  149. package/packages/analyze/src/lib/files/analyze/validateDependencyAnalyses.js +0 -3
  150. package/packages/analyze/src/lib/files/analyze/validateDependencyAnalyses.js.map +1 -1
  151. package/packages/analyze/src/lib/files/analyzeRemixRoute.js +3 -2
  152. package/packages/analyze/src/lib/files/analyzeRemixRoute.js.map +1 -1
  153. package/packages/analyze/src/lib/files/getImportedExports.js +11 -7
  154. package/packages/analyze/src/lib/files/getImportedExports.js.map +1 -1
  155. package/packages/analyze/src/lib/files/scenarios/enrichArrayTypesFromChildSignatures.js +52 -10
  156. package/packages/analyze/src/lib/files/scenarios/enrichArrayTypesFromChildSignatures.js.map +1 -1
  157. package/packages/analyze/src/lib/files/scenarios/gatherDataForMocks.js +25 -8
  158. package/packages/analyze/src/lib/files/scenarios/gatherDataForMocks.js.map +1 -1
  159. package/packages/analyze/src/lib/files/scenarios/generateDataStructure.js +34 -4
  160. package/packages/analyze/src/lib/files/scenarios/generateDataStructure.js.map +1 -1
  161. package/packages/analyze/src/lib/files/scenarios/generateExecutionFlows.js +56 -8
  162. package/packages/analyze/src/lib/files/scenarios/generateExecutionFlows.js.map +1 -1
  163. package/packages/analyze/src/lib/files/scenarios/mergeInDependentDataStructure.js +168 -9
  164. package/packages/analyze/src/lib/files/scenarios/mergeInDependentDataStructure.js.map +1 -1
  165. package/packages/analyze/src/lib/files/setImportedExports.js +2 -1
  166. package/packages/analyze/src/lib/files/setImportedExports.js.map +1 -1
  167. package/packages/analyze/src/lib/utils/getFileByPath.js +12 -0
  168. package/packages/analyze/src/lib/utils/getFileByPath.js.map +1 -0
  169. package/codeyam-cli/src/webserver/build/client/assets/globals-D3yhhV8x.css +0 -1
  170. package/codeyam-cli/src/webserver/build/client/assets/memory-yxFcrxBX.js +0 -92
  171. package/codeyam-cli/src/webserver/build/server/assets/server-build-4Cr0uToj.js +0 -257
@@ -1088,21 +1088,36 @@ export class ScopeDataStructure {
1088
1088
  }
1089
1089
  setInstantiatedVariables(scopeNode) {
1090
1090
  let instantiatedVariables = scopeNode.analysis?.instantiatedVariables ?? [];
1091
- for (const [path, equivalentPath] of Object.entries(scopeNode.analysis.isolatedEquivalentVariables ?? {})) {
1092
- if (typeof equivalentPath !== 'string') {
1093
- continue;
1094
- }
1095
- if (equivalentPath.startsWith('signature[')) {
1096
- const equivalentPathParts = this.splitPath(equivalentPath);
1097
- instantiatedVariables.push(equivalentPathParts[0]);
1098
- instantiatedVariables.push(path);
1091
+ for (const [path, rawEquivalentPath] of Object.entries(scopeNode.analysis.isolatedEquivalentVariables ?? {})) {
1092
+ // Normalize to array for consistent handling (supports both string and string[])
1093
+ const equivalentPaths = Array.isArray(rawEquivalentPath)
1094
+ ? rawEquivalentPath
1095
+ : rawEquivalentPath
1096
+ ? [rawEquivalentPath]
1097
+ : [];
1098
+ for (const equivalentPath of equivalentPaths) {
1099
+ if (typeof equivalentPath !== 'string') {
1100
+ continue;
1101
+ }
1102
+ if (equivalentPath.startsWith('signature[')) {
1103
+ const equivalentPathParts = this.splitPath(equivalentPath);
1104
+ instantiatedVariables.push(equivalentPathParts[0]);
1105
+ instantiatedVariables.push(path);
1106
+ }
1099
1107
  }
1100
1108
  const duplicateInstantiated = instantiatedVariables.find((v) => path.split('::cyDuplicateKey')[0] === v.split('::cyDuplicateKey')[0]);
1101
1109
  if (duplicateInstantiated) {
1102
1110
  instantiatedVariables.push(path);
1103
1111
  }
1104
1112
  }
1105
- instantiatedVariables = instantiatedVariables.filter((varName, index, self) => self.indexOf(varName) === index);
1113
+ const instantiatedSeen = new Set();
1114
+ instantiatedVariables = instantiatedVariables.filter((varName) => {
1115
+ if (instantiatedSeen.has(varName)) {
1116
+ return false;
1117
+ }
1118
+ instantiatedSeen.add(varName);
1119
+ return true;
1120
+ });
1106
1121
  scopeNode.instantiatedVariables = instantiatedVariables;
1107
1122
  if (!scopeNode.tree || scopeNode.tree.length === 0) {
1108
1123
  return;
@@ -1114,9 +1129,16 @@ export class ScopeDataStructure {
1114
1129
  const parentInstantiatedVariables = [
1115
1130
  ...(parentScopeNode.parentInstantiatedVariables ?? []),
1116
1131
  ...parentScopeNode.instantiatedVariables.filter((v) => !v.startsWith('signature[') && !v.startsWith('returnValue')),
1117
- ].filter((varName, index, self) => !instantiatedVariables.includes(varName) &&
1118
- self.indexOf(varName) === index);
1119
- scopeNode.parentInstantiatedVariables = parentInstantiatedVariables;
1132
+ ].filter((varName) => !instantiatedSeen.has(varName));
1133
+ const parentInstantiatedSeen = new Set();
1134
+ const dedupedParentInstantiatedVariables = parentInstantiatedVariables.filter((varName) => {
1135
+ if (parentInstantiatedSeen.has(varName)) {
1136
+ return false;
1137
+ }
1138
+ parentInstantiatedSeen.add(varName);
1139
+ return true;
1140
+ });
1141
+ scopeNode.parentInstantiatedVariables = dedupedParentInstantiatedVariables;
1120
1142
  }
1121
1143
  trackFunctionCalls(scopeNode) {
1122
1144
  this.captureFunctionCalls(scopeNode);
@@ -1127,116 +1149,136 @@ export class ScopeDataStructure {
1127
1149
  return;
1128
1150
  }
1129
1151
  const { isolatedStructure, isolatedEquivalentVariables } = scopeNode.analysis;
1152
+ // Flatten isolatedEquivalentVariables values for allPaths (handles both string and string[])
1153
+ const flattenedEquivValues = Object.values(isolatedEquivalentVariables || {}).flatMap((v) => (Array.isArray(v) ? v : [v]));
1130
1154
  const allPaths = Array.from(new Set([
1131
1155
  ...Object.keys(isolatedStructure || {}),
1132
1156
  ...Object.keys(isolatedEquivalentVariables || {}),
1133
- ...Object.values(isolatedEquivalentVariables || {}),
1157
+ ...flattenedEquivValues,
1134
1158
  ]));
1135
1159
  for (let path in isolatedEquivalentVariables) {
1136
- let equivalentValue = isolatedEquivalentVariables?.[path];
1137
- if (equivalentValue && this.isValidPath(equivalentValue)) {
1138
- // IMPORTANT: DO NOT strip ::cyDuplicateKey:: markers from equivalencies.
1139
- // These markers are critical for distinguishing variable reassignments.
1140
- // For example, with:
1141
- // let fetcher = useFetcher<ConfigData>();
1142
- // const configData = fetcher.data?.data;
1143
- // fetcher = useFetcher<SettingsData>();
1144
- // const settingsData = fetcher.data?.data;
1145
- //
1146
- // mergeStatements creates:
1147
- // fetcher useFetcher<ConfigData>()...
1148
- // fetcher::cyDuplicateKey1:: useFetcher<SettingsData>()...
1149
- // configData fetcher.data.data
1150
- // settingsData → fetcher::cyDuplicateKey1::.data.data
1151
- //
1152
- // If we strip ::cyDuplicateKey::, settingsData would incorrectly trace
1153
- // to useFetcher<ConfigData>() instead of useFetcher<SettingsData>().
1154
- path = cleanPath(path, allPaths);
1155
- equivalentValue = cleanPath(equivalentValue, allPaths);
1156
- this.addEquivalency(path, equivalentValue, scopeNode.name, scopeNode, 'original equivalency');
1157
- // Propagate equivalencies involving parent-scope variables to those parent scopes.
1158
- // This handles patterns like: collected.push({...entity}) where 'collected' is defined
1159
- // in a parent scope. The equivalency collected[] -> push().signature[0] needs to be
1160
- // visible when tracing from the parent scope.
1161
- const rootVariable = this.extractRootVariable(path);
1162
- const equivalentRootVariable = this.extractRootVariable(equivalentValue);
1163
- // Skip propagation for self-referential reassignment patterns like:
1164
- // x = x.method().functionCallReturnValue
1165
- // where the path IS the variable itself (not a sub-path like x[] or x.prop).
1166
- // These create circular references since both sides reference the same variable.
1167
- //
1168
- // But DO propagate for patterns like collected[] -> collected.push(...).signature[0]
1169
- // where the path has additional segments beyond the root variable.
1170
- const pathIsJustRootVariable = path === rootVariable;
1171
- const isSelfReferentialReassignment = pathIsJustRootVariable && rootVariable === equivalentRootVariable;
1172
- if (rootVariable &&
1173
- !isSelfReferentialReassignment &&
1174
- scopeNode.parentInstantiatedVariables?.includes(rootVariable)) {
1175
- // Find the parent scope where this variable is defined
1176
- for (const parentScopeName of scopeNode.tree || []) {
1177
- const parentScope = this.scopeNodes[parentScopeName];
1178
- if (parentScope?.instantiatedVariables?.includes(rootVariable)) {
1179
- // Add the equivalency to the parent scope as well
1180
- this.addEquivalency(path, equivalentValue, scopeNode.name, // The equivalent path's scope remains the child scope
1181
- parentScope, // But store it in the parent scope's equivalencies
1182
- 'propagated parent-variable equivalency');
1183
- break;
1160
+ const rawEquivalentValue = isolatedEquivalentVariables?.[path];
1161
+ // Normalize to array for consistent handling
1162
+ const equivalentValues = Array.isArray(rawEquivalentValue)
1163
+ ? rawEquivalentValue
1164
+ : [rawEquivalentValue];
1165
+ for (let equivalentValue of equivalentValues) {
1166
+ if (equivalentValue && this.isValidPath(equivalentValue)) {
1167
+ // IMPORTANT: DO NOT strip ::cyDuplicateKey:: markers from equivalencies.
1168
+ // These markers are critical for distinguishing variable reassignments.
1169
+ // For example, with:
1170
+ // let fetcher = useFetcher<ConfigData>();
1171
+ // const configData = fetcher.data?.data;
1172
+ // fetcher = useFetcher<SettingsData>();
1173
+ // const settingsData = fetcher.data?.data;
1174
+ //
1175
+ // mergeStatements creates:
1176
+ // fetcher useFetcher<ConfigData>()...
1177
+ // fetcher::cyDuplicateKey1:: useFetcher<SettingsData>()...
1178
+ // configData fetcher.data.data
1179
+ // settingsData fetcher::cyDuplicateKey1::.data.data
1180
+ //
1181
+ // If we strip ::cyDuplicateKey::, settingsData would incorrectly trace
1182
+ // to useFetcher<ConfigData>() instead of useFetcher<SettingsData>().
1183
+ path = cleanPath(path, allPaths);
1184
+ equivalentValue = cleanPath(equivalentValue, allPaths);
1185
+ this.addEquivalency(path, equivalentValue, scopeNode.name, scopeNode, 'original equivalency');
1186
+ // Propagate equivalencies involving parent-scope variables to those parent scopes.
1187
+ // This handles patterns like: collected.push({...entity}) where 'collected' is defined
1188
+ // in a parent scope. The equivalency collected[] -> push().signature[0] needs to be
1189
+ // visible when tracing from the parent scope.
1190
+ const rootVariable = this.extractRootVariable(path);
1191
+ const equivalentRootVariable = this.extractRootVariable(equivalentValue);
1192
+ // Skip propagation for self-referential reassignment patterns like:
1193
+ // x = x.method().functionCallReturnValue
1194
+ // where the path IS the variable itself (not a sub-path like x[] or x.prop).
1195
+ // These create circular references since both sides reference the same variable.
1196
+ //
1197
+ // But DO propagate for patterns like collected[] -> collected.push(...).signature[0]
1198
+ // where the path has additional segments beyond the root variable.
1199
+ const pathIsJustRootVariable = path === rootVariable;
1200
+ const isSelfReferentialReassignment = pathIsJustRootVariable && rootVariable === equivalentRootVariable;
1201
+ if (rootVariable &&
1202
+ !isSelfReferentialReassignment &&
1203
+ scopeNode.parentInstantiatedVariables?.includes(rootVariable)) {
1204
+ // Find the parent scope where this variable is defined
1205
+ for (const parentScopeName of scopeNode.tree || []) {
1206
+ const parentScope = this.scopeNodes[parentScopeName];
1207
+ if (parentScope?.instantiatedVariables?.includes(rootVariable)) {
1208
+ // Add the equivalency to the parent scope as well
1209
+ this.addEquivalency(path, equivalentValue, scopeNode.name, // The equivalent path's scope remains the child scope
1210
+ parentScope, // But store it in the parent scope's equivalencies
1211
+ 'propagated parent-variable equivalency');
1212
+ break;
1213
+ }
1184
1214
  }
1185
1215
  }
1186
- }
1187
- // Propagate sub-property equivalencies when the equivalentValue is a simple variable
1188
- // that has sub-properties defined in the isolatedEquivalentVariables.
1189
- // This handles cases like: dataItem={{ structure: completeDataStructure }}
1190
- // where completeDataStructure has sub-properties like completeDataStructure['Function Arguments']
1191
- // We need to propagate these to create: dataItem.structure['Function Arguments'] equivalencies
1192
- const isSimpleVariable = !equivalentValue.startsWith('signature[') &&
1193
- !equivalentValue.includes('functionCallReturnValue') &&
1194
- !equivalentValue.includes('.') &&
1195
- !equivalentValue.includes('[');
1196
- if (isSimpleVariable) {
1197
- // Look in current scope and all parent scopes for sub-properties
1198
- const scopesToCheck = [scopeNode.name, ...scopeNode.tree];
1199
- for (const scopeName of scopesToCheck) {
1200
- const checkScope = this.scopeNodes[scopeName];
1201
- if (!checkScope?.analysis?.isolatedEquivalentVariables)
1202
- continue;
1203
- for (const [subPath, subValue] of Object.entries(checkScope.analysis.isolatedEquivalentVariables)) {
1204
- // Check if this is a sub-property of the equivalentValue variable
1205
- // e.g., completeDataStructure['Function Arguments'] or completeDataStructure.foo
1206
- const matchesDot = subPath.startsWith(equivalentValue + '.');
1207
- const matchesBracket = subPath.startsWith(equivalentValue + '[');
1208
- if (matchesDot || matchesBracket) {
1209
- const subPropertyPath = subPath.substring(equivalentValue.length);
1210
- const newPath = cleanPath(path + subPropertyPath, allPaths);
1211
- const newEquivalentValue = cleanPath(subValue.replace(/::cyDuplicateKey\d+::/g, ''), allPaths);
1212
- if (newEquivalentValue &&
1213
- this.isValidPath(newEquivalentValue)) {
1214
- this.addEquivalency(newPath, newEquivalentValue, checkScope.name, // Use the scope where the sub-property was found
1215
- scopeNode, 'propagated sub-property equivalency');
1216
+ // Propagate sub-property equivalencies when the equivalentValue is a simple variable
1217
+ // that has sub-properties defined in the isolatedEquivalentVariables.
1218
+ // This handles cases like: dataItem={{ structure: completeDataStructure }}
1219
+ // where completeDataStructure has sub-properties like completeDataStructure['Function Arguments']
1220
+ // We need to propagate these to create: dataItem.structure['Function Arguments'] equivalencies
1221
+ const isSimpleVariable = !equivalentValue.startsWith('signature[') &&
1222
+ !equivalentValue.includes('functionCallReturnValue') &&
1223
+ !equivalentValue.includes('.') &&
1224
+ !equivalentValue.includes('[');
1225
+ if (isSimpleVariable) {
1226
+ // Look in current scope and all parent scopes for sub-properties
1227
+ const scopesToCheck = [scopeNode.name, ...scopeNode.tree];
1228
+ for (const scopeName of scopesToCheck) {
1229
+ const checkScope = this.scopeNodes[scopeName];
1230
+ if (!checkScope?.analysis?.isolatedEquivalentVariables)
1231
+ continue;
1232
+ for (const [subPath, rawSubValue] of Object.entries(checkScope.analysis.isolatedEquivalentVariables)) {
1233
+ // Normalize to array for consistent handling
1234
+ const subValues = Array.isArray(rawSubValue)
1235
+ ? rawSubValue
1236
+ : rawSubValue
1237
+ ? [rawSubValue]
1238
+ : [];
1239
+ // Check if this is a sub-property of the equivalentValue variable
1240
+ // e.g., completeDataStructure['Function Arguments'] or completeDataStructure.foo
1241
+ const matchesDot = subPath.startsWith(equivalentValue + '.');
1242
+ const matchesBracket = subPath.startsWith(equivalentValue + '[');
1243
+ if (matchesDot || matchesBracket) {
1244
+ const subPropertyPath = subPath.substring(equivalentValue.length);
1245
+ const newPath = cleanPath(path + subPropertyPath, allPaths);
1246
+ for (const subValue of subValues) {
1247
+ if (typeof subValue !== 'string')
1248
+ continue;
1249
+ const newEquivalentValue = cleanPath(subValue.replace(/::cyDuplicateKey\d+::/g, ''), allPaths);
1250
+ if (newEquivalentValue &&
1251
+ this.isValidPath(newEquivalentValue)) {
1252
+ this.addEquivalency(newPath, newEquivalentValue, checkScope.name, // Use the scope where the sub-property was found
1253
+ scopeNode, 'propagated sub-property equivalency');
1254
+ }
1255
+ }
1256
+ }
1257
+ // Also check if equivalentValue itself maps to a functionCallReturnValue
1258
+ // e.g., result = useMemo(...).functionCallReturnValue
1259
+ for (const subValue of subValues) {
1260
+ if (subPath === equivalentValue &&
1261
+ typeof subValue === 'string' &&
1262
+ subValue.endsWith('.functionCallReturnValue')) {
1263
+ this.propagateFunctionCallReturnSubProperties(path, subValue, scopeNode, allPaths);
1264
+ }
1216
1265
  }
1217
- }
1218
- // Also check if equivalentValue itself maps to a functionCallReturnValue
1219
- // e.g., result = useMemo(...).functionCallReturnValue
1220
- if (subPath === equivalentValue &&
1221
- typeof subValue === 'string' &&
1222
- subValue.endsWith('.functionCallReturnValue')) {
1223
- this.propagateFunctionCallReturnSubProperties(path, subValue, scopeNode, allPaths);
1224
1266
  }
1225
1267
  }
1226
1268
  }
1227
- }
1228
- // Handle function call return values by propagating returnValue.* sub-properties
1229
- // from the callback scope to the usage path
1230
- if (equivalentValue.endsWith('.functionCallReturnValue')) {
1231
- this.propagateFunctionCallReturnSubProperties(path, equivalentValue, scopeNode, allPaths);
1232
- // Track which variable receives the return value of each function call
1233
- // This enables generating separate mock data for each call site
1234
- this.trackReceivingVariable(path, equivalentValue);
1235
- }
1236
- // Also track variables that receive destructured properties from function call return values
1237
- // e.g., "userData" -> "db.query('users').functionCallReturnValue.data"
1238
- if (equivalentValue.includes('.functionCallReturnValue.')) {
1239
- this.trackReceivingVariable(path, equivalentValue);
1269
+ // Handle function call return values by propagating returnValue.* sub-properties
1270
+ // from the callback scope to the usage path
1271
+ if (equivalentValue.endsWith('.functionCallReturnValue')) {
1272
+ this.propagateFunctionCallReturnSubProperties(path, equivalentValue, scopeNode, allPaths);
1273
+ // Track which variable receives the return value of each function call
1274
+ // This enables generating separate mock data for each call site
1275
+ this.trackReceivingVariable(path, equivalentValue);
1276
+ }
1277
+ // Also track variables that receive destructured properties from function call return values
1278
+ // e.g., "userData" -> "db.query('users').functionCallReturnValue.data"
1279
+ if (equivalentValue.includes('.functionCallReturnValue.')) {
1280
+ this.trackReceivingVariable(path, equivalentValue);
1281
+ }
1240
1282
  }
1241
1283
  }
1242
1284
  }
@@ -1380,8 +1422,15 @@ export class ScopeDataStructure {
1380
1422
  const checkScope = this.scopeNodes[scopeName];
1381
1423
  if (!checkScope?.analysis?.isolatedEquivalentVariables)
1382
1424
  continue;
1383
- const functionRef = checkScope.analysis.isolatedEquivalentVariables[functionName];
1384
- if (typeof functionRef === 'string' && functionRef.endsWith('F')) {
1425
+ const rawFunctionRef = checkScope.analysis.isolatedEquivalentVariables[functionName];
1426
+ // Normalize to array and find first string ending with 'F'
1427
+ const functionRefs = Array.isArray(rawFunctionRef)
1428
+ ? rawFunctionRef
1429
+ : rawFunctionRef
1430
+ ? [rawFunctionRef]
1431
+ : [];
1432
+ const functionRef = functionRefs.find((r) => typeof r === 'string' && r.endsWith('F'));
1433
+ if (typeof functionRef === 'string') {
1385
1434
  callbackScopeName = functionRef.slice(0, -1);
1386
1435
  break;
1387
1436
  }
@@ -1404,22 +1453,32 @@ export class ScopeDataStructure {
1404
1453
  if (!callbackScope.analysis?.isolatedEquivalentVariables)
1405
1454
  return;
1406
1455
  const isolatedVars = callbackScope.analysis.isolatedEquivalentVariables;
1456
+ // Get the first returnValue equivalency (normalize array to single value for these checks)
1457
+ const rawReturnValue = isolatedVars.returnValue;
1458
+ const firstReturnValue = Array.isArray(rawReturnValue)
1459
+ ? rawReturnValue[0]
1460
+ : rawReturnValue;
1407
1461
  // First, check if returnValue is an alias to another variable (e.g., returnValue = intermediate)
1408
1462
  // If so, we need to look for that variable's sub-properties too
1409
- const returnValueAlias = typeof isolatedVars.returnValue === 'string' &&
1410
- !isolatedVars.returnValue.includes('.')
1411
- ? isolatedVars.returnValue
1463
+ const returnValueAlias = typeof firstReturnValue === 'string' && !firstReturnValue.includes('.')
1464
+ ? firstReturnValue
1412
1465
  : undefined;
1413
1466
  // Pattern 3: Object.keys(X).reduce() - the reduce result has the same sub-properties as X
1414
1467
  // When returnValue = "Object.keys(source).reduce(...).functionCallReturnValue", look for source.* sub-properties
1415
1468
  let reduceSourceVar;
1416
- if (typeof isolatedVars.returnValue === 'string') {
1417
- const reduceMatch = isolatedVars.returnValue.match(/^Object\.keys\((\w+)\)\.reduce\(.*\)\.functionCallReturnValue$/);
1469
+ if (typeof firstReturnValue === 'string') {
1470
+ const reduceMatch = firstReturnValue.match(/^Object\.keys\((\w+)\)\.reduce\(.*\)\.functionCallReturnValue$/);
1418
1471
  if (reduceMatch) {
1419
1472
  reduceSourceVar = reduceMatch[1];
1420
1473
  }
1421
1474
  }
1422
- for (const [subPath, subValue] of Object.entries(isolatedVars)) {
1475
+ for (const [subPath, rawSubValue] of Object.entries(isolatedVars)) {
1476
+ // Normalize to array for consistent handling
1477
+ const subValues = Array.isArray(rawSubValue)
1478
+ ? rawSubValue
1479
+ : rawSubValue
1480
+ ? [rawSubValue]
1481
+ : [];
1423
1482
  // Check for direct returnValue.* sub-properties
1424
1483
  const isReturnValueSub = subPath.startsWith('returnValue.') ||
1425
1484
  subPath.startsWith('returnValue[');
@@ -1431,33 +1490,36 @@ export class ScopeDataStructure {
1431
1490
  const isReduceSourceSub = reduceSourceVar &&
1432
1491
  (subPath.startsWith(reduceSourceVar + '.') ||
1433
1492
  subPath.startsWith(reduceSourceVar + '['));
1434
- if (typeof subValue !== 'string' ||
1435
- (!isReturnValueSub && !isAliasSub && !isReduceSourceSub))
1436
- continue;
1437
- // Convert alias/reduceSource paths to returnValue paths
1438
- let effectiveSubPath = subPath;
1439
- if (isAliasSub && !isReturnValueSub) {
1440
- // Replace the alias prefix with returnValue
1441
- effectiveSubPath =
1442
- 'returnValue' + subPath.substring(returnValueAlias.length);
1443
- }
1444
- else if (isReduceSourceSub && !isReturnValueSub && !isAliasSub) {
1445
- // Replace the reduce source prefix with returnValue
1446
- effectiveSubPath =
1447
- 'returnValue' + subPath.substring(reduceSourceVar.length);
1448
- }
1449
- const subPropertyPath = effectiveSubPath.substring('returnValue'.length);
1450
- const newPath = cleanPath(path + subPropertyPath, allPaths);
1451
- let newEquivalentValue = cleanPath(subValue.replace(/::cyDuplicateKey\d+::/g, ''), allPaths);
1452
- // Resolve variable references through parent scope equivalencies
1453
- const resolved = this.resolveVariableThroughParentScopes(newEquivalentValue, callbackScope, allPaths);
1454
- newEquivalentValue = resolved.resolvedPath;
1455
- const equivalentScopeName = resolved.scopeName;
1456
- if (!newEquivalentValue || !this.isValidPath(newEquivalentValue))
1493
+ if (!isReturnValueSub && !isAliasSub && !isReduceSourceSub)
1457
1494
  continue;
1458
- this.addEquivalency(newPath, newEquivalentValue, equivalentScopeName, scopeNode, 'propagated function call return sub-property equivalency');
1459
- // Ensure the database entry has the usage path
1460
- this.addUsageToEquivalencyDatabaseEntry(newPath, newEquivalentValue, equivalentScopeName, scopeNode.name);
1495
+ for (const subValue of subValues) {
1496
+ if (typeof subValue !== 'string')
1497
+ continue;
1498
+ // Convert alias/reduceSource paths to returnValue paths
1499
+ let effectiveSubPath = subPath;
1500
+ if (isAliasSub && !isReturnValueSub) {
1501
+ // Replace the alias prefix with returnValue
1502
+ effectiveSubPath =
1503
+ 'returnValue' + subPath.substring(returnValueAlias.length);
1504
+ }
1505
+ else if (isReduceSourceSub && !isReturnValueSub && !isAliasSub) {
1506
+ // Replace the reduce source prefix with returnValue
1507
+ effectiveSubPath =
1508
+ 'returnValue' + subPath.substring(reduceSourceVar.length);
1509
+ }
1510
+ const subPropertyPath = effectiveSubPath.substring('returnValue'.length);
1511
+ const newPath = cleanPath(path + subPropertyPath, allPaths);
1512
+ let newEquivalentValue = cleanPath(subValue.replace(/::cyDuplicateKey\d+::/g, ''), allPaths);
1513
+ // Resolve variable references through parent scope equivalencies
1514
+ const resolved = this.resolveVariableThroughParentScopes(newEquivalentValue, callbackScope, allPaths);
1515
+ newEquivalentValue = resolved.resolvedPath;
1516
+ const equivalentScopeName = resolved.scopeName;
1517
+ if (!newEquivalentValue || !this.isValidPath(newEquivalentValue))
1518
+ continue;
1519
+ this.addEquivalency(newPath, newEquivalentValue, equivalentScopeName, scopeNode, 'propagated function call return sub-property equivalency');
1520
+ // Ensure the database entry has the usage path
1521
+ this.addUsageToEquivalencyDatabaseEntry(newPath, newEquivalentValue, equivalentScopeName, scopeNode.name);
1522
+ }
1461
1523
  }
1462
1524
  }
1463
1525
  /**
@@ -1489,7 +1551,14 @@ export class ScopeDataStructure {
1489
1551
  const parentScope = this.scopeNodes[parentScopeName];
1490
1552
  if (!parentScope?.analysis?.isolatedEquivalentVariables)
1491
1553
  continue;
1492
- const rootEquiv = parentScope.analysis.isolatedEquivalentVariables[rootVar];
1554
+ const rawRootEquiv = parentScope.analysis.isolatedEquivalentVariables[rootVar];
1555
+ // Normalize to array and use first string value
1556
+ const rootEquivs = Array.isArray(rawRootEquiv)
1557
+ ? rawRootEquiv
1558
+ : rawRootEquiv
1559
+ ? [rawRootEquiv]
1560
+ : [];
1561
+ const rootEquiv = rootEquivs.find((r) => typeof r === 'string');
1493
1562
  if (typeof rootEquiv === 'string') {
1494
1563
  return {
1495
1564
  resolvedPath: cleanPath(rootEquiv + restOfPath, allPaths),
@@ -1968,9 +2037,70 @@ export class ScopeDataStructure {
1968
2037
  // Update inverted index
1969
2038
  this.intermediatesOrderIndex.set(pathId, databaseEntry);
1970
2039
  if (intermediateIndex === 0) {
1971
- const isValidSourceCandidate = pathInfo.schemaPath.startsWith('signature[') ||
2040
+ let isValidSourceCandidate = pathInfo.schemaPath.startsWith('signature[') ||
1972
2041
  pathInfo.schemaPath.includes('functionCallReturnValue');
1973
- if (isValidSourceCandidate) {
2042
+ // Check if path STARTS with a spread pattern like [...var]
2043
+ // This handles cases like [...files][][0] or [...files].sort(...).functionCallReturnValue[][0]
2044
+ // where the spread source variable needs to be resolved to a signature path.
2045
+ // We do this REGARDLESS of isValidSourceCandidate because even paths containing
2046
+ // functionCallReturnValue may need spread resolution to trace back to the signature.
2047
+ const spreadMatch = pathInfo.schemaPath.match(/^\[\.\.\.(\w+)\]/);
2048
+ if (spreadMatch) {
2049
+ const spreadVar = spreadMatch[1];
2050
+ const spreadPattern = spreadMatch[0]; // The full [...var] match
2051
+ const scopeNode = this.scopeNodes[pathInfo.scopeNodeName];
2052
+ if (scopeNode?.equivalencies) {
2053
+ // Follow the equivalency chain to find a signature path
2054
+ // e.g., files (cyScope1) → files (root) → signature[0].files
2055
+ const resolveToSignature = (varName, currentScopeName, visited) => {
2056
+ const visitKey = `${currentScopeName}::${varName}`;
2057
+ if (visited.has(visitKey))
2058
+ return null;
2059
+ visited.add(visitKey);
2060
+ const currentScope = this.scopeNodes[currentScopeName];
2061
+ if (!currentScope?.equivalencies)
2062
+ return null;
2063
+ const varEquivs = currentScope.equivalencies[varName];
2064
+ if (!varEquivs)
2065
+ return null;
2066
+ // First check if any equivalency directly points to a signature path
2067
+ const signatureEquiv = varEquivs.find((eq) => eq.schemaPath.startsWith('signature['));
2068
+ if (signatureEquiv) {
2069
+ return signatureEquiv;
2070
+ }
2071
+ // Otherwise, follow the chain to other scopes
2072
+ for (const equiv of varEquivs) {
2073
+ // If the equivalency points to the same variable in a different scope,
2074
+ // follow the chain
2075
+ if (equiv.schemaPath === varName &&
2076
+ equiv.scopeNodeName !== currentScopeName) {
2077
+ const result = resolveToSignature(varName, equiv.scopeNodeName, visited);
2078
+ if (result)
2079
+ return result;
2080
+ }
2081
+ }
2082
+ return null;
2083
+ };
2084
+ const signatureEquiv = resolveToSignature(spreadVar, pathInfo.scopeNodeName, new Set());
2085
+ if (signatureEquiv) {
2086
+ // Replace ONLY the [...var] part with the resolved signature path
2087
+ // This preserves any suffix like .sort(...).functionCallReturnValue[][0]
2088
+ const resolvedPath = pathInfo.schemaPath.replace(spreadPattern, signatureEquiv.schemaPath);
2089
+ // Add the resolved path as a source candidate
2090
+ if (!databaseEntry.sourceCandidates.some((sc) => sc.schemaPath === resolvedPath &&
2091
+ sc.scopeNodeName === pathInfo.scopeNodeName)) {
2092
+ databaseEntry.sourceCandidates.push({
2093
+ scopeNodeName: pathInfo.scopeNodeName,
2094
+ schemaPath: resolvedPath,
2095
+ });
2096
+ }
2097
+ isValidSourceCandidate = true;
2098
+ }
2099
+ }
2100
+ }
2101
+ if (isValidSourceCandidate &&
2102
+ !databaseEntry.sourceCandidates.some((sc) => sc.schemaPath === pathInfo.schemaPath &&
2103
+ sc.scopeNodeName === pathInfo.scopeNodeName)) {
1974
2104
  databaseEntry.sourceCandidates.push(pathInfo);
1975
2105
  }
1976
2106
  }
@@ -2380,15 +2510,131 @@ export class ScopeDataStructure {
2380
2510
  if (!scopeNode) {
2381
2511
  return {};
2382
2512
  }
2383
- const entries = this.equivalencyDatabase.filter((entry) => entry.usages.some((usage) => usage.scopeNodeName === scopeNode.name));
2513
+ // Collect all descendant scope names (including the scope itself)
2514
+ // This ensures we include external calls from nested scopes like cyScope2
2515
+ const getAllDescendantScopeNames = (node) => {
2516
+ const names = new Set([node.name]);
2517
+ for (const child of node.children) {
2518
+ for (const name of getAllDescendantScopeNames(child)) {
2519
+ names.add(name);
2520
+ }
2521
+ }
2522
+ return names;
2523
+ };
2524
+ const treeNode = this.scopeTreeManager.findNode(scopeNode.name);
2525
+ const descendantScopeNames = treeNode
2526
+ ? getAllDescendantScopeNames(treeNode)
2527
+ : new Set([scopeNode.name]);
2528
+ // Get all external function calls made from this scope or any descendant scope
2529
+ // This allows us to include prop equivalencies from JSX components
2530
+ // that were rendered in nested scopes (e.g., FileTableRow called from cyScope2)
2531
+ const externalCallsFromScope = this.externalFunctionCalls.filter((efc) => descendantScopeNames.has(efc.callScope));
2532
+ const externalCallNames = new Set(externalCallsFromScope.map((efc) => efc.name));
2533
+ // Helper to check if a usage belongs to this scope (directly, via descendant, or via external call)
2534
+ const usageMatchesScope = (usage) => descendantScopeNames.has(usage.scopeNodeName) ||
2535
+ externalCallNames.has(usage.scopeNodeName);
2536
+ const entries = this.equivalencyDatabase.filter((entry) => entry.usages.some(usageMatchesScope));
2537
+ // Helper to resolve a source candidate through equivalency chains to find signature paths
2538
+ const resolveToSignature = (source, visited) => {
2539
+ const visitKey = `${source.scopeNodeName}::${source.schemaPath}`;
2540
+ if (visited.has(visitKey))
2541
+ return [];
2542
+ visited.add(visitKey);
2543
+ // If already a signature path, return as-is
2544
+ if (source.schemaPath.startsWith('signature[')) {
2545
+ return [source];
2546
+ }
2547
+ const currentScope = this.scopeNodes[source.scopeNodeName];
2548
+ if (!currentScope?.equivalencies)
2549
+ return [source];
2550
+ // Check for direct equivalencies FIRST (full path match)
2551
+ // This ensures paths like "useMemo(...).functionCallReturnValue" follow to "cyScope1::returnValue"
2552
+ // before prefix matching tries "useMemo(...)" which goes to the useMemo scope
2553
+ const directEquivs = currentScope.equivalencies[source.schemaPath];
2554
+ if (directEquivs?.length > 0) {
2555
+ const results = [];
2556
+ for (const equiv of directEquivs) {
2557
+ const resolved = resolveToSignature({
2558
+ scopeNodeName: equiv.scopeNodeName,
2559
+ schemaPath: equiv.schemaPath,
2560
+ }, visited);
2561
+ results.push(...resolved);
2562
+ }
2563
+ if (results.length > 0)
2564
+ return results;
2565
+ }
2566
+ // Handle spread patterns like [...items].sort().functionCallReturnValue
2567
+ // Extract the spread variable and resolve it through the equivalency chain
2568
+ const spreadMatch = source.schemaPath.match(/^\[\.\.\.(\w+)\]/);
2569
+ if (spreadMatch) {
2570
+ const spreadVar = spreadMatch[1];
2571
+ const spreadPattern = spreadMatch[0];
2572
+ const varEquivs = currentScope.equivalencies[spreadVar];
2573
+ if (varEquivs?.length > 0) {
2574
+ const results = [];
2575
+ for (const equiv of varEquivs) {
2576
+ // Follow the variable equivalency and then resolve from there
2577
+ const resolvedVar = resolveToSignature({
2578
+ scopeNodeName: equiv.scopeNodeName,
2579
+ schemaPath: equiv.schemaPath,
2580
+ }, visited);
2581
+ // For each resolved variable path, create the full path with array element suffix
2582
+ for (const rv of resolvedVar) {
2583
+ if (rv.schemaPath.startsWith('signature[')) {
2584
+ // Get the suffix after the spread pattern
2585
+ let suffix = source.schemaPath.slice(spreadPattern.length);
2586
+ // Clean the suffix: strip array method chains like .sort(...).functionCallReturnValue[]
2587
+ // These don't change the data identity, just transform it.
2588
+ // Keep only the final element access parts like [0], [1], etc.
2589
+ // Pattern: strip everything from a method call up through functionCallReturnValue[]
2590
+ suffix = suffix.replace(/\.\w+\([^)]*\)\.functionCallReturnValue\[\]/g, '');
2591
+ // Also handle simpler case without nested parens
2592
+ suffix = suffix.replace(/\.sort\(\w*\(\)\)\.functionCallReturnValue\[\]/g, '');
2593
+ // Add [] to indicate array element access from the spread
2594
+ const resolvedPath = rv.schemaPath + '[]' + suffix;
2595
+ results.push({
2596
+ scopeNodeName: rv.scopeNodeName,
2597
+ schemaPath: resolvedPath,
2598
+ });
2599
+ }
2600
+ }
2601
+ }
2602
+ if (results.length > 0)
2603
+ return results;
2604
+ }
2605
+ }
2606
+ // Try to find prefix equivalencies that can resolve this path
2607
+ // For path like "cyScope3().signature[0][0]", check "cyScope3().signature[0]", etc.
2608
+ const pathParts = this.splitPath(source.schemaPath);
2609
+ for (let i = pathParts.length - 1; i > 0; i--) {
2610
+ const prefix = this.joinPathParts(pathParts.slice(0, i));
2611
+ const suffix = this.joinPathParts(pathParts.slice(i));
2612
+ const prefixEquivs = currentScope.equivalencies[prefix];
2613
+ if (prefixEquivs?.length > 0) {
2614
+ const results = [];
2615
+ for (const equiv of prefixEquivs) {
2616
+ const newPath = this.joinPathParts([equiv.schemaPath, suffix]);
2617
+ const resolved = resolveToSignature({ scopeNodeName: equiv.scopeNodeName, schemaPath: newPath }, visited);
2618
+ results.push(...resolved);
2619
+ }
2620
+ if (results.length > 0)
2621
+ return results;
2622
+ }
2623
+ }
2624
+ return [source];
2625
+ };
2384
2626
  return entries.reduce((acc, entry) => {
2385
2627
  var _a;
2386
2628
  if (entry.sourceCandidates.length === 0)
2387
2629
  return acc;
2388
- const usages = entry.usages.filter((u) => u.scopeNodeName === scopeNode.name);
2630
+ const usages = entry.usages.filter(usageMatchesScope);
2389
2631
  for (const usage of usages) {
2390
2632
  acc[_a = usage.schemaPath] || (acc[_a] = []);
2391
- acc[usage.schemaPath].push(...entry.sourceCandidates);
2633
+ // Resolve each source candidate through the equivalency chain
2634
+ for (const source of entry.sourceCandidates) {
2635
+ const resolvedSources = resolveToSignature(source, new Set());
2636
+ acc[usage.schemaPath].push(...resolvedSources);
2637
+ }
2392
2638
  }
2393
2639
  return acc;
2394
2640
  }, {});
@@ -2677,13 +2923,35 @@ export class ScopeDataStructure {
2677
2923
  getEquivalentSignatureVariables() {
2678
2924
  const scopeNode = this.scopeNodes[this.scopeTreeManager.getRootName()];
2679
2925
  const equivalentSignatureVariables = {};
2926
+ // Helper to add equivalencies - accumulates into array if multiple values for same key
2927
+ // This is critical for OR expressions like `x = a || b` where x should map to both a and b
2928
+ const addEquivalency = (key, value) => {
2929
+ const existing = equivalentSignatureVariables[key];
2930
+ if (existing === undefined) {
2931
+ // First value - store as string
2932
+ equivalentSignatureVariables[key] = value;
2933
+ }
2934
+ else if (typeof existing === 'string') {
2935
+ if (existing !== value) {
2936
+ // Second different value - convert to array
2937
+ equivalentSignatureVariables[key] = [existing, value];
2938
+ }
2939
+ // Same value - no change needed
2940
+ }
2941
+ else {
2942
+ // Already an array - add if not already present
2943
+ if (!existing.includes(value)) {
2944
+ existing.push(value);
2945
+ }
2946
+ }
2947
+ };
2680
2948
  for (const [path, equivalentValues] of Object.entries(scopeNode.equivalencies)) {
2681
2949
  for (const equivalentValue of equivalentValues) {
2682
2950
  // Case 1: Props/signature equivalencies (existing behavior)
2683
2951
  // Maps local variable names to their signature paths
2684
2952
  // e.g., "propValue" -> "signature[0].prop"
2685
2953
  if (path.startsWith('signature[')) {
2686
- equivalentSignatureVariables[equivalentValue.schemaPath] = path;
2954
+ addEquivalency(equivalentValue.schemaPath, path);
2687
2955
  }
2688
2956
  // Case 2: Hook variable equivalencies (new behavior)
2689
2957
  // The equivalencies are stored as: path = variable name, schemaPath = data source
@@ -2711,7 +2979,7 @@ export class ScopeDataStructure {
2711
2979
  hookCallPath = dbEntry.sourceCandidates[0].schemaPath;
2712
2980
  }
2713
2981
  }
2714
- equivalentSignatureVariables[path] = hookCallPath;
2982
+ addEquivalency(path, hookCallPath);
2715
2983
  }
2716
2984
  }
2717
2985
  // Case 3: Destructured variables from local variables
@@ -2723,10 +2991,8 @@ export class ScopeDataStructure {
2723
2991
  !equivalentValue.schemaPath.startsWith('signature[') && // not a signature path
2724
2992
  !equivalentValue.schemaPath.endsWith('.functionCallReturnValue') // not already handled above
2725
2993
  ) {
2726
- // Only add if we haven't already captured this variable in Case 1 or 2
2727
- if (!(path in equivalentSignatureVariables)) {
2728
- equivalentSignatureVariables[path] = equivalentValue.schemaPath;
2729
- }
2994
+ // Add equivalency (will accumulate if multiple values for OR expressions)
2995
+ addEquivalency(path, equivalentValue.schemaPath);
2730
2996
  }
2731
2997
  // Case 4: Child component prop mappings (Fix 22)
2732
2998
  // When parent renders <ChildComponent prop={value} />, we get equivalencies like:
@@ -2737,7 +3003,7 @@ export class ScopeDataStructure {
2737
3003
  if (path.includes('().signature[') &&
2738
3004
  !equivalentValue.schemaPath.includes('()') // schemaPath is a simple variable, not a function call
2739
3005
  ) {
2740
- equivalentSignatureVariables[path] = equivalentValue.schemaPath;
3006
+ addEquivalency(path, equivalentValue.schemaPath);
2741
3007
  }
2742
3008
  // Case 5: Destructured function parameters (Fix 25)
2743
3009
  // When a function has destructured props: function Comp({ propA, propB }: Props)
@@ -2750,7 +3016,7 @@ export class ScopeDataStructure {
2750
3016
  if (!path.includes('.') && // path is a simple identifier (destructured prop name)
2751
3017
  equivalentValue.schemaPath.startsWith('signature[') // schemaPath IS a signature path
2752
3018
  ) {
2753
- equivalentSignatureVariables[path] = equivalentValue.schemaPath;
3019
+ addEquivalency(path, equivalentValue.schemaPath);
2754
3020
  }
2755
3021
  // Case 7: Method calls on variables that result in .functionCallReturnValue (Fix 33)
2756
3022
  // When we have patterns like:
@@ -2762,8 +3028,7 @@ export class ScopeDataStructure {
2762
3028
  // segments -> useParams().functionCallReturnValue['*'].split('/').functionCallReturnValue
2763
3029
  if (!path.includes('.') && // path is a simple identifier
2764
3030
  equivalentValue.schemaPath.endsWith('.functionCallReturnValue') && // ends with function return
2765
- equivalentValue.schemaPath.includes('.') && // has property access (method call)
2766
- !(path in equivalentSignatureVariables) // not already captured
3031
+ equivalentValue.schemaPath.includes('.') // has property access (method call)
2767
3032
  ) {
2768
3033
  // Check if this looks like a method call on a variable (not a hook call)
2769
3034
  // Hook calls look like: hookName() or hookName<T>()
@@ -2774,7 +3039,7 @@ export class ScopeDataStructure {
2774
3039
  const parenPos = hookCallPath.indexOf('(');
2775
3040
  if (dotBeforeParen !== -1 && dotBeforeParen < parenPos) {
2776
3041
  // This is a method call like "splat.split('/')", not a hook call
2777
- equivalentSignatureVariables[path] = equivalentValue.schemaPath;
3042
+ addEquivalency(path, equivalentValue.schemaPath);
2778
3043
  }
2779
3044
  }
2780
3045
  }
@@ -2801,8 +3066,9 @@ export class ScopeDataStructure {
2801
3066
  !equivalentValue.schemaPath.includes('()') // schemaPath is a simple variable
2802
3067
  ) {
2803
3068
  // Only add if not already present from the root scope
3069
+ // Root scope values take precedence over child scope values
2804
3070
  if (!(path in equivalentSignatureVariables)) {
2805
- equivalentSignatureVariables[path] = equivalentValue.schemaPath;
3071
+ addEquivalency(path, equivalentValue.schemaPath);
2806
3072
  }
2807
3073
  }
2808
3074
  }
@@ -2812,9 +3078,72 @@ export class ScopeDataStructure {
2812
3078
  // E.g., analysis → currentEntityAnalysis → useLoaderData().functionCallReturnValue.currentEntityAnalysis
2813
3079
  // We need multiple passes because resolutions can depend on each other
2814
3080
  const maxIterations = 5; // Prevent infinite loops
3081
+ // Helper function to resolve a single source path using equivalencies
3082
+ const resolveSourcePath = (sourcePath, equivMap) => {
3083
+ // Extract base variable from the path
3084
+ const dotIndex = sourcePath.indexOf('.');
3085
+ const bracketIndex = sourcePath.indexOf('[');
3086
+ let baseVar;
3087
+ let rest;
3088
+ if (dotIndex === -1 && bracketIndex === -1) {
3089
+ baseVar = sourcePath;
3090
+ rest = '';
3091
+ }
3092
+ else if (dotIndex === -1) {
3093
+ baseVar = sourcePath.slice(0, bracketIndex);
3094
+ rest = sourcePath.slice(bracketIndex);
3095
+ }
3096
+ else if (bracketIndex === -1) {
3097
+ baseVar = sourcePath.slice(0, dotIndex);
3098
+ rest = sourcePath.slice(dotIndex);
3099
+ }
3100
+ else {
3101
+ const firstIndex = Math.min(dotIndex, bracketIndex);
3102
+ baseVar = sourcePath.slice(0, firstIndex);
3103
+ rest = sourcePath.slice(firstIndex);
3104
+ }
3105
+ // Look up the base variable in equivalencies
3106
+ if (baseVar in equivMap && equivMap[baseVar] !== sourcePath) {
3107
+ const baseResolved = equivMap[baseVar];
3108
+ // Skip if baseResolved is an array (handle later)
3109
+ if (Array.isArray(baseResolved))
3110
+ return null;
3111
+ // If it resolves to a signature path, build the full resolved path
3112
+ if (baseResolved.startsWith('signature[') ||
3113
+ baseResolved.includes('()')) {
3114
+ if (baseResolved.endsWith('()')) {
3115
+ return baseResolved + '.functionCallReturnValue' + rest;
3116
+ }
3117
+ return baseResolved + rest;
3118
+ }
3119
+ }
3120
+ return null;
3121
+ };
2815
3122
  for (let iteration = 0; iteration < maxIterations; iteration++) {
2816
3123
  let changed = false;
2817
- for (const [varName, sourcePath] of Object.entries(equivalentSignatureVariables)) {
3124
+ for (const [varName, sourcePathOrArray] of Object.entries(equivalentSignatureVariables)) {
3125
+ // Handle arrays (OR expressions) by resolving each element
3126
+ if (Array.isArray(sourcePathOrArray)) {
3127
+ const resolvedArray = [];
3128
+ let arrayChanged = false;
3129
+ for (const sourcePath of sourcePathOrArray) {
3130
+ // Try to resolve this path using transitive resolution
3131
+ const resolved = resolveSourcePath(sourcePath, equivalentSignatureVariables);
3132
+ if (resolved && resolved !== sourcePath) {
3133
+ resolvedArray.push(resolved);
3134
+ arrayChanged = true;
3135
+ }
3136
+ else {
3137
+ resolvedArray.push(sourcePath);
3138
+ }
3139
+ }
3140
+ if (arrayChanged) {
3141
+ equivalentSignatureVariables[varName] = resolvedArray;
3142
+ changed = true;
3143
+ }
3144
+ continue;
3145
+ }
3146
+ const sourcePath = sourcePathOrArray;
2818
3147
  // Skip if already fully resolved (contains function call syntax)
2819
3148
  // BUT first check for computed value patterns that need resolution (Fix 28)
2820
3149
  // AND method call patterns that need base variable resolution (Fix 33)
@@ -2867,6 +3196,9 @@ export class ScopeDataStructure {
2867
3196
  if (baseVar in equivalentSignatureVariables &&
2868
3197
  baseVar !== varName) {
2869
3198
  const baseResolved = equivalentSignatureVariables[baseVar];
3199
+ // Skip if baseResolved is an array (OR expression)
3200
+ if (Array.isArray(baseResolved))
3201
+ continue;
2870
3202
  // Only resolve if the base resolved to something useful (contains () or .)
2871
3203
  if (baseResolved.includes('()') || baseResolved.includes('.')) {
2872
3204
  const newPath = baseResolved + rest;
@@ -2922,7 +3254,13 @@ export class ScopeDataStructure {
2922
3254
  rest = '';
2923
3255
  }
2924
3256
  if (baseVar in equivalentSignatureVariables && baseVar !== varName) {
2925
- const baseResolved = equivalentSignatureVariables[baseVar];
3257
+ // Handle array case (OR expressions) - use first element
3258
+ const rawBaseResolved = equivalentSignatureVariables[baseVar];
3259
+ const baseResolved = Array.isArray(rawBaseResolved)
3260
+ ? rawBaseResolved[0]
3261
+ : rawBaseResolved;
3262
+ if (!baseResolved)
3263
+ continue;
2926
3264
  // If the base resolves to a hook call, add .functionCallReturnValue
2927
3265
  if (baseResolved.endsWith('()')) {
2928
3266
  const newPath = baseResolved + '.functionCallReturnValue' + rest;