@codeyam/codeyam-cli 0.1.0-staging.b8a55ba → 0.1.0-staging.d0ad4ae

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 (340) hide show
  1. package/analyzer-template/.build-info.json +7 -7
  2. package/analyzer-template/common/execAsync.ts +1 -1
  3. package/analyzer-template/log.txt +3 -3
  4. package/analyzer-template/package.json +7 -4
  5. package/analyzer-template/packages/ai/package.json +1 -1
  6. package/analyzer-template/packages/ai/src/lib/astScopes/processExpression.ts +14 -1
  7. package/analyzer-template/packages/ai/src/lib/checkAllAttributes.ts +29 -10
  8. package/analyzer-template/packages/ai/src/lib/dataStructure/ScopeDataStructure.ts +120 -19
  9. package/analyzer-template/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/JavascriptFrameworkManager.ts +2 -1
  10. package/analyzer-template/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/MuiManager.ts +91 -35
  11. package/analyzer-template/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/ReactFrameworkManager.ts +110 -74
  12. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/cleanNonObjectFunctions.ts +11 -0
  13. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/convertNullToUndefinedBySchema.ts +98 -0
  14. package/analyzer-template/packages/ai/src/lib/deepEqual.ts +30 -0
  15. package/analyzer-template/packages/ai/src/lib/findMatchingAttribute.ts +24 -17
  16. package/analyzer-template/packages/ai/src/lib/gatherRelevantDependentKeyAttributes.ts +214 -39
  17. package/analyzer-template/packages/ai/src/lib/generateChangesEntityKeyAttributes.ts +54 -1
  18. package/analyzer-template/packages/ai/src/lib/generateChangesEntityScenarioData.ts +72 -6
  19. package/analyzer-template/packages/ai/src/lib/generateChangesEntityScenarios.ts +12 -5
  20. package/analyzer-template/packages/ai/src/lib/generateEntityScenarioData.ts +39 -23
  21. package/analyzer-template/packages/ai/src/lib/promptGenerators/generateChangesEntityScenariosGenerator.ts +32 -0
  22. package/analyzer-template/packages/analyze/src/lib/FileAnalyzer.ts +14 -0
  23. package/analyzer-template/packages/analyze/src/lib/asts/nodes/index.ts +1 -0
  24. package/analyzer-template/packages/analyze/src/lib/asts/nodes/isAsyncFunction.ts +67 -0
  25. package/analyzer-template/packages/analyze/src/lib/files/analyze/analyzeEntities/prepareDataStructures.ts +73 -69
  26. package/analyzer-template/packages/analyze/src/lib/files/analyze/analyzeEntities.ts +6 -0
  27. package/analyzer-template/packages/analyze/src/lib/files/analyze/findOrCreateEntity.ts +3 -0
  28. package/analyzer-template/packages/analyze/src/lib/files/analyzeChange.ts +22 -6
  29. package/analyzer-template/packages/analyze/src/lib/files/analyzeEntity.ts +9 -5
  30. package/analyzer-template/packages/analyze/src/lib/files/scenarios/enrichArrayTypesFromChildSignatures.ts +49 -11
  31. package/analyzer-template/packages/analyze/src/lib/files/scenarios/enrichUnknownTypesFromSourceEquivalencies.ts +102 -0
  32. package/analyzer-template/packages/analyze/src/lib/files/scenarios/gatherDataForMocks.ts +399 -52
  33. package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateChangesScenarios.ts +128 -2
  34. package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateDataStructure.ts +114 -70
  35. package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateScenarioData.ts +34 -129
  36. package/analyzer-template/packages/analyze/src/lib/files/scenarios/mergeInDependentDataStructure.ts +155 -79
  37. package/analyzer-template/packages/aws/codebuild/index.ts +1 -0
  38. package/analyzer-template/packages/aws/dist/src/lib/codebuild/waitForBuild.d.ts +11 -1
  39. package/analyzer-template/packages/aws/dist/src/lib/codebuild/waitForBuild.d.ts.map +1 -1
  40. package/analyzer-template/packages/aws/dist/src/lib/codebuild/waitForBuild.js +29 -18
  41. package/analyzer-template/packages/aws/dist/src/lib/codebuild/waitForBuild.js.map +1 -1
  42. package/analyzer-template/packages/aws/dist/src/lib/ecs/ecsDefineContainer.d.ts +2 -2
  43. package/analyzer-template/packages/aws/dist/src/lib/ecs/ecsDefineContainer.d.ts.map +1 -1
  44. package/analyzer-template/packages/aws/dist/src/lib/ecs/ecsDefineContainer.js +2 -2
  45. package/analyzer-template/packages/aws/dist/src/lib/ecs/ecsDefineContainer.js.map +1 -1
  46. package/analyzer-template/packages/aws/dist/src/lib/ecs/ecsTaskFactory.d.ts +8 -18
  47. package/analyzer-template/packages/aws/dist/src/lib/ecs/ecsTaskFactory.d.ts.map +1 -1
  48. package/analyzer-template/packages/aws/dist/src/lib/ecs/ecsTaskFactory.js +17 -61
  49. package/analyzer-template/packages/aws/dist/src/lib/ecs/ecsTaskFactory.js.map +1 -1
  50. package/analyzer-template/packages/aws/dist/src/lib/s3/uploadFileToS3.d.ts.map +1 -1
  51. package/analyzer-template/packages/aws/dist/src/lib/s3/uploadFileToS3.js +8 -1
  52. package/analyzer-template/packages/aws/dist/src/lib/s3/uploadFileToS3.js.map +1 -1
  53. package/analyzer-template/packages/aws/package.json +1 -1
  54. package/analyzer-template/packages/aws/src/lib/codebuild/waitForBuild.ts +43 -19
  55. package/analyzer-template/packages/aws/src/lib/ecs/ecsDefineContainer.ts +3 -3
  56. package/analyzer-template/packages/aws/src/lib/ecs/ecsTaskFactory.ts +17 -69
  57. package/analyzer-template/packages/aws/src/lib/s3/uploadFileToS3.ts +8 -1
  58. package/analyzer-template/packages/generate/index.ts +3 -0
  59. package/analyzer-template/packages/generate/src/lib/componentScenarioPage/componentScenarioPageNext.ts +17 -1
  60. package/analyzer-template/packages/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.ts +193 -0
  61. package/analyzer-template/packages/generate/src/lib/componentScenarioPage/generateScenarioServerComponent.ts +73 -0
  62. package/analyzer-template/packages/generate/src/lib/scenarioComponentForServer.ts +114 -0
  63. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/entitiesTable.d.ts +1 -0
  64. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/entitiesTable.d.ts.map +1 -1
  65. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/scenariosTable.d.ts +1 -0
  66. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/scenariosTable.d.ts.map +1 -1
  67. package/analyzer-template/packages/github/dist/generate/index.d.ts +3 -0
  68. package/analyzer-template/packages/github/dist/generate/index.d.ts.map +1 -1
  69. package/analyzer-template/packages/github/dist/generate/index.js +3 -0
  70. package/analyzer-template/packages/github/dist/generate/index.js.map +1 -1
  71. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/componentScenarioPageNext.d.ts.map +1 -1
  72. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/componentScenarioPageNext.js +16 -1
  73. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/componentScenarioPageNext.js.map +1 -1
  74. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.d.ts +9 -0
  75. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.d.ts.map +1 -0
  76. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.js +189 -0
  77. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.js.map +1 -0
  78. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/generateScenarioServerComponent.d.ts +20 -0
  79. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/generateScenarioServerComponent.d.ts.map +1 -0
  80. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/generateScenarioServerComponent.js +53 -0
  81. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/generateScenarioServerComponent.js.map +1 -0
  82. package/analyzer-template/packages/github/dist/generate/src/lib/scenarioComponentForServer.d.ts +8 -0
  83. package/analyzer-template/packages/github/dist/generate/src/lib/scenarioComponentForServer.d.ts.map +1 -0
  84. package/analyzer-template/packages/github/dist/generate/src/lib/scenarioComponentForServer.js +89 -0
  85. package/analyzer-template/packages/github/dist/generate/src/lib/scenarioComponentForServer.js.map +1 -0
  86. package/analyzer-template/packages/github/dist/github/src/lib/loadOrCreateCommit.d.ts.map +1 -1
  87. package/analyzer-template/packages/github/dist/github/src/lib/loadOrCreateCommit.js +10 -0
  88. package/analyzer-template/packages/github/dist/github/src/lib/loadOrCreateCommit.js.map +1 -1
  89. package/analyzer-template/packages/github/dist/github/src/lib/syncPrimaryBranch.d.ts.map +1 -1
  90. package/analyzer-template/packages/github/dist/github/src/lib/syncPrimaryBranch.js +3 -0
  91. package/analyzer-template/packages/github/dist/github/src/lib/syncPrimaryBranch.js.map +1 -1
  92. package/analyzer-template/packages/github/dist/types/src/types/Entity.d.ts +2 -0
  93. package/analyzer-template/packages/github/dist/types/src/types/Entity.d.ts.map +1 -1
  94. package/analyzer-template/packages/github/dist/types/src/types/Scenario.d.ts +6 -0
  95. package/analyzer-template/packages/github/dist/types/src/types/Scenario.d.ts.map +1 -1
  96. package/analyzer-template/packages/github/src/lib/loadOrCreateCommit.ts +14 -0
  97. package/analyzer-template/packages/github/src/lib/syncPrimaryBranch.ts +2 -0
  98. package/analyzer-template/packages/process/index.ts +2 -0
  99. package/analyzer-template/packages/process/package.json +12 -0
  100. package/analyzer-template/packages/process/tsconfig.json +8 -0
  101. package/analyzer-template/packages/types/src/types/Entity.ts +2 -0
  102. package/analyzer-template/packages/types/src/types/Scenario.ts +6 -0
  103. package/analyzer-template/packages/utils/dist/types/src/types/Entity.d.ts +2 -0
  104. package/analyzer-template/packages/utils/dist/types/src/types/Entity.d.ts.map +1 -1
  105. package/analyzer-template/packages/utils/dist/types/src/types/Scenario.d.ts +6 -0
  106. package/analyzer-template/packages/utils/dist/types/src/types/Scenario.d.ts.map +1 -1
  107. package/analyzer-template/playwright/capture.ts +37 -18
  108. package/analyzer-template/playwright/waitForServer.ts +21 -6
  109. package/analyzer-template/project/constructMockCode.ts +781 -140
  110. package/analyzer-template/project/orchestrateCapture/KyselyAnalysisLoader.ts +3 -6
  111. package/analyzer-template/project/orchestrateCapture.ts +10 -3
  112. package/analyzer-template/project/reconcileMockDataKeys.ts +28 -100
  113. package/analyzer-template/project/runAnalysis.ts +5 -0
  114. package/analyzer-template/project/serverOnlyModules.ts +127 -2
  115. package/analyzer-template/project/start.ts +5 -3
  116. package/analyzer-template/project/startScenarioCapture.ts +6 -0
  117. package/analyzer-template/project/writeMockDataTsx.ts +50 -22
  118. package/analyzer-template/project/writeScenarioClientWrapper.ts +21 -0
  119. package/analyzer-template/project/writeScenarioComponents.ts +162 -100
  120. package/analyzer-template/project/writeScenarioFiles.ts +26 -0
  121. package/analyzer-template/project/writeSimpleRoot.ts +11 -35
  122. package/analyzer-template/scripts/comboWorkerLoop.cjs +1 -0
  123. package/analyzer-template/scripts/defaultCmd.sh +9 -0
  124. package/background/src/lib/local/createLocalAnalyzer.js +1 -29
  125. package/background/src/lib/local/createLocalAnalyzer.js.map +1 -1
  126. package/background/src/lib/local/execAsync.js +1 -1
  127. package/background/src/lib/local/execAsync.js.map +1 -1
  128. package/background/src/lib/virtualized/common/execAsync.js +1 -1
  129. package/background/src/lib/virtualized/common/execAsync.js.map +1 -1
  130. package/background/src/lib/virtualized/project/constructMockCode.js +718 -127
  131. package/background/src/lib/virtualized/project/constructMockCode.js.map +1 -1
  132. package/background/src/lib/virtualized/project/orchestrateCapture/KyselyAnalysisLoader.js +3 -2
  133. package/background/src/lib/virtualized/project/orchestrateCapture/KyselyAnalysisLoader.js.map +1 -1
  134. package/background/src/lib/virtualized/project/orchestrateCapture.js +7 -4
  135. package/background/src/lib/virtualized/project/orchestrateCapture.js.map +1 -1
  136. package/background/src/lib/virtualized/project/reconcileMockDataKeys.js +25 -61
  137. package/background/src/lib/virtualized/project/reconcileMockDataKeys.js.map +1 -1
  138. package/background/src/lib/virtualized/project/runAnalysis.js +4 -0
  139. package/background/src/lib/virtualized/project/runAnalysis.js.map +1 -1
  140. package/background/src/lib/virtualized/project/serverOnlyModules.js +106 -3
  141. package/background/src/lib/virtualized/project/serverOnlyModules.js.map +1 -1
  142. package/background/src/lib/virtualized/project/start.js +5 -3
  143. package/background/src/lib/virtualized/project/start.js.map +1 -1
  144. package/background/src/lib/virtualized/project/startScenarioCapture.js +7 -0
  145. package/background/src/lib/virtualized/project/startScenarioCapture.js.map +1 -1
  146. package/background/src/lib/virtualized/project/writeMockDataTsx.js +52 -23
  147. package/background/src/lib/virtualized/project/writeMockDataTsx.js.map +1 -1
  148. package/background/src/lib/virtualized/project/writeScenarioClientWrapper.js +15 -0
  149. package/background/src/lib/virtualized/project/writeScenarioClientWrapper.js.map +1 -0
  150. package/background/src/lib/virtualized/project/writeScenarioComponents.js +136 -83
  151. package/background/src/lib/virtualized/project/writeScenarioComponents.js.map +1 -1
  152. package/background/src/lib/virtualized/project/writeScenarioFiles.js +19 -0
  153. package/background/src/lib/virtualized/project/writeScenarioFiles.js.map +1 -1
  154. package/background/src/lib/virtualized/project/writeSimpleRoot.js +11 -34
  155. package/background/src/lib/virtualized/project/writeSimpleRoot.js.map +1 -1
  156. package/codeyam-cli/src/cli.js +5 -1
  157. package/codeyam-cli/src/cli.js.map +1 -1
  158. package/codeyam-cli/src/commands/analyze.js +1 -1
  159. package/codeyam-cli/src/commands/analyze.js.map +1 -1
  160. package/codeyam-cli/src/commands/baseline.js +177 -0
  161. package/codeyam-cli/src/commands/baseline.js.map +1 -0
  162. package/codeyam-cli/src/commands/status.js +23 -1
  163. package/codeyam-cli/src/commands/status.js.map +1 -1
  164. package/codeyam-cli/src/commands/test-startup.js +1 -1
  165. package/codeyam-cli/src/commands/test-startup.js.map +1 -1
  166. package/codeyam-cli/src/commands/wipe.js +108 -0
  167. package/codeyam-cli/src/commands/wipe.js.map +1 -0
  168. package/codeyam-cli/src/utils/database.js +91 -5
  169. package/codeyam-cli/src/utils/database.js.map +1 -1
  170. package/codeyam-cli/src/utils/git.js +79 -0
  171. package/codeyam-cli/src/utils/git.js.map +1 -0
  172. package/codeyam-cli/src/utils/queue/job.js +104 -0
  173. package/codeyam-cli/src/utils/queue/job.js.map +1 -1
  174. package/codeyam-cli/src/utils/queue/persistence.js.map +1 -1
  175. package/codeyam-cli/src/utils/wipe.js +128 -0
  176. package/codeyam-cli/src/utils/wipe.js.map +1 -0
  177. package/codeyam-cli/src/webserver/app/lib/database.js +66 -17
  178. package/codeyam-cli/src/webserver/app/lib/database.js.map +1 -1
  179. package/codeyam-cli/src/webserver/build/client/assets/{EntityItem-wXL1Z2Aq.js → EntityItem-Cmysw5OP.js} +1 -1
  180. package/codeyam-cli/src/webserver/build/client/assets/{EntityTypeBadge-CzGX-miz.js → EntityTypeBadge-DLqD3qNt.js} +1 -1
  181. package/codeyam-cli/src/webserver/build/client/assets/{EntityTypeIcon-CXFKsCOD.js → EntityTypeIcon-CAneekK2.js} +1 -1
  182. package/codeyam-cli/src/webserver/build/client/assets/{InteractivePreview-D-9pXIaY.js → InteractivePreview-Cu16OUmx.js} +2 -2
  183. package/codeyam-cli/src/webserver/build/client/assets/{LibraryFunctionPreview-CBQPrpT0.js → LibraryFunctionPreview-CVtiBnY5.js} +1 -1
  184. package/codeyam-cli/src/webserver/build/client/assets/{LoadingDots-D1CdlbrV.js → LoadingDots-B0GLXMsr.js} +1 -1
  185. package/codeyam-cli/src/webserver/build/client/assets/{LogViewer-wDPcZNKx.js → LogViewer-xgeCVgSM.js} +1 -1
  186. package/codeyam-cli/src/webserver/build/client/assets/{ReportIssueModal-4lcOlid-.js → ReportIssueModal-DcAUIpD_.js} +1 -1
  187. package/codeyam-cli/src/webserver/build/client/assets/{SafeScreenshot-BfmDgXxG.js → SafeScreenshot-DuDvi0jm.js} +1 -1
  188. package/codeyam-cli/src/webserver/build/client/assets/ScenarioViewer-BMKg0SAF.js +15 -0
  189. package/codeyam-cli/src/webserver/build/client/assets/{TruncatedFilePath-6J7zDUD5.js → TruncatedFilePath-DyFZkK0l.js} +1 -1
  190. package/codeyam-cli/src/webserver/build/client/assets/_index-DSmTpjmK.js +11 -0
  191. package/codeyam-cli/src/webserver/build/client/assets/activity.(_tab)-BF_aK4y6.js +32 -0
  192. package/codeyam-cli/src/webserver/build/client/assets/{chevron-down-BYimnrHg.js → chevron-down-Cx24_aWc.js} +1 -1
  193. package/codeyam-cli/src/webserver/build/client/assets/chunk-EPOLDU6W-CXRTFQ3F.js +51 -0
  194. package/codeyam-cli/src/webserver/build/client/assets/{circle-check-CaVsIRxt.js → circle-check-BOARzkeR.js} +1 -1
  195. package/codeyam-cli/src/webserver/build/client/assets/{createLucideIcon-CgUsG7ib.js → createLucideIcon-BdhJEx6B.js} +1 -1
  196. package/codeyam-cli/src/webserver/build/client/assets/{dev.empty-DW_hdGUc.js → dev.empty-RJCf3Tvw.js} +1 -1
  197. package/codeyam-cli/src/webserver/build/client/assets/{entity._sha._-zUEpfPsu.js → entity._sha._-D0-YwkBh.js} +12 -12
  198. package/codeyam-cli/src/webserver/build/client/assets/entity._sha.scenarios._scenarioId.fullscreen-EylcgScH.js +1 -0
  199. package/codeyam-cli/src/webserver/build/client/assets/{entity._sha_.create-scenario-D_3ero5o.js → entity._sha_.create-scenario-DMe7kvgo.js} +1 -1
  200. package/codeyam-cli/src/webserver/build/client/assets/{entity._sha_.edit._scenarioId-CfLCUi9S.js → entity._sha_.edit._scenarioId-C1H_a_Y3.js} +1 -1
  201. package/codeyam-cli/src/webserver/build/client/assets/{entry.client-DKJyZfAY.js → entry.client-CS2cb_eZ.js} +6 -6
  202. package/codeyam-cli/src/webserver/build/client/assets/{fileTableUtils-DAtOlaWE.js → fileTableUtils-DMJ7zii9.js} +1 -1
  203. package/codeyam-cli/src/webserver/build/client/assets/{files-ClR0d32A.js → files-BW7Cyeyi.js} +1 -1
  204. package/codeyam-cli/src/webserver/build/client/assets/{git-D62Lxxmv.js → git-CZu4fif0.js} +2 -2
  205. package/codeyam-cli/src/webserver/build/client/assets/globals-wHVy_II5.css +1 -0
  206. package/codeyam-cli/src/webserver/build/client/assets/{index-CzNNiTkw.js → index-B1h680n5.js} +1 -1
  207. package/codeyam-cli/src/webserver/build/client/assets/{index-BosqDOlH.js → index-lzqtyFU8.js} +1 -1
  208. package/codeyam-cli/src/webserver/build/client/assets/{loader-circle-CNp9QFCX.js → loader-circle-B7B9V-bu.js} +1 -1
  209. package/codeyam-cli/src/webserver/build/client/assets/{manifest-09d684be.js → manifest-2d191949.js} +1 -1
  210. package/codeyam-cli/src/webserver/build/client/assets/root-FHgpM6gc.js +56 -0
  211. package/codeyam-cli/src/webserver/build/client/assets/{search-DDGjYAMJ.js → search-CxXUmBSd.js} +1 -1
  212. package/codeyam-cli/src/webserver/build/client/assets/{settings-DgTyB-Wg.js → settings-6D8k8Jp5.js} +1 -1
  213. package/codeyam-cli/src/webserver/build/client/assets/simulations-CDJZnWhN.js +1 -0
  214. package/codeyam-cli/src/webserver/build/client/assets/{triangle-alert-CBc5dE1s.js → triangle-alert-B6LgvRJg.js} +1 -1
  215. package/codeyam-cli/src/webserver/build/client/assets/{useCustomSizes-BMIGFP-m.js → useCustomSizes-Dv18q8LD.js} +1 -1
  216. package/codeyam-cli/src/webserver/build/client/assets/{useInteractiveMode-Dk_FQqWJ.js → useInteractiveMode-0ToGk4K3.js} +1 -1
  217. package/codeyam-cli/src/webserver/build/client/assets/{useLastLogLine-BqPPNjAl.js → useLastLogLine-aSv48UbS.js} +1 -1
  218. package/codeyam-cli/src/webserver/build/client/assets/{useReportContext-DsJbgMY9.js → useReportContext-1BX144Eg.js} +1 -1
  219. package/codeyam-cli/src/webserver/build/client/assets/{useToast-DWHcCcl1.js → useToast-mBRpZPiu.js} +1 -1
  220. package/codeyam-cli/src/webserver/build/server/assets/{index-CV6i1S1A.js → index-pU0o5t1o.js} +1 -1
  221. package/codeyam-cli/src/webserver/build/server/assets/server-build-YzfkRwdn.js +178 -0
  222. package/codeyam-cli/src/webserver/build/server/index.js +1 -1
  223. package/codeyam-cli/src/webserver/build-info.json +5 -5
  224. package/codeyam-cli/templates/codeyam-setup-skill.md +138 -3
  225. package/codeyam-cli/templates/debug-codeyam.md +7 -2
  226. package/package.json +5 -5
  227. package/packages/ai/src/lib/astScopes/processExpression.js +13 -1
  228. package/packages/ai/src/lib/astScopes/processExpression.js.map +1 -1
  229. package/packages/ai/src/lib/checkAllAttributes.js +24 -9
  230. package/packages/ai/src/lib/checkAllAttributes.js.map +1 -1
  231. package/packages/ai/src/lib/dataStructure/ScopeDataStructure.js +94 -18
  232. package/packages/ai/src/lib/dataStructure/ScopeDataStructure.js.map +1 -1
  233. package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/JavascriptFrameworkManager.js +2 -1
  234. package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/JavascriptFrameworkManager.js.map +1 -1
  235. package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/MuiManager.js +51 -23
  236. package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/MuiManager.js.map +1 -1
  237. package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/ReactFrameworkManager.js +70 -54
  238. package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/ReactFrameworkManager.js.map +1 -1
  239. package/packages/ai/src/lib/dataStructure/helpers/cleanNonObjectFunctions.js +11 -0
  240. package/packages/ai/src/lib/dataStructure/helpers/cleanNonObjectFunctions.js.map +1 -1
  241. package/packages/ai/src/lib/dataStructure/helpers/convertNullToUndefinedBySchema.js +86 -0
  242. package/packages/ai/src/lib/dataStructure/helpers/convertNullToUndefinedBySchema.js.map +1 -0
  243. package/packages/ai/src/lib/deepEqual.js +32 -0
  244. package/packages/ai/src/lib/deepEqual.js.map +1 -0
  245. package/packages/ai/src/lib/findMatchingAttribute.js +20 -16
  246. package/packages/ai/src/lib/findMatchingAttribute.js.map +1 -1
  247. package/packages/ai/src/lib/gatherRelevantDependentKeyAttributes.js +168 -41
  248. package/packages/ai/src/lib/gatherRelevantDependentKeyAttributes.js.map +1 -1
  249. package/packages/ai/src/lib/generateChangesEntityKeyAttributes.js +42 -1
  250. package/packages/ai/src/lib/generateChangesEntityKeyAttributes.js.map +1 -1
  251. package/packages/ai/src/lib/generateChangesEntityScenarioData.js +59 -3
  252. package/packages/ai/src/lib/generateChangesEntityScenarioData.js.map +1 -1
  253. package/packages/ai/src/lib/generateChangesEntityScenarios.js +6 -6
  254. package/packages/ai/src/lib/generateChangesEntityScenarios.js.map +1 -1
  255. package/packages/ai/src/lib/generateEntityScenarioData.js +32 -23
  256. package/packages/ai/src/lib/generateEntityScenarioData.js.map +1 -1
  257. package/packages/ai/src/lib/promptGenerators/generateChangesEntityScenariosGenerator.js +20 -1
  258. package/packages/ai/src/lib/promptGenerators/generateChangesEntityScenariosGenerator.js.map +1 -1
  259. package/packages/analyze/src/lib/FileAnalyzer.js +15 -0
  260. package/packages/analyze/src/lib/FileAnalyzer.js.map +1 -1
  261. package/packages/analyze/src/lib/asts/nodes/index.js +1 -0
  262. package/packages/analyze/src/lib/asts/nodes/index.js.map +1 -1
  263. package/packages/analyze/src/lib/asts/nodes/isAsyncFunction.js +52 -0
  264. package/packages/analyze/src/lib/asts/nodes/isAsyncFunction.js.map +1 -0
  265. package/packages/analyze/src/lib/files/analyze/analyzeEntities/prepareDataStructures.js +59 -50
  266. package/packages/analyze/src/lib/files/analyze/analyzeEntities/prepareDataStructures.js.map +1 -1
  267. package/packages/analyze/src/lib/files/analyze/analyzeEntities.js +6 -0
  268. package/packages/analyze/src/lib/files/analyze/analyzeEntities.js.map +1 -1
  269. package/packages/analyze/src/lib/files/analyze/findOrCreateEntity.js +2 -0
  270. package/packages/analyze/src/lib/files/analyze/findOrCreateEntity.js.map +1 -1
  271. package/packages/analyze/src/lib/files/analyzeChange.js +14 -4
  272. package/packages/analyze/src/lib/files/analyzeChange.js.map +1 -1
  273. package/packages/analyze/src/lib/files/analyzeEntity.js +7 -6
  274. package/packages/analyze/src/lib/files/analyzeEntity.js.map +1 -1
  275. package/packages/analyze/src/lib/files/scenarios/enrichArrayTypesFromChildSignatures.js +44 -10
  276. package/packages/analyze/src/lib/files/scenarios/enrichArrayTypesFromChildSignatures.js.map +1 -1
  277. package/packages/analyze/src/lib/files/scenarios/enrichUnknownTypesFromSourceEquivalencies.js +85 -0
  278. package/packages/analyze/src/lib/files/scenarios/enrichUnknownTypesFromSourceEquivalencies.js.map +1 -0
  279. package/packages/analyze/src/lib/files/scenarios/gatherDataForMocks.js +314 -52
  280. package/packages/analyze/src/lib/files/scenarios/gatherDataForMocks.js.map +1 -1
  281. package/packages/analyze/src/lib/files/scenarios/generateChangesScenarios.js +97 -2
  282. package/packages/analyze/src/lib/files/scenarios/generateChangesScenarios.js.map +1 -1
  283. package/packages/analyze/src/lib/files/scenarios/generateDataStructure.js +88 -52
  284. package/packages/analyze/src/lib/files/scenarios/generateDataStructure.js.map +1 -1
  285. package/packages/analyze/src/lib/files/scenarios/generateScenarioData.js +26 -98
  286. package/packages/analyze/src/lib/files/scenarios/generateScenarioData.js.map +1 -1
  287. package/packages/analyze/src/lib/files/scenarios/mergeInDependentDataStructure.js +141 -75
  288. package/packages/analyze/src/lib/files/scenarios/mergeInDependentDataStructure.js.map +1 -1
  289. package/packages/aws/src/lib/ecs/ecsDefineContainer.js +2 -2
  290. package/packages/aws/src/lib/ecs/ecsDefineContainer.js.map +1 -1
  291. package/packages/aws/src/lib/ecs/ecsTaskFactory.js +17 -61
  292. package/packages/aws/src/lib/ecs/ecsTaskFactory.js.map +1 -1
  293. package/packages/generate/index.js +3 -0
  294. package/packages/generate/index.js.map +1 -1
  295. package/packages/generate/src/lib/componentScenarioPage/componentScenarioPageNext.js +16 -1
  296. package/packages/generate/src/lib/componentScenarioPage/componentScenarioPageNext.js.map +1 -1
  297. package/packages/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.js +189 -0
  298. package/packages/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.js.map +1 -0
  299. package/packages/generate/src/lib/componentScenarioPage/generateScenarioServerComponent.js +53 -0
  300. package/packages/generate/src/lib/componentScenarioPage/generateScenarioServerComponent.js.map +1 -0
  301. package/packages/generate/src/lib/scenarioComponentForServer.js +89 -0
  302. package/packages/generate/src/lib/scenarioComponentForServer.js.map +1 -0
  303. package/packages/github/src/lib/loadOrCreateCommit.js +10 -0
  304. package/packages/github/src/lib/loadOrCreateCommit.js.map +1 -1
  305. package/packages/github/src/lib/syncPrimaryBranch.js +3 -0
  306. package/packages/github/src/lib/syncPrimaryBranch.js.map +1 -1
  307. package/packages/process/index.js +3 -0
  308. package/packages/process/index.js.map +1 -0
  309. package/packages/process/src/GlobalProcessManager.js.map +1 -0
  310. package/{background/src/lib/process → packages/process/src}/ProcessManager.js +1 -1
  311. package/packages/process/src/ProcessManager.js.map +1 -0
  312. package/packages/process/src/index.js.map +1 -0
  313. package/packages/process/src/managedExecAsync.js.map +1 -0
  314. package/analyzer-template/process/INTEGRATION_COMPLETE.md +0 -333
  315. package/analyzer-template/process/INTEGRATION_EXAMPLE.md +0 -525
  316. package/analyzer-template/process/README.md +0 -507
  317. package/background/src/lib/process/GlobalProcessManager.js.map +0 -1
  318. package/background/src/lib/process/ProcessManager.js.map +0 -1
  319. package/background/src/lib/process/index.js.map +0 -1
  320. package/background/src/lib/process/managedExecAsync.js.map +0 -1
  321. package/codeyam-cli/scripts/fixtures/cal.com/universal-mocks/packages/prisma/index.js +0 -238
  322. package/codeyam-cli/scripts/fixtures/cal.com/universal-mocks/packages/prisma/index.js.map +0 -1
  323. package/codeyam-cli/scripts/fixtures/formbricks/universal-mocks/apps/web/lib/instance/service.js +0 -7
  324. package/codeyam-cli/scripts/fixtures/formbricks/universal-mocks/apps/web/lib/instance/service.js.map +0 -1
  325. package/codeyam-cli/src/webserver/build/client/assets/ScenarioViewer-CUxUNEEC.js +0 -15
  326. package/codeyam-cli/src/webserver/build/client/assets/_index-DHImXdXq.js +0 -11
  327. package/codeyam-cli/src/webserver/build/client/assets/activity.(_tab)-2mG6mjVb.js +0 -32
  328. package/codeyam-cli/src/webserver/build/client/assets/chunk-JMJ3UQ3L-BambyYE_.js +0 -51
  329. package/codeyam-cli/src/webserver/build/client/assets/entity._sha.scenarios._scenarioId.fullscreen-DyB90fWk.js +0 -1
  330. package/codeyam-cli/src/webserver/build/client/assets/globals-C6vQASxy.css +0 -1
  331. package/codeyam-cli/src/webserver/build/client/assets/root-BxJUvKau.js +0 -56
  332. package/codeyam-cli/src/webserver/build/client/assets/simulations-CoNWGt0K.js +0 -1
  333. package/codeyam-cli/src/webserver/build/server/assets/server-build-BDlyhfrv.js +0 -175
  334. /package/analyzer-template/{process → packages/process/src}/GlobalProcessManager.ts +0 -0
  335. /package/analyzer-template/{process → packages/process/src}/ProcessManager.ts +0 -0
  336. /package/analyzer-template/{process → packages/process/src}/index.ts +0 -0
  337. /package/analyzer-template/{process → packages/process/src}/managedExecAsync.ts +0 -0
  338. /package/{background/src/lib/process → packages/process/src}/GlobalProcessManager.js +0 -0
  339. /package/{background/src/lib/process → packages/process/src}/index.js +0 -0
  340. /package/{background/src/lib/process → packages/process/src}/managedExecAsync.js +0 -0
