@codeyam/codeyam-cli 0.1.0-staging.8e7b1bd → 0.1.0-staging.b8a55ba

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 (385) 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 +7 -6
  4. package/analyzer-template/packages/ai/package.json +1 -1
  5. package/analyzer-template/packages/ai/src/lib/analyzeScope.ts +2 -0
  6. package/analyzer-template/packages/ai/src/lib/astScopes/astScopeAnalyzer.ts +22 -0
  7. package/analyzer-template/packages/ai/src/lib/astScopes/patterns/switchStatementHandler.ts +23 -1
  8. package/analyzer-template/packages/ai/src/lib/astScopes/processExpression.ts +401 -106
  9. package/analyzer-template/packages/ai/src/lib/astScopes/types.ts +60 -0
  10. package/analyzer-template/packages/ai/src/lib/dataStructure/ScopeDataStructure.ts +661 -50
  11. package/analyzer-template/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/JavascriptFrameworkManager.ts +14 -2
  12. package/analyzer-template/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/MuiManager.ts +715 -0
  13. package/analyzer-template/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/ReactFrameworkManager.ts +123 -1
  14. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/cleanKnownObjectFunctions.ts +19 -1
  15. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/cleanNonObjectFunctions.ts +23 -1
  16. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/convertDotNotation.ts +23 -0
  17. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/fillInSchemaGapsAndUnknowns.ts +34 -1
  18. package/analyzer-template/packages/ai/src/lib/gatherRelevantDependentKeyAttributes.ts +236 -24
  19. package/analyzer-template/packages/ai/src/lib/generateChangesEntityKeyAttributes.ts +18 -1
  20. package/analyzer-template/packages/ai/src/lib/generateChangesEntityScenarios.ts +37 -4
  21. package/analyzer-template/packages/ai/src/lib/generateEntityDataStructure.ts +5 -0
  22. package/analyzer-template/packages/ai/src/lib/generateEntityKeyAttributes.ts +213 -12
  23. package/analyzer-template/packages/ai/src/lib/generateEntityScenarioData.ts +11 -15
  24. package/analyzer-template/packages/ai/src/lib/generateEntityScenarios.ts +114 -11
  25. package/analyzer-template/packages/ai/src/lib/getConditionalUsagesFromCode.ts +143 -31
  26. package/analyzer-template/packages/ai/src/lib/guessScenarioDataFromDescription.ts +8 -2
  27. package/analyzer-template/packages/ai/src/lib/promptGenerators/gatherAttributesMap.ts +7 -0
  28. package/analyzer-template/packages/ai/src/lib/promptGenerators/generateChangesEntityScenariosGenerator.ts +42 -2
  29. package/analyzer-template/packages/ai/src/lib/promptGenerators/generateEntityScenariosGenerator.ts +38 -2
  30. package/analyzer-template/packages/ai/src/lib/promptGenerators/guessNewScenarioDataFromDescriptionGenerator.ts +28 -2
  31. package/analyzer-template/packages/ai/src/lib/worker/SerializableDataStructure.ts +5 -0
  32. package/analyzer-template/packages/ai/src/lib/worker/analyzeScopeWorker.ts +8 -1
  33. package/analyzer-template/packages/analyze/src/lib/files/analyze/analyzeEntities/prepareDataStructures.ts +339 -145
  34. package/analyzer-template/packages/analyze/src/lib/files/analyze/analyzeEntities.ts +20 -0
  35. package/analyzer-template/packages/analyze/src/lib/files/getImportedExports.ts +8 -1
  36. package/analyzer-template/packages/analyze/src/lib/files/scenarios/enrichArrayTypesFromChildSignatures.ts +158 -0
  37. package/analyzer-template/packages/analyze/src/lib/files/scenarios/gatherDataForMocks.ts +107 -18
  38. package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateChangesScenarioData.ts +1 -1
  39. package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateDataStructure.ts +223 -103
  40. package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateKeyAttributes.ts +10 -5
  41. package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateScenarioData.ts +172 -83
  42. package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateScenarios.ts +2 -5
  43. package/analyzer-template/packages/analyze/src/lib/files/scenarios/mergeInDependentDataStructure.ts +97 -27
  44. package/analyzer-template/packages/aws/dist/src/lib/s3/checkS3ObjectExists.d.ts +15 -0
  45. package/analyzer-template/packages/aws/dist/src/lib/s3/checkS3ObjectExists.d.ts.map +1 -0
  46. package/analyzer-template/packages/aws/dist/src/lib/s3/checkS3ObjectExists.js +31 -0
  47. package/analyzer-template/packages/aws/dist/src/lib/s3/checkS3ObjectExists.js.map +1 -0
  48. package/analyzer-template/packages/aws/package.json +1 -1
  49. package/analyzer-template/packages/aws/s3/index.ts +1 -0
  50. package/analyzer-template/packages/aws/src/lib/s3/checkS3ObjectExists.ts +47 -0
  51. package/analyzer-template/packages/database/src/lib/kysely/db.ts +4 -4
  52. package/analyzer-template/packages/database/src/lib/kysely/tableRelations.ts +2 -2
  53. package/analyzer-template/packages/database/src/lib/kysely/tables/debugReportsTable.ts +20 -9
  54. package/analyzer-template/packages/database/src/lib/loadReadyToBeCapturedAnalyses.ts +3 -2
  55. package/analyzer-template/packages/generate/src/lib/componentScenarioPage/getIFrameMessageListenerCode.ts +9 -4
  56. package/analyzer-template/packages/generate/src/lib/deepMerge.ts +26 -1
  57. package/analyzer-template/packages/generate/src/lib/getComponentScenarioPath.ts +8 -3
  58. package/analyzer-template/packages/github/dist/database/src/lib/kysely/db.d.ts +2 -2
  59. package/analyzer-template/packages/github/dist/database/src/lib/kysely/db.js +2 -2
  60. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tableRelations.d.ts +2 -2
  61. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/analysesTable.d.ts +8 -1
  62. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/analysesTable.d.ts.map +1 -1
  63. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/debugReportsTable.d.ts +14 -7
  64. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/debugReportsTable.d.ts.map +1 -1
  65. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/debugReportsTable.js +9 -3
  66. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/debugReportsTable.js.map +1 -1
  67. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/scenariosTable.d.ts +1 -1
  68. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/scenariosTable.d.ts.map +1 -1
  69. package/analyzer-template/packages/github/dist/database/src/lib/loadReadyToBeCapturedAnalyses.d.ts.map +1 -1
  70. package/analyzer-template/packages/github/dist/database/src/lib/loadReadyToBeCapturedAnalyses.js +4 -2
  71. package/analyzer-template/packages/github/dist/database/src/lib/loadReadyToBeCapturedAnalyses.js.map +1 -1
  72. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/getIFrameMessageListenerCode.d.ts.map +1 -1
  73. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/getIFrameMessageListenerCode.js +8 -4
  74. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/getIFrameMessageListenerCode.js.map +1 -1
  75. package/analyzer-template/packages/github/dist/generate/src/lib/deepMerge.d.ts.map +1 -1
  76. package/analyzer-template/packages/github/dist/generate/src/lib/deepMerge.js +27 -1
  77. package/analyzer-template/packages/github/dist/generate/src/lib/deepMerge.js.map +1 -1
  78. package/analyzer-template/packages/github/dist/generate/src/lib/getComponentScenarioPath.d.ts.map +1 -1
  79. package/analyzer-template/packages/github/dist/generate/src/lib/getComponentScenarioPath.js +7 -3
  80. package/analyzer-template/packages/github/dist/generate/src/lib/getComponentScenarioPath.js.map +1 -1
  81. package/analyzer-template/packages/github/dist/types/index.d.ts +4 -3
  82. package/analyzer-template/packages/github/dist/types/index.d.ts.map +1 -1
  83. package/analyzer-template/packages/github/dist/types/index.js +1 -0
  84. package/analyzer-template/packages/github/dist/types/index.js.map +1 -1
  85. package/analyzer-template/packages/github/dist/types/src/types/Analysis.d.ts +31 -1
  86. package/analyzer-template/packages/github/dist/types/src/types/Analysis.d.ts.map +1 -1
  87. package/analyzer-template/packages/github/dist/types/src/types/Scenario.d.ts +51 -1
  88. package/analyzer-template/packages/github/dist/types/src/types/Scenario.d.ts.map +1 -1
  89. package/analyzer-template/packages/github/dist/types/src/types/Scenario.js +21 -1
  90. package/analyzer-template/packages/github/dist/types/src/types/Scenario.js.map +1 -1
  91. package/analyzer-template/packages/github/dist/types/src/types/ScenariosDataStructure.d.ts +48 -0
  92. package/analyzer-template/packages/github/dist/types/src/types/ScenariosDataStructure.d.ts.map +1 -1
  93. package/analyzer-template/packages/github/dist/utils/src/lib/applyUniversalMocks.d.ts.map +1 -1
  94. package/analyzer-template/packages/github/dist/utils/src/lib/applyUniversalMocks.js +26 -2
  95. package/analyzer-template/packages/github/dist/utils/src/lib/applyUniversalMocks.js.map +1 -1
  96. package/analyzer-template/packages/github/dist/utils/src/lib/lightweightEntityExtractor.d.ts.map +1 -1
  97. package/analyzer-template/packages/github/dist/utils/src/lib/lightweightEntityExtractor.js +25 -0
  98. package/analyzer-template/packages/github/dist/utils/src/lib/lightweightEntityExtractor.js.map +1 -1
  99. package/analyzer-template/packages/types/index.ts +8 -0
  100. package/analyzer-template/packages/types/src/types/Analysis.ts +32 -1
  101. package/analyzer-template/packages/types/src/types/Scenario.ts +75 -6
  102. package/analyzer-template/packages/types/src/types/ScenariosDataStructure.ts +49 -0
  103. package/analyzer-template/packages/ui-components/package.json +4 -4
  104. package/analyzer-template/packages/ui-components/src/components/ScenarioDetailInteractiveView.tsx +23 -7
  105. package/analyzer-template/packages/utils/dist/types/index.d.ts +4 -3
  106. package/analyzer-template/packages/utils/dist/types/index.d.ts.map +1 -1
  107. package/analyzer-template/packages/utils/dist/types/index.js +1 -0
  108. package/analyzer-template/packages/utils/dist/types/index.js.map +1 -1
  109. package/analyzer-template/packages/utils/dist/types/src/types/Analysis.d.ts +31 -1
  110. package/analyzer-template/packages/utils/dist/types/src/types/Analysis.d.ts.map +1 -1
  111. package/analyzer-template/packages/utils/dist/types/src/types/Scenario.d.ts +51 -1
  112. package/analyzer-template/packages/utils/dist/types/src/types/Scenario.d.ts.map +1 -1
  113. package/analyzer-template/packages/utils/dist/types/src/types/Scenario.js +21 -1
  114. package/analyzer-template/packages/utils/dist/types/src/types/Scenario.js.map +1 -1
  115. package/analyzer-template/packages/utils/dist/types/src/types/ScenariosDataStructure.d.ts +48 -0
  116. package/analyzer-template/packages/utils/dist/types/src/types/ScenariosDataStructure.d.ts.map +1 -1
  117. package/analyzer-template/packages/utils/dist/utils/src/lib/applyUniversalMocks.d.ts.map +1 -1
  118. package/analyzer-template/packages/utils/dist/utils/src/lib/applyUniversalMocks.js +26 -2
  119. package/analyzer-template/packages/utils/dist/utils/src/lib/applyUniversalMocks.js.map +1 -1
  120. package/analyzer-template/packages/utils/dist/utils/src/lib/lightweightEntityExtractor.d.ts.map +1 -1
  121. package/analyzer-template/packages/utils/dist/utils/src/lib/lightweightEntityExtractor.js +25 -0
  122. package/analyzer-template/packages/utils/dist/utils/src/lib/lightweightEntityExtractor.js.map +1 -1
  123. package/analyzer-template/packages/utils/src/lib/applyUniversalMocks.ts +28 -2
  124. package/analyzer-template/packages/utils/src/lib/lightweightEntityExtractor.ts +27 -0
  125. package/analyzer-template/playwright/takeElementScreenshot.ts +26 -11
  126. package/analyzer-template/playwright/takeScreenshot.ts +9 -7
  127. package/analyzer-template/project/TESTING.md +83 -0
  128. package/analyzer-template/project/constructMockCode.ts +151 -30
  129. package/analyzer-template/project/loadReadyToBeCaptured.ts +17 -1
  130. package/analyzer-template/project/orchestrateCapture/KyselyAnalysisLoader.ts +16 -9
  131. package/analyzer-template/project/orchestrateCapture/SequentialCaptureTaskRunner.ts +77 -37
  132. package/analyzer-template/project/reconcileMockDataKeys.ts +104 -3
  133. package/analyzer-template/project/runMultiScenarioServer.ts +11 -10
  134. package/analyzer-template/project/serverOnlyModules.ts +288 -0
  135. package/analyzer-template/project/start.ts +10 -0
  136. package/analyzer-template/project/startScenarioCapture.ts +73 -41
  137. package/analyzer-template/project/writeMockDataTsx.ts +103 -40
  138. package/analyzer-template/project/writeScenarioComponents.ts +1162 -203
  139. package/analyzer-template/project/writeSimpleRoot.ts +26 -4
  140. package/analyzer-template/project/writeUniversalMocks.ts +32 -11
  141. package/background/src/lib/virtualized/project/constructMockCode.js +132 -25
  142. package/background/src/lib/virtualized/project/constructMockCode.js.map +1 -1
  143. package/background/src/lib/virtualized/project/loadReadyToBeCaptured.js +15 -1
  144. package/background/src/lib/virtualized/project/loadReadyToBeCaptured.js.map +1 -1
  145. package/background/src/lib/virtualized/project/orchestrateCapture/KyselyAnalysisLoader.js +11 -6
  146. package/background/src/lib/virtualized/project/orchestrateCapture/KyselyAnalysisLoader.js.map +1 -1
  147. package/background/src/lib/virtualized/project/orchestrateCapture/SequentialCaptureTaskRunner.js +67 -32
  148. package/background/src/lib/virtualized/project/orchestrateCapture/SequentialCaptureTaskRunner.js.map +1 -1
  149. package/background/src/lib/virtualized/project/reconcileMockDataKeys.js +65 -4
  150. package/background/src/lib/virtualized/project/reconcileMockDataKeys.js.map +1 -1
  151. package/background/src/lib/virtualized/project/runMultiScenarioServer.js +11 -9
  152. package/background/src/lib/virtualized/project/runMultiScenarioServer.js.map +1 -1
  153. package/background/src/lib/virtualized/project/serverOnlyModules.js +235 -0
  154. package/background/src/lib/virtualized/project/serverOnlyModules.js.map +1 -0
  155. package/background/src/lib/virtualized/project/start.js +6 -0
  156. package/background/src/lib/virtualized/project/start.js.map +1 -1
  157. package/background/src/lib/virtualized/project/startScenarioCapture.js +54 -31
  158. package/background/src/lib/virtualized/project/startScenarioCapture.js.map +1 -1
  159. package/background/src/lib/virtualized/project/writeMockDataTsx.js +87 -34
  160. package/background/src/lib/virtualized/project/writeMockDataTsx.js.map +1 -1
  161. package/background/src/lib/virtualized/project/writeScenarioComponents.js +852 -133
  162. package/background/src/lib/virtualized/project/writeScenarioComponents.js.map +1 -1
  163. package/background/src/lib/virtualized/project/writeSimpleRoot.js +25 -2
  164. package/background/src/lib/virtualized/project/writeSimpleRoot.js.map +1 -1
  165. package/background/src/lib/virtualized/project/writeUniversalMocks.js +27 -12
  166. package/background/src/lib/virtualized/project/writeUniversalMocks.js.map +1 -1
  167. package/codeyam-cli/scripts/fixtures/formbricks/universal-mocks/apps/web/lib/instance/service.js +7 -0
  168. package/codeyam-cli/scripts/fixtures/formbricks/universal-mocks/apps/web/lib/instance/service.js.map +1 -0
  169. package/codeyam-cli/src/cli.js +2 -0
  170. package/codeyam-cli/src/cli.js.map +1 -1
  171. package/codeyam-cli/src/commands/debug.js +14 -2
  172. package/codeyam-cli/src/commands/debug.js.map +1 -1
  173. package/codeyam-cli/src/commands/recapture.js +215 -0
  174. package/codeyam-cli/src/commands/recapture.js.map +1 -0
  175. package/codeyam-cli/src/commands/report.js +26 -23
  176. package/codeyam-cli/src/commands/report.js.map +1 -1
  177. package/codeyam-cli/src/utils/backgroundServer.js +2 -2
  178. package/codeyam-cli/src/utils/backgroundServer.js.map +1 -1
  179. package/codeyam-cli/src/utils/generateReport.js +252 -106
  180. package/codeyam-cli/src/utils/generateReport.js.map +1 -1
  181. package/codeyam-cli/src/utils/install-skills.js +2 -7
  182. package/codeyam-cli/src/utils/install-skills.js.map +1 -1
  183. package/codeyam-cli/src/utils/queue/__tests__/manager.test.js +38 -0
  184. package/codeyam-cli/src/utils/queue/__tests__/manager.test.js.map +1 -1
  185. package/codeyam-cli/src/utils/queue/job.js +140 -16
  186. package/codeyam-cli/src/utils/queue/job.js.map +1 -1
  187. package/codeyam-cli/src/utils/queue/manager.js +19 -7
  188. package/codeyam-cli/src/utils/queue/manager.js.map +1 -1
  189. package/codeyam-cli/src/utils/queue/persistence.js.map +1 -1
  190. package/codeyam-cli/src/webserver/app/lib/database.js +47 -0
  191. package/codeyam-cli/src/webserver/app/lib/database.js.map +1 -1
  192. package/codeyam-cli/src/webserver/app/lib/dbNotifier.js.map +1 -1
  193. package/codeyam-cli/src/webserver/backgroundServer.js +5 -10
  194. package/codeyam-cli/src/webserver/backgroundServer.js.map +1 -1
  195. package/codeyam-cli/src/webserver/bootstrap.js +9 -0
  196. package/codeyam-cli/src/webserver/bootstrap.js.map +1 -0
  197. package/codeyam-cli/src/webserver/build/client/assets/EntityItem-wXL1Z2Aq.js +1 -0
  198. package/codeyam-cli/src/webserver/build/client/assets/{EntityTypeBadge-DQeyk25_.js → EntityTypeBadge-CzGX-miz.js} +1 -1
  199. package/codeyam-cli/src/webserver/build/client/assets/EntityTypeIcon-CXFKsCOD.js +41 -0
  200. package/codeyam-cli/src/webserver/build/client/assets/InteractivePreview-D-9pXIaY.js +25 -0
  201. package/codeyam-cli/src/webserver/build/client/assets/LibraryFunctionPreview-CBQPrpT0.js +3 -0
  202. package/codeyam-cli/src/webserver/build/client/assets/LoadingDots-D1CdlbrV.js +6 -0
  203. package/codeyam-cli/src/webserver/build/client/assets/LogViewer-wDPcZNKx.js +3 -0
  204. package/codeyam-cli/src/webserver/build/client/assets/ReportIssueModal-4lcOlid-.js +11 -0
  205. package/codeyam-cli/src/webserver/build/client/assets/SafeScreenshot-BfmDgXxG.js +1 -0
  206. package/codeyam-cli/src/webserver/build/client/assets/ScenarioViewer-CUxUNEEC.js +15 -0
  207. package/codeyam-cli/src/webserver/build/client/assets/{TruncatedFilePath-ayCJdUAc.js → TruncatedFilePath-6J7zDUD5.js} +1 -1
  208. package/codeyam-cli/src/webserver/build/client/assets/_index-DHImXdXq.js +11 -0
  209. package/codeyam-cli/src/webserver/build/client/assets/activity.(_tab)-2mG6mjVb.js +32 -0
  210. package/codeyam-cli/src/webserver/build/client/assets/api.link-scenario-value-l0sNRNKZ.js +1 -0
  211. package/codeyam-cli/src/webserver/build/client/assets/api.update-key-attributes-l0sNRNKZ.js +1 -0
  212. package/codeyam-cli/src/webserver/build/client/assets/api.update-valid-values-l0sNRNKZ.js +1 -0
  213. package/codeyam-cli/src/webserver/build/client/assets/chevron-down-BYimnrHg.js +6 -0
  214. package/codeyam-cli/src/webserver/build/client/assets/chunk-JMJ3UQ3L-BambyYE_.js +51 -0
  215. package/codeyam-cli/src/webserver/build/client/assets/circle-check-CaVsIRxt.js +6 -0
  216. package/codeyam-cli/src/webserver/build/client/assets/createLucideIcon-CgUsG7ib.js +21 -0
  217. package/codeyam-cli/src/webserver/build/client/assets/cy-logo-cli-CKnwPCDr.js +1 -0
  218. package/codeyam-cli/src/webserver/build/client/assets/dev.empty-DW_hdGUc.js +1 -0
  219. package/codeyam-cli/src/webserver/build/client/assets/{entity._sha._-FHOVOgFN.js → entity._sha._-zUEpfPsu.js} +22 -15
  220. package/codeyam-cli/src/webserver/build/client/assets/entity._sha.scenarios._scenarioId.fullscreen-DyB90fWk.js +1 -0
  221. package/codeyam-cli/src/webserver/build/client/assets/entity._sha_.create-scenario-D_3ero5o.js +1 -0
  222. package/codeyam-cli/src/webserver/build/client/assets/entity._sha_.edit._scenarioId-CfLCUi9S.js +5 -0
  223. package/codeyam-cli/src/webserver/build/client/assets/entry.client-DKJyZfAY.js +29 -0
  224. package/codeyam-cli/src/webserver/build/client/assets/fileTableUtils-DAtOlaWE.js +1 -0
  225. package/codeyam-cli/src/webserver/build/client/assets/files-ClR0d32A.js +1 -0
  226. package/codeyam-cli/src/webserver/build/client/assets/git-D62Lxxmv.js +15 -0
  227. package/codeyam-cli/src/webserver/build/client/assets/globals-C6vQASxy.css +1 -0
  228. package/codeyam-cli/src/webserver/build/client/assets/html2canvas-pro.esm-fmIEn3Bc.js +9 -0
  229. package/codeyam-cli/src/webserver/build/client/assets/index-BosqDOlH.js +3 -0
  230. package/codeyam-cli/src/webserver/build/client/assets/index-CzNNiTkw.js +9 -0
  231. package/codeyam-cli/src/webserver/build/client/assets/keyAttributeCoverage-CTlFMihX.js +1 -0
  232. package/codeyam-cli/src/webserver/build/client/assets/loader-circle-CNp9QFCX.js +6 -0
  233. package/codeyam-cli/src/webserver/build/client/assets/manifest-09d684be.js +1 -0
  234. package/codeyam-cli/src/webserver/build/client/assets/preload-helper-ckwbz45p.js +1 -0
  235. package/codeyam-cli/src/webserver/build/client/assets/root-BxJUvKau.js +56 -0
  236. package/codeyam-cli/src/webserver/build/client/assets/scenarioStatus-B_8jpV3e.js +1 -0
  237. package/codeyam-cli/src/webserver/build/client/assets/search-DDGjYAMJ.js +6 -0
  238. package/codeyam-cli/src/webserver/build/client/assets/settings-DgTyB-Wg.js +1 -0
  239. package/codeyam-cli/src/webserver/build/client/assets/simulations-CoNWGt0K.js +1 -0
  240. package/codeyam-cli/src/webserver/build/client/assets/triangle-alert-CBc5dE1s.js +6 -0
  241. package/codeyam-cli/src/webserver/build/client/assets/useCustomSizes-BMIGFP-m.js +1 -0
  242. package/codeyam-cli/src/webserver/build/client/assets/useInteractiveMode-Dk_FQqWJ.js +1 -0
  243. package/codeyam-cli/src/webserver/build/client/assets/{useLastLogLine-DOGXmJcI.js → useLastLogLine-BqPPNjAl.js} +1 -1
  244. package/codeyam-cli/src/webserver/build/client/assets/useReportContext-DsJbgMY9.js +1 -0
  245. package/codeyam-cli/src/webserver/build/client/assets/{useToast-C07gRg7Z.js → useToast-DWHcCcl1.js} +1 -1
  246. package/codeyam-cli/src/webserver/build/server/assets/index-CV6i1S1A.js +1 -0
  247. package/codeyam-cli/src/webserver/build/server/assets/server-build-BDlyhfrv.js +175 -0
  248. package/codeyam-cli/src/webserver/build/server/index.js +1 -1
  249. package/codeyam-cli/src/webserver/build-info.json +5 -5
  250. package/codeyam-cli/src/webserver/devServer.js +1 -3
  251. package/codeyam-cli/src/webserver/devServer.js.map +1 -1
  252. package/codeyam-cli/templates/debug-codeyam.md +620 -0
  253. package/package.json +14 -14
  254. package/packages/ai/src/lib/analyzeScope.js +2 -0
  255. package/packages/ai/src/lib/analyzeScope.js.map +1 -1
  256. package/packages/ai/src/lib/astScopes/astScopeAnalyzer.js +16 -0
  257. package/packages/ai/src/lib/astScopes/astScopeAnalyzer.js.map +1 -1
  258. package/packages/ai/src/lib/astScopes/patterns/switchStatementHandler.js +16 -0
  259. package/packages/ai/src/lib/astScopes/patterns/switchStatementHandler.js.map +1 -1
  260. package/packages/ai/src/lib/astScopes/processExpression.js +305 -88
  261. package/packages/ai/src/lib/astScopes/processExpression.js.map +1 -1
  262. package/packages/ai/src/lib/dataStructure/ScopeDataStructure.js +523 -42
  263. package/packages/ai/src/lib/dataStructure/ScopeDataStructure.js.map +1 -1
  264. package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/JavascriptFrameworkManager.js +12 -2
  265. package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/JavascriptFrameworkManager.js.map +1 -1
  266. package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/MuiManager.js +454 -0
  267. package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/MuiManager.js.map +1 -0
  268. package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/ReactFrameworkManager.js +103 -1
  269. package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/ReactFrameworkManager.js.map +1 -1
  270. package/packages/ai/src/lib/dataStructure/helpers/cleanKnownObjectFunctions.js +16 -1
  271. package/packages/ai/src/lib/dataStructure/helpers/cleanKnownObjectFunctions.js.map +1 -1
  272. package/packages/ai/src/lib/dataStructure/helpers/cleanNonObjectFunctions.js +19 -1
  273. package/packages/ai/src/lib/dataStructure/helpers/cleanNonObjectFunctions.js.map +1 -1
  274. package/packages/ai/src/lib/dataStructure/helpers/convertDotNotation.js +20 -0
  275. package/packages/ai/src/lib/dataStructure/helpers/convertDotNotation.js.map +1 -1
  276. package/packages/ai/src/lib/dataStructure/helpers/fillInSchemaGapsAndUnknowns.js +28 -2
  277. package/packages/ai/src/lib/dataStructure/helpers/fillInSchemaGapsAndUnknowns.js.map +1 -1
  278. package/packages/ai/src/lib/gatherRelevantDependentKeyAttributes.js +179 -17
  279. package/packages/ai/src/lib/gatherRelevantDependentKeyAttributes.js.map +1 -1
  280. package/packages/ai/src/lib/generateChangesEntityKeyAttributes.js +6 -0
  281. package/packages/ai/src/lib/generateChangesEntityKeyAttributes.js.map +1 -1
  282. package/packages/ai/src/lib/generateChangesEntityScenarios.js +37 -4
  283. package/packages/ai/src/lib/generateChangesEntityScenarios.js.map +1 -1
  284. package/packages/ai/src/lib/generateEntityDataStructure.js +4 -0
  285. package/packages/ai/src/lib/generateEntityDataStructure.js.map +1 -1
  286. package/packages/ai/src/lib/generateEntityKeyAttributes.js +176 -9
  287. package/packages/ai/src/lib/generateEntityKeyAttributes.js.map +1 -1
  288. package/packages/ai/src/lib/generateEntityScenarioData.js +11 -15
  289. package/packages/ai/src/lib/generateEntityScenarioData.js.map +1 -1
  290. package/packages/ai/src/lib/generateEntityScenarios.js +105 -9
  291. package/packages/ai/src/lib/generateEntityScenarios.js.map +1 -1
  292. package/packages/ai/src/lib/getConditionalUsagesFromCode.js +84 -14
  293. package/packages/ai/src/lib/getConditionalUsagesFromCode.js.map +1 -1
  294. package/packages/ai/src/lib/guessScenarioDataFromDescription.js +2 -1
  295. package/packages/ai/src/lib/guessScenarioDataFromDescription.js.map +1 -1
  296. package/packages/ai/src/lib/promptGenerators/gatherAttributesMap.js +6 -0
  297. package/packages/ai/src/lib/promptGenerators/gatherAttributesMap.js.map +1 -1
  298. package/packages/ai/src/lib/promptGenerators/generateChangesEntityScenariosGenerator.js +38 -2
  299. package/packages/ai/src/lib/promptGenerators/generateChangesEntityScenariosGenerator.js.map +1 -1
  300. package/packages/ai/src/lib/promptGenerators/generateEntityScenariosGenerator.js +38 -2
  301. package/packages/ai/src/lib/promptGenerators/generateEntityScenariosGenerator.js.map +1 -1
  302. package/packages/ai/src/lib/promptGenerators/guessNewScenarioDataFromDescriptionGenerator.js +16 -3
  303. package/packages/ai/src/lib/promptGenerators/guessNewScenarioDataFromDescriptionGenerator.js.map +1 -1
  304. package/packages/ai/src/lib/worker/SerializableDataStructure.js.map +1 -1
  305. package/packages/ai/src/lib/worker/analyzeScopeWorker.js +4 -0
  306. package/packages/ai/src/lib/worker/analyzeScopeWorker.js.map +1 -1
  307. package/packages/analyze/src/lib/files/analyze/analyzeEntities/prepareDataStructures.js +258 -110
  308. package/packages/analyze/src/lib/files/analyze/analyzeEntities/prepareDataStructures.js.map +1 -1
  309. package/packages/analyze/src/lib/files/analyze/analyzeEntities.js +18 -0
  310. package/packages/analyze/src/lib/files/analyze/analyzeEntities.js.map +1 -1
  311. package/packages/analyze/src/lib/files/getImportedExports.js +6 -1
  312. package/packages/analyze/src/lib/files/getImportedExports.js.map +1 -1
  313. package/packages/analyze/src/lib/files/scenarios/enrichArrayTypesFromChildSignatures.js +125 -0
  314. package/packages/analyze/src/lib/files/scenarios/enrichArrayTypesFromChildSignatures.js.map +1 -0
  315. package/packages/analyze/src/lib/files/scenarios/gatherDataForMocks.js +74 -19
  316. package/packages/analyze/src/lib/files/scenarios/gatherDataForMocks.js.map +1 -1
  317. package/packages/analyze/src/lib/files/scenarios/generateChangesScenarioData.js +1 -1
  318. package/packages/analyze/src/lib/files/scenarios/generateChangesScenarioData.js.map +1 -1
  319. package/packages/analyze/src/lib/files/scenarios/generateDataStructure.js +175 -58
  320. package/packages/analyze/src/lib/files/scenarios/generateDataStructure.js.map +1 -1
  321. package/packages/analyze/src/lib/files/scenarios/generateKeyAttributes.js +10 -5
  322. package/packages/analyze/src/lib/files/scenarios/generateKeyAttributes.js.map +1 -1
  323. package/packages/analyze/src/lib/files/scenarios/generateScenarioData.js +127 -69
  324. package/packages/analyze/src/lib/files/scenarios/generateScenarioData.js.map +1 -1
  325. package/packages/analyze/src/lib/files/scenarios/generateScenarios.js +2 -5
  326. package/packages/analyze/src/lib/files/scenarios/generateScenarios.js.map +1 -1
  327. package/packages/analyze/src/lib/files/scenarios/mergeInDependentDataStructure.js +74 -23
  328. package/packages/analyze/src/lib/files/scenarios/mergeInDependentDataStructure.js.map +1 -1
  329. package/packages/database/src/lib/kysely/db.js +2 -2
  330. package/packages/database/src/lib/kysely/tables/debugReportsTable.js +9 -3
  331. package/packages/database/src/lib/kysely/tables/debugReportsTable.js.map +1 -1
  332. package/packages/database/src/lib/loadReadyToBeCapturedAnalyses.js +4 -2
  333. package/packages/database/src/lib/loadReadyToBeCapturedAnalyses.js.map +1 -1
  334. package/packages/generate/src/lib/componentScenarioPage/getIFrameMessageListenerCode.js +8 -4
  335. package/packages/generate/src/lib/componentScenarioPage/getIFrameMessageListenerCode.js.map +1 -1
  336. package/packages/generate/src/lib/deepMerge.js +27 -1
  337. package/packages/generate/src/lib/deepMerge.js.map +1 -1
  338. package/packages/generate/src/lib/getComponentScenarioPath.js +7 -3
  339. package/packages/generate/src/lib/getComponentScenarioPath.js.map +1 -1
  340. package/packages/types/index.js +1 -0
  341. package/packages/types/index.js.map +1 -1
  342. package/packages/types/src/types/Scenario.js +21 -1
  343. package/packages/types/src/types/Scenario.js.map +1 -1
  344. package/packages/utils/src/lib/applyUniversalMocks.js +26 -2
  345. package/packages/utils/src/lib/applyUniversalMocks.js.map +1 -1
  346. package/packages/utils/src/lib/lightweightEntityExtractor.js +25 -0
  347. package/packages/utils/src/lib/lightweightEntityExtractor.js.map +1 -1
  348. package/scripts/finalize-analyzer.cjs +3 -1
  349. package/codeyam-cli/src/webserver/build/client/assets/EntityItem-CWKV2GEz.js +0 -1
  350. package/codeyam-cli/src/webserver/build/client/assets/EntityTypeIcon-D2hFeDeg.js +0 -1
  351. package/codeyam-cli/src/webserver/build/client/assets/InteractivePreview-C8K-4kKP.js +0 -26
  352. package/codeyam-cli/src/webserver/build/client/assets/LibraryFunctionPreview-DgXLv61M.js +0 -3
  353. package/codeyam-cli/src/webserver/build/client/assets/LogViewer-DFdLQbPS.js +0 -3
  354. package/codeyam-cli/src/webserver/build/client/assets/ReportIssueModal-DlRDjT4h.js +0 -1
  355. package/codeyam-cli/src/webserver/build/client/assets/SafeScreenshot-7UkVL-UI.js +0 -1
  356. package/codeyam-cli/src/webserver/build/client/assets/ScenarioViewer-XjtsGuPo.js +0 -5
  357. package/codeyam-cli/src/webserver/build/client/assets/_index-D2eJjWLf.js +0 -1
  358. package/codeyam-cli/src/webserver/build/client/assets/activity.(_tab)-w6sbwlOd.js +0 -7
  359. package/codeyam-cli/src/webserver/build/client/assets/chevron-down-BBNQ8hup.js +0 -1
  360. package/codeyam-cli/src/webserver/build/client/assets/chunk-WWGJGFF6-Bex4RrGs.js +0 -26
  361. package/codeyam-cli/src/webserver/build/client/assets/circle-check-cdhjVtom.js +0 -1
  362. package/codeyam-cli/src/webserver/build/client/assets/createLucideIcon-DkgmwwRC.js +0 -1
  363. package/codeyam-cli/src/webserver/build/client/assets/dev.empty-CwLmCS0J.js +0 -1
  364. package/codeyam-cli/src/webserver/build/client/assets/entity._sha_.create-scenario-YZ-kM3ZG.js +0 -1
  365. package/codeyam-cli/src/webserver/build/client/assets/entity._sha_.edit._scenarioId-BeQlz94_.js +0 -5
  366. package/codeyam-cli/src/webserver/build/client/assets/entry.client-DN2XXM7Z.js +0 -5
  367. package/codeyam-cli/src/webserver/build/client/assets/fileTableUtils-CUeAIQNI.js +0 -1
  368. package/codeyam-cli/src/webserver/build/client/assets/files-ccMQfhGf.js +0 -1
  369. package/codeyam-cli/src/webserver/build/client/assets/git-JmESAHx5.js +0 -12
  370. package/codeyam-cli/src/webserver/build/client/assets/globals-CO-U8Bpo.css +0 -1
  371. package/codeyam-cli/src/webserver/build/client/assets/html2canvas-pro.esm-XQCGvadH.js +0 -5
  372. package/codeyam-cli/src/webserver/build/client/assets/index-DsL9BiOc.js +0 -8
  373. package/codeyam-cli/src/webserver/build/client/assets/loader-circle-COYCR2oZ.js +0 -1
  374. package/codeyam-cli/src/webserver/build/client/assets/manifest-90adba57.js +0 -1
  375. package/codeyam-cli/src/webserver/build/client/assets/root-DfbVEEjF.js +0 -16
  376. package/codeyam-cli/src/webserver/build/client/assets/search-DvK9iMBu.js +0 -1
  377. package/codeyam-cli/src/webserver/build/client/assets/server-build-CMKNK2uU.css +0 -1
  378. package/codeyam-cli/src/webserver/build/client/assets/settings-9LTbit4Z.js +0 -1
  379. package/codeyam-cli/src/webserver/build/client/assets/simulations-BrxN5ZtV.js +0 -1
  380. package/codeyam-cli/src/webserver/build/client/assets/triangle-alert-Iv0p8T-1.js +0 -1
  381. package/codeyam-cli/src/webserver/build/client/assets/useReportContext-BWmSRPH6.js +0 -1
  382. package/codeyam-cli/src/webserver/build/server/assets/index-CE_1qXCG.js +0 -1
  383. package/codeyam-cli/src/webserver/build/server/assets/server-build-BY_VDhiD.js +0 -166
  384. package/codeyam-cli/templates/debug-command.md +0 -141
  385. /package/codeyam-cli/src/webserver/build/client/assets/{InteractivePreview-CMKNK2uU.css → styles-CMKNK2uU.css} +0 -0