@@ -25,13 +25,102 @@ interface ReturnValuePart {
25
25
  }
26
26
 
27
27
  /**
28
- * Converts a variable qualifier to a safe identifier for use in function/const names.
29
- * Handles indexed format like "data[1]" -> "data_1"
28
+ * Converts a call signature to a valid JavaScript identifier (function name).
29
+ * The original signature is preserved for data access - this only creates the function name.
30
+ *
31
+ * Examples:
32
+ * - "useAuth()" → "useAuth"
33
+ * - "db.select(usersQuery)" → "db_select_usersQuery"
34
+ * - "db.select(postsQuery)" → "db_select_postsQuery"
35
+ * - "useFetcher<User>()" → "useFetcher_User"
36
+ * - "useFetcher<{ data: UserData | null }>()" → "useFetcher_data_UserData_null"
37
+ * - "eq('user_id', value)" → "eq_user_id_value"
38
+ * - "from('workouts')" → "from_workouts"
30
39
  */
31
- function safeVariableQualifier(qualifier: string): string {
32
- // Replace brackets with underscores for valid JS identifier
33
- // "data[1]" -> "data_1"
34
- return qualifier.replace(/\[(\d+)\]/g, '_$1');
40
+ function callSignatureToFunctionName(signature: string): string {
41
+ // Extract components from the signature
42
+ const components: string[] = [];
43
+
44
+ // 1. Extract function path (parts separated by dots outside parens/brackets)
45
+ const pathMatch = signature.match(/^([^<(]+)/);
46
+ if (pathMatch) {
47
+ const path = pathMatch[1];
48
+ // Split on dots but preserve the parts
49
+ components.push(...path.split('.').filter(Boolean));
50
+ }
51
+
52
+ // 2. Extract generic type parameters (content between < and >)
53
+ const genericMatch = signature.match(/<([^>]+)>/);
54
+ if (genericMatch) {
55
+ const genericContent = genericMatch[1];
56
+ // Extract meaningful identifiers from generic type
57
+ // Handle complex types like "{ data: UserData | null }"
58
+ const typeIdentifiers = genericContent
59
+ .replace(/[{}:;,]/g, ' ') // Remove structural chars
60
+ .replace(/\|/g, ' ') // Handle union types
61
+ .split(/\s+/)
62
+ .filter(Boolean)
63
+ .filter((s) => /^[A-Za-z_][A-Za-z0-9_]*$/.test(s)) // Only valid identifiers
64
+ .filter(
65
+ (s) =>
66
+ ![
67
+ 'null',
68
+ 'undefined',
69
+ 'void',
70
+ 'never',
71
+ 'any',
72
+ 'unknown',
73
+ 'data',
74
+ 'typeof',
75
+ ].includes(s),
76
+ ); // Skip common non-meaningful keywords
77
+
78
+ if (typeIdentifiers.length > 0) {
79
+ components.push(...typeIdentifiers.slice(0, 2)); // Limit to first 2 for reasonable length
80
+ }
81
+ }
82
+
83
+ // 3. Extract function arguments (first 2 for disambiguation)
84
+ const argsMatch = signature.match(/\(([^)]*)\)/);
85
+ if (argsMatch && argsMatch[1]) {
86
+ const argsContent = argsMatch[1].trim();
87
+ if (argsContent) {
88
+ const args = argsContent.split(',').map((arg) => arg.trim());
89
+ for (const arg of args.slice(0, 2)) {
90
+ // For quoted strings, extract the content
91
+ const stringMatch = arg.match(/^['"`](.+)['"`]$/);
92
+ if (stringMatch) {
93
+ // Split on dots for string paths like 'users.id'
94
+ const parts = stringMatch[1].split('.').filter(Boolean);
95
+ components.push(...parts);
96
+ } else if (/^[A-Za-z_][A-Za-z0-9_]*$/.test(arg)) {
97
+ // Valid identifier - use as-is
98
+ components.push(arg);
99
+ } else if (/^\d+$/.test(arg)) {
100
+ // Number - use as-is
101
+ components.push(arg);
102
+ }
103
+ // Skip complex expressions
104
+ }
105
+ }
106
+ }
107
+
108
+ // Build the function name from components
109
+ const functionName = components
110
+ .join('_')
111
+ .replace(/[^a-zA-Z0-9_]/g, '_') // Sanitize special chars
112
+ .replace(/_+/g, '_') // Collapse multiple underscores
113
+ .replace(/^_|_$/g, ''); // Trim underscores
114
+
115
+ return functionName || 'mock';
116
+ }
117
+
118
+ /**
119
+ * Check if a mock name is a call signature (e.g., "useFetcher<User>()", "db.select(query)")
120
+ */
121
+ function isCallSignature(mockName: string): boolean {
122
+ // Call signatures contain parentheses (function calls)
123
+ return mockName.includes('(');
35
124
  }
36
125
 
37
126
  /**
@@ -196,9 +285,12 @@ function funcArgs(functionSignature: string): string[] {
196
285
 
197
286
  // isValidKey ensures that the key does not contain any characters that would make it invalid in a JavaScript object.
198
287
  // For example, it should not contain spaces, special characters, or start with a number.
288
+ // Also rejects keys that are pure function calls like "()" or "(args)" - these aren't property names.
199
289
  function isValidKey(key: string) {
200
290
  if (!key || key.length === 0) return false;
201
291
  const keyWithOutArguments = key.split('(')[0];
292
+ // Reject empty keys (happens when key is "()" or "(args)") - these are function calls, not property names
293
+ if (!keyWithOutArguments || keyWithOutArguments.length === 0) return false;
202
294
  return !/\s/.test(keyWithOutArguments);
203
295
  }
204
296
 
@@ -206,21 +298,28 @@ export default function constructMockCode(
206
298
  mockName: string,
207
299
  dependencySchemas: DeepReadonly<DataStructure['dependencySchemas']>,
208
300
  entityType?: EntityType,
209
- canonicalKey?: string,
210
- options?: { keepOriginalFunctionName?: boolean },
301
+ _canonicalKey?: string, // DEPRECATED: No longer used, kept for API compatibility
302
+ options?: {
303
+ keepOriginalFunctionName?: boolean;
304
+ uniqueFunctionSuffix?: string;
305
+ skipOriginalSpread?: boolean; // Skip spreading from __cyOriginal when it won't be defined
306
+ },
211
307
  ) {
212
- // Check for variable-qualified mock name (e.g., "entityDiffFetcher <- useFetcher")
213
- // Format: "variableName <- functionName" which reads naturally as "variableName receives from functionName"
214
- // Also handles indexed format: "data[1] <- useFetch" for disambiguating reused variable names
215
- const variableQualifierMatch = mockName.match(
216
- /^([a-zA-Z_][a-zA-Z0-9_]*(?:\[\d+\])?)\s*<-\s*/,
217
- );
218
- let variableQualifier = variableQualifierMatch
219
- ? variableQualifierMatch[1]
308
+ // Check if mockName is a call signature (e.g., "useFetcher<User>()", "db.select(query)")
309
+ const mockNameIsCallSignature = isCallSignature(mockName);
310
+
311
+ // For call signatures, use the original signature for data access but generate
312
+ // a valid JS function name from it
313
+ const derivedFunctionName = mockNameIsCallSignature
314
+ ? callSignatureToFunctionName(mockName)
220
315
  : null;
221
- const baseMockName = variableQualifier
222
- ? mockName.slice(variableQualifierMatch[0].length)
223
- : mockName;
316
+
317
+ // The baseMockName is the function name without type params and args
318
+ // e.g., "useFetcher<User>()" -> "useFetcher", "db.select(query)" -> "db"
319
+ const baseMockName = mockName.split(/[<(]/)[0];
320
+
321
+ // The data key is the mockName (call signature) for data access
322
+ let dataKey: string;
224
323
 
225
324
  const mockNameParts = splitOutsideParenthesesAndArrays(baseMockName);
226
325
 
@@ -232,31 +331,10 @@ export default function constructMockCode(
232
331
 
233
332
  for (const filePath in dependencySchemas) {
234
333
  for (const entityName in dependencySchemas[filePath]) {
235
- // For variable-qualified mocks, look for the full qualified name first
236
- // Format: "variableName <- functionName" (e.g., "entityDiffFetcher <- useFetcher")
237
- const targetEntityName = variableQualifier
238
- ? `${variableQualifier} <- ${baseMockName}`
239
- : mockNameParts[0];
240
-
241
- // Check for direct match
242
- let matches =
243
- entityName === targetEntityName || entityName === mockNameParts[0];
244
-
245
- // If no direct match and no qualifier was provided, check if the entity
246
- // is stored under a variable-qualified key (e.g., "stateBadge <- getStateBadge")
247
- // This handles the case where gatherDataForMocks stored the entity with a variable
248
- // qualifier but writeScenarioComponents called constructMockCode without one.
249
- if (!matches && !variableQualifier) {
250
- const qualifiedKeyMatch = entityName.match(
251
- new RegExp(`^([a-zA-Z_][a-zA-Z0-9_]*)\\s*<-\\s*${mockNameParts[0]}$`),
252
- );
253
- if (qualifiedKeyMatch) {
254
- matches = true;
255
- // Extract the variable qualifier from the entity name so we can use
256
- // it for the data lookup key later
257
- variableQualifier = qualifiedKeyMatch[1];
258
- }
259
- }
334
+ // Match entity by base name (without generics/args)
335
+ const entityBaseName = entityName.split(/[<(]/)[0];
336
+ const matches =
337
+ entityBaseName === baseMockName || entityName === mockNameParts[0];
260
338
 
261
339
  if (!matches) continue;
262
340
 
@@ -300,6 +378,44 @@ export default function constructMockCode(
300
378
  }
301
379
  }
302
380
 
381
+ // Check if the entity is used as a function (called with ()) vs an object/namespace.
382
+ // Look for paths in the schema that start with "baseMockName(" or "baseMockName<" indicating function calls.
383
+ // The "<" handles generic type parameters like useLoaderData<T>().
384
+ // Also check dataStructurePath === 'returnValue' which indicates a function return value.
385
+ const entityIsFunction =
386
+ foundEntityWithSignature ||
387
+ dataStructurePath === 'returnValue' ||
388
+ Object.keys(relevantReturnValueSchema ?? {}).some(
389
+ (key) =>
390
+ key.startsWith(`${baseMockName}(`) ||
391
+ key.startsWith(`${baseMockName}<`),
392
+ );
393
+
394
+ // Calculate the data key - use the call signature (mockName) for data access
395
+ // For simple names without parentheses:
396
+ // - Append () ONLY if the entity is a function/hook (detected above)
397
+ // - Don't append () for object/namespace mocks like "supabase"
398
+ if (mockNameIsCallSignature || mockName.includes('(')) {
399
+ dataKey = mockName;
400
+ } else if (entityIsFunction) {
401
+ // Entity is a function/hook - append () to match call signature format
402
+ dataKey = `${mockName}()`;
403
+ } else {
404
+ // Entity is an object/namespace - use bare name as key
405
+ dataKey = mockName;
406
+ }
407
+
408
+ // Helper to wrap key in appropriate quotes for computed property access
409
+ // Use single quotes when key contains double quotes to avoid syntax errors
410
+ const quotePropertyKey = (key: string): string => {
411
+ const escaped = key.replace(/\n/g, '\\n');
412
+ if (escaped.includes('"')) {
413
+ // Use single quotes, escaping any single quotes in the key
414
+ return `['${escaped.replace(/'/g, "\\'")}']`;
415
+ }
416
+ return `["${escaped}"]`;
417
+ };
418
+
303
419
  // Check if the return value schema only contains function type markers
304
420
  // (e.g., "validateInputs()": "function") without actual return data
305
421
  // (no functionCallReturnValue entries)
@@ -328,6 +444,8 @@ export default function constructMockCode(
328
444
  key.startsWith('signature['),
329
445
  ).length;
330
446
  const args = Array.from({ length: argCount }, (_, i) => `arg${i + 1}`);
447
+ // Always add ...rest to accept extra arguments beyond the signature
448
+ args.push('...rest');
331
449
  const argsString = args.join(', ');
332
450
 
333
451
  // Generate empty mock function
@@ -352,8 +470,38 @@ export default function constructMockCode(
352
470
  key.startsWith('signature['),
353
471
  ).length;
354
472
  const args = Array.from({ length: argCount }, (_, i) => `arg${i + 1}`);
473
+ // Always add ...rest to accept extra arguments beyond the signature
474
+ args.push('...rest');
355
475
  const argsString = args.join(', ');
356
476
 
477
+ // Check for Higher-Order Component (HOC) pattern:
478
+ // - First argument is a function (component) or unknown (couldn't trace type)
479
+ // - Returns a function
480
+ // HOCs like memo, forwardRef, createContext should return their first argument
481
+ //
482
+ // The return value key can be either:
483
+ // - 'memo()' (clean format)
484
+ // - 'memo(({ value, width }: Props) => { ... })' (full component code format)
485
+ const firstArgIsFunctionOrUnknown =
486
+ signatureSchema['signature[0]'] === 'function' ||
487
+ signatureSchema['signature[0]'] === 'unknown';
488
+ const returnsFunction = relevantReturnValueSchema
489
+ ? Object.entries(relevantReturnValueSchema).some(([key, value]) => {
490
+ // Check if key represents a function call that returns a function
491
+ // Key should start with the mock name, contain '(', end with ')', and have value 'function'
492
+ const isFunctionCall =
493
+ key.startsWith(mockName + '(') && key.endsWith(')');
494
+ return isFunctionCall && value === 'function';
495
+ })
496
+ : false;
497
+
498
+ if (firstArgIsFunctionOrUnknown && returnsFunction) {
499
+ // HOC pattern detected - return the first argument
500
+ return `function ${mockName}(${argsString}) {
501
+ return arg1;
502
+ }`;
503
+ }
504
+
357
505
  // Generate empty mock function
358
506
  return `function ${mockName}(${argsString}) {
359
507
  // Empty mock - original function mocked out
@@ -414,26 +562,21 @@ export default function constructMockCode(
414
562
  // so "useLoaderData<typeof loader>()" becomes "useLoaderData()"
415
563
  name = cleanOutTypes(name);
416
564
 
417
- // For root data access, use the canonical key if provided
418
- // Canonical keys use format: EntityName::hookName::index (e.g., "Dashboard::useLoaderData::0")
419
- if (isRootAccess && canonicalKey) {
420
- return `?.["${canonicalKey}"]`;
421
- }
422
-
423
- // Fallback for variable-qualified mocks when no canonical key provided
424
- // Format: "variableName <- functionName" (legacy format)
425
- if (isRootAccess && variableQualifier) {
426
- const baseName = name.replace(/\(\)$/, '');
427
- name = `${variableQualifier} <- ${baseName}`;
565
+ // For root data access, use the dataKey (original call signature or canonical key)
566
+ // This preserves the original call signature for LLM clarity
567
+ if (isRootAccess) {
568
+ // For call signature format, use the original mockName as the data key
569
+ // e.g., scenarios().data()?.["useFetcher<User>()"]
570
+ // e.g., scenarios().data()?.["db.select(usersQuery)"]
571
+ return `?.${quotePropertyKey(dataKey)}`;
428
572
  }
429
573
 
430
574
  // Only use unquoted array access syntax for pure array indices like [0], [1]
431
- // NOT for variable-qualified names like "fetcher[1] <- useFetcher" which need quotes
432
- if (name.match(/^\[\d+\]$/) && !name.includes(' <- ')) {
575
+ if (name.match(/^\[\d+\]$/)) {
433
576
  return `?.${name}`;
434
577
  }
435
578
 
436
- return `?.["${name.replace(/\n/g, '\\n')}"]`;
579
+ return `?.${quotePropertyKey(name)}`;
437
580
  };
438
581
 
439
582
  const constructDataPaths = () => {
@@ -501,7 +644,20 @@ export default function constructMockCode(
501
644
  hasNoReturnData,
502
645
  } = returnValue;
503
646
 
504
- const nestedContent: (string | undefined)[] = (nested ?? []).map(
647
+ // When an array has differentiated indices ([0], [1], etc.), filter out any
648
+ // non-index items from nested. These non-index items come from generic [] paths
649
+ // like [].filter or [].sort, which describe element properties, not array elements.
650
+ // Including them would generate invalid syntax like "sort: ..." inside an array literal.
651
+ const hasDifferentiatedIndices =
652
+ isArray &&
653
+ nested &&
654
+ nested.some((n) => n.name.match(/^\[\d+\]$/) && n.name !== '[0]');
655
+ const filteredNested =
656
+ hasDifferentiatedIndices && nested
657
+ ? nested.filter((n) => n.name.match(/^\[\d+\]$/))
658
+ : nested;
659
+
660
+ const nestedContent: (string | undefined)[] = (filteredNested ?? []).map(
505
661
  (nestedItem) => {
506
662
  const nestedContent = constructReturnValueString(
507
663
  nestedItem,
@@ -585,53 +741,114 @@ export default function constructMockCode(
585
741
  ) {
586
742
  levelContentItems.push(...dataPaths.map((path) => `...${path}`));
587
743
  }
588
- levelContentItems.push(...nestedContent);
744
+ // Filter out nested content that would be invalid as object properties
745
+ // (e.g., bare arrow functions like "() => {...}" without a property name)
746
+ // Only apply this filter when building object content, not array content.
747
+ // Bare arrow functions ARE valid as array elements (like [0] = {...}, [1] = () => {...})
748
+ // Check both isArray (item IS an array) and returnsFunctionArray (item returns an array)
749
+ const inArrayContext = isArray || returnsFunctionArray;
750
+ const validNestedContent = nestedContent.filter((content) => {
751
+ if (!content) return false;
752
+ // Only filter bare arrow functions when NOT in array context
753
+ // In arrays, bare arrow functions are valid elements
754
+ if (!inArrayContext && content.match(/^\s*\([^)]*\)\s*=>/)) {
755
+ return false;
756
+ }
757
+ return true;
758
+ });
759
+ levelContentItems.push(...validNestedContent);
589
760
 
590
761
  let levelContents: string = levelContentItems.filter(Boolean).join(',\n');
591
762
  if (returnsFunctionArgs) {
592
- const argsString = returnsFunctionArgs
593
- .map((_, index) => `arg${index + 1}`)
594
- .join(', ');
595
- let funcContents = '';
596
- if (returnsFunctionArray) {
597
- if (hasNoReturnData) {
598
- // Function has no return data (only signatures) - return empty array
599
- funcContents = 'return []';
600
- } else if (levelContents.length === 0 && dataPaths.length === 1) {
601
- // When returning an array with no nested content, return the data path directly
602
- // (the data path points to the array in scenario data)
603
- funcContents = `return ${dataPaths[0]}`;
604
- } else if (levelContents.length === 0) {
605
- funcContents = 'return []';
606
- } else {
607
- funcContents = `return [\n${indent(levelContents)}\n]`;
763
+ // When returnsFunctionArgs is empty [] OR has a single literal string argument,
764
+ // the function returns a callable function (e.g., getTranslate() returns t,
765
+ // where t('key') looks up translations)
766
+ // Generate a dispatch function that looks up keys based on the argument
767
+ //
768
+ // Detect translation-like pattern:
769
+ // - Data path ends with ["('some.literal')"] - a literal string key
770
+ // - This means the mock data has keys like "('common.surveys')": "Surveys"
771
+ // - Exclude ["()"] which is an empty function call (not a translation pattern)
772
+ const dataPath = dataPaths[0];
773
+ // Pattern matches ?.["('...')"] at end of path, but NOT ?.["()"] (empty args)
774
+ const literalKeyPattern = dataPath?.match(/\?\.\["\('.+'\)"\]$/);
775
+
776
+ if (
777
+ !returnsFunctionArray &&
778
+ dataPaths.length === 1 &&
779
+ literalKeyPattern // Only dispatch when there's a literal key pattern
780
+ ) {
781
+ // Function returns a function - generate dispatch function
782
+ // Strip the literal key from the path and use dynamic lookup
783
+ const dataPathBase = literalKeyPattern
784
+ ? dataPath.replace(/\?\.\["\('.+'\)"\]$/, '')
785
+ : dataPath;
786
+ const funcContents = `return ${dataPathBase}?.[\`('\${arg1}')\`]`;
787
+ levelContents = `(arg1) => {\n${indent(funcContents)}\n}`;
788
+
789
+ if (!isArray) {
790
+ return levelContents;
608
791
  }
609
792
  } else {
610
- // Check if function has no actual return data (only signatures)
611
- const hasNestedItems = nested && nested.length > 0;
612
- const hasActualNestedContent =
613
- nestedContent.filter(Boolean).length > 0;
614
-
615
- if (levelContentItems.length === 1 && dataPaths.length === 1) {
616
- if (
617
- hasNoReturnData ||
618
- (hasNestedItems && !hasActualNestedContent)
619
- ) {
793
+ const argsString = returnsFunctionArgs
794
+ .map((_, index) => `arg${index + 1}`)
795
+ .join(', ');
796
+ let funcContents = '';
797
+ if (returnsFunctionArray) {
798
+ if (hasNoReturnData) {
620
799
  // Function has no return data (only signatures) - return empty array
621
800
  funcContents = 'return []';
622
- } else {
623
- // Has return data - return data path
801
+ } else if (levelContents.length === 0 && dataPaths.length === 1) {
802
+ // When returning an array with no nested content, return the data path directly
803
+ // (the data path points to the array in scenario data)
624
804
  funcContents = `return ${dataPaths[0]}`;
805
+ } else if (levelContents.length === 0) {
806
+ funcContents = 'return []';
807
+ } else {
808
+ funcContents = `return [\n${indent(levelContents)}\n]`;
625
809
  }
626
810
  } else {
627
- funcContents = `return {\n${indent(levelContents)}\n}`;
811
+ // Check if function has no actual return data (only signatures)
812
+ const hasNestedItems = nested && nested.length > 0;
813
+ const hasActualNestedContent =
814
+ nestedContent.filter(Boolean).length > 0;
815
+
816
+ if (levelContentItems.length === 1 && dataPaths.length === 1) {
817
+ if (
818
+ hasNoReturnData ||
819
+ (hasNestedItems && !hasActualNestedContent)
820
+ ) {
821
+ // Function has no return data (only signatures) - return empty array
822
+ funcContents = 'return []';
823
+ } else {
824
+ // Has return data - return data path
825
+ funcContents = `return ${dataPaths[0]}`;
826
+ }
827
+ } else {
828
+ funcContents = `return {\n${indent(levelContents)}\n}`;
829
+ }
628
830
  }
629
- }
630
831
 
631
- levelContents = `(${argsString}) => {\n${indent(funcContents)}\n}`;
832
+ levelContents = `(${argsString}) => {\n${indent(funcContents)}\n}`;
632
833
 
633
- if (!isArray) {
634
- return levelContents;
834
+ if (!isArray) {
835
+ return levelContents;
836
+ }
837
+ }
838
+
839
+ // For generic arrays of functions WITH nested properties (e.g., functionCallReturnValue[] = "function"
840
+ // with nested .filter, .sort, etc.), the levelContents would be a bare arrow function "() => {...}"
841
+ // that wraps object content. Using this in a .map(({...})) creates invalid syntax like "({ () => {...} })".
842
+ // When isGenericArray is true AND there are nested properties, we're accessing data from the elements,
843
+ // not calling them - so skip the function wrapping.
844
+ // But if there are NO nested properties, keep the wrapper because callers may want to call the elements.
845
+ const hasNonStructuralNestedItems =
846
+ nested &&
847
+ nested.length > 0 &&
848
+ nested.some((n) => !n.name.match(/^\[\d*\]$/));
849
+ if (isGenericArray && hasNonStructuralNestedItems) {
850
+ // Skip the arrow function wrapper - just use the nested content directly
851
+ levelContents = levelContentItems.filter(Boolean).join(',\n');
635
852
  }
636
853
  }
637
854
 
@@ -685,16 +902,335 @@ export default function constructMockCode(
685
902
  // Get the array base path (without the [0])
686
903
  const arrayBasePath = dataPaths[0].replace(/\?\.\[0\]$/, '');
687
904
  // Replace [0] references with [__idx__] in level contents
688
- const mappedContents = levelContents.replace(
905
+ let mappedContents = levelContents.replace(
689
906
  /\?\.\[0\]/g,
690
907
  '?.[__idx__]',
691
908
  );
692
909
  // levelContents may already be wrapped in {...} from structural [0] element,
693
910
  // so check if we need to add the wrapper or not
694
911
  const needsWrapper = !mappedContents.trim().startsWith('{');
912
+
913
+ // Helper to check if a position is inside a string literal
914
+ // Returns the end position of the string if inside one, -1 otherwise
915
+ // Defined here so it's accessible in both needsWrapper branches
916
+ const skipStringLiteral = (
917
+ content: string,
918
+ pos: number,
919
+ ): number => {
920
+ const char = content[pos];
921
+ if (char !== '"' && char !== "'" && char !== '`') return -1;
922
+ // Find the matching closing quote
923
+ let j = pos + 1;
924
+ while (j < content.length) {
925
+ if (content[j] === '\\') {
926
+ j += 2; // Skip escaped character
927
+ continue;
928
+ }
929
+ if (content[j] === char) {
930
+ return j + 1; // Return position after closing quote
931
+ }
932
+ j++;
933
+ }
934
+ return content.length; // Unclosed string, skip to end
935
+ };
936
+
937
+ // Filter out bare arrow functions which are invalid as object properties.
938
+ // Arrow functions can be multi-line, so we need to match the entire function body, not just the first line.
939
+ // Pattern: starts with "(args) =>", followed by either:
940
+ // - A single-line body: "() => expression"
941
+ // - A multi-line body: "() => { ... }" (with matching braces)
942
+ // IMPORTANT: Only filter BARE arrow functions (without property names).
943
+ // "() => {...}" is invalid, but "get: (arg1) => {...}" is valid.
944
+ // We use a function to properly handle nested braces.
945
+ // Defined here so it's accessible in both needsWrapper branches
946
+ const filterOutArrowFunctions = (content: string): string => {
947
+ const result: string[] = [];
948
+ let i = 0;
949
+ while (i < content.length) {
950
+ // Skip over string literals entirely
951
+ const stringEnd = skipStringLiteral(content, i);
952
+ if (stringEnd !== -1) {
953
+ result.push(content.slice(i, stringEnd));
954
+ i = stringEnd;
955
+ continue;
956
+ }
957
+
958
+ // Check if we're at the start of an arrow function (with optional leading whitespace)
959
+ const arrowMatch = content
960
+ .slice(i)
961
+ .match(/^(\s*)\([^)]*\)\s*=>\s*/);
962
+ if (arrowMatch) {
963
+ // Check if this is a bare arrow function or a named property with arrow function value
964
+ // Look back to see if there's a "key:" pattern before this position
965
+ const before = content.slice(0, i);
966
+ const beforeTrimmed = before.trim();
967
+ // Valid patterns where arrow function is NOT bare:
968
+ // 1. Property value: "key: (arg) => ..." - ends with ':'
969
+ // 2. Function argument: ".map((arg) => ..." - ends with '('
970
+ // NOTE: We don't include ',' because "{ prop, () => {} }" is invalid
971
+ // (can't distinguish function argument from object property context)
972
+ const isPropertyValue = beforeTrimmed.endsWith(':');
973
+ const isFunctionArg = beforeTrimmed.endsWith('(');
974
+ const hasPropertyName = isPropertyValue || isFunctionArg;
975
+
976
+ if (!hasPropertyName) {
977
+ // This is a bare arrow function - filter it out
978
+ // Found arrow function start, need to find its end
979
+ const afterArrow = i + arrowMatch[0].length;
980
+ if (content[afterArrow] === '{') {
981
+ // Multi-line arrow function - find matching closing brace
982
+ // Must respect string literals when counting braces
983
+ let braceCount = 1;
984
+ let j = afterArrow + 1;
985
+ while (j < content.length && braceCount > 0) {
986
+ const strEnd = skipStringLiteral(content, j);
987
+ if (strEnd !== -1) {
988
+ j = strEnd;
989
+ continue;
990
+ }
991
+ if (content[j] === '{') braceCount++;
992
+ if (content[j] === '}') braceCount--;
993
+ j++;
994
+ }
995
+ // Skip past the arrow function
996
+ i = j;
997
+ // Only skip trailing comma, keep newlines
998
+ while (i < content.length && content[i] === ' ') {
999
+ i++;
1000
+ }
1001
+ if (content[i] === ',') {
1002
+ i++; // Skip the comma after the arrow function
1003
+ }
1004
+ } else {
1005
+ // Single expression arrow function - skip to next comma or newline
1006
+ let j = afterArrow;
1007
+ while (
1008
+ j < content.length &&
1009
+ content[j] !== ',' &&
1010
+ content[j] !== '\n'
1011
+ ) {
1012
+ j++;
1013
+ }
1014
+ i = j;
1015
+ if (content[i] === ',') i++; // Skip the comma
1016
+ }
1017
+ continue;
1018
+ }
1019
+ }
1020
+ // Not a bare arrow function, keep this character
1021
+ result.push(content[i]);
1022
+ i++;
1023
+ }
1024
+ return result.join('');
1025
+ };
1026
+
1027
+ // Filter out bare object blocks (e.g., "{ ...spread, props }," without a property name)
1028
+ // These are invalid in object literal context - you need "key: { ... }" not just "{ ... }"
1029
+ // Defined here so it's accessible in both needsWrapper branches
1030
+ // The skipFirstBrace parameter allows the else branch to preserve the outer object
1031
+ const filterOutBareObjects = (
1032
+ content: string,
1033
+ skipFirstBrace = false,
1034
+ ): string => {
1035
+ const result: string[] = [];
1036
+ let i = 0;
1037
+ let firstBraceSkipped = false;
1038
+ while (i < content.length) {
1039
+ // Skip over string literals entirely - braces inside strings should not be processed
1040
+ const stringEnd = skipStringLiteral(content, i);
1041
+ if (stringEnd !== -1) {
1042
+ result.push(content.slice(i, stringEnd));
1043
+ i = stringEnd;
1044
+ continue;
1045
+ }
1046
+
1047
+ // Check if we're at a bare object start (newline/comma followed by { without : before it)
1048
+ // Look back to see if there's a colon (property assignment) before this brace
1049
+ const isStartOfLine =
1050
+ i === 0 ||
1051
+ content[i - 1] === '\n' ||
1052
+ content.slice(0, i).trim().endsWith(',');
1053
+ if (content[i] === '{' && isStartOfLine) {
1054
+ // Check if this is actually a bare object (not "key: {")
1055
+ const beforeTrimmed = content.slice(0, i).trim();
1056
+ const isBareObject =
1057
+ beforeTrimmed.endsWith(',') ||
1058
+ beforeTrimmed === '' ||
1059
+ beforeTrimmed.endsWith('(');
1060
+
1061
+ if (isBareObject) {
1062
+ // If skipFirstBrace is true and this is the first bare brace at position 0,
1063
+ // don't filter it - it's the intentional outer object wrapper
1064
+ if (skipFirstBrace && !firstBraceSkipped && i === 0) {
1065
+ firstBraceSkipped = true;
1066
+ result.push(content[i]);
1067
+ i++;
1068
+ continue;
1069
+ }
1070
+
1071
+ // Find matching closing brace, respecting string literals
1072
+ let braceCount = 1;
1073
+ let j = i + 1;
1074
+ while (j < content.length && braceCount > 0) {
1075
+ const strEnd = skipStringLiteral(content, j);
1076
+ if (strEnd !== -1) {
1077
+ j = strEnd;
1078
+ continue;
1079
+ }
1080
+ if (content[j] === '{') braceCount++;
1081
+ if (content[j] === '}') braceCount--;
1082
+ j++;
1083
+ }
1084
+ // Skip past the object
1085
+ i = j;
1086
+ // Skip trailing comma
1087
+ while (i < content.length && content[i] === ' ') {
1088
+ i++;
1089
+ }
1090
+ if (content[i] === ',') {
1091
+ i++;
1092
+ }
1093
+ continue;
1094
+ }
1095
+ }
1096
+ result.push(content[i]);
1097
+ i++;
1098
+ }
1099
+ return result.join('');
1100
+ };
1101
+
1102
+ // Helper to clean up formatting issues after filtering
1103
+ const cleanupContent = (content: string): string => {
1104
+ return (
1105
+ content
1106
+ .replace(/,\s*,/g, ',') // Double commas
1107
+ .replace(/,(\s*\n\s*\})/g, '$1') // Trailing comma before closing brace
1108
+ .replace(/\{\s*\n\s*,/g, '{\n') // Leading comma after opening brace
1109
+ // Remove incomplete .map calls where callback was filtered out
1110
+ // Pattern: ".map" followed by newline/whitespace without "(" for args
1111
+ .replace(/\?\.map(?=\s*[\n\r,}\]])/g, '')
1112
+ .replace(/\.map(?=\s*[\n\r,}\]])/g, '')
1113
+ // Clean up orphan })) sequences (from nested filtered map callbacks)
1114
+ .replace(/\s*\}\)\)\s*\n\s*\}/g, '\n}')
1115
+ .replace(/^\s*\n/gm, '') // Empty lines
1116
+ .trim()
1117
+ );
1118
+ };
1119
+
695
1120
  if (needsWrapper) {
696
- returnValueContents = `${arrayBasePath}?.map((__item__, __idx__) => ({\n${indent(mappedContents)}\n}))`;
1121
+ // Apply filters to remove invalid content
1122
+ mappedContents = filterOutArrowFunctions(mappedContents);
1123
+ mappedContents = filterOutBareObjects(mappedContents);
1124
+ mappedContents = cleanupContent(mappedContents);
1125
+
1126
+ // If mappedContents is empty after filtering, don't generate .map() at all
1127
+ // Just use the array path directly with spread or as-is
1128
+ // This prevents orphan )) from empty .map() callbacks
1129
+ const cleanedForEmptyCheck = mappedContents
1130
+ .replace(/\s+/g, '')
1131
+ .replace(/,+/g, '');
1132
+ if (cleanedForEmptyCheck.length === 0) {
1133
+ // Content is empty - just return the array directly
1134
+ returnValueContents = arrayBasePath;
1135
+ } else {
1136
+ // Check if mappedContents is just a bare expression (no property names)
1137
+ // A bare expression like "scenarios().data()?.["key"]?.[__idx__]," cannot be
1138
+ // wrapped in ({ }) because it's not a valid object property.
1139
+ // Pattern: content has no ":" that's not inside brackets/parens/strings
1140
+ const hasBareExpression = (() => {
1141
+ const trimmed = mappedContents.trim().replace(/,\s*$/, ''); // Remove trailing comma
1142
+ let depth = 0;
1143
+ let inString = false;
1144
+ let stringChar = '';
1145
+ for (let i = 0; i < trimmed.length; i++) {
1146
+ const char = trimmed[i];
1147
+ if (inString) {
1148
+ if (char === '\\') {
1149
+ i++; // Skip escaped char
1150
+ continue;
1151
+ }
1152
+ if (char === stringChar) {
1153
+ inString = false;
1154
+ }
1155
+ continue;
1156
+ }
1157
+ if (char === '"' || char === "'" || char === '`') {
1158
+ inString = true;
1159
+ stringChar = char;
1160
+ continue;
1161
+ }
1162
+ if (char === '(' || char === '[' || char === '{') {
1163
+ depth++;
1164
+ continue;
1165
+ }
1166
+ if (char === ')' || char === ']' || char === '}') {
1167
+ depth--;
1168
+ continue;
1169
+ }
1170
+ // Found a colon at depth 0 = has property name
1171
+ if (char === ':' && depth === 0) {
1172
+ return false;
1173
+ }
1174
+ }
1175
+ return true;
1176
+ })();
1177
+
1178
+ if (hasBareExpression) {
1179
+ // Content is just an expression - return it directly without object wrapper
1180
+ const trimmedContent = mappedContents
1181
+ .trim()
1182
+ .replace(/,\s*$/, '');
1183
+ returnValueContents = `${arrayBasePath}?.map((__item__, __idx__) => (\n${indent(trimmedContent)}\n))`;
1184
+ } else {
1185
+ returnValueContents = `${arrayBasePath}?.map((__item__, __idx__) => ({\n${indent(mappedContents)}\n}))`;
1186
+ }
1187
+ } // Close the empty content check else block
697
1188
  } else {
1189
+ // Content already starts with '{'. Check if there are additional properties after the inner object.
1190
+ // If so, we need to merge them INTO the object, not leave them outside.
1191
+ // Pattern: "{ ...spread, props },\nfilter: ...,\nsort: ..."
1192
+ // Should become: "{ ...spread, props, filter: ..., sort: ... }"
1193
+ const trimmed = mappedContents.trim();
1194
+
1195
+ // Find first }, that is NOT inside a string literal
1196
+ // This prevents splitting keys like ?.["useQuery({ id }, { enabled })"]
1197
+ const findBraceCommaOutsideStrings = (
1198
+ content: string,
1199
+ ): number => {
1200
+ let i = 0;
1201
+ while (i < content.length - 1) {
1202
+ // Skip over string literals
1203
+ const strEnd = skipStringLiteral(content, i);
1204
+ if (strEnd !== -1) {
1205
+ i = strEnd;
1206
+ continue;
1207
+ }
1208
+ // Check for }, pattern
1209
+ if (content[i] === '}' && content[i + 1] === ',') {
1210
+ return i;
1211
+ }
1212
+ i++;
1213
+ }
1214
+ return -1;
1215
+ };
1216
+
1217
+ const firstBraceEnd = findBraceCommaOutsideStrings(trimmed);
1218
+ if (firstBraceEnd !== -1) {
1219
+ // Found pattern "{ ... }," followed by more content
1220
+ // Extract the inner object and the trailing properties
1221
+ const innerObject = trimmed.slice(0, firstBraceEnd);
1222
+ const trailingContent = trimmed.slice(firstBraceEnd + 2).trim();
1223
+ if (trailingContent) {
1224
+ // Merge trailing properties into the inner object
1225
+ mappedContents = `${innerObject},\n${trailingContent}\n}`;
1226
+ }
1227
+ }
1228
+ // Even when content starts with {, we need to filter out invalid properties inside
1229
+ // (arrow functions and bare objects that were generated from the schema)
1230
+ // Pass skipFirstBrace=true because the content's outer { is the intentional wrapper
1231
+ mappedContents = filterOutArrowFunctions(mappedContents);
1232
+ mappedContents = filterOutBareObjects(mappedContents, true);
1233
+ mappedContents = cleanupContent(mappedContents);
698
1234
  returnValueContents = `${arrayBasePath}?.map((__item__, __idx__) => (\n${indent(mappedContents)}\n))`;
699
1235
  }
700
1236
  } else {
@@ -800,14 +1336,29 @@ export default function constructMockCode(
800
1336
  content = `${cleanOutTypes(name)}: ${isAsyncFunction ? 'async ' : ''}(${argsString}) => {\n${indent(funcContents)}\n}`;
801
1337
  } else {
802
1338
  // No argument variants - use existing behavior
803
- const funcContents = `return ${returnValueContents}`;
1339
+ // But if there's nested content, we need to include it in the return object
1340
+ // (similar to how argument variant branches handle this at line 1070-1072)
1341
+ const hasNestedContent = validNestedContent.length > 0;
1342
+ let funcReturnContents: string;
1343
+ if (hasNestedContent && levelContentItems.length > 1) {
1344
+ // Include both spread and nested content in the return
1345
+ funcReturnContents = `{\n${indent(levelContents)}\n}`;
1346
+ } else {
1347
+ funcReturnContents = returnValueContents;
1348
+ }
1349
+ const funcContents = `return ${funcReturnContents}`;
804
1350
  content = `${cleanOutTypes(name)}: ${isAsyncFunction ? 'async ' : ''}(${argsString}) => {\n${indent(funcContents)}\n}`;
805
1351
  }
806
1352
  } else {
807
1353
  if (!isValidKey(name)) {
808
1354
  return;
809
1355
  } else if (name.match(/\[\d*\]/)) {
1356
+ // Numeric array index like [0], [1] - can be used as computed property
810
1357
  content = returnValueContents;
1358
+ } else if (name.match(/^\[[a-zA-Z_]\w*\]$/)) {
1359
+ // Variable-based index like [currentItemIndex] - must be quoted string key
1360
+ // Otherwise JavaScript would try to evaluate the variable name
1361
+ content = `"${safeString(name)}": ${returnValueContents}`;
811
1362
  } else {
812
1363
  content = `${safeString(name)}: ${returnValueContents}`;
813
1364
  }
@@ -884,8 +1435,8 @@ export default function constructMockCode(
884
1435
  }
885
1436
  }