@@ -25,6 +25,68 @@ import * as fs from 'fs';
25
25
  import * as path from 'path';
26
26
  import ts from 'typescript';
27
27
  import { LazyFileStore } from './LazyFileStore';
28
+ import { applyServerOnlyMocks } from './serverOnlyModules';
29
+
30
+ // Debug timing helper for tracking where time is spent
31
+ const DEBUG_TIMING = process.env.DEBUG_WRITE_SCENARIO === 'true';
32
+ let debugStartTime: number;
33
+ let debugLastTime: number;
34
+
35
+ // Timeout protection to prevent infinite hangs
36
+ const WRITE_SCENARIO_TIMEOUT_MS = parseInt(
37
+ process.env.WRITE_SCENARIO_TIMEOUT_MS || '300000', // Default 5 minutes
38
+ 10,
39
+ );
40
+
41
+ class WriteScenarioTimeoutError extends Error {
42
+ constructor(operation: string, timeoutMs: number) {
43
+ super(
44
+ `WriteScenarioComponents timed out after ${timeoutMs}ms during: ${operation}`,
45
+ );
46
+ this.name = 'WriteScenarioTimeoutError';
47
+ }
48
+ }
49
+
50
+ async function withTimeout<T>(
51
+ operation: string,
52
+ promise: Promise<T>,
53
+ timeoutMs: number = WRITE_SCENARIO_TIMEOUT_MS,
54
+ ): Promise<T> {
55
+ let timeoutId: NodeJS.Timeout | undefined;
56
+
57
+ const timeoutPromise = new Promise<never>((_, reject) => {
58
+ timeoutId = setTimeout(() => {
59
+ reject(new WriteScenarioTimeoutError(operation, timeoutMs));
60
+ }, timeoutMs);
61
+ });
62
+
63
+ try {
64
+ return await Promise.race([promise, timeoutPromise]);
65
+ } finally {
66
+ if (timeoutId) clearTimeout(timeoutId);
67
+ }
68
+ }
69
+
70
+ function debugLog(message: string, extra?: Record<string, unknown>): void {
71
+ if (!DEBUG_TIMING) return;
72
+ const now = Date.now();
73
+ if (!debugStartTime) {
74
+ debugStartTime = now;
75
+ debugLastTime = now;
76
+ }
77
+ const elapsed = now - debugStartTime;
78
+ const delta = now - debugLastTime;
79
+ debugLastTime = now;
80
+ console.log(
81
+ `[WriteScenario +${elapsed}ms Δ${delta}ms] ${message}`,
82
+ extra ? JSON.stringify(extra, null, 2) : '',
83
+ );
84
+ }
85
+
86
+ function resetDebugTiming(): void {
87
+ debugStartTime = 0;
88
+ debugLastTime = 0;
89
+ }
28
90
 
29
91
  /**
30
92
  * Find the end position of the last import/export-from statement using TypeScript AST.
@@ -74,6 +136,125 @@ function escapeRegExp(str: string): string {
74
136
  return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
75
137
  }
76
138
 
139
+ /**
140
+ * Remove a named import from file content using TypeScript AST.
141
+ * Handles both regular imports (`EntityName`) and type-only imports (`type EntityName`).
142
+ *
143
+ * @param fileContent - The file content to modify
144
+ * @param entityName - The name of the entity to remove from imports
145
+ * @returns The modified file content with the entity removed from imports
146
+ */
147
+ function removeNamedImportAst(fileContent: string, entityName: string): string {
148
+ try {
149
+ const sourceFile = ts.createSourceFile(
150
+ 'temp.tsx',
151
+ fileContent,
152
+ ts.ScriptTarget.Latest,
153
+ true,
154
+ ts.ScriptKind.TSX,
155
+ );
156
+
157
+ const replacements: { start: number; end: number; replacement: string }[] =
158
+ [];
159
+
160
+ for (const statement of sourceFile.statements) {
161
+ if (!ts.isImportDeclaration(statement)) continue;
162
+ if (!statement.importClause?.namedBindings) continue;
163
+ if (!ts.isNamedImports(statement.importClause.namedBindings)) continue;
164
+
165
+ const namedImports = statement.importClause.namedBindings;
166
+ const elements = namedImports.elements;
167
+
168
+ // Find the element that matches our entity name
169
+ const matchingIndex = elements.findIndex(
170
+ (el) => el.name.text === entityName,
171
+ );
172
+ if (matchingIndex === -1) continue;
173
+
174
+ // Check if there's a default import (e.g., `import DefaultName, { NamedImport } from '...'`)
175
+ const hasDefaultImport = !!statement.importClause.name;
176
+
177
+ // If this is the only named import AND there's no default import, remove the entire statement
178
+ if (elements.length === 1 && !hasDefaultImport) {
179
+ // Find the end including any trailing newline
180
+ let end = statement.getEnd();
181
+ const afterStatement = fileContent.slice(end);
182
+ const trailingNewline = afterStatement.match(/^\r?\n/);
183
+ if (trailingNewline) {
184
+ end += trailingNewline[0].length;
185
+ }
186
+ replacements.push({
187
+ start: statement.getStart(sourceFile),
188
+ end,
189
+ replacement: '',
190
+ });
191
+ continue;
192
+ }
193
+
194
+ // Otherwise, rebuild the import without this element
195
+ const remainingElements = elements.filter((_, i) => i !== matchingIndex);
196
+
197
+ // Get the module specifier
198
+ const moduleSpecifier = statement.moduleSpecifier;
199
+ if (!ts.isStringLiteral(moduleSpecifier)) continue;
200
+
201
+ // Preserve import type modifier if present
202
+ const importTypePrefix = statement.importClause.isTypeOnly ? 'type ' : '';
203
+
204
+ // Get the default import name if present
205
+ const defaultImportName = statement.importClause.name?.text;
206
+
207
+ let newImport: string;
208
+
209
+ if (remainingElements.length === 0) {
210
+ // All named imports were removed, but there's a default import to preserve
211
+ // (we only get here when hasDefaultImport is true, because otherwise we'd have
212
+ // removed the whole statement at the elements.length === 1 check above)
213
+ newImport = `import ${defaultImportName} from ${moduleSpecifier.getText(sourceFile)};`;
214
+ } else {
215
+ // Build the new named imports string
216
+ const newNamedImports = remainingElements
217
+ .map((el) => {
218
+ const isTypeOnly = el.isTypeOnly;
219
+ const name = el.name.text;
220
+ const propertyName = el.propertyName?.text;
221
+ if (propertyName) {
222
+ return isTypeOnly
223
+ ? `type ${propertyName} as ${name}`
224
+ : `${propertyName} as ${name}`;
225
+ }
226
+ return isTypeOnly ? `type ${name}` : name;
227
+ })
228
+ .join(', ');
229
+
230
+ // Build the new import statement, preserving default import if present
231
+ const defaultImportPrefix = defaultImportName
232
+ ? `${defaultImportName}, `
233
+ : '';
234
+ newImport = `import ${importTypePrefix}${defaultImportPrefix}{ ${newNamedImports} } from ${moduleSpecifier.getText(sourceFile)};`;
235
+ }
236
+
237
+ replacements.push({
238
+ start: statement.getStart(sourceFile),
239
+ end: statement.getEnd(),
240
+ replacement: newImport,
241
+ });
242
+ }
243
+
244
+ // Apply replacements in reverse order to preserve positions
245
+ let result = fileContent;
246
+ replacements.sort((a, b) => b.start - a.start);
247
+ for (const { start, end, replacement } of replacements) {
248
+ result = result.slice(0, start) + replacement + result.slice(end);
249
+ }
250
+
251
+ return result;
252
+ } catch (error) {
253
+ console.warn('[removeNamedImportAst] Failed to parse file:', error);
254
+ return fileContent; // Return original content on error
255
+ }
256
+ }
257
+
77
258
  /**
78
259
  * Map nested dist paths to src paths.
79
260
  * Some build tools create nested structures like:
@@ -263,10 +444,6 @@ function convertDtsToStubs(content: string, entityName: string): string {
263
444
  // Keep export type and export interface statements as-is (they're valid in .ts)
264
445
  // No transformation needed for these
265
446
 
266
- console.log(
267
- `CodeYam: Converted .d.ts content for entity "${entityName}". Result length: ${result.length}`,
268
- );
269
-
270
447
  return result;
271
448
  }
272
449
 
@@ -452,10 +629,6 @@ function stripHtmlBodyTags(
452
629
  return fileContent;
453
630
  }
454
631
 
455
- console.log(
456
- `CodeYam: Stripping <html> and <body> tags from root layout: ${filePath}`,
457
- );
458
-
459
632
  // Extract the body className/attributes if any, to preserve styling
460
633
  const bodyMatch = fileContent.match(/<body([^>]*)>/);
461
634
  const bodyAttributes = bodyMatch?.[1]?.trim() || '';
@@ -501,8 +674,169 @@ function stripHtmlBodyTags(
501
674
  return result;
502
675
  }
503
676
 
677
+ /**
678
+ * Strip `import "server-only"` or `import 'server-only'` directives from file content.
679
+ *
680
+ * Next.js "server-only" package is used to mark modules that should only run on the server.
681
+ * When we generate scenario components for client-side rendering in the browser, importing
682
+ * a file with this directive causes an error:
683
+ *
684
+ * "You're importing a component that needs 'server-only'. That only works in a Server Component"
685
+ *
686
+ * Since our scenario components are rendered client-side for capture purposes, we need to
687
+ * strip this import to allow the file to be imported.
688
+ */
689
+ function stripServerOnlyImport(fileContent: string): string {
690
+ // Match import "server-only" or import 'server-only' with optional semicolon and newline
691
+ // Handles both double and single quotes, with or without trailing semicolon
692
+ return fileContent.replace(/import\s+["']server-only["'];?\s*\n?/g, '');
693
+ }
694
+
695
+ /**
696
+ * Extract all internal import paths from file content.
697
+ * Internal imports are those that start with '.', '@/', '~/', or are relative paths.
698
+ * Excludes node_modules imports (bare specifiers like 'react', '@prisma/client').
699
+ */
700
+ function extractInternalImportPaths(fileContent: string): string[] {
701
+ // Always use AST parsing - regex with nested quantifiers can cause catastrophic
702
+ // backtracking that hangs on a single .exec() call (before iteration limits kick in)
703
+ return extractInternalImportPathsAst(fileContent);
704
+ }
705
+
706
+ /**
707
+ * Extract internal import paths using TypeScript AST - more reliable for large files
708
+ */
709
+ function extractInternalImportPathsAst(fileContent: string): string[] {
710
+ const importPaths: string[] = [];
711
+
712
+ try {
713
+ const sourceFile = ts.createSourceFile(
714
+ 'temp.ts',
715
+ fileContent,
716
+ ts.ScriptTarget.Latest,
717
+ true,
718
+ );
719
+
720
+ for (const statement of sourceFile.statements) {
721
+ if (ts.isImportDeclaration(statement) && statement.moduleSpecifier) {
722
+ const moduleSpecifier = statement.moduleSpecifier;
723
+ if (ts.isStringLiteral(moduleSpecifier)) {
724
+ const importPath = moduleSpecifier.text;
725
+ // Skip node_modules imports (bare specifiers)
726
+ if (
727
+ importPath.startsWith('.') ||
728
+ importPath.startsWith('@/') ||
729
+ importPath.startsWith('~/') ||
730
+ importPath.startsWith('#')
731
+ ) {
732
+ importPaths.push(importPath);
733
+ }
734
+ }
735
+ }
736
+ }
737
+ } catch (error) {
738
+ console.warn(
739
+ '[extractInternalImportPathsAst] Failed to parse file:',
740
+ error,
741
+ );
742
+ }
743
+
744
+ return importPaths;
745
+ }
746
+
747
+ /**
748
+ * Resolve an import path to a file path relative to the project.
749
+ * Handles path aliases like @/, ~/, and relative paths.
750
+ */
751
+ function resolveImportPath(
752
+ importPath: string,
753
+ currentFilePath: string,
754
+ project: Project,
755
+ ): string | null {
756
+ let resolvedPath: string;
757
+ let appPrefix = '';
758
+
759
+ if (importPath.startsWith('./') || importPath.startsWith('../')) {
760
+ // Relative import - resolve relative to current file
761
+ const currentDir = currentFilePath.split('/').slice(0, -1).join('/');
762
+ const parts = [...currentDir.split('/'), ...importPath.split('/')];
763
+ const resolved: string[] = [];
764
+
765
+ for (const part of parts) {
766
+ if (part === '..') {
767
+ resolved.pop();
768
+ } else if (part !== '.' && part !== '') {
769
+ resolved.push(part);
770
+ }
771
+ }
772
+ resolvedPath = resolved.join('/');
773
+ } else if (importPath.startsWith('@/') || importPath.startsWith('~/')) {
774
+ // Path alias - strip the prefix
775
+ resolvedPath = importPath.slice(2);
776
+
777
+ // Infer app prefix from current file path
778
+ // e.g., if currentFilePath is "apps/web/lib/user/service.ts"
779
+ // and import is "@/modules/auth/lib/brevo", the actual file is at
780
+ // "apps/web/modules/auth/lib/brevo.ts"
781
+ // We detect this by checking if current file starts with "apps/XXX/"
782
+ const appMatch = currentFilePath.match(/^(apps\/[^/]+\/)/);
783
+ if (appMatch) {
784
+ appPrefix = appMatch[1];
785
+ }
786
+ } else if (importPath.startsWith('#')) {
787
+ // Package imports - not supported yet
788
+ return null;
789
+ } else {
790
+ // Unknown format
791
+ return null;
792
+ }
793
+
794
+ // Try to find the file with various extensions
795
+ const extensions = ['', '.ts', '.tsx', '.js', '.jsx'];
796
+
797
+ // First try with app prefix (for monorepo structures like apps/web/)
798
+ if (appPrefix) {
799
+ for (const ext of extensions) {
800
+ const fullPath = appPrefix + resolvedPath + ext;
801
+ const file = project.files?.find((f) => f.path === fullPath);
802
+ if (file) {
803
+ return file.path;
804
+ }
805
+ }
806
+
807
+ // Try index files with prefix
808
+ for (const ext of ['.ts', '.tsx', '.js', '.jsx']) {
809
+ const indexPath = `${appPrefix}${resolvedPath}/index${ext}`;
810
+ const file = project.files?.find((f) => f.path === indexPath);
811
+ if (file) {
812
+ return file.path;
813
+ }
814
+ }
815
+ }
816
+
817
+ // Then try without prefix (for simpler project structures)
818
+ for (const ext of extensions) {
819
+ const fullPath = resolvedPath + ext;
820
+ const file = project.files?.find((f) => f.path === fullPath);
821
+ if (file) {
822
+ return file.path;
823
+ }
824
+ }
825
+
826
+ // Try index files
827
+ for (const ext of ['.ts', '.tsx', '.js', '.jsx']) {
828
+ const indexPath = `${resolvedPath}/index${ext}`;
829
+ const file = project.files?.find((f) => f.path === indexPath);
830
+ if (file) {
831
+ return file.path;
832
+ }
833
+ }
834
+
835
+ return null;
836
+ }
837
+
504
838
  // Version for tracking deployments - increment when making changes
505
- const WRITE_SCENARIO_COMPONENTS_VERSION = '2.1.0-ast-based-import-detection';
839
+ const WRITE_SCENARIO_COMPONENTS_VERSION = '2.5.17-configurable-server-mocks';
506
840
 
507
841
  function addMockToContent(
508
842
  fileContent: string,
@@ -513,9 +847,6 @@ function addMockToContent(
513
847
  scenarioName: string,
514
848
  importPath?: string,
515
849
  ) {
516
- console.log(
517
- `CodeYam [v${WRITE_SCENARIO_COMPONENTS_VERSION}]: Adding mock for ${importedExport.name} from ${importedExport.filePath}`,
518
- );
519
850
  // First try to find dependency schemas in fileAnalyses (for same-file dependencies)
520
851
  let dependencySchemas = fileAnalyses.find(
521
852
  (a) =>
@@ -539,34 +870,31 @@ function addMockToContent(
539
870
  importedExport.callVariableNames &&
540
871
  importedExport.callVariableNames.length === importedExport.calls.length;
541
872
 
542
- // DEBUG: Log import info for multiple calls debugging
543
- if (
544
- importedExport.name === 'useFetcher' ||
545
- importedExport.name?.includes('Fetcher')
546
- ) {
547
- console.log(
548
- 'CodeYam DEBUG: addMockToContent useFetcher import:',
549
- JSON.stringify(
550
- {
551
- name: importedExport.name,
552
- calls: importedExport.calls,
553
- callVariableNames: importedExport.callVariableNames,
554
- hasMultipleCallsWithVariables,
555
- isMocked: importedExport.isMocked,
556
- },
557
- null,
558
- 2,
559
- ),
560
- );
561
- }
562
-
563
873
  let mockCode: string | undefined;
564
874
  const variableMockCodes: string[] = [];
565
875
 
566
876
  if (hasMultipleCallsWithVariables) {
567
877
  // Generate separate mock functions for each variable-qualified call
568
- // Track variable name occurrences to disambiguate when same variable is reused
569
- // (mirrors the logic in gatherDataForMocks)
878
+ // Look up canonical keys from dataForMocks and track variable names for function naming
879
+
880
+ // Get all canonical keys for this hook (sorted by index)
881
+ const dataForMocks =
882
+ rootAnalysis.metadata?.scenariosDataStructure?.dataForMocks;
883
+ const canonicalKeysForHook = dataForMocks
884
+ ? Object.keys(dataForMocks)
885
+ .filter((key) => {
886
+ const match = key.match(/^[^:]+::([^:]+)::\d+$/);
887
+ return match && match[1] === importedExport.name;
888
+ })
889
+ .sort((a, b) => {
890
+ // Sort by the index part (last ::N)
891
+ const indexA = parseInt(a.split('::').pop() || '0');
892
+ const indexB = parseInt(b.split('::').pop() || '0');
893
+ return indexA - indexB;
894
+ })
895
+ : [];
896
+
897
+ // Track variable name occurrences for unique function naming
570
898
  const variableNameCounts: Record<string, number> = {};
571
899
 
572
900
  for (let i = 0; i < importedExport.calls!.length; i++) {
@@ -577,18 +905,32 @@ function addMockToContent(
577
905
  const occurrence = variableNameCounts[variableName] ?? 0;
578
906
  variableNameCounts[variableName] = occurrence + 1;
579
907
 
580
- // If this is a reused variable name (occurrence > 0), append index
581
- // e.g., "fetcher[1] <- useFetcher" for the second usage of "fetcher"
908
+ // Build indexed variable name for function naming
582
909
  const indexedVariableName =
583
910
  occurrence > 0 ? `${variableName}[${occurrence}]` : variableName;
584
911
 
585
- // Generate mock code for this specific call using variable-qualified name
586
- // Format: "variableName <- functionName" (reads as "variableName receives from functionName")
587
- const qualifiedName = `${indexedVariableName} <- ${importedExport.name}`;
912
+ // Use safe function name with underscores instead of brackets
913
+ // e.g., fetcher[1] -> fetcher_1
914
+ const safeFunctionName = indexedVariableName.replace(/\[(\d+)\]/g, '_$1');
915
+ // Compute unique mock function name for call site replacement
916
+ // e.g., useFetcher_entityDiffFetcher, useFetcher_reportFetcher
917
+ const mockFunctionName = `${importedExport.name}_${safeFunctionName}`;
918
+
919
+ // Use the canonical key at index i if available
920
+ const canonicalKey = canonicalKeysForHook[i];
921
+
922
+ // Use variable-qualified format that constructMockCode understands
923
+ // e.g., "entityDiffFetcher <- useFetcher" for schema lookup
924
+ // This generates unique variable names like useFetcher_entityDiffFetcherReturnValue
925
+ const qualifiedMockName = `${indexedVariableName} <- ${importedExport.name}`;
926
+
927
+ // Generate mock code using the variable-qualified name and canonical key for data lookup
928
+ // This prevents "symbol already declared" errors when multiple calls exist
588
929
  const variableMockCode = constructMockCode(
589
- qualifiedName,
930
+ qualifiedMockName, // Use variable-qualified format for unique naming
590
931
  dependencySchemas,
591
932
  importedExport.entityType,
933
+ canonicalKey,
592
934
  );
593
935
 
594
936
  if (variableMockCode) {
@@ -597,7 +939,6 @@ function addMockToContent(
597
939
  // Replace the call site with the variable-specific mock function
598
940
  // e.g., useFetcher<BranchEntityDiffResult>() -> useFetcher_entityDiffFetcher()
599
941
  // e.g., useFetcher() -> useFetcher_reportFetcher()
600
- // For indexed variables: useFetcher() -> useFetcher_fetcher_1()
601
942
  const callSignature = importedExport.calls![i];
602
943
  // Escape special regex characters in the call signature
603
944
  const escapedCallSignature = callSignature.replace(
@@ -609,13 +950,6 @@ function addMockToContent(
609
950
  escapedCallSignature.replace(/\s+/g, '\\s*'),
610
951
  'g',
611
952
  );
612
- // Use safe function name with underscores instead of brackets
613
- // e.g., fetcher[1] -> fetcher_1
614
- const safeFunctionName = indexedVariableName.replace(
615
- /\[(\d+)\]/g,
616
- '_$1',
617
- );
618
- const mockFunctionName = `${importedExport.name}_${safeFunctionName}`;
619
953
  fileContent = fileContent.replace(callRegex, `${mockFunctionName}()`);
620
954
  }
621
955
  }
@@ -631,54 +965,109 @@ function addMockToContent(
631
965
  : undefined;
632
966
 
633
967
  if (singleCallVariableName) {
634
- // For single variable assignments, use the variable-qualified key for data lookup
635
- // but keep the original function name (no need for unique function names when there's only one assignment)
636
- const qualifiedKey = `${singleCallVariableName} <- ${importedExport.name}`;
637
- mockCode = `const ${importedExport.name}ReturnValue = scenarios().data()?.["${qualifiedKey}"];
968
+ // For single variable assignments, look up canonical key from dataForMocks
969
+ const dataForMocks =
970
+ rootAnalysis.metadata?.scenariosDataStructure?.dataForMocks;
971
+ let canonicalKey = dataForMocks
972
+ ? Object.keys(dataForMocks).find((key) => {
973
+ // Check canonical key format: EntityName::hookName::index
974
+ const canonicalMatch = key.match(/^[^:]+::([^:]+)::\d+$/);
975
+ if (canonicalMatch && canonicalMatch[1] === importedExport.name) {
976
+ return true;
977
+ }
978
+ // Fall back to legacy format
979
+ const legacyMatch = key.match(
980
+ /^([a-zA-Z_][a-zA-Z0-9_]*)\s*<-\s*(.+)$/,
981
+ );
982
+ return legacyMatch && legacyMatch[2] === importedExport.name;
983
+ })
984
+ : undefined;
985
+
986
+ // If no canonical key found in dataForMocks, use variable-qualified format directly
987
+ // This allows constructMockCode to find the schema in dependencySchemas
988
+ if (!canonicalKey) {
989
+ canonicalKey = `${singleCallVariableName} <- ${importedExport.name}`;
990
+ }
991
+
992
+ // Keep the original function name since there's only one call
993
+ mockCode = constructMockCode(
994
+ importedExport.name,
995
+ dependencySchemas,
996
+ importedExport.entityType,
997
+ canonicalKey,
998
+ { keepOriginalFunctionName: true },
999
+ );
1000
+ // If constructMockCode didn't generate code, fall back to simple return
1001
+ if (!mockCode) {
1002
+ mockCode = `const ${importedExport.name}ReturnValue = scenarios().data()?.["${canonicalKey}"];
638
1003
 
639
1004
  function ${importedExport.name}() {
640
1005
  return ${importedExport.name}ReturnValue;
641
1006
  }`;
1007
+ }
642
1008
  } else {
643
- // Check if any analysis (fileAnalyses or rootAnalysis) has this function's data
644
- // under a variable-qualified key. The entity that CALLS the function (e.g., FileTableRow)
645
- // has the dataForMocks with the variable-qualified key, not the root analysis (e.g., GitView).
646
- let variableQualifiedKey: string | undefined;
647
-
648
- // First check fileAnalyses (the analyses for the entity being written)
649
- for (const analysis of fileAnalyses) {
650
- const dataForMocks =
651
- analysis.metadata?.scenariosDataStructure?.dataForMocks;
652
- if (dataForMocks) {
653
- variableQualifiedKey = Object.keys(dataForMocks).find((key) => {
654
- const match = key.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\s*<-\s*(.+)$/);
655
- return match && match[2] === importedExport.name;
656
- });
657
- if (variableQualifiedKey) {
658
- break;
1009
+ // Look for canonical key (format: EntityName::hookName::index) or legacy variable-qualified key
1010
+ let canonicalKey: string | undefined;
1011
+
1012
+ // Helper to find matching key from dataForMocks
1013
+ const findMatchingKey = (
1014
+ dataForMocks: Record<string, unknown> | undefined,
1015
+ ): string | undefined => {
1016
+ if (!dataForMocks) return undefined;
1017
+ return Object.keys(dataForMocks).find((key) => {
1018
+ // Check canonical key format: EntityName::hookName::index
1019
+ const canonicalMatch = key.match(/^[^:]+::([^:]+)::\d+$/);
1020
+ if (canonicalMatch && canonicalMatch[1] === importedExport.name) {
1021
+ return true;
659
1022
  }
660
- }
661
- }
1023
+ // Fall back to legacy variable-qualified format: variableName <- functionName
1024
+ const legacyMatch = key.match(
1025
+ /^([a-zA-Z_][a-zA-Z0-9_]*)\s*<-\s*(.+)$/,
1026
+ );
1027
+ return legacyMatch && legacyMatch[2] === importedExport.name;
1028
+ });
1029
+ };
1030
+
1031
+ // CRITICAL: Check rootAnalysis FIRST for canonical keys.
1032
+ // This ensures we use the same keys that will be in the mock DATA.
1033
+ // The mock DATA is generated from rootAnalysis, so the mock CODE must
1034
+ // also use rootAnalysis keys to ensure the lookup succeeds.
1035
+ // Bug scenario (if we check fileAnalyses first):
1036
+ // - Child component's fileAnalysis has: "ChildComponent::hook::0"
1037
+ // - Root's dataForMocks has: "RootEntity::hook::0"
1038
+ // - Mock CODE uses child key, but mock DATA has root key → lookup fails
1039
+ canonicalKey = findMatchingKey(
1040
+ rootAnalysis.metadata?.scenariosDataStructure?.dataForMocks,
1041
+ );
662
1042
 
663
- // If not found in fileAnalyses, fall back to rootAnalysis
664
- if (!variableQualifiedKey) {
665
- const dataForMocks =
666
- rootAnalysis.metadata?.scenariosDataStructure?.dataForMocks;
667
- if (dataForMocks) {
668
- variableQualifiedKey = Object.keys(dataForMocks).find((key) => {
669
- const match = key.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\s*<-\s*(.+)$/);
670
- return match && match[2] === importedExport.name;
671
- });
1043
+ // If not found in rootAnalysis, fall back to fileAnalyses
1044
+ if (!canonicalKey) {
1045
+ for (const analysis of fileAnalyses) {
1046
+ canonicalKey = findMatchingKey(
1047
+ analysis.metadata?.scenariosDataStructure?.dataForMocks,
1048
+ );
1049
+ if (canonicalKey) break;
672
1050
  }
673
1051
  }
674
1052
 
675
- if (variableQualifiedKey) {
676
- // Use the variable-qualified key found in the analysis
677
- mockCode = `const ${importedExport.name}ReturnValue = scenarios().data()?.["${variableQualifiedKey}"];
1053
+ if (canonicalKey) {
1054
+ // Use the canonical key for data lookup
1055
+ // Keep the original function name since there's only one call
1056
+ mockCode = constructMockCode(
1057
+ importedExport.name,
1058
+ dependencySchemas,
1059
+ importedExport.entityType,
1060
+ canonicalKey,
1061
+ { keepOriginalFunctionName: true },
1062
+ );
1063
+ // If constructMockCode didn't generate code, fall back to simple return
1064
+ if (!mockCode) {
1065
+ mockCode = `const ${importedExport.name}ReturnValue = scenarios().data()?.["${canonicalKey}"];
678
1066
 
679
1067
  function ${importedExport.name}() {
680
1068
  return ${importedExport.name}ReturnValue;
681
1069
  }`;
1070
+ }
682
1071
  } else {
683
1072
  // Original behavior for calls without variable names
684
1073
  mockCode = constructMockCode(
@@ -695,35 +1084,6 @@ function ${importedExport.name}() {
695
1084
  variableMockCodes.length > 0 ? variableMockCodes.join('\n\n') : mockCode;
696
1085
 
697
1086
  if (!allMockCodes) {
698
- console.log(
699
- 'CodeYam Error: Mock code not found',
700
- JSON.stringify(
701
- {
702
- importedExportFilePath: importedExport.filePath,
703
- importedExportEntityName: importedExport.name,
704
- hasMultipleCallsWithVariables,
705
- analysisIds: fileAnalyses.map((a) => ({
706
- id: a.id,
707
- filePath: a.filePath,
708
- entityName: a.entityName,
709
- })),
710
- analysisFilePath: fileAnalyses?.[0]?.filePath,
711
- analysisEntityNames: fileAnalyses.map((a) => a.entityName),
712
- dependencySchemas: fileAnalyses.find(
713
- (a) =>
714
- !!a.entity.metadata?.isolatedDataStructure?.dependencySchemas?.[
715
- importedExport.filePath
716
- ]?.[importedExport.name],
717
- )?.entity.metadata?.isolatedDataStructure?.dependencySchemas,
718
- allDependencySchemas: fileAnalyses.map(
719
- (a) => a.entity.metadata?.isolatedDataStructure?.dependencySchemas,
720
- ),
721
- },
722
- null,
723
- 2,
724
- ),
725
- );
726
-
727
1087
  return fileContent;
728
1088
  }
729
1089
 
@@ -818,18 +1178,12 @@ function ${importedExport.name}() {
818
1178
 
819
1179
  if (lastImportEnd > 0) {
820
1180
  // Insert after the last original import
821
- console.log(
822
- `CodeYam [v${WRITE_SCENARIO_COMPONENTS_VERSION}]: Inserting mock at position ${lastImportEnd} (after imports), not at end`,
823
- );
824
1181
  fileContent =
825
1182
  fileContent.slice(0, lastImportEnd) +
826
1183
  insertContent +
827
1184
  fileContent.slice(lastImportEnd);
828
1185
  } else {
829
1186
  // Fallback: append at end if no imports found
830
- console.log(
831
- `CodeYam [v${WRITE_SCENARIO_COMPONENTS_VERSION}]: No imports found, appending mock at end`,
832
- );
833
1187
  fileContent += insertContent;
834
1188
  }
835
1189
 
@@ -1011,6 +1365,15 @@ export default async function writeScenarioComponents({
1011
1365
  scenarioComponentPaths: string[];
1012
1366
  writtenScenarioComponents: { [key: string]: string[] };
1013
1367
  }> {
1368
+ // Reset debug timing for this invocation
1369
+ resetDebugTiming();
1370
+ debugLog('START writeScenarioComponents', {
1371
+ filePath: file.path,
1372
+ entityName: entity.name,
1373
+ scenarioName: scenario.name,
1374
+ isRootFile: !rootFile || rootFile === file,
1375
+ });
1376
+
1014
1377
  // Capture arguments for testing if debug mode is enabled
1015
1378
  captureArgumentsForTesting({
1016
1379
  project,
@@ -1132,9 +1495,6 @@ export default async function writeScenarioComponents({
1132
1495
  // .d.ts files only have type declarations (e.g., "export declare const logger")
1133
1496
  // which don't provide runtime exports. We need to generate actual stub implementations.
1134
1497
  if (file.path.endsWith('.d.ts')) {
1135
- console.log(
1136
- `CodeYam: Converting .d.ts file to stub implementations: ${file.path}`,
1137
- );
1138
1498
  fileContent = convertDtsToStubs(fileContent, entity.name);
1139
1499
 
1140
1500
  // After basic .d.ts conversion, enhance the entity's stub with proper mock code
@@ -1233,7 +1593,24 @@ export default async function writeScenarioComponents({
1233
1593
  return 0;
1234
1594
  });
1235
1595
 
1596
+ debugLog('Starting main importedExports loop', {
1597
+ count: sortedImportedExports.length,
1598
+ fileContentLength: fileContent.length,
1599
+ });
1600
+
1601
+ let importedExportIndex = 0;
1236
1602
  for (const importedExport of sortedImportedExports) {
1603
+ importedExportIndex++;
1604
+ if (importedExportIndex % 5 === 0 || importedExportIndex === 1) {
1605
+ debugLog(
1606
+ `Processing importedExport ${importedExportIndex}/${sortedImportedExports.length}`,
1607
+ {
1608
+ name: importedExport.name,
1609
+ filePath: importedExport.filePath,
1610
+ isMocked: importedExport.isMocked,
1611
+ },
1612
+ );
1613
+ }
1237
1614
  // IMPORTANT: The import mapping keys may be either absolute or relative paths
1238
1615
  // depending on how they were created by the file analyzer. We try multiple formats.
1239
1616
  // Also need to normalize paths to handle /tmp vs /private/tmp on macOS
@@ -1305,15 +1682,6 @@ export default async function writeScenarioComponents({
1305
1682
  importedExport.name,
1306
1683
  )
1307
1684
  ) {
1308
- // Skip recursion for type/data entities - they don't need scenario components
1309
- // Only recurse for visual and library entities that need mocking
1310
- if (
1311
- importedExportEntity.entityType === 'type' ||
1312
- importedExportEntity.entityType === 'data'
1313
- ) {
1314
- continue;
1315
- }
1316
-
1317
1685
  // Use fileStore for O(1) lookup when available
1318
1686
  let fileNotMocked = fileStore
1319
1687
  ? fileStore.getByPath(importedExportFilePath)
@@ -1347,35 +1715,119 @@ export default async function writeScenarioComponents({
1347
1715
  fileNotMocked = await fileStore.ensureContent(fileNotMocked.path);
1348
1716
  }
1349
1717
 
1350
- // When a default export is imported as named (via index re-export), we need
1351
- // to add a named re-export to the scenario component so the import works.
1352
- // e.g., if file has `export default X` but parent does `import { X } from '...'`
1353
- const needsNamedReExport =
1354
- importedExport.resolvedIsDefault === true &&
1355
- importedExport.isDefault === false;
1356
-
1357
- const {
1358
- scenarioComponentPaths: newScenarioComponentPaths,
1359
- writtenScenarioComponents: updatedWrittenScenarioComponents,
1360
- } = await writeScenarioComponents({
1361
- project,
1362
- file: fileNotMocked,
1363
- entity: importedExportEntity,
1364
- rootAnalysis,
1365
- scenario,
1366
- context,
1367
- projectAnalyzer,
1368
- framework,
1369
- mocksDir,
1370
- rootFile,
1371
- namespaceMocks,
1372
- writtenScenarioComponents,
1373
- fileStore,
1374
- // Pass the import name so we can add `export { default as Name };`
1375
- exportAsNamed: needsNamedReExport ? importedExport.name : undefined,
1376
- });
1377
- writtenScenarioComponents = updatedWrittenScenarioComponents;
1378
- scenarioComponentPaths.push(...newScenarioComponentPaths);
1718
+ // For type/data entities, create a transformed copy WITHOUT recursion.
1719
+ // Data entities don't need mocking - they're just constants/types that need
1720
+ // to be available. But we still need to:
1721
+ // 1. Strip server-only imports (Next.js directive that breaks client components)
1722
+ // 2. Write the transformed file so imports can be rewritten to point to it
1723
+ if (
1724
+ importedExportEntity.entityType === 'type' ||
1725
+ importedExportEntity.entityType === 'data'
1726
+ ) {
1727
+ // For data entities, we write ONE transformed copy per source file, not per entity.
1728
+ // Check if we've already written ANY entity from this file - if so, skip writing.
1729
+ // Use a special marker '__data_file_written__' to track file-level writes.
1730
+ // Also track which SHA was used via '__data_file_sha__:xxx' so subsequent
1731
+ // entities from the same file can reuse it for import rewriting.
1732
+ const dataFileWritten = writtenScenarioComponents[
1733
+ importedExportFilePath
1734
+ ]?.includes('__data_file_written__');
1735
+
1736
+ if (!dataFileWritten) {
1737
+ // Construct the scenario file path for the data file
1738
+ // Use a file-level identifier (first entity's sha) for consistency
1739
+ const dataFileBasePath = safeFolder(
1740
+ fileNotMocked.path.split('/').slice(0, -1).join('/'),
1741
+ );
1742
+ const dataFileExtension = fileNotMocked.name.split('.').pop();
1743
+ const dataFileIsIndex = isIndexPath(fileNotMocked.path);
1744
+ // Use 'data' prefix to distinguish from entity-specific files
1745
+ const dataScenarioPath = `${PROJECT_RELATIVE_PATH}/${dataFileBasePath}/${importedExportEntity.sha}_${dataFileIsIndex ? 'index_' : ''}data_${safeFileName(scenario.name)}.${dataFileExtension}`;
1746
+
1747
+ // Get the file content and apply transformations
1748
+ let dataFileContent = fileNotMocked.content ?? '';
1749
+
1750
+ // Strip server-only imports - these break when imported by client components
1751
+ dataFileContent = stripServerOnlyImport(dataFileContent);
1752
+ dataFileContent = applyServerOnlyMocks(dataFileContent);
1753
+
1754
+ // Write the transformed data entity file
1755
+ await writeFile(dataScenarioPath, dataFileContent);
1756
+ scenarioComponentPaths.push(dataScenarioPath);
1757
+
1758
+ // Mark file as written so we don't duplicate for other entities from same file
1759
+ if (!writtenScenarioComponents[importedExportFilePath]) {
1760
+ writtenScenarioComponents[importedExportFilePath] = [];
1761
+ }
1762
+ writtenScenarioComponents[importedExportFilePath].push(
1763
+ '__data_file_written__',
1764
+ );
1765
+ // Also store the SHA used for this data file so subsequent entities can use it
1766
+ writtenScenarioComponents[importedExportFilePath].push(
1767
+ `__data_file_sha__:${importedExportEntity.sha}`,
1768
+ );
1769
+ }
1770
+
1771
+ // Mark this specific entity as written (for the entity-level check)
1772
+ if (!writtenScenarioComponents[importedExportFilePath]) {
1773
+ writtenScenarioComponents[importedExportFilePath] = [];
1774
+ }
1775
+ writtenScenarioComponents[importedExportFilePath].push(
1776
+ importedExport.name,
1777
+ );
1778
+
1779
+ // Don't recurse - data entities don't need their dependencies processed
1780
+ // The import rewriting will happen later in this same loop iteration
1781
+ // (at lines ~1590-1702) to point imports to this transformed file
1782
+ } else {
1783
+ // For visual/library entities, recurse to process their dependencies
1784
+
1785
+ // When a default export is imported as named (via index re-export), we need
1786
+ // to add a named re-export to the scenario component so the import works.
1787
+ // e.g., if file has `export default X` but parent does `import { X } from '...'`
1788
+ const needsNamedReExport =
1789
+ importedExport.resolvedIsDefault === true &&
1790
+ importedExport.isDefault === false;
1791
+
1792
+ debugLog(
1793
+ `Recursing into writeScenarioComponents for ${importedExportEntity.name}`,
1794
+ {
1795
+ entityName: importedExportEntity.name,
1796
+ filePath: fileNotMocked.path,
1797
+ },
1798
+ );
1799
+ const {
1800
+ scenarioComponentPaths: newScenarioComponentPaths,
1801
+ writtenScenarioComponents: updatedWrittenScenarioComponents,
1802
+ } = await withTimeout(
1803
+ `recursive writeScenarioComponents for ${importedExportEntity.name}`,
1804
+ writeScenarioComponents({
1805
+ project,
1806
+ file: fileNotMocked,
1807
+ entity: importedExportEntity,
1808
+ rootAnalysis,
1809
+ scenario,
1810
+ context,
1811
+ projectAnalyzer,
1812
+ framework,
1813
+ mocksDir,
1814
+ rootFile,
1815
+ namespaceMocks,
1816
+ writtenScenarioComponents,
1817
+ fileStore,
1818
+ // Pass the import name so we can add `export { default as Name };`
1819
+ exportAsNamed: needsNamedReExport
1820
+ ? importedExport.name
1821
+ : undefined,
1822
+ }),
1823
+ 60000, // 1 minute timeout for recursive calls
1824
+ );
1825
+ debugLog(
1826
+ `Completed recursive writeScenarioComponents for ${importedExportEntity.name}`,
1827
+ );
1828
+ writtenScenarioComponents = updatedWrittenScenarioComponents;
1829
+ scenarioComponentPaths.push(...newScenarioComponentPaths);
1830
+ }
1379
1831
  }
1380
1832
  }
1381
1833
  } else if (
@@ -1403,12 +1855,6 @@ export default async function writeScenarioComponents({
1403
1855
  ),
1404
1856
  );
1405
1857
 
1406
- if (looksLikeZodSchema) {
1407
- console.log(
1408
- `CodeYam: Detected Zod schema "${importedExport.name}" (misclassified as library) - will preserve`,
1409
- );
1410
- }
1411
-
1412
1858
  // Callable entities can be safely stubbed (but not Zod schemas)
1413
1859
  const isCallable =
1414
1860
  !isDataEntity && !looksLikeZodSchema && entityType !== undefined;
@@ -1431,9 +1877,6 @@ export default async function writeScenarioComponents({
1431
1877
  if (shouldPreserve) {
1432
1878
  // For data entities (like Zod schemas), don't strip or stub - preserve the original
1433
1879
  // This ensures schema methods like .superRefine() continue to work
1434
- console.log(
1435
- `CodeYam: Preserving ${importedExport.name} (entityType: ${entityType}) - not stripping data entities`,
1436
- );
1437
1880
  // Don't modify fileContent - keep the original code
1438
1881
  } else if (shouldStripAndReplace || shouldStripAndStub) {
1439
1882
  // Strip the original code
@@ -1457,9 +1900,6 @@ export default async function writeScenarioComponents({
1457
1900
  // This prevents ReferenceError at runtime when the stripped
1458
1901
  // function is called (e.g., local helper functions like getInitialProps).
1459
1902
  const functionName = importedExport.name;
1460
- console.log(
1461
- `CodeYam: Generating stub mock for ${functionName} (entityType: ${entityType}) in ${file.path}`,
1462
- );
1463
1903
 
1464
1904
  // Add scenarios import if not present
1465
1905
  if (fileContent.indexOf('import { scenarios } from') === -1) {
@@ -1594,6 +2034,31 @@ ${exportKeyword}const ${functionName} = new Proxy(() => scenarios().data()?.["${
1594
2034
 
1595
2035
  const fileName = actualScenarioFilePathRelative.split('/').pop();
1596
2036
  const fileNotMockedIsIndex = isIndexPath(fileNotMocked?.path);
2037
+
2038
+ // For data/type entities, use 'data' instead of entity name since we write
2039
+ // ONE file per source file (not per entity) for data entities
2040
+ const isDataEntity =
2041
+ importedExportEntity?.entityType === 'data' ||
2042
+ importedExportEntity?.entityType === 'type';
2043
+ const scenarioFileName = isDataEntity
2044
+ ? 'data'
2045
+ : safeFileName(importedExportEntity.name);
2046
+
2047
+ // For data entities, look up the SHA that was used to create the data file
2048
+ // (stored when the file was first written). This ensures all entities from
2049
+ // the same source file have their imports rewritten to point to the same file.
2050
+ // Use actualScenarioFilePathRelative as the key since that's what matches
2051
+ // importedExportFilePath used when storing (both are relative paths).
2052
+ let entityShaForPath = importedExportEntity.sha;
2053
+ if (isDataEntity && actualScenarioFilePathRelative) {
2054
+ const storedShaMarker = writtenScenarioComponents[
2055
+ actualScenarioFilePathRelative
2056
+ ]?.find((m) => m.startsWith('__data_file_sha__:'));
2057
+ if (storedShaMarker) {
2058
+ entityShaForPath = storedShaMarker.replace('__data_file_sha__:', '');
2059
+ }
2060
+ }
2061
+
1597
2062
  const mockFilePath = isFrameworkRoute(
1598
2063
  fileNotMocked,
1599
2064
  importedExportEntity,
@@ -1615,7 +2080,7 @@ ${exportKeyword}const ${functionName} = new Proxy(() => scenarios().data()?.["${
1615
2080
  .join('.')
1616
2081
  : actualScenarioFilePathRelative.replace(
1617
2082
  `${fileName}`,
1618
- `${importedExportEntity.sha}_${fileNotMockedIsIndex ? 'index_' : ''}${safeFileName(importedExportEntity.name)}_${safeFileName(scenario.name)}`,
2083
+ `${entityShaForPath}_${fileNotMockedIsIndex ? 'index_' : ''}${scenarioFileName}_${safeFileName(scenario.name)}`,
1619
2084
  );
1620
2085
 
1621
2086
  const path = safeFolder(getRelativePath(filePath, mockFilePath));
@@ -1656,21 +2121,33 @@ ${exportKeyword}const ${functionName} = new Proxy(() => scenarios().data()?.["${
1656
2121
  // This handles cases where multiple entities are imported from the same index file
1657
2122
  // (e.g., import { A, B, C } from '@pkg') and each has its own scenario file
1658
2123
  const entityImportName = importedExport.name;
1659
- const newImport = `import { ${entityImportName} } from '${path}';`;
2124
+ // Use default import syntax for default exports, named import for named exports
2125
+ const newImport = importedExport.isDefault
2126
+ ? `import ${entityImportName} from '${path}';`
2127
+ : `import { ${entityImportName} } from '${path}';`;
1660
2128
 
1661
2129
  // First, try to remove this entity from the already-rewritten grouped import
1662
2130
  // This prevents duplicate/conflicting imports
1663
- // Match patterns like "EntityName," or ", EntityName" or "EntityName" (if only one)
1664
- // Note: entityImportName needs escaping since JS identifiers can contain $ (a regex metacharacter)
2131
+ // Use AST-based removal to properly handle type-only imports like `type EntityName`
1665
2132
  const escapedEntityName = escapeRegExp(entityImportName);
1666
- const removeFromGroupedImportPatterns = [
1667
- new RegExp(`\\b${escapedEntityName}\\s*,\\s*`, 'g'), // "EntityName, "
1668
- new RegExp(`\\s*,\\s*${escapedEntityName}\\b`, 'g'), // ", EntityName"
1669
- ];
1670
- for (const pattern of removeFromGroupedImportPatterns) {
1671
- fileContent = fileContent.replace(pattern, '');
2133
+
2134
+ // For default imports: remove "DefaultName, " from "import DefaultName, { ... }"
2135
+ // This handles the case where a default export is being split out
2136
+ if (importedExport.isDefault) {
2137
+ const defaultImportPattern = new RegExp(
2138
+ `(import\\s+)${escapedEntityName}\\s*,\\s*(\\{)`,
2139
+ 'gm',
2140
+ );
2141
+ fileContent = fileContent.replace(defaultImportPattern, '$1$2');
1672
2142
  }
1673
2143
 
2144
+ // Remove the named import using AST parsing
2145
+ // This properly handles:
2146
+ // - Regular imports: `import { EntityName } from '...'`
2147
+ // - Type-only imports: `import { type EntityName } from '...'`
2148
+ // - Mixed imports: `import { type EntityName, OtherName } from '...'`
2149
+ fileContent = removeNamedImportAst(fileContent, entityImportName);
2150
+
1674
2151
  // Add the new import at the beginning of fileContent
1675
2152
  // Note: The header comment (// Scenario:) doesn't exist yet - it's prepended at writeFile time
1676
2153
  // So prepending here puts the import right after the header in the final output
@@ -1685,9 +2162,28 @@ ${exportKeyword}const ${functionName} = new Proxy(() => scenarios().data()?.["${
1685
2162
  }
1686
2163
  }
1687
2164
 
2165
+ // Collect universal mocks BEFORE processing nodeModuleImports
2166
+ // This is needed to check if a node module import is handled by a universal mock
2167
+ const universalMocks = project.metadata?.universalMocks ?? [];
2168
+ const nodeModuleUniversalMocks = universalMocks.filter(
2169
+ (mock) => mock.nodeModule && mock.content,
2170
+ );
2171
+
2172
+ // Create a set of import paths that have universal mocks for quick lookup
2173
+ const universalMockPaths = new Set(
2174
+ nodeModuleUniversalMocks.map((mock) => mock.filePath),
2175
+ );
2176
+
1688
2177
  for (const nodeModuleImport of nodeModuleImports) {
1689
2178
  if (!nodeModuleImport.isMocked) continue;
1690
2179
 
2180
+ // Skip generating local mock functions for imports that have universal mocks.
2181
+ // Universal mocks provide the exports via rewritten import paths (handled below).
2182
+ // Generating a local mock function would cause "name defined multiple times" errors.
2183
+ if (universalMockPaths.has(nodeModuleImport.filePath)) {
2184
+ continue;
2185
+ }
2186
+
1691
2187
  fileContent = addMockToContent(
1692
2188
  fileContent,
1693
2189
  nodeModuleImport,
@@ -1703,10 +2199,6 @@ ${exportKeyword}const ${functionName} = new Proxy(() => scenarios().data()?.["${
1703
2199
  // Universal mocks create mock files at __codeyamMocks__/{safeFileName}.tsx
1704
2200
  // We need to rewrite imports like `import { logger } from "@formbricks/logger"`
1705
2201
  // to `import { logger } from "../__codeyamMocks__/_formbricks_logger"`
1706
- const universalMocks = project.metadata?.universalMocks ?? [];
1707
- const nodeModuleUniversalMocks = universalMocks.filter(
1708
- (mock) => mock.nodeModule && mock.content,
1709
- );
1710
2202
 
1711
2203
  for (const universalMock of nodeModuleUniversalMocks) {
1712
2204
  const originalPath = universalMock.filePath;
@@ -1770,34 +2262,503 @@ ${exportKeyword}const ${functionName} = new Proxy(() => scenarios().data()?.["${
1770
2262
  });
1771
2263
  }
1772
2264
 
2265
+ debugLog('Route path computed', { scenarioComponentPath });
2266
+
1773
2267
  // Strip <html> and <body> tags from root layout files for Next.js
1774
2268
  // These tags cause hydration errors when the scenario layout is nested under the real root
2269
+ debugLog('Starting stripHtmlBodyTags');
1775
2270
  fileContent = stripHtmlBodyTags(fileContent, file.path, framework);
2271
+ debugLog('Completed stripHtmlBodyTags');
2272
+
2273
+ // Strip "server-only" imports for Next.js
2274
+ // These cause errors when the scenario component is rendered client-side
2275
+ debugLog('Starting stripServerOnlyImport');
2276
+ fileContent = stripServerOnlyImport(fileContent);
2277
+ debugLog('Starting applyServerOnlyMocks');
2278
+ fileContent = applyServerOnlyMocks(fileContent);
2279
+ debugLog('Completed server-only processing');
1776
2280
 
1777
2281
  // Rewrite asset imports (CSS, images, fonts, etc.) to correct relative paths
1778
2282
  // The original file path is relative to PROJECT_RELATIVE_PATH, the new path is scenarioComponentPath
2283
+ debugLog('Starting rewriteAssetImports');
1779
2284
  fileContent = rewriteAssetImports(
1780
2285
  fileContent,
1781
2286
  `${PROJECT_RELATIVE_PATH}/${file.path}`,
1782
2287
  scenarioComponentPath,
1783
2288
  );
2289
+ debugLog('Completed rewriteAssetImports');
1784
2290
 
1785
2291
  // Rewrite relative TypeScript/JavaScript module imports to correct relative paths
1786
2292
  // This handles cases where the file is moved (e.g., from [environmentId]/ to _environmentId_/)
1787
2293
  // and relative imports like "./lib/organization" need to be rewritten
2294
+ debugLog('Starting rewriteRelativeModuleImports');
1788
2295
  fileContent = rewriteRelativeModuleImports(
1789
2296
  fileContent,
1790
2297
  `${PROJECT_RELATIVE_PATH}/${file.path}`,
1791
2298
  scenarioComponentPath,
1792
2299
  );
2300
+ debugLog('Completed rewriteRelativeModuleImports');
1793
2301
 
1794
- console.log(
1795
- 'Writing scenario component',
1796
- file.path,
1797
- entity.name,
1798
- scenarioComponentPath,
1799
- fileContent.length,
2302
+ /**
2303
+ * Recursively process a file's imports to create transitive copies with server-only stripped.
2304
+ * This handles chains of arbitrary depth: A -> B -> C -> D where each needs server-only removed.
2305
+ * Uses a visited set to detect and break circular import chains.
2306
+ *
2307
+ * @param content - The file content to process
2308
+ * @param sourceFilePath - The original source file path (for resolving relative imports)
2309
+ * @param targetFilePath - The path where this content will be written (for computing relative imports)
2310
+ * @param visitedPaths - Set of file paths currently being processed (for cycle detection)
2311
+ * @returns The modified content with imports rewritten to point to transitive copies
2312
+ */
2313
+ async function processTransitiveImportsRecursively(
2314
+ content: string,
2315
+ sourceFilePath: string,
2316
+ targetFilePath: string,
2317
+ visitedPaths: Set<string> = new Set(),
2318
+ depth: number = 0,
2319
+ startTime: number = Date.now(),
2320
+ ): Promise<string> {
2321
+ // Global timeout for entire transitive processing
2322
+ const GLOBAL_TIMEOUT_MS = 60000; // 1 minute max for all transitive processing
2323
+ const elapsed = Date.now() - startTime;
2324
+ if (elapsed > GLOBAL_TIMEOUT_MS) {
2325
+ throw new Error(
2326
+ `processTransitiveImportsRecursively exceeded ${GLOBAL_TIMEOUT_MS}ms (elapsed: ${elapsed}ms) at depth=${depth} for ${sourceFilePath}`,
2327
+ );
2328
+ }
2329
+
2330
+ const importPaths = extractInternalImportPaths(content);
2331
+ debugLog(`processTransitiveImportsRecursively depth=${depth}`, {
2332
+ sourceFilePath,
2333
+ importCount: importPaths.length,
2334
+ visitedCount: visitedPaths.size,
2335
+ });
2336
+ let modifiedContent = content;
2337
+
2338
+ // Safety check: limit iterations to prevent infinite loops
2339
+ const MAX_IMPORTS_PER_FILE = 100;
2340
+ if (importPaths.length > MAX_IMPORTS_PER_FILE) {
2341
+ console.warn(
2342
+ `[WriteScenario] WARNING: File ${sourceFilePath} has ${importPaths.length} imports (> ${MAX_IMPORTS_PER_FILE}), limiting processing`,
2343
+ );
2344
+ }
2345
+
2346
+ let importIndex = 0;
2347
+ debugLog(
2348
+ `Starting import loop at depth=${depth}, ${importPaths.length} imports to process`,
2349
+ );
2350
+ const slicedImports = importPaths.slice(0, MAX_IMPORTS_PER_FILE);
2351
+ for (const importPath of slicedImports) {
2352
+ if (!importPath) {
2353
+ continue;
2354
+ }
2355
+ importIndex++;
2356
+ debugLog(
2357
+ `[LOOP] depth=${depth} import ${importIndex}/${Math.min(importPaths.length, MAX_IMPORTS_PER_FILE)}: ${importPath}`,
2358
+ );
2359
+ debugLog(`[LOOP] Calling resolveImportPath...`);
2360
+ const resolvedPath = resolveImportPath(
2361
+ importPath,
2362
+ sourceFilePath,
2363
+ project,
2364
+ );
2365
+ debugLog(
2366
+ `[LOOP] resolveImportPath returned: ${resolvedPath?.slice(0, 80) ?? 'null'}`,
2367
+ );
2368
+ if (!resolvedPath) continue;
2369
+
2370
+ debugLog(`[LOOP] Looking up importFile...`);
2371
+ let importFile = fileStore
2372
+ ? fileStore.getByPath(resolvedPath)
2373
+ : project.files?.find((f) => f.path === resolvedPath);
2374
+ debugLog(
2375
+ `[LOOP] importFile lookup result: ${importFile ? 'found' : 'not found'}`,
2376
+ );
2377
+ if (!importFile) continue;
2378
+
2379
+ // Build the transitive file path (needed for import rewriting even if we skip creating)
2380
+ const basePath = safeFolder(
2381
+ importFile.path.split('/').slice(0, -1).join('/'),
2382
+ );
2383
+ const extension = importFile.name.split('.').pop();
2384
+ const isIndex = isIndexPath(importFile.path);
2385
+ const pathHash = safeFileName(importFile.path);
2386
+ const transitiveFilePath = `${PROJECT_RELATIVE_PATH}/${basePath}/${pathHash}_${isIndex ? 'index_' : ''}transitive_${safeFileName(scenario.name)}.${extension}`;
2387
+
2388
+ // Check if this is a circular import (we're already processing this file)
2389
+ const isCircularImport = visitedPaths.has(resolvedPath);
2390
+
2391
+ // Check if already processed
2392
+ const alreadyProcessed = writtenScenarioComponents[
2393
+ resolvedPath
2394
+ ]?.includes('__transitive_file_written__');
2395
+
2396
+ // Only create the transitive file if not circular and not already processed
2397
+ if (!isCircularImport && !alreadyProcessed) {
2398
+ // Load content if needed
2399
+ if (!importFile.content && fileStore) {
2400
+ importFile = await fileStore.ensureContent(resolvedPath);
2401
+ }
2402
+ if (!importFile?.content) {
2403
+ // Can't create transitive, but still try to rewrite import below
2404
+ } else {
2405
+ // Mark as being processed BEFORE recursing (to detect cycles)
2406
+ visitedPaths.add(resolvedPath);
2407
+
2408
+ // Strip server-only and mock server-only packages, then recursively process imports
2409
+ let transitiveContent = stripServerOnlyImport(importFile.content);
2410
+ transitiveContent = applyServerOnlyMocks(transitiveContent);
2411
+ debugLog(
2412
+ `processTransitiveImportsRecursively depth=${depth} for ${importFile.path}`,
2413
+ );
2414
+ debugLog(
2415
+ `Calling processTransitiveImportsRecursively depth=${depth + 1} for ${importFile.path}`,
2416
+ );
2417
+ transitiveContent = await withTimeout(
2418
+ `processTransitiveImportsRecursively depth=${depth} for ${path.basename(importFile.path)}`,
2419
+ processTransitiveImportsRecursively(
2420
+ transitiveContent,
2421
+ importFile.path,
2422
+ transitiveFilePath,
2423
+ visitedPaths,
2424
+ depth + 1,
2425
+ startTime, // Pass through the original start time
2426
+ ),
2427
+ 30000, // 30 second timeout per transitive import
2428
+ );
2429
+ debugLog(
2430
+ `withTimeout returned for depth=${depth}, transitiveContent length=${transitiveContent.length}`,
2431
+ );
2432
+ debugLog(
2433
+ `Completed processTransitiveImportsRecursively depth=${depth} for ${importFile.path}`,
2434
+ );
2435
+
2436
+ debugLog(`Writing transitive file depth=${depth}`, {
2437
+ transitiveFilePath: path.basename(transitiveFilePath),
2438
+ contentLength: transitiveContent.length,
2439
+ });
2440
+ await writeFile(transitiveFilePath, transitiveContent);
2441
+ debugLog(`Wrote transitive file depth=${depth}`);
2442
+ scenarioComponentPaths.push(transitiveFilePath);
2443
+
2444
+ if (!writtenScenarioComponents[resolvedPath]) {
2445
+ writtenScenarioComponents[resolvedPath] = [];
2446
+ }
2447
+ writtenScenarioComponents[resolvedPath].push(
2448
+ '__transitive_file_written__',
2449
+ );
2450
+ }
2451
+ }
2452
+
2453
+ // ALWAYS rewrite the import to point to the transitive copy
2454
+ // (even for circular imports or already-processed files)
2455
+ debugLog(`Rewriting import path depth=${depth}`, {
2456
+ importPath,
2457
+ resolvedPath,
2458
+ });
2459
+ const relativePath = getRelativePath(targetFilePath, transitiveFilePath);
2460
+ const relativePathWithoutExt = relativePath.replace(
2461
+ /\.(ts|tsx|js|jsx)$/,
2462
+ '',
2463
+ );
2464
+ const safeRelativePath = safeFolder(relativePathWithoutExt);
2465
+ const escapedImportPath = importPath.replace(
2466
+ /[.*+?^${}()|[\]\\]/g,
2467
+ '\\$&',
2468
+ );
2469
+ debugLog(`Applying regex depth=${depth}`, {
2470
+ escapedImportPath,
2471
+ contentLength: modifiedContent.length,
2472
+ });
2473
+ // Quick check if the import path even exists in content
2474
+ const simpleCheck = modifiedContent.includes(importPath);
2475
+ debugLog(
2476
+ `Simple check: importPath "${importPath}" exists: ${simpleCheck}`,
2477
+ );
2478
+ if (!simpleCheck) {
2479
+ debugLog(`Skipping regex - import path not found in content`);
2480
+ } else {
2481
+ const regexPattern = `(from\\s*["'])${escapedImportPath}(["'])`;
2482
+ debugLog(`Regex pattern: ${regexPattern.slice(0, 100)}`);
2483
+ const importRegex = new RegExp(regexPattern, 'g');
2484
+ debugLog(`About to call replace...`);
2485
+
2486
+ // Timing for regex replace to detect slow operations
2487
+ const replaceStart = Date.now();
2488
+ modifiedContent = modifiedContent.replace(
2489
+ importRegex,
2490
+ `$1${safeRelativePath}$2`,
2491
+ );
2492
+ const replaceTime = Date.now() - replaceStart;
2493
+ if (replaceTime > 100) {
2494
+ console.warn(
2495
+ `[WriteScenario] SLOW regex replace: ${replaceTime}ms for pattern ${regexPattern.slice(0, 50)} on ${modifiedContent.length} bytes`,
2496
+ );
2497
+ }
2498
+ debugLog(`Regex applied depth=${depth} in ${replaceTime}ms`);
2499
+ }
2500
+ debugLog(`[LOOP END] depth=${depth} import ${importIndex} completed`);
2501
+ }
2502
+
2503
+ debugLog(`[LOOP DONE] Exiting import loop at depth=${depth}`);
2504
+ debugLog(
2505
+ `Returning from processTransitiveImportsRecursively depth=${depth}`,
2506
+ );
2507
+ return modifiedContent;
2508
+ }
2509
+
2510
+ // Process remaining internal imports that weren't in importedExports
2511
+ // This handles transitive dependencies: when the file content includes code (e.g., from
2512
+ // other functions in the same file) that imports from files with "server-only"
2513
+ debugLog('Extracting remaining import paths');
2514
+ const remainingImportPaths = extractInternalImportPaths(fileContent);
2515
+ debugLog('Found remaining import paths', {
2516
+ count: remainingImportPaths.length,
2517
+ });
2518
+
2519
+ // Get all file paths that are in importedExports - these are handled by main processing
2520
+ const importedExportFilePaths = new Set(
2521
+ allImportedExports.map((ie) => ie.resolvedFilePath || ie.filePath),
2522
+ );
2523
+
2524
+ debugLog('Starting remaining imports loop', {
2525
+ remainingCount: remainingImportPaths.length,
2526
+ importedExportCount: importedExportFilePaths.size,
2527
+ });
2528
+
2529
+ let remainingImportIndex = 0;
2530
+ debugLog(
2531
+ `[REMAINING] Starting remaining imports loop, ${remainingImportPaths.length} imports`,
1800
2532
  );
2533
+ for (const importPath of remainingImportPaths) {
2534
+ remainingImportIndex++;
2535
+ debugLog(
2536
+ `[REMAINING LOOP] import ${remainingImportIndex}/${remainingImportPaths.length}: ${importPath}`,
2537
+ );
2538
+ // Resolve the import path to a project file path
2539
+ const resolvedFilePath = resolveImportPath(importPath, file.path, project);
2540
+
2541
+ if (!resolvedFilePath) {
2542
+ // Can't resolve - might be a path we don't handle, skip it
2543
+ continue;
2544
+ }
2545
+
2546
+ // Find the file in project.files, using fileStore for O(1) lookup when available
2547
+ // We need to find the file BEFORE checking importedExports to see if it has server-only
2548
+ let targetFile = fileStore
2549
+ ? fileStore.getByPath(resolvedFilePath)
2550
+ : project.files?.find((f) => f.path === resolvedFilePath);
2551
+
2552
+ // Skip if this import is in importedExports - it's handled by the main processing loop
2553
+ // UNLESS the file contains "server-only", in which case we still need a transitive copy
2554
+ // with server-only stripped (even if some exports from the file are mocked).
2555
+ if (importedExportFilePaths.has(resolvedFilePath)) {
2556
+ // Check if the file has server-only before skipping
2557
+ let fileContent = targetFile?.content;
2558
+ if (!fileContent && targetFile && fileStore) {
2559
+ // Load content to check for server-only
2560
+ const loadedFile = await fileStore.ensureContent(resolvedFilePath);
2561
+ fileContent = loadedFile?.content;
2562
+ if (loadedFile) {
2563
+ targetFile = loadedFile;
2564
+ }
2565
+ }
2566
+
2567
+ const hasServerOnly =
2568
+ fileContent && /import\s+["']server-only["']/.test(fileContent);
2569
+
2570
+ if (!hasServerOnly) {
2571
+ continue;
2572
+ }
2573
+ // File has server-only - continue processing to create transitive copy
2574
+ }
2575
+ if (!targetFile) {
2576
+ continue;
2577
+ }
2578
+
2579
+ // Compute the transformed file path (needed for import rewriting even if already processed)
2580
+ const targetFileBasePath = safeFolder(
2581
+ targetFile.path.split('/').slice(0, -1).join('/'),
2582
+ );
2583
+ const targetFileExtension = targetFile.name.split('.').pop();
2584
+ const targetFileIsIndex = isIndexPath(targetFile.path);
2585
+ const filePathHash = safeFileName(targetFile.path);
2586
+ const transformedFilePath = `${PROJECT_RELATIVE_PATH}/${targetFileBasePath}/${filePathHash}_${targetFileIsIndex ? 'index_' : ''}transitive_${safeFileName(scenario.name)}.${targetFileExtension}`;
2587
+
2588
+ // Check if we've already processed this file as a transitive copy
2589
+ // Note: __data_file_written__ is for entity-specific scenario files with different naming,
2590
+ // but we still need transitive copies for server-only stripping. Data entity files may
2591
+ // only export specific items, so we need a full transitive copy with all exports.
2592
+ const alreadyTransitive = writtenScenarioComponents[
2593
+ resolvedFilePath
2594
+ ]?.includes('__transitive_file_written__');
2595
+
2596
+ if (!alreadyTransitive) {
2597
+ // Ensure content is loaded (LazyFileStore loads content on-demand)
2598
+ if (!targetFile.content && fileStore) {
2599
+ targetFile = await fileStore.ensureContent(resolvedFilePath);
2600
+ }
2601
+ if (!targetFile?.content) {
2602
+ continue;
2603
+ }
2604
+
2605
+ // Get the file content and apply transformations
2606
+ let transformedContent = targetFile.content;
2607
+ transformedContent = stripServerOnlyImport(transformedContent);
2608
+ transformedContent = applyServerOnlyMocks(transformedContent);
2609
+
2610
+ // Recursively process this transitive file's imports
2611
+ // This handles the nested case: service.ts → brevo.ts → constants.ts
2612
+ const nestedImportPaths = extractInternalImportPaths(transformedContent);
2613
+ debugLog(
2614
+ `[NESTED] Processing ${nestedImportPaths.length} nested imports for ${targetFile.path}`,
2615
+ );
2616
+ let nestedIndex = 0;
2617
+ for (const nestedImportPath of nestedImportPaths) {
2618
+ nestedIndex++;
2619
+ debugLog(
2620
+ `[NESTED LOOP] import ${nestedIndex}/${nestedImportPaths.length}: ${nestedImportPath}`,
2621
+ );
2622
+ const nestedResolvedPath = resolveImportPath(
2623
+ nestedImportPath,
2624
+ targetFile.path,
2625
+ project,
2626
+ );
2627
+ if (!nestedResolvedPath) continue;
2628
+
2629
+ // Get file info for building the transformed path
2630
+ let nestedFile = fileStore
2631
+ ? fileStore.getByPath(nestedResolvedPath)
2632
+ : project.files?.find((f) => f.path === nestedResolvedPath);
2633
+ if (!nestedFile) continue;
2634
+
2635
+ // Build the transformed path (needed for import rewriting even if already processed)
2636
+ const nestedBasePath = safeFolder(
2637
+ nestedFile.path.split('/').slice(0, -1).join('/'),
2638
+ );
2639
+ const nestedExtension = nestedFile.name.split('.').pop();
2640
+ const nestedIsIndex = isIndexPath(nestedFile.path);
2641
+ const nestedPathHash = safeFileName(nestedFile.path);
2642
+ const nestedTransformedPath = `${PROJECT_RELATIVE_PATH}/${nestedBasePath}/${nestedPathHash}_${nestedIsIndex ? 'index_' : ''}transitive_${safeFileName(scenario.name)}.${nestedExtension}`;
2643
+
2644
+ // Check if already processed as a transitive file (we can rewrite to point to it)
2645
+ // Note: __data_file_written__ is for entity-specific scenario files with different naming,
2646
+ // but we still need transitive copies for server-only stripping in the import chain
2647
+ const nestedAlreadyTransitive = writtenScenarioComponents[
2648
+ nestedResolvedPath
2649
+ ]?.includes('__transitive_file_written__');
2650
+
2651
+ if (!nestedAlreadyTransitive) {
2652
+ // Ensure content is loaded for nested files
2653
+ if (!nestedFile.content && fileStore) {
2654
+ nestedFile = await fileStore.ensureContent(nestedResolvedPath);
2655
+ }
2656
+ if (!nestedFile?.content) continue;
2657
+
2658
+ // Strip server-only, mock server-only packages, and recursively process imports
2659
+ // This handles chains of any depth: A -> B -> C -> D
2660
+ let nestedContent = stripServerOnlyImport(nestedFile.content);
2661
+ nestedContent = applyServerOnlyMocks(nestedContent);
2662
+ debugLog(
2663
+ `processTransitiveImportsRecursively (nested) for ${nestedFile.path}`,
2664
+ );
2665
+ nestedContent = await withTimeout(
2666
+ `processTransitiveImportsRecursively (nested) for ${path.basename(nestedFile.path)}`,
2667
+ processTransitiveImportsRecursively(
2668
+ nestedContent,
2669
+ nestedFile.path,
2670
+ nestedTransformedPath,
2671
+ ),
2672
+ 30000, // 30 second timeout per nested transitive import
2673
+ );
2674
+ debugLog(
2675
+ `Completed processTransitiveImportsRecursively (nested) for ${nestedFile.path}`,
2676
+ );
2677
+
2678
+ await writeFile(nestedTransformedPath, nestedContent);
2679
+ scenarioComponentPaths.push(nestedTransformedPath);
2680
+
2681
+ // Mark as written
2682
+ if (!writtenScenarioComponents[nestedResolvedPath]) {
2683
+ writtenScenarioComponents[nestedResolvedPath] = [];
2684
+ }
2685
+ writtenScenarioComponents[nestedResolvedPath].push(
2686
+ '__transitive_file_written__',
2687
+ );
2688
+ }
2689
+
2690
+ // Rewrite the import to point to the transitive copy
2691
+ const nestedRelativePath = getRelativePath(
2692
+ transformedFilePath,
2693
+ nestedTransformedPath,
2694
+ );
2695
+ // Strip the extension before applying safeFolder - import paths in TypeScript
2696
+ // should NOT include extensions (Next.js resolves .ts/.tsx automatically).
2697
+ // Without this, safeFolder converts ".ts" to "_ts" causing "Module not found" errors.
2698
+ const nestedRelativePathWithoutExt = nestedRelativePath.replace(
2699
+ /\.(ts|tsx|js|jsx)$/,
2700
+ '',
2701
+ );
2702
+ const safeNestedRelativePath = safeFolder(nestedRelativePathWithoutExt);
2703
+ const escapedNestedImportPath = nestedImportPath.replace(
2704
+ /[.*+?^${}()|[\]\\]/g,
2705
+ '\\$&',
2706
+ );
2707
+ const nestedImportRegex = new RegExp(
2708
+ `(from\\s*["'])${escapedNestedImportPath}(["'])`,
2709
+ 'g',
2710
+ );
2711
+ transformedContent = transformedContent.replace(
2712
+ nestedImportRegex,
2713
+ `$1${safeNestedRelativePath}$2`,
2714
+ );
2715
+ }
2716
+
2717
+ // Re-check if file was written during recursive processing
2718
+ // (processTransitiveImportsRecursively might have created this file while processing
2719
+ // a nested import that circularly imports back to this file)
2720
+ const writtenDuringRecursion = writtenScenarioComponents[
2721
+ resolvedFilePath
2722
+ ]?.includes('__transitive_file_written__');
2723
+
2724
+ if (!writtenDuringRecursion) {
2725
+ // Write the transformed file
2726
+ await writeFile(transformedFilePath, transformedContent);
2727
+ scenarioComponentPaths.push(transformedFilePath);
2728
+
2729
+ // Mark as written
2730
+ if (!writtenScenarioComponents[resolvedFilePath]) {
2731
+ writtenScenarioComponents[resolvedFilePath] = [];
2732
+ }
2733
+ writtenScenarioComponents[resolvedFilePath].push(
2734
+ '__transitive_file_written__',
2735
+ );
2736
+ }
2737
+ }
2738
+
2739
+ // ALWAYS rewrite the import in fileContent to point to the transformed file
2740
+ // (even if the transitive copy was already created by another entity)
2741
+ const relativePath = getRelativePath(
2742
+ scenarioComponentPath,
2743
+ transformedFilePath,
2744
+ );
2745
+ // Strip the extension before applying safeFolder - import paths in TypeScript
2746
+ // should NOT include extensions (Next.js resolves .ts/.tsx automatically).
2747
+ // Without this, safeFolder converts ".ts" to "_ts" causing "Module not found" errors.
2748
+ const relativePathWithoutExt = relativePath.replace(
2749
+ /\.(ts|tsx|js|jsx)$/,
2750
+ '',
2751
+ );
2752
+ const safeRelativePath = safeFolder(relativePathWithoutExt);
2753
+
2754
+ // Escape special regex characters in the import path
2755
+ const escapedImportPath = importPath.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
2756
+ const importRegex = new RegExp(
2757
+ `(from\\s*["'])${escapedImportPath}(["'])`,
2758
+ 'g',
2759
+ );
2760
+ fileContent = fileContent.replace(importRegex, `$1${safeRelativePath}$2`);
2761
+ }
1801
2762
 
1802
2763
  const scenarioComponentComment = `// This file is auto-generated by CodeYam. Do not edit this file manually.
1803
2764
  // This file contains content for a scenario component:
@@ -1812,26 +2773,24 @@ ${exportKeyword}const ${functionName} = new Proxy(() => scenarios().data()?.["${
1812
2773
 
1813
2774
  // Use the directive that was extracted at the beginning of processing
1814
2775
  // This ensures it stays at the very top even after imports are prepended
2776
+ // NOTE: We only preserve "use client" directives, NOT "use server" directives.
2777
+ // Server action files get mocked with objects that aren't async functions,
2778
+ // which would violate Next.js's "use server" requirement:
2779
+ // "A 'use server' file can only export async functions, found object."
1815
2780
  let finalContent: string;
1816
- if (extractedDirective) {
2781
+ if (extractedDirective && extractedDirective.includes('client')) {
1817
2782
  finalContent = `${extractedDirective}\n\n${scenarioComponentComment}\n\n${fileContent}`;
1818
- console.log(
1819
- `CodeYam: Placed "${extractedDirective}" directive at top of file: ${scenarioComponentPath}`,
1820
- );
1821
2783
  } else {
1822
2784
  finalContent = `${scenarioComponentComment}\n\n${fileContent}`;
1823
2785
  }
1824
2786
 
2787
+ debugLog('About to write final scenario file', {
2788
+ scenarioComponentPath,
2789
+ contentLength: finalContent.length,
2790
+ });
1825
2791
  await writeFile(scenarioComponentPath, finalContent);
2792
+ debugLog('Successfully wrote scenario file');
1826
2793
  scenarioComponentPaths.push(scenarioComponentPath);
1827
2794
 
1828
- console.log('CodeYam [writeScenarioComponents]: Generated scenario files', {
1829
- entityName: entity.name,
1830
- filePath: file.path,
1831
- scenarioName: scenario.name,
1832
- scenarioComponentPathsGenerated: scenarioComponentPaths,
1833
- writtenScenarioComponentKeys: Object.keys(writtenScenarioComponents),
1834
- });
1835
-
1836
2795
  return { scenarioComponentPaths, writtenScenarioComponents };
1837
2796
  }