886
1437
 
887
- // For variable-qualified mocks like "revalidator <- useRevalidator",
888
- // compare against baseMockName ("useRevalidator"), not the full mockName
1438
+ // Compare against baseMockName (without generics/args), not the full mockName
1439
+ // e.g., for "useFetcher<User>()", baseMockName is "useFetcher"
889
1440
  if (parts[0].split('(')[0] !== baseMockName) continue;
890
1441
 
891
1442
  // Include paths with functionCallReturnValue OR function-typed paths that need mocking
@@ -1001,6 +1552,17 @@ export default function constructMockCode(
1001
1552
  const nextIsArray = !!nextPart?.match(/^\[\d*\]/);
1002
1553
  const isDifferentiatedArray = !!part?.match(/^\[\d+\]/);
1003
1554
  const nextIsDifferentiatedArray = !!nextPart?.match(/^\[\d+\]/);
1555
+
1556
+ // Variable index patterns like [currentItemIndex] or [targetIndex] indicate array access
1557
+ // but don't represent actual data structure - they're markers from variable-based index tracking.
1558
+ // Skip them AND all remaining parts to avoid creating spurious nested structure that breaks array iteration.
1559
+ // The remaining parts (e.g., .missing_attributes) describe properties of array elements, which are
1560
+ // already handled by the generic [] accessor path.
1561
+ const isVariableIndex = !!part?.match(/^\[[a-zA-Z_]\w*\]$/);
1562
+ if (isVariableIndex) {
1563
+ // Break out of the loop entirely - don't process any remaining parts
1564
+ break;
1565
+ }
1004
1566
  // Find the correct value for the current part being processed
1005
1567
  let partValue = value; // default to the final value
1006
1568
  if (isFunctionCallReturnValue(part) && nextIsArray) {
@@ -1108,7 +1670,52 @@ export default function constructMockCode(
1108
1670
  }
1109
1671
  }
1110
1672
  } else {
1111
- returnValueSection.returnsFunctionArgs = [];
1673
+ // Before setting returnsFunctionArgs on the parent (for generic [] = function),
1674
+ // check if there are specific array indices (like [0], [1]) that are NOT functions.
1675
+ // If so, don't set returnsFunctionArgs because those specific indices take precedence.
1676
+ // This prevents adding ["()"] to paths like [0] when [0] is 'unknown' but [] is 'function'.
1677
+ //
1678
+ // Use parts.slice(0, i + 1) to get the current path INCLUDING functionCallReturnValue.
1679
+ // For example, if parts = ['useAtom()','functionCallReturnValue','[]']
1680
+ // and i = 1, we want to check 'useAtom().functionCallReturnValue[0]' etc.
1681
+ const arrayContainerPath = joinParenthesesAndArrays(
1682
+ parts.slice(0, i + 1),
1683
+ );
1684
+
1685
+ const hasNonFunctionSpecificIndices = Object.entries(
1686
+ relevantReturnValueSchema,
1687
+ ).some(([k, v]) => {
1688
+ // Look for paths like "arrayContainerPath[0]", "arrayContainerPath[1]" etc.
1689
+ const indexMatch = k.match(
1690
+ new RegExp(
1691
+ `^${arrayContainerPath.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\[(\\d+)\\]$`,
1692
+ ),
1693
+ );
1694
+ // If found and it's NOT a function type, we have a conflict
1695
+ return (
1696
+ indexMatch &&
1697
+ !['function', 'async-function'].includes(v as string)
1698
+ );
1699
+ });
1700
+
1701
+ // Also check if [] has nested object properties (like [].filter, [].name)
1702
+ // If so, [] items are objects with properties, not pure functions to be called
1703
+ // This handles cases where the schema shows [].filter = object but doesn't
1704
+ // have explicit [0] entries
1705
+ const genericArrayPath = `${arrayContainerPath}[]`;
1706
+ const hasNestedProperties = Object.keys(
1707
+ relevantReturnValueSchema,
1708
+ ).some((k) => {
1709
+ // Check for paths like "arrayContainerPath[].propertyName" (not [].())
1710
+ return (
1711
+ k.startsWith(genericArrayPath + '.') &&
1712
+ !k.startsWith(genericArrayPath + '.(')
1713
+ );
1714
+ });
1715
+
1716
+ if (!hasNonFunctionSpecificIndices && !hasNestedProperties) {
1717
+ returnValueSection.returnsFunctionArgs = [];
1718
+ }
1112
1719
  }
1113
1720
  }
1114
1721
  }
@@ -1133,7 +1740,8 @@ export default function constructMockCode(
1133
1740
  }
1134
1741
  // If the next part is an object with nested content, continue processing
1135
1742
  // This handles paths like functionCallReturnValue.selectedOptions.elementOptions[]
1136
- if (nextValue === 'object' || nextValue === 'array') {
1743
+ // Also handles union types like 'array | undefined' or 'object | undefined'
1744
+ if (nextValue?.includes('object') || nextValue?.includes('array')) {
1137
1745
  continue;
1138
1746
  }
1139
1747
  }
@@ -1287,7 +1895,14 @@ export default function constructMockCode(
1287
1895
  relevantPart.isGenericArray = true;
1288
1896
  }
1289
1897
 
1290
- if (!hasNestedFunction) {
1898
+ // Check if there are remaining parts after functionCallReturnValue that need processing
1899
+ // (e.g., data properties like useQuery().functionCallReturnValue.data)
1900
+ const hasRemainingPartsAfterReturnValue =
1901
+ nextPart &&
1902
+ (isFunctionCallReturnValue(nextPart) ||
1903
+ (isFunctionCallReturnValue(parts[i]) && i < parts.length - 1));
1904
+
1905
+ if (!hasNestedFunction && !hasRemainingPartsAfterReturnValue) {
1291
1906
  // Before breaking, check if this function returns an array
1292
1907
  // by looking for a functionCallReturnValue: 'array' entry in the schema
1293
1908
  if (relevantPart && part.endsWith(')')) {
@@ -1319,6 +1934,7 @@ export default function constructMockCode(
1319
1934
 
1320
1935
  if (mockNameParts.length > 1) {
1321
1936
  const originalLib = `${mockNameParts[0]}__cyOriginal`;
1937
+ const skipOriginalSpread = options?.skipOriginalSpread;
1322
1938
 
1323
1939
  const subPart = (
1324
1940
  parts: string[],
@@ -1330,7 +1946,9 @@ export default function constructMockCode(
1330
1946
 
1331
1947
  const partContents = isLast
1332
1948
  ? contents
1333
- : `...${originalLib}.${part},\n${subPart(parts, originalLib)}`;
1949
+ : skipOriginalSpread
1950
+ ? subPart(parts, originalLib)
1951
+ : `...${originalLib}.${part},\n${subPart(parts, originalLib)}`;
1334
1952
 
1335
1953
  let code = `${part}: {\n${indent(partContents)}\n}`;
1336
1954
 
@@ -1344,29 +1962,31 @@ export default function constructMockCode(
1344
1962
  return code;
1345
1963
  };
1346
1964
 
1347
- const returnParts = [
1348
- `...${mockNameParts[0]}__cyOriginal`,
1349
- subPart(mockNameParts.slice(1), originalLib),
1350
- ].filter(Boolean);
1965
+ const returnParts = skipOriginalSpread
1966
+ ? [subPart(mockNameParts.slice(1), originalLib)]
1967
+ : [
1968
+ `...${mockNameParts[0]}__cyOriginal`,
1969
+ subPart(mockNameParts.slice(1), originalLib),
1970
+ ];
1351
1971
 
1352
- return `const ${mockNameParts[0]} = {\n${indent(returnParts.join(',\n'))}\n};`;
1972
+ return `const ${mockNameParts[0]} = {\n${indent(returnParts.filter(Boolean).join(',\n'))}\n};`;
1353
1973
  } else if (isFunction) {
1354
1974
  // For headers() and cookies() from next/headers, add common iterator methods
1355
1975
  // These are needed when the mock is passed to functions that use .entries(), .keys(), etc.
1356
1976
  // (e.g., Object.fromEntries(headers.entries()) in buildLegacyHeaders)
1357
1977
  const needsIteratorMethods =
1358
- mockName === 'headers' || mockName === 'cookies';
1978
+ baseMockName === 'headers' || baseMockName === 'cookies';
1359
1979
  let enhancedContents = contents;
1360
1980
  if (needsIteratorMethods && contents.trim().startsWith('{')) {
1361
1981
  // Add iterator methods that operate on the scenario data
1362
- // Use canonical key if provided, otherwise fall back to legacy format
1363
- const dataKey = canonicalKey || `${mockName}()`;
1982
+ // Use the dataKey (original call signature or canonical key)
1983
+ const quotedDataKey = quotePropertyKey(dataKey);
1364
1984
  const iteratorMethods = `,
1365
- entries: () => Object.entries(scenarios().data()?.["${dataKey}"] || {}),
1366
- keys: () => Object.keys(scenarios().data()?.["${dataKey}"] || {}),
1367
- values: () => Object.values(scenarios().data()?.["${dataKey}"] || {}),
1368
- forEach: (fn) => Object.entries(scenarios().data()?.["${dataKey}"] || {}).forEach(([k, v]) => fn(v, k)),
1369
- has: (key) => Object.prototype.hasOwnProperty.call(scenarios().data()?.["${dataKey}"] || {}, key)`;
1985
+ entries: () => Object.entries(scenarios().data()?.${quotedDataKey} || {}),
1986
+ keys: () => Object.keys(scenarios().data()?.${quotedDataKey} || {}),
1987
+ values: () => Object.values(scenarios().data()?.${quotedDataKey} || {}),
1988
+ forEach: (fn) => Object.entries(scenarios().data()?.${quotedDataKey} || {}).forEach(([k, v]) => fn(v, k)),
1989
+ has: (key) => Object.prototype.hasOwnProperty.call(scenarios().data()?.${quotedDataKey} || {}, key)`;
1370
1990
  // Insert before the closing brace (handle trailing whitespace)
1371
1991
  enhancedContents = contents.replace(/\}\s*$/, iteratorMethods + '\n}');
1372
1992
  }
@@ -1377,32 +1997,42 @@ export default function constructMockCode(
1377
1997
  // `new ClassName("arg")` wouldn't create the expected instance.
1378
1998
  // For Error subclasses (detected by name ending in "Error"), extend Error for proper error handling.
1379
1999
  if (entityType === 'class') {
1380
- const isErrorSubclass = mockName.endsWith('Error');
1381
- const baseClass = isErrorSubclass ? 'Error' : 'Object';
2000
+ const isErrorSubclass = baseMockName.endsWith('Error');
1382
2001
  const superCall = isErrorSubclass ? 'super(message);' : '';
1383
2002
  const nameAssignment = isErrorSubclass
1384
- ? `this.name = '${mockName}';`
2003
+ ? `this.name = '${baseMockName}';`
1385
2004
  : '';
1386
- // Use canonical key if provided, otherwise fall back to legacy format
1387
- const dataKey = canonicalKey || `${mockName}()`;
2005
+ // Use the safe function name for the class definition
2006
+ const className = mockNameIsCallSignature
2007
+ ? derivedFunctionName
2008
+ : baseMockName;
1388
2009
 
1389
- return `class ${mockName}${isErrorSubclass ? ' extends Error' : ''} {
2010
+ return `class ${className}${isErrorSubclass ? ' extends Error' : ''} {
1390
2011
  constructor(message) {
1391
2012
  ${superCall}
1392
2013
  ${nameAssignment}
1393
- Object.assign(this, scenarios().data()?.["${dataKey}"] || {});
2014
+ Object.assign(this, scenarios().data()?.${quotePropertyKey(dataKey)} || {});
1394
2015
  }
1395
2016
  }`;
1396
2017
  }
1397
2018
 
1398
- // For variable-qualified mocks, use underscore separator in the function name
1399
- // e.g., "entityDiffFetcher <- useFetcher" becomes "useFetcher_entityDiffFetcher"
1400
- // For indexed qualifiers like "data[1]", convert to safe identifier: "useFetcher_data_1"
1401
- // EXCEPTION: When keepOriginalFunctionName is true (for single-call cases), use the base name
1402
- const safeFunctionName =
1403
- variableQualifier && !options?.keepOriginalFunctionName
1404
- ? `${baseMockName}_${safeVariableQualifier(variableQualifier)}`
1405
- : baseMockName;
2019
+ // Generate safe function name:
2020
+ // 1. For call signatures: use derivedFunctionName
2021
+ // e.g., "useFetcher<User>()" becomes "useFetcher_User"
2022
+ // e.g., "db.select(usersQuery)" becomes "db_select_usersQuery"
2023
+ // 2. With uniqueFunctionSuffix option: append suffix for unique naming
2024
+ // e.g., baseMockName = "useFetcher", suffix = "entityDiffFetcher" -> "useFetcher_entityDiffFetcher"
2025
+ // 3. EXCEPTION: When keepOriginalFunctionName is true (for single-call cases), use the base name
2026
+ let safeFunctionName: string;
2027
+ if (options?.keepOriginalFunctionName) {
2028
+ safeFunctionName = baseMockName;
2029
+ } else if (options?.uniqueFunctionSuffix) {
2030
+ safeFunctionName = `${baseMockName}_${options.uniqueFunctionSuffix}`;
2031
+ } else if (mockNameIsCallSignature && derivedFunctionName) {
2032
+ safeFunctionName = derivedFunctionName;
2033
+ } else {
2034
+ safeFunctionName = baseMockName;
2035
+ }
1406
2036
 
1407
2037
  // Check if this function returns a function (detected by double-call pattern: mockName(args)())
1408
2038
  // This happens when the schema has keys like "wrapThrows(() => JSON.parse(savedFilters))()"
@@ -1441,21 +2071,32 @@ export default function constructMockCode(
1441
2071
  return false;
1442
2072
  });
1443
2073
 
2074
+ // Use ...args to accept any number of arguments - prevents TypeScript errors
2075
+ // like "Expected 0 arguments, but got X" when caller passes arguments
1444
2076
  // For higher-order functions, wrap the return in an arrow function
1445
2077
  // so that mockFunc(arg)() works correctly (outer call returns a function, inner call gets the data)
1446
2078
  const returnValue = isHigherOrderFunction
1447
- ? `() => ${safeFunctionName}ReturnValue`
1448
- : `${safeFunctionName}ReturnValue`;
2079
+ ? `() => (${enhancedContents})`
2080
+ : enhancedContents;
1449
2081
 
1450
- return `const ${safeFunctionName}ReturnValue = ${enhancedContents};\n\n${isRootAsyncFunction ? 'async ' : ''}function ${safeFunctionName}() {\n${indent(`return ${returnValue};`)}\n}`;
2082
+ // Inline the return value directly in the function to avoid module-level const
2083
+ // that would be evaluated before scenario context is ready
2084
+ return `${isRootAsyncFunction ? 'async ' : ''}function ${safeFunctionName}(...args) {\n${indent(`return ${returnValue};`)}\n}`;
1451
2085
  } else {
1452
- // For variable-qualified mocks, use underscore separator in the const name
1453
- // For indexed qualifiers like "data[1]", convert to safe identifier: "useFetcher_data_1"
1454
- // EXCEPTION: When keepOriginalFunctionName is true (for single-call cases), use the base name
1455
- const safeName =
1456
- variableQualifier && !options?.keepOriginalFunctionName
1457
- ? `${baseMockName}_${safeVariableQualifier(variableQualifier)}`
1458
- : baseMockName;
2086
+ // Generate safe const name:
2087
+ // 1. For call signatures: use derivedFunctionName
2088
+ // 2. With uniqueFunctionSuffix option: append suffix for unique naming
2089
+ // 3. EXCEPTION: When keepOriginalFunctionName is true (for single-call cases), use the base name
2090
+ let safeName: string;
2091
+ if (options?.keepOriginalFunctionName) {
2092
+ safeName = baseMockName;
2093
+ } else if (options?.uniqueFunctionSuffix) {
2094
+ safeName = `${baseMockName}_${options.uniqueFunctionSuffix}`;
2095
+ } else if (mockNameIsCallSignature && derivedFunctionName) {
2096
+ safeName = derivedFunctionName;
2097
+ } else {
2098
+ safeName = baseMockName;
2099
+ }
1459
2100
 
1460
2101
  // Get any jsx-component properties that need to be preserved from the original
1461
2102
  const jsxProperties = getJsxComponentProperties